]> Cypherpunks.ru repositories - goircd.git/blob - client.go
Perform DNS lookup of client addresses
[goircd.git] / client.go
1 /*
2 goircd -- minimalistic simple Internet Relay Chat (IRC) server
3 Copyright (C) 2014-2015 Sergey Matveev <stargrave@stargrave.org>
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 package main
20
21 import (
22         "bytes"
23         "log"
24         "net"
25         "strings"
26         "sync"
27         "time"
28 )
29
30 const (
31         BufSize   = 1500
32         MaxOutBuf = 1 << 12
33 )
34
35 var (
36         CRLF []byte = []byte{'\x0d', '\x0a'}
37 )
38
39 type Client struct {
40         conn          net.Conn
41         registered    bool
42         nickname      *string
43         username      *string
44         realname      *string
45         password      *string
46         away          *string
47         recvTimestamp time.Time
48         sendTimestamp time.Time
49         outBuf        chan string
50         alive         bool
51         sync.Mutex
52 }
53
54 func (c Client) Host() string {
55         addr := c.conn.RemoteAddr().String()
56         if host, _, err := net.SplitHostPort(addr); err == nil {
57                 addr = host
58         }
59         if domains, err := net.LookupAddr(addr); err == nil {
60                 addr = strings.TrimSuffix(domains[0], ".")
61         }
62         return addr
63 }
64
65 func (c Client) String() string {
66         return *c.nickname + "!" + *c.username + "@" + c.Host()
67 }
68
69 func NewClient(conn net.Conn) *Client {
70         nickname := "*"
71         username := ""
72         c := Client{
73                 conn:          conn,
74                 nickname:      &nickname,
75                 username:      &username,
76                 recvTimestamp: time.Now(),
77                 sendTimestamp: time.Now(),
78                 alive:         true,
79                 outBuf:        make(chan string, MaxOutBuf),
80         }
81         go c.MsgSender()
82         return &c
83 }
84
85 func (c *Client) SetDead() {
86         close(c.outBuf)
87         c.alive = false
88 }
89
90 func (c *Client) Close() {
91         c.Lock()
92         c.conn.Close()
93         if c.alive {
94                 c.SetDead()
95         }
96         c.Unlock()
97 }
98
99 // Client processor blockingly reads everything remote client sends,
100 // splits messages by CRLF and send them to Daemon gorouting for processing
101 // it futher. Also it can signalize that client is unavailable (disconnected).
102 func (c *Client) Processor(sink chan ClientEvent) {
103         sink <- ClientEvent{c, EventNew, ""}
104         log.Println(c, "New client")
105         buf := make([]byte, BufSize*2)
106         var n int
107         var prev int
108         var i int
109         var err error
110         for {
111                 if prev == BufSize {
112                         log.Println(c, "input buffer size exceeded, kicking him")
113                         break
114                 }
115                 n, err = c.conn.Read(buf[prev:])
116                 if err != nil {
117                         break
118                 }
119                 prev += n
120         CheckMore:
121                 i = bytes.Index(buf[:prev], CRLF)
122                 if i == -1 {
123                         continue
124                 }
125                 sink <- ClientEvent{c, EventMsg, string(buf[:i])}
126                 copy(buf, buf[i+2:prev])
127                 prev -= (i + 2)
128                 goto CheckMore
129         }
130         c.Close()
131         sink <- ClientEvent{c, EventDel, ""}
132 }
133
134 func (c *Client) MsgSender() {
135         for msg := range c.outBuf {
136                 c.conn.Write(append([]byte(msg), CRLF...))
137         }
138 }
139
140 // Send message as is with CRLF appended.
141 func (c *Client) Msg(text string) {
142         c.Lock()
143         defer c.Unlock()
144         if !c.alive {
145                 return
146         }
147         if len(c.outBuf) == MaxOutBuf {
148                 log.Println(c, "output buffer size exceeded, kicking him")
149                 go c.Close()
150                 c.SetDead()
151                 return
152         }
153         c.outBuf <- text
154 }
155
156 // Send message from server. It has ": servername" prefix.
157 func (c *Client) Reply(text string) {
158         c.Msg(":" + *hostname + " " + text)
159 }
160
161 // Send server message, concatenating all provided text parts and
162 // prefix the last one with ":".
163 func (c *Client) ReplyParts(code string, text ...string) {
164         parts := []string{code}
165         for _, t := range text {
166                 parts = append(parts, t)
167         }
168         parts[len(parts)-1] = ":" + parts[len(parts)-1]
169         c.Reply(strings.Join(parts, " "))
170 }
171
172 // Send nicknamed server message. After servername it always has target
173 // client's nickname. The last part is prefixed with ":".
174 func (c *Client) ReplyNicknamed(code string, text ...string) {
175         c.ReplyParts(code, append([]string{*c.nickname}, text...)...)
176 }
177
178 // Reply "461 not enough parameters" error for given command.
179 func (c *Client) ReplyNotEnoughParameters(command string) {
180         c.ReplyNicknamed("461", command, "Not enough parameters")
181 }
182
183 // Reply "403 no such channel" error for specified channel.
184 func (c *Client) ReplyNoChannel(channel string) {
185         c.ReplyNicknamed("403", channel, "No such channel")
186 }
187
188 func (c *Client) ReplyNoNickChan(channel string) {
189         c.ReplyNicknamed("401", channel, "No such nick/channel")
190 }