-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
76 lines (63 loc) · 1.63 KB
/
connection.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright (c) 2015 Bertrand Janin <[email protected]>
// Copyright 2014-2015, Truveris Inc. All Rights Reserved.
// Use of this source code is governed by the ISC license in the LICENSE file.
package main
import (
"fmt"
"log"
"net"
"regexp"
"strconv"
"strings"
)
// Connection states
const (
ConnStateInit = iota
ConnStateWaitingForHello = iota
ConnStateLive = iota
)
// Connection error codes (RFC 1459)
const (
ErrCodeNoNicknameGiven = 431
ErrCodeErroneusNickname = 432
ErrCodeNicknameInUse = 433
ErrCodeNickCollision = 436
)
var (
// ConnectionState is the current state of the connection state machine.
ConnectionState = ConnStateInit
// reServerMessage is a regexp to parse IRC server messages.
reServerMessage = regexp.MustCompile(`^:[^ ]+ ([0-9]{2,4}) ([^ ]+) (.*)`)
)
// Send a command to the IRC server.
func sendLine(conn net.Conn, cmd string) {
cmd = strings.TrimSpace(cmd)
log.Printf("> %s", cmd)
fmt.Fprintf(conn, "%s\r\n", cmd)
}
func parseServerMessageCode(line string) int16 {
tokens := reServerMessage.FindStringSubmatch(line)
if tokens == nil {
return 0
}
code, err := strconv.ParseInt(tokens[1], 10, 16)
if err != nil {
log.Printf("error: invalid server message: bad code (%s) in: %s",
err.Error(), line)
return 0
}
if tokens[2] != cfg.IRCNickname {
log.Printf("error: invalid server message: wrong nickname in: %s",
line)
return 0
}
return int16(code)
}
// Connect to the selected server and join all the specified channels.
func connect() (net.Conn, error) {
conn, err := net.Dial("tcp", cfg.IRCServer)
if err != nil {
return nil, err
}
return conn, nil
}