1 | package soju
|
---|
2 |
|
---|
3 | import (
|
---|
4 | "crypto/tls"
|
---|
5 | "encoding/base64"
|
---|
6 | "fmt"
|
---|
7 | "io"
|
---|
8 | "net"
|
---|
9 | "strconv"
|
---|
10 | "strings"
|
---|
11 | "time"
|
---|
12 |
|
---|
13 | "github.com/emersion/go-sasl"
|
---|
14 | "golang.org/x/crypto/bcrypt"
|
---|
15 | "gopkg.in/irc.v3"
|
---|
16 | )
|
---|
17 |
|
---|
18 | type ircError struct {
|
---|
19 | Message *irc.Message
|
---|
20 | }
|
---|
21 |
|
---|
22 | func (err ircError) Error() string {
|
---|
23 | return err.Message.String()
|
---|
24 | }
|
---|
25 |
|
---|
26 | func newUnknownCommandError(cmd string) ircError {
|
---|
27 | return ircError{&irc.Message{
|
---|
28 | Command: irc.ERR_UNKNOWNCOMMAND,
|
---|
29 | Params: []string{
|
---|
30 | "*",
|
---|
31 | cmd,
|
---|
32 | "Unknown command",
|
---|
33 | },
|
---|
34 | }}
|
---|
35 | }
|
---|
36 |
|
---|
37 | func newNeedMoreParamsError(cmd string) ircError {
|
---|
38 | return ircError{&irc.Message{
|
---|
39 | Command: irc.ERR_NEEDMOREPARAMS,
|
---|
40 | Params: []string{
|
---|
41 | "*",
|
---|
42 | cmd,
|
---|
43 | "Not enough parameters",
|
---|
44 | },
|
---|
45 | }}
|
---|
46 | }
|
---|
47 |
|
---|
48 | func newChatHistoryError(subcommand string, target string) ircError {
|
---|
49 | return ircError{&irc.Message{
|
---|
50 | Command: "FAIL",
|
---|
51 | Params: []string{"CHATHISTORY", "MESSAGE_ERROR", subcommand, target, "Messages could not be retrieved"},
|
---|
52 | }}
|
---|
53 | }
|
---|
54 |
|
---|
55 | var errAuthFailed = ircError{&irc.Message{
|
---|
56 | Command: irc.ERR_PASSWDMISMATCH,
|
---|
57 | Params: []string{"*", "Invalid username or password"},
|
---|
58 | }}
|
---|
59 |
|
---|
60 | func parseBouncerNetID(subcommand, s string) (int64, error) {
|
---|
61 | id, err := strconv.ParseInt(s, 10, 64)
|
---|
62 | if err != nil {
|
---|
63 | return 0, ircError{&irc.Message{
|
---|
64 | Command: "FAIL",
|
---|
65 | Params: []string{"BOUNCER", "INVALID_NETID", subcommand, s, "Invalid network ID"},
|
---|
66 | }}
|
---|
67 | }
|
---|
68 | return id, nil
|
---|
69 | }
|
---|
70 |
|
---|
71 | func getNetworkAttrs(network *network) irc.Tags {
|
---|
72 | state := "disconnected"
|
---|
73 | if uc := network.conn; uc != nil {
|
---|
74 | state = "connected"
|
---|
75 | }
|
---|
76 |
|
---|
77 | attrs := irc.Tags{
|
---|
78 | "name": irc.TagValue(network.GetName()),
|
---|
79 | "state": irc.TagValue(state),
|
---|
80 | "nickname": irc.TagValue(network.Nick),
|
---|
81 | }
|
---|
82 |
|
---|
83 | if network.Username != "" {
|
---|
84 | attrs["username"] = irc.TagValue(network.Username)
|
---|
85 | }
|
---|
86 | if network.Realname != "" {
|
---|
87 | attrs["realname"] = irc.TagValue(network.Realname)
|
---|
88 | }
|
---|
89 |
|
---|
90 | if u, err := network.URL(); err == nil {
|
---|
91 | hasHostPort := true
|
---|
92 | switch u.Scheme {
|
---|
93 | case "ircs":
|
---|
94 | attrs["tls"] = irc.TagValue("1")
|
---|
95 | case "irc+insecure":
|
---|
96 | attrs["tls"] = irc.TagValue("0")
|
---|
97 | default:
|
---|
98 | hasHostPort = false
|
---|
99 | }
|
---|
100 | if host, port, err := net.SplitHostPort(u.Host); err == nil && hasHostPort {
|
---|
101 | attrs["host"] = irc.TagValue(host)
|
---|
102 | attrs["port"] = irc.TagValue(port)
|
---|
103 | } else if hasHostPort {
|
---|
104 | attrs["host"] = irc.TagValue(u.Host)
|
---|
105 | }
|
---|
106 | }
|
---|
107 |
|
---|
108 | return attrs
|
---|
109 | }
|
---|
110 |
|
---|
111 | // ' ' and ':' break the IRC message wire format, '@' and '!' break prefixes,
|
---|
112 | // '*' and '?' break masks
|
---|
113 | const illegalNickChars = " :@!*?"
|
---|
114 |
|
---|
115 | // permanentDownstreamCaps is the list of always-supported downstream
|
---|
116 | // capabilities.
|
---|
117 | var permanentDownstreamCaps = map[string]string{
|
---|
118 | "batch": "",
|
---|
119 | "cap-notify": "",
|
---|
120 | "echo-message": "",
|
---|
121 | "invite-notify": "",
|
---|
122 | "message-tags": "",
|
---|
123 | "sasl": "PLAIN",
|
---|
124 | "server-time": "",
|
---|
125 |
|
---|
126 | "soju.im/bouncer-networks": "",
|
---|
127 | "soju.im/bouncer-networks-notify": "",
|
---|
128 | }
|
---|
129 |
|
---|
130 | // needAllDownstreamCaps is the list of downstream capabilities that
|
---|
131 | // require support from all upstreams to be enabled
|
---|
132 | var needAllDownstreamCaps = map[string]string{
|
---|
133 | "away-notify": "",
|
---|
134 | "extended-join": "",
|
---|
135 | "multi-prefix": "",
|
---|
136 | }
|
---|
137 |
|
---|
138 | // passthroughIsupport is the set of ISUPPORT tokens that are directly passed
|
---|
139 | // through from the upstream server to downstream clients.
|
---|
140 | //
|
---|
141 | // This is only effective in single-upstream mode.
|
---|
142 | var passthroughIsupport = map[string]bool{
|
---|
143 | "AWAYLEN": true,
|
---|
144 | "BOT": true,
|
---|
145 | "CHANLIMIT": true,
|
---|
146 | "CHANMODES": true,
|
---|
147 | "CHANNELLEN": true,
|
---|
148 | "CHANTYPES": true,
|
---|
149 | "EXCEPTS": true,
|
---|
150 | "EXTBAN": true,
|
---|
151 | "HOSTLEN": true,
|
---|
152 | "INVEX": true,
|
---|
153 | "KICKLEN": true,
|
---|
154 | "MAXLIST": true,
|
---|
155 | "MAXTARGETS": true,
|
---|
156 | "MODES": true,
|
---|
157 | "NETWORK": true,
|
---|
158 | "NICKLEN": true,
|
---|
159 | "PREFIX": true,
|
---|
160 | "SAFELIST": true,
|
---|
161 | "TARGMAX": true,
|
---|
162 | "TOPICLEN": true,
|
---|
163 | "USERLEN": true,
|
---|
164 | }
|
---|
165 |
|
---|
166 | type downstreamConn struct {
|
---|
167 | conn
|
---|
168 |
|
---|
169 | id uint64
|
---|
170 |
|
---|
171 | registered bool
|
---|
172 | user *user
|
---|
173 | nick string
|
---|
174 | nickCM string
|
---|
175 | rawUsername string
|
---|
176 | networkName string
|
---|
177 | clientName string
|
---|
178 | realname string
|
---|
179 | hostname string
|
---|
180 | password string // empty after authentication
|
---|
181 | network *network // can be nil
|
---|
182 |
|
---|
183 | negociatingCaps bool
|
---|
184 | capVersion int
|
---|
185 | supportedCaps map[string]string
|
---|
186 | caps map[string]bool
|
---|
187 |
|
---|
188 | saslServer sasl.Server
|
---|
189 | }
|
---|
190 |
|
---|
191 | func newDownstreamConn(srv *Server, ic ircConn, id uint64) *downstreamConn {
|
---|
192 | remoteAddr := ic.RemoteAddr().String()
|
---|
193 | logger := &prefixLogger{srv.Logger, fmt.Sprintf("downstream %q: ", remoteAddr)}
|
---|
194 | options := connOptions{Logger: logger}
|
---|
195 | dc := &downstreamConn{
|
---|
196 | conn: *newConn(srv, ic, &options),
|
---|
197 | id: id,
|
---|
198 | supportedCaps: make(map[string]string),
|
---|
199 | caps: make(map[string]bool),
|
---|
200 | }
|
---|
201 | dc.hostname = remoteAddr
|
---|
202 | if host, _, err := net.SplitHostPort(dc.hostname); err == nil {
|
---|
203 | dc.hostname = host
|
---|
204 | }
|
---|
205 | for k, v := range permanentDownstreamCaps {
|
---|
206 | dc.supportedCaps[k] = v
|
---|
207 | }
|
---|
208 | if srv.LogPath != "" {
|
---|
209 | dc.supportedCaps["draft/chathistory"] = ""
|
---|
210 | }
|
---|
211 | return dc
|
---|
212 | }
|
---|
213 |
|
---|
214 | func (dc *downstreamConn) prefix() *irc.Prefix {
|
---|
215 | return &irc.Prefix{
|
---|
216 | Name: dc.nick,
|
---|
217 | User: dc.user.Username,
|
---|
218 | Host: dc.hostname,
|
---|
219 | }
|
---|
220 | }
|
---|
221 |
|
---|
222 | func (dc *downstreamConn) forEachNetwork(f func(*network)) {
|
---|
223 | if dc.network != nil {
|
---|
224 | f(dc.network)
|
---|
225 | } else if !dc.caps["soju.im/bouncer-networks"] {
|
---|
226 | dc.user.forEachNetwork(f)
|
---|
227 | }
|
---|
228 | }
|
---|
229 |
|
---|
230 | func (dc *downstreamConn) forEachUpstream(f func(*upstreamConn)) {
|
---|
231 | if dc.network == nil && dc.caps["soju.im/bouncer-networks"] {
|
---|
232 | return
|
---|
233 | }
|
---|
234 | dc.user.forEachUpstream(func(uc *upstreamConn) {
|
---|
235 | if dc.network != nil && uc.network != dc.network {
|
---|
236 | return
|
---|
237 | }
|
---|
238 | f(uc)
|
---|
239 | })
|
---|
240 | }
|
---|
241 |
|
---|
242 | // upstream returns the upstream connection, if any. If there are zero or if
|
---|
243 | // there are multiple upstream connections, it returns nil.
|
---|
244 | func (dc *downstreamConn) upstream() *upstreamConn {
|
---|
245 | if dc.network == nil {
|
---|
246 | return nil
|
---|
247 | }
|
---|
248 | return dc.network.conn
|
---|
249 | }
|
---|
250 |
|
---|
251 | func isOurNick(net *network, nick string) bool {
|
---|
252 | // TODO: this doesn't account for nick changes
|
---|
253 | if net.conn != nil {
|
---|
254 | return net.casemap(nick) == net.conn.nickCM
|
---|
255 | }
|
---|
256 | // We're not currently connected to the upstream connection, so we don't
|
---|
257 | // know whether this name is our nickname. Best-effort: use the network's
|
---|
258 | // configured nickname and hope it was the one being used when we were
|
---|
259 | // connected.
|
---|
260 | return net.casemap(nick) == net.casemap(net.Nick)
|
---|
261 | }
|
---|
262 |
|
---|
263 | // marshalEntity converts an upstream entity name (ie. channel or nick) into a
|
---|
264 | // downstream entity name.
|
---|
265 | //
|
---|
266 | // This involves adding a "/<network>" suffix if the entity isn't the current
|
---|
267 | // user.
|
---|
268 | func (dc *downstreamConn) marshalEntity(net *network, name string) string {
|
---|
269 | if isOurNick(net, name) {
|
---|
270 | return dc.nick
|
---|
271 | }
|
---|
272 | name = partialCasemap(net.casemap, name)
|
---|
273 | if dc.network != nil {
|
---|
274 | if dc.network != net {
|
---|
275 | panic("soju: tried to marshal an entity for another network")
|
---|
276 | }
|
---|
277 | return name
|
---|
278 | }
|
---|
279 | return name + "/" + net.GetName()
|
---|
280 | }
|
---|
281 |
|
---|
282 | func (dc *downstreamConn) marshalUserPrefix(net *network, prefix *irc.Prefix) *irc.Prefix {
|
---|
283 | if isOurNick(net, prefix.Name) {
|
---|
284 | return dc.prefix()
|
---|
285 | }
|
---|
286 | prefix.Name = partialCasemap(net.casemap, prefix.Name)
|
---|
287 | if dc.network != nil {
|
---|
288 | if dc.network != net {
|
---|
289 | panic("soju: tried to marshal a user prefix for another network")
|
---|
290 | }
|
---|
291 | return prefix
|
---|
292 | }
|
---|
293 | return &irc.Prefix{
|
---|
294 | Name: prefix.Name + "/" + net.GetName(),
|
---|
295 | User: prefix.User,
|
---|
296 | Host: prefix.Host,
|
---|
297 | }
|
---|
298 | }
|
---|
299 |
|
---|
300 | // unmarshalEntity converts a downstream entity name (ie. channel or nick) into
|
---|
301 | // an upstream entity name.
|
---|
302 | //
|
---|
303 | // This involves removing the "/<network>" suffix.
|
---|
304 | func (dc *downstreamConn) unmarshalEntity(name string) (*upstreamConn, string, error) {
|
---|
305 | if uc := dc.upstream(); uc != nil {
|
---|
306 | return uc, name, nil
|
---|
307 | }
|
---|
308 | if dc.network != nil {
|
---|
309 | return nil, "", ircError{&irc.Message{
|
---|
310 | Command: irc.ERR_NOSUCHCHANNEL,
|
---|
311 | Params: []string{name, "Disconnected from upstream network"},
|
---|
312 | }}
|
---|
313 | }
|
---|
314 |
|
---|
315 | var conn *upstreamConn
|
---|
316 | if i := strings.LastIndexByte(name, '/'); i >= 0 {
|
---|
317 | network := name[i+1:]
|
---|
318 | name = name[:i]
|
---|
319 |
|
---|
320 | dc.forEachUpstream(func(uc *upstreamConn) {
|
---|
321 | if network != uc.network.GetName() {
|
---|
322 | return
|
---|
323 | }
|
---|
324 | conn = uc
|
---|
325 | })
|
---|
326 | }
|
---|
327 |
|
---|
328 | if conn == nil {
|
---|
329 | return nil, "", ircError{&irc.Message{
|
---|
330 | Command: irc.ERR_NOSUCHCHANNEL,
|
---|
331 | Params: []string{name, "Missing network suffix in channel name"},
|
---|
332 | }}
|
---|
333 | }
|
---|
334 | return conn, name, nil
|
---|
335 | }
|
---|
336 |
|
---|
337 | func (dc *downstreamConn) unmarshalText(uc *upstreamConn, text string) string {
|
---|
338 | if dc.upstream() != nil {
|
---|
339 | return text
|
---|
340 | }
|
---|
341 | // TODO: smarter parsing that ignores URLs
|
---|
342 | return strings.ReplaceAll(text, "/"+uc.network.GetName(), "")
|
---|
343 | }
|
---|
344 |
|
---|
345 | func (dc *downstreamConn) readMessages(ch chan<- event) error {
|
---|
346 | for {
|
---|
347 | msg, err := dc.ReadMessage()
|
---|
348 | if err == io.EOF {
|
---|
349 | break
|
---|
350 | } else if err != nil {
|
---|
351 | return fmt.Errorf("failed to read IRC command: %v", err)
|
---|
352 | }
|
---|
353 |
|
---|
354 | ch <- eventDownstreamMessage{msg, dc}
|
---|
355 | }
|
---|
356 |
|
---|
357 | return nil
|
---|
358 | }
|
---|
359 |
|
---|
360 | // SendMessage sends an outgoing message.
|
---|
361 | //
|
---|
362 | // This can only called from the user goroutine.
|
---|
363 | func (dc *downstreamConn) SendMessage(msg *irc.Message) {
|
---|
364 | if !dc.caps["message-tags"] {
|
---|
365 | if msg.Command == "TAGMSG" {
|
---|
366 | return
|
---|
367 | }
|
---|
368 | msg = msg.Copy()
|
---|
369 | for name := range msg.Tags {
|
---|
370 | supported := false
|
---|
371 | switch name {
|
---|
372 | case "time":
|
---|
373 | supported = dc.caps["server-time"]
|
---|
374 | }
|
---|
375 | if !supported {
|
---|
376 | delete(msg.Tags, name)
|
---|
377 | }
|
---|
378 | }
|
---|
379 | }
|
---|
380 | if msg.Command == "JOIN" && !dc.caps["extended-join"] {
|
---|
381 | msg.Params = msg.Params[:1]
|
---|
382 | }
|
---|
383 |
|
---|
384 | dc.conn.SendMessage(msg)
|
---|
385 | }
|
---|
386 |
|
---|
387 | // sendMessageWithID sends an outgoing message with the specified internal ID.
|
---|
388 | func (dc *downstreamConn) sendMessageWithID(msg *irc.Message, id string) {
|
---|
389 | dc.SendMessage(msg)
|
---|
390 |
|
---|
391 | if id == "" || !dc.messageSupportsHistory(msg) {
|
---|
392 | return
|
---|
393 | }
|
---|
394 |
|
---|
395 | dc.sendPing(id)
|
---|
396 | }
|
---|
397 |
|
---|
398 | // advanceMessageWithID advances history to the specified message ID without
|
---|
399 | // sending a message. This is useful e.g. for self-messages when echo-message
|
---|
400 | // isn't enabled.
|
---|
401 | func (dc *downstreamConn) advanceMessageWithID(msg *irc.Message, id string) {
|
---|
402 | if id == "" || !dc.messageSupportsHistory(msg) {
|
---|
403 | return
|
---|
404 | }
|
---|
405 |
|
---|
406 | dc.sendPing(id)
|
---|
407 | }
|
---|
408 |
|
---|
409 | // ackMsgID acknowledges that a message has been received.
|
---|
410 | func (dc *downstreamConn) ackMsgID(id string) {
|
---|
411 | netID, entity, err := parseMsgID(id, nil)
|
---|
412 | if err != nil {
|
---|
413 | dc.logger.Printf("failed to ACK message ID %q: %v", id, err)
|
---|
414 | return
|
---|
415 | }
|
---|
416 |
|
---|
417 | network := dc.user.getNetworkByID(netID)
|
---|
418 | if network == nil {
|
---|
419 | return
|
---|
420 | }
|
---|
421 |
|
---|
422 | network.delivered.StoreID(entity, dc.clientName, id)
|
---|
423 | }
|
---|
424 |
|
---|
425 | func (dc *downstreamConn) sendPing(msgID string) {
|
---|
426 | token := "soju-msgid-" + msgID
|
---|
427 | dc.SendMessage(&irc.Message{
|
---|
428 | Command: "PING",
|
---|
429 | Params: []string{token},
|
---|
430 | })
|
---|
431 | }
|
---|
432 |
|
---|
433 | func (dc *downstreamConn) handlePong(token string) {
|
---|
434 | if !strings.HasPrefix(token, "soju-msgid-") {
|
---|
435 | dc.logger.Printf("received unrecognized PONG token %q", token)
|
---|
436 | return
|
---|
437 | }
|
---|
438 | msgID := strings.TrimPrefix(token, "soju-msgid-")
|
---|
439 | dc.ackMsgID(msgID)
|
---|
440 | }
|
---|
441 |
|
---|
442 | // marshalMessage re-formats a message coming from an upstream connection so
|
---|
443 | // that it's suitable for being sent on this downstream connection. Only
|
---|
444 | // messages that may appear in logs are supported, except MODE.
|
---|
445 | func (dc *downstreamConn) marshalMessage(msg *irc.Message, net *network) *irc.Message {
|
---|
446 | msg = msg.Copy()
|
---|
447 | msg.Prefix = dc.marshalUserPrefix(net, msg.Prefix)
|
---|
448 |
|
---|
449 | switch msg.Command {
|
---|
450 | case "PRIVMSG", "NOTICE", "TAGMSG":
|
---|
451 | msg.Params[0] = dc.marshalEntity(net, msg.Params[0])
|
---|
452 | case "NICK":
|
---|
453 | // Nick change for another user
|
---|
454 | msg.Params[0] = dc.marshalEntity(net, msg.Params[0])
|
---|
455 | case "JOIN", "PART":
|
---|
456 | msg.Params[0] = dc.marshalEntity(net, msg.Params[0])
|
---|
457 | case "KICK":
|
---|
458 | msg.Params[0] = dc.marshalEntity(net, msg.Params[0])
|
---|
459 | msg.Params[1] = dc.marshalEntity(net, msg.Params[1])
|
---|
460 | case "TOPIC":
|
---|
461 | msg.Params[0] = dc.marshalEntity(net, msg.Params[0])
|
---|
462 | case "QUIT":
|
---|
463 | // This space is intentionally left blank
|
---|
464 | default:
|
---|
465 | panic(fmt.Sprintf("unexpected %q message", msg.Command))
|
---|
466 | }
|
---|
467 |
|
---|
468 | return msg
|
---|
469 | }
|
---|
470 |
|
---|
471 | func (dc *downstreamConn) handleMessage(msg *irc.Message) error {
|
---|
472 | switch msg.Command {
|
---|
473 | case "QUIT":
|
---|
474 | return dc.Close()
|
---|
475 | default:
|
---|
476 | if dc.registered {
|
---|
477 | return dc.handleMessageRegistered(msg)
|
---|
478 | } else {
|
---|
479 | return dc.handleMessageUnregistered(msg)
|
---|
480 | }
|
---|
481 | }
|
---|
482 | }
|
---|
483 |
|
---|
484 | func (dc *downstreamConn) handleMessageUnregistered(msg *irc.Message) error {
|
---|
485 | switch msg.Command {
|
---|
486 | case "NICK":
|
---|
487 | var nick string
|
---|
488 | if err := parseMessageParams(msg, &nick); err != nil {
|
---|
489 | return err
|
---|
490 | }
|
---|
491 | if strings.ContainsAny(nick, illegalNickChars) {
|
---|
492 | return ircError{&irc.Message{
|
---|
493 | Command: irc.ERR_ERRONEUSNICKNAME,
|
---|
494 | Params: []string{dc.nick, nick, "contains illegal characters"},
|
---|
495 | }}
|
---|
496 | }
|
---|
497 | nickCM := casemapASCII(nick)
|
---|
498 | if nickCM == serviceNickCM {
|
---|
499 | return ircError{&irc.Message{
|
---|
500 | Command: irc.ERR_NICKNAMEINUSE,
|
---|
501 | Params: []string{dc.nick, nick, "Nickname reserved for bouncer service"},
|
---|
502 | }}
|
---|
503 | }
|
---|
504 | dc.nick = nick
|
---|
505 | dc.nickCM = nickCM
|
---|
506 | case "USER":
|
---|
507 | if err := parseMessageParams(msg, &dc.rawUsername, nil, nil, &dc.realname); err != nil {
|
---|
508 | return err
|
---|
509 | }
|
---|
510 | case "PASS":
|
---|
511 | if err := parseMessageParams(msg, &dc.password); err != nil {
|
---|
512 | return err
|
---|
513 | }
|
---|
514 | case "CAP":
|
---|
515 | var subCmd string
|
---|
516 | if err := parseMessageParams(msg, &subCmd); err != nil {
|
---|
517 | return err
|
---|
518 | }
|
---|
519 | if err := dc.handleCapCommand(subCmd, msg.Params[1:]); err != nil {
|
---|
520 | return err
|
---|
521 | }
|
---|
522 | case "AUTHENTICATE":
|
---|
523 | if !dc.caps["sasl"] {
|
---|
524 | return ircError{&irc.Message{
|
---|
525 | Command: irc.ERR_SASLFAIL,
|
---|
526 | Params: []string{"*", "AUTHENTICATE requires the \"sasl\" capability to be enabled"},
|
---|
527 | }}
|
---|
528 | }
|
---|
529 | if len(msg.Params) == 0 {
|
---|
530 | return ircError{&irc.Message{
|
---|
531 | Command: irc.ERR_SASLFAIL,
|
---|
532 | Params: []string{"*", "Missing AUTHENTICATE argument"},
|
---|
533 | }}
|
---|
534 | }
|
---|
535 | if dc.nick == "" {
|
---|
536 | return ircError{&irc.Message{
|
---|
537 | Command: irc.ERR_SASLFAIL,
|
---|
538 | Params: []string{"*", "Expected NICK command before AUTHENTICATE"},
|
---|
539 | }}
|
---|
540 | }
|
---|
541 |
|
---|
542 | var resp []byte
|
---|
543 | if dc.saslServer == nil {
|
---|
544 | mech := strings.ToUpper(msg.Params[0])
|
---|
545 | switch mech {
|
---|
546 | case "PLAIN":
|
---|
547 | dc.saslServer = sasl.NewPlainServer(sasl.PlainAuthenticator(func(identity, username, password string) error {
|
---|
548 | return dc.authenticate(username, password)
|
---|
549 | }))
|
---|
550 | default:
|
---|
551 | return ircError{&irc.Message{
|
---|
552 | Command: irc.ERR_SASLFAIL,
|
---|
553 | Params: []string{"*", fmt.Sprintf("Unsupported SASL mechanism %q", mech)},
|
---|
554 | }}
|
---|
555 | }
|
---|
556 | } else if msg.Params[0] == "*" {
|
---|
557 | dc.saslServer = nil
|
---|
558 | return ircError{&irc.Message{
|
---|
559 | Command: irc.ERR_SASLABORTED,
|
---|
560 | Params: []string{"*", "SASL authentication aborted"},
|
---|
561 | }}
|
---|
562 | } else if msg.Params[0] == "+" {
|
---|
563 | resp = nil
|
---|
564 | } else {
|
---|
565 | // TODO: multi-line messages
|
---|
566 | var err error
|
---|
567 | resp, err = base64.StdEncoding.DecodeString(msg.Params[0])
|
---|
568 | if err != nil {
|
---|
569 | dc.saslServer = nil
|
---|
570 | return ircError{&irc.Message{
|
---|
571 | Command: irc.ERR_SASLFAIL,
|
---|
572 | Params: []string{"*", "Invalid base64-encoded response"},
|
---|
573 | }}
|
---|
574 | }
|
---|
575 | }
|
---|
576 |
|
---|
577 | challenge, done, err := dc.saslServer.Next(resp)
|
---|
578 | if err != nil {
|
---|
579 | dc.saslServer = nil
|
---|
580 | if ircErr, ok := err.(ircError); ok && ircErr.Message.Command == irc.ERR_PASSWDMISMATCH {
|
---|
581 | return ircError{&irc.Message{
|
---|
582 | Command: irc.ERR_SASLFAIL,
|
---|
583 | Params: []string{"*", ircErr.Message.Params[1]},
|
---|
584 | }}
|
---|
585 | }
|
---|
586 | dc.SendMessage(&irc.Message{
|
---|
587 | Prefix: dc.srv.prefix(),
|
---|
588 | Command: irc.ERR_SASLFAIL,
|
---|
589 | Params: []string{"*", "SASL error"},
|
---|
590 | })
|
---|
591 | return fmt.Errorf("SASL authentication failed: %v", err)
|
---|
592 | } else if done {
|
---|
593 | dc.saslServer = nil
|
---|
594 | dc.SendMessage(&irc.Message{
|
---|
595 | Prefix: dc.srv.prefix(),
|
---|
596 | Command: irc.RPL_LOGGEDIN,
|
---|
597 | Params: []string{dc.nick, dc.prefix().String(), dc.user.Username, "You are now logged in"},
|
---|
598 | })
|
---|
599 | dc.SendMessage(&irc.Message{
|
---|
600 | Prefix: dc.srv.prefix(),
|
---|
601 | Command: irc.RPL_SASLSUCCESS,
|
---|
602 | Params: []string{dc.nick, "SASL authentication successful"},
|
---|
603 | })
|
---|
604 | } else {
|
---|
605 | challengeStr := "+"
|
---|
606 | if len(challenge) > 0 {
|
---|
607 | challengeStr = base64.StdEncoding.EncodeToString(challenge)
|
---|
608 | }
|
---|
609 |
|
---|
610 | // TODO: multi-line messages
|
---|
611 | dc.SendMessage(&irc.Message{
|
---|
612 | Prefix: dc.srv.prefix(),
|
---|
613 | Command: "AUTHENTICATE",
|
---|
614 | Params: []string{challengeStr},
|
---|
615 | })
|
---|
616 | }
|
---|
617 | case "BOUNCER":
|
---|
618 | var subcommand string
|
---|
619 | if err := parseMessageParams(msg, &subcommand); err != nil {
|
---|
620 | return err
|
---|
621 | }
|
---|
622 |
|
---|
623 | switch strings.ToUpper(subcommand) {
|
---|
624 | case "BIND":
|
---|
625 | var idStr string
|
---|
626 | if err := parseMessageParams(msg, nil, &idStr); err != nil {
|
---|
627 | return err
|
---|
628 | }
|
---|
629 |
|
---|
630 | if dc.registered {
|
---|
631 | return ircError{&irc.Message{
|
---|
632 | Command: "FAIL",
|
---|
633 | Params: []string{"BOUNCER", "REGISTRATION_IS_COMPLETED", "BIND", "Cannot bind bouncer network after registration"},
|
---|
634 | }}
|
---|
635 | }
|
---|
636 | if dc.user == nil {
|
---|
637 | return ircError{&irc.Message{
|
---|
638 | Command: "FAIL",
|
---|
639 | Params: []string{"BOUNCER", "ACCOUNT_REQUIRED", "BIND", "Authentication needed to bind to bouncer network"},
|
---|
640 | }}
|
---|
641 | }
|
---|
642 |
|
---|
643 | id, err := parseBouncerNetID(subcommand, idStr)
|
---|
644 | if err != nil {
|
---|
645 | return err
|
---|
646 | }
|
---|
647 |
|
---|
648 | var match *network
|
---|
649 | dc.user.forEachNetwork(func(net *network) {
|
---|
650 | if net.ID == id {
|
---|
651 | match = net
|
---|
652 | }
|
---|
653 | })
|
---|
654 | if match == nil {
|
---|
655 | return ircError{&irc.Message{
|
---|
656 | Command: "FAIL",
|
---|
657 | Params: []string{"BOUNCER", "INVALID_NETID", idStr, "Unknown network ID"},
|
---|
658 | }}
|
---|
659 | }
|
---|
660 |
|
---|
661 | dc.networkName = match.GetName()
|
---|
662 | }
|
---|
663 | default:
|
---|
664 | dc.logger.Printf("unhandled message: %v", msg)
|
---|
665 | return newUnknownCommandError(msg.Command)
|
---|
666 | }
|
---|
667 | if dc.rawUsername != "" && dc.nick != "" && !dc.negociatingCaps {
|
---|
668 | return dc.register()
|
---|
669 | }
|
---|
670 | return nil
|
---|
671 | }
|
---|
672 |
|
---|
673 | func (dc *downstreamConn) handleCapCommand(cmd string, args []string) error {
|
---|
674 | cmd = strings.ToUpper(cmd)
|
---|
675 |
|
---|
676 | replyTo := dc.nick
|
---|
677 | if !dc.registered {
|
---|
678 | replyTo = "*"
|
---|
679 | }
|
---|
680 |
|
---|
681 | switch cmd {
|
---|
682 | case "LS":
|
---|
683 | if len(args) > 0 {
|
---|
684 | var err error
|
---|
685 | if dc.capVersion, err = strconv.Atoi(args[0]); err != nil {
|
---|
686 | return err
|
---|
687 | }
|
---|
688 | }
|
---|
689 | if !dc.registered && dc.capVersion >= 302 {
|
---|
690 | // Let downstream show everything it supports, and trim
|
---|
691 | // down the available capabilities when upstreams are
|
---|
692 | // known.
|
---|
693 | for k, v := range needAllDownstreamCaps {
|
---|
694 | dc.supportedCaps[k] = v
|
---|
695 | }
|
---|
696 | }
|
---|
697 |
|
---|
698 | caps := make([]string, 0, len(dc.supportedCaps))
|
---|
699 | for k, v := range dc.supportedCaps {
|
---|
700 | if dc.capVersion >= 302 && v != "" {
|
---|
701 | caps = append(caps, k+"="+v)
|
---|
702 | } else {
|
---|
703 | caps = append(caps, k)
|
---|
704 | }
|
---|
705 | }
|
---|
706 |
|
---|
707 | // TODO: multi-line replies
|
---|
708 | dc.SendMessage(&irc.Message{
|
---|
709 | Prefix: dc.srv.prefix(),
|
---|
710 | Command: "CAP",
|
---|
711 | Params: []string{replyTo, "LS", strings.Join(caps, " ")},
|
---|
712 | })
|
---|
713 |
|
---|
714 | if dc.capVersion >= 302 {
|
---|
715 | // CAP version 302 implicitly enables cap-notify
|
---|
716 | dc.caps["cap-notify"] = true
|
---|
717 | }
|
---|
718 |
|
---|
719 | if !dc.registered {
|
---|
720 | dc.negociatingCaps = true
|
---|
721 | }
|
---|
722 | case "LIST":
|
---|
723 | var caps []string
|
---|
724 | for name, enabled := range dc.caps {
|
---|
725 | if enabled {
|
---|
726 | caps = append(caps, name)
|
---|
727 | }
|
---|
728 | }
|
---|
729 |
|
---|
730 | // TODO: multi-line replies
|
---|
731 | dc.SendMessage(&irc.Message{
|
---|
732 | Prefix: dc.srv.prefix(),
|
---|
733 | Command: "CAP",
|
---|
734 | Params: []string{replyTo, "LIST", strings.Join(caps, " ")},
|
---|
735 | })
|
---|
736 | case "REQ":
|
---|
737 | if len(args) == 0 {
|
---|
738 | return ircError{&irc.Message{
|
---|
739 | Command: err_invalidcapcmd,
|
---|
740 | Params: []string{replyTo, cmd, "Missing argument in CAP REQ command"},
|
---|
741 | }}
|
---|
742 | }
|
---|
743 |
|
---|
744 | // TODO: atomically ack/nak the whole capability set
|
---|
745 | caps := strings.Fields(args[0])
|
---|
746 | ack := true
|
---|
747 | for _, name := range caps {
|
---|
748 | name = strings.ToLower(name)
|
---|
749 | enable := !strings.HasPrefix(name, "-")
|
---|
750 | if !enable {
|
---|
751 | name = strings.TrimPrefix(name, "-")
|
---|
752 | }
|
---|
753 |
|
---|
754 | if enable == dc.caps[name] {
|
---|
755 | continue
|
---|
756 | }
|
---|
757 |
|
---|
758 | _, ok := dc.supportedCaps[name]
|
---|
759 | if !ok {
|
---|
760 | ack = false
|
---|
761 | break
|
---|
762 | }
|
---|
763 |
|
---|
764 | if name == "cap-notify" && dc.capVersion >= 302 && !enable {
|
---|
765 | // cap-notify cannot be disabled with CAP version 302
|
---|
766 | ack = false
|
---|
767 | break
|
---|
768 | }
|
---|
769 |
|
---|
770 | dc.caps[name] = enable
|
---|
771 | }
|
---|
772 |
|
---|
773 | reply := "NAK"
|
---|
774 | if ack {
|
---|
775 | reply = "ACK"
|
---|
776 | }
|
---|
777 | dc.SendMessage(&irc.Message{
|
---|
778 | Prefix: dc.srv.prefix(),
|
---|
779 | Command: "CAP",
|
---|
780 | Params: []string{replyTo, reply, args[0]},
|
---|
781 | })
|
---|
782 | case "END":
|
---|
783 | dc.negociatingCaps = false
|
---|
784 | default:
|
---|
785 | return ircError{&irc.Message{
|
---|
786 | Command: err_invalidcapcmd,
|
---|
787 | Params: []string{replyTo, cmd, "Unknown CAP command"},
|
---|
788 | }}
|
---|
789 | }
|
---|
790 | return nil
|
---|
791 | }
|
---|
792 |
|
---|
793 | func (dc *downstreamConn) setSupportedCap(name, value string) {
|
---|
794 | prevValue, hasPrev := dc.supportedCaps[name]
|
---|
795 | changed := !hasPrev || prevValue != value
|
---|
796 | dc.supportedCaps[name] = value
|
---|
797 |
|
---|
798 | if !dc.caps["cap-notify"] || !changed {
|
---|
799 | return
|
---|
800 | }
|
---|
801 |
|
---|
802 | replyTo := dc.nick
|
---|
803 | if !dc.registered {
|
---|
804 | replyTo = "*"
|
---|
805 | }
|
---|
806 |
|
---|
807 | cap := name
|
---|
808 | if value != "" && dc.capVersion >= 302 {
|
---|
809 | cap = name + "=" + value
|
---|
810 | }
|
---|
811 |
|
---|
812 | dc.SendMessage(&irc.Message{
|
---|
813 | Prefix: dc.srv.prefix(),
|
---|
814 | Command: "CAP",
|
---|
815 | Params: []string{replyTo, "NEW", cap},
|
---|
816 | })
|
---|
817 | }
|
---|
818 |
|
---|
819 | func (dc *downstreamConn) unsetSupportedCap(name string) {
|
---|
820 | _, hasPrev := dc.supportedCaps[name]
|
---|
821 | delete(dc.supportedCaps, name)
|
---|
822 | delete(dc.caps, name)
|
---|
823 |
|
---|
824 | if !dc.caps["cap-notify"] || !hasPrev {
|
---|
825 | return
|
---|
826 | }
|
---|
827 |
|
---|
828 | replyTo := dc.nick
|
---|
829 | if !dc.registered {
|
---|
830 | replyTo = "*"
|
---|
831 | }
|
---|
832 |
|
---|
833 | dc.SendMessage(&irc.Message{
|
---|
834 | Prefix: dc.srv.prefix(),
|
---|
835 | Command: "CAP",
|
---|
836 | Params: []string{replyTo, "DEL", name},
|
---|
837 | })
|
---|
838 | }
|
---|
839 |
|
---|
840 | func (dc *downstreamConn) updateSupportedCaps() {
|
---|
841 | supportedCaps := make(map[string]bool)
|
---|
842 | for cap := range needAllDownstreamCaps {
|
---|
843 | supportedCaps[cap] = true
|
---|
844 | }
|
---|
845 | dc.forEachUpstream(func(uc *upstreamConn) {
|
---|
846 | for cap, supported := range supportedCaps {
|
---|
847 | supportedCaps[cap] = supported && uc.caps[cap]
|
---|
848 | }
|
---|
849 | })
|
---|
850 |
|
---|
851 | for cap, supported := range supportedCaps {
|
---|
852 | if supported {
|
---|
853 | dc.setSupportedCap(cap, needAllDownstreamCaps[cap])
|
---|
854 | } else {
|
---|
855 | dc.unsetSupportedCap(cap)
|
---|
856 | }
|
---|
857 | }
|
---|
858 | }
|
---|
859 |
|
---|
860 | func (dc *downstreamConn) updateNick() {
|
---|
861 | if uc := dc.upstream(); uc != nil && uc.nick != dc.nick {
|
---|
862 | dc.SendMessage(&irc.Message{
|
---|
863 | Prefix: dc.prefix(),
|
---|
864 | Command: "NICK",
|
---|
865 | Params: []string{uc.nick},
|
---|
866 | })
|
---|
867 | dc.nick = uc.nick
|
---|
868 | dc.nickCM = casemapASCII(dc.nick)
|
---|
869 | }
|
---|
870 | }
|
---|
871 |
|
---|
872 | func sanityCheckServer(addr string) error {
|
---|
873 | dialer := net.Dialer{Timeout: 30 * time.Second}
|
---|
874 | conn, err := tls.DialWithDialer(&dialer, "tcp", addr, nil)
|
---|
875 | if err != nil {
|
---|
876 | return err
|
---|
877 | }
|
---|
878 | return conn.Close()
|
---|
879 | }
|
---|
880 |
|
---|
881 | func unmarshalUsername(rawUsername string) (username, client, network string) {
|
---|
882 | username = rawUsername
|
---|
883 |
|
---|
884 | i := strings.IndexAny(username, "/@")
|
---|
885 | j := strings.LastIndexAny(username, "/@")
|
---|
886 | if i >= 0 {
|
---|
887 | username = rawUsername[:i]
|
---|
888 | }
|
---|
889 | if j >= 0 {
|
---|
890 | if rawUsername[j] == '@' {
|
---|
891 | client = rawUsername[j+1:]
|
---|
892 | } else {
|
---|
893 | network = rawUsername[j+1:]
|
---|
894 | }
|
---|
895 | }
|
---|
896 | if i >= 0 && j >= 0 && i < j {
|
---|
897 | if rawUsername[i] == '@' {
|
---|
898 | client = rawUsername[i+1 : j]
|
---|
899 | } else {
|
---|
900 | network = rawUsername[i+1 : j]
|
---|
901 | }
|
---|
902 | }
|
---|
903 |
|
---|
904 | return username, client, network
|
---|
905 | }
|
---|
906 |
|
---|
907 | func (dc *downstreamConn) authenticate(username, password string) error {
|
---|
908 | username, clientName, networkName := unmarshalUsername(username)
|
---|
909 |
|
---|
910 | u, err := dc.srv.db.GetUser(username)
|
---|
911 | if err != nil {
|
---|
912 | dc.logger.Printf("failed authentication for %q: user not found: %v", username, err)
|
---|
913 | return errAuthFailed
|
---|
914 | }
|
---|
915 |
|
---|
916 | // Password auth disabled
|
---|
917 | if u.Password == "" {
|
---|
918 | return errAuthFailed
|
---|
919 | }
|
---|
920 |
|
---|
921 | err = bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
|
---|
922 | if err != nil {
|
---|
923 | dc.logger.Printf("failed authentication for %q: wrong password: %v", username, err)
|
---|
924 | return errAuthFailed
|
---|
925 | }
|
---|
926 |
|
---|
927 | dc.user = dc.srv.getUser(username)
|
---|
928 | if dc.user == nil {
|
---|
929 | dc.logger.Printf("failed authentication for %q: user not active", username)
|
---|
930 | return errAuthFailed
|
---|
931 | }
|
---|
932 | dc.clientName = clientName
|
---|
933 | dc.networkName = networkName
|
---|
934 | return nil
|
---|
935 | }
|
---|
936 |
|
---|
937 | func (dc *downstreamConn) register() error {
|
---|
938 | if dc.registered {
|
---|
939 | return fmt.Errorf("tried to register twice")
|
---|
940 | }
|
---|
941 |
|
---|
942 | password := dc.password
|
---|
943 | dc.password = ""
|
---|
944 | if dc.user == nil {
|
---|
945 | if err := dc.authenticate(dc.rawUsername, password); err != nil {
|
---|
946 | return err
|
---|
947 | }
|
---|
948 | }
|
---|
949 |
|
---|
950 | if dc.clientName == "" && dc.networkName == "" {
|
---|
951 | _, dc.clientName, dc.networkName = unmarshalUsername(dc.rawUsername)
|
---|
952 | }
|
---|
953 |
|
---|
954 | dc.registered = true
|
---|
955 | dc.logger.Printf("registration complete for user %q", dc.user.Username)
|
---|
956 | return nil
|
---|
957 | }
|
---|
958 |
|
---|
959 | func (dc *downstreamConn) loadNetwork() error {
|
---|
960 | if dc.networkName == "" {
|
---|
961 | return nil
|
---|
962 | }
|
---|
963 |
|
---|
964 | network := dc.user.getNetwork(dc.networkName)
|
---|
965 | if network == nil {
|
---|
966 | addr := dc.networkName
|
---|
967 | if !strings.ContainsRune(addr, ':') {
|
---|
968 | addr = addr + ":6697"
|
---|
969 | }
|
---|
970 |
|
---|
971 | dc.logger.Printf("trying to connect to new network %q", addr)
|
---|
972 | if err := sanityCheckServer(addr); err != nil {
|
---|
973 | dc.logger.Printf("failed to connect to %q: %v", addr, err)
|
---|
974 | return ircError{&irc.Message{
|
---|
975 | Command: irc.ERR_PASSWDMISMATCH,
|
---|
976 | Params: []string{"*", fmt.Sprintf("Failed to connect to %q", dc.networkName)},
|
---|
977 | }}
|
---|
978 | }
|
---|
979 |
|
---|
980 | // Some clients only allow specifying the nickname (and use the
|
---|
981 | // nickname as a username too). Strip the network name from the
|
---|
982 | // nickname when auto-saving networks.
|
---|
983 | nick, _, _ := unmarshalUsername(dc.nick)
|
---|
984 |
|
---|
985 | dc.logger.Printf("auto-saving network %q", dc.networkName)
|
---|
986 | var err error
|
---|
987 | network, err = dc.user.createNetwork(&Network{
|
---|
988 | Addr: dc.networkName,
|
---|
989 | Nick: nick,
|
---|
990 | })
|
---|
991 | if err != nil {
|
---|
992 | return err
|
---|
993 | }
|
---|
994 | }
|
---|
995 |
|
---|
996 | dc.network = network
|
---|
997 | return nil
|
---|
998 | }
|
---|
999 |
|
---|
1000 | func (dc *downstreamConn) welcome() error {
|
---|
1001 | if dc.user == nil || !dc.registered {
|
---|
1002 | panic("tried to welcome an unregistered connection")
|
---|
1003 | }
|
---|
1004 |
|
---|
1005 | // TODO: doing this might take some time. We should do it in dc.register
|
---|
1006 | // instead, but we'll potentially be adding a new network and this must be
|
---|
1007 | // done in the user goroutine.
|
---|
1008 | if err := dc.loadNetwork(); err != nil {
|
---|
1009 | return err
|
---|
1010 | }
|
---|
1011 |
|
---|
1012 | isupport := []string{
|
---|
1013 | fmt.Sprintf("CHATHISTORY=%v", dc.srv.HistoryLimit),
|
---|
1014 | "CASEMAPPING=ascii",
|
---|
1015 | }
|
---|
1016 |
|
---|
1017 | if dc.network != nil {
|
---|
1018 | isupport = append(isupport, fmt.Sprintf("BOUNCER_NETID=%v", dc.network.ID))
|
---|
1019 | }
|
---|
1020 |
|
---|
1021 | if uc := dc.upstream(); uc != nil {
|
---|
1022 | for k := range passthroughIsupport {
|
---|
1023 | v, ok := uc.isupport[k]
|
---|
1024 | if !ok {
|
---|
1025 | continue
|
---|
1026 | }
|
---|
1027 | if v != nil {
|
---|
1028 | isupport = append(isupport, fmt.Sprintf("%v=%v", k, *v))
|
---|
1029 | } else {
|
---|
1030 | isupport = append(isupport, k)
|
---|
1031 | }
|
---|
1032 | }
|
---|
1033 | }
|
---|
1034 |
|
---|
1035 | dc.SendMessage(&irc.Message{
|
---|
1036 | Prefix: dc.srv.prefix(),
|
---|
1037 | Command: irc.RPL_WELCOME,
|
---|
1038 | Params: []string{dc.nick, "Welcome to soju, " + dc.nick},
|
---|
1039 | })
|
---|
1040 | dc.SendMessage(&irc.Message{
|
---|
1041 | Prefix: dc.srv.prefix(),
|
---|
1042 | Command: irc.RPL_YOURHOST,
|
---|
1043 | Params: []string{dc.nick, "Your host is " + dc.srv.Hostname},
|
---|
1044 | })
|
---|
1045 | dc.SendMessage(&irc.Message{
|
---|
1046 | Prefix: dc.srv.prefix(),
|
---|
1047 | Command: irc.RPL_CREATED,
|
---|
1048 | Params: []string{dc.nick, "Who cares when the server was created?"},
|
---|
1049 | })
|
---|
1050 | dc.SendMessage(&irc.Message{
|
---|
1051 | Prefix: dc.srv.prefix(),
|
---|
1052 | Command: irc.RPL_MYINFO,
|
---|
1053 | Params: []string{dc.nick, dc.srv.Hostname, "soju", "aiwroO", "OovaimnqpsrtklbeI"},
|
---|
1054 | })
|
---|
1055 | for _, msg := range generateIsupport(dc.srv.prefix(), dc.nick, isupport) {
|
---|
1056 | dc.SendMessage(msg)
|
---|
1057 | }
|
---|
1058 | dc.SendMessage(&irc.Message{
|
---|
1059 | Prefix: dc.srv.prefix(),
|
---|
1060 | Command: irc.ERR_NOMOTD,
|
---|
1061 | Params: []string{dc.nick, "No MOTD"},
|
---|
1062 | })
|
---|
1063 |
|
---|
1064 | dc.updateNick()
|
---|
1065 | dc.updateSupportedCaps()
|
---|
1066 |
|
---|
1067 | if dc.caps["soju.im/bouncer-networks-notify"] {
|
---|
1068 | dc.SendMessage(&irc.Message{
|
---|
1069 | Prefix: dc.srv.prefix(),
|
---|
1070 | Command: "BATCH",
|
---|
1071 | Params: []string{"+networks", "bouncer-networks"},
|
---|
1072 | })
|
---|
1073 | dc.user.forEachNetwork(func(network *network) {
|
---|
1074 | idStr := fmt.Sprintf("%v", network.ID)
|
---|
1075 | attrs := getNetworkAttrs(network)
|
---|
1076 | dc.SendMessage(&irc.Message{
|
---|
1077 | Tags: irc.Tags{"batch": irc.TagValue("networks")},
|
---|
1078 | Prefix: dc.srv.prefix(),
|
---|
1079 | Command: "BOUNCER",
|
---|
1080 | Params: []string{"NETWORK", idStr, attrs.String()},
|
---|
1081 | })
|
---|
1082 | })
|
---|
1083 | dc.SendMessage(&irc.Message{
|
---|
1084 | Prefix: dc.srv.prefix(),
|
---|
1085 | Command: "BATCH",
|
---|
1086 | Params: []string{"-networks"},
|
---|
1087 | })
|
---|
1088 | }
|
---|
1089 |
|
---|
1090 | dc.forEachUpstream(func(uc *upstreamConn) {
|
---|
1091 | for _, entry := range uc.channels.innerMap {
|
---|
1092 | ch := entry.value.(*upstreamChannel)
|
---|
1093 | if !ch.complete {
|
---|
1094 | continue
|
---|
1095 | }
|
---|
1096 | record := uc.network.channels.Value(ch.Name)
|
---|
1097 | if record != nil && record.Detached {
|
---|
1098 | continue
|
---|
1099 | }
|
---|
1100 |
|
---|
1101 | dc.SendMessage(&irc.Message{
|
---|
1102 | Prefix: dc.prefix(),
|
---|
1103 | Command: "JOIN",
|
---|
1104 | Params: []string{dc.marshalEntity(ch.conn.network, ch.Name)},
|
---|
1105 | })
|
---|
1106 |
|
---|
1107 | forwardChannel(dc, ch)
|
---|
1108 | }
|
---|
1109 | })
|
---|
1110 |
|
---|
1111 | dc.forEachNetwork(func(net *network) {
|
---|
1112 | if dc.caps["draft/chathistory"] || dc.user.msgStore == nil {
|
---|
1113 | return
|
---|
1114 | }
|
---|
1115 |
|
---|
1116 | // Only send history if we're the first connected client with that name
|
---|
1117 | // for the network
|
---|
1118 | firstClient := true
|
---|
1119 | dc.user.forEachDownstream(func(c *downstreamConn) {
|
---|
1120 | if c != dc && c.clientName == dc.clientName && c.network == dc.network {
|
---|
1121 | firstClient = false
|
---|
1122 | }
|
---|
1123 | })
|
---|
1124 | if firstClient {
|
---|
1125 | net.delivered.ForEachTarget(func(target string) {
|
---|
1126 | lastDelivered := net.delivered.LoadID(target, dc.clientName)
|
---|
1127 | if lastDelivered == "" {
|
---|
1128 | return
|
---|
1129 | }
|
---|
1130 |
|
---|
1131 | dc.sendTargetBacklog(net, target, lastDelivered)
|
---|
1132 |
|
---|
1133 | // Fast-forward history to last message
|
---|
1134 | targetCM := net.casemap(target)
|
---|
1135 | lastID, err := dc.user.msgStore.LastMsgID(net, targetCM, time.Now())
|
---|
1136 | if err != nil {
|
---|
1137 | dc.logger.Printf("failed to get last message ID: %v", err)
|
---|
1138 | return
|
---|
1139 | }
|
---|
1140 | net.delivered.StoreID(target, dc.clientName, lastID)
|
---|
1141 | })
|
---|
1142 | }
|
---|
1143 | })
|
---|
1144 |
|
---|
1145 | return nil
|
---|
1146 | }
|
---|
1147 |
|
---|
1148 | // messageSupportsHistory checks whether the provided message can be sent as
|
---|
1149 | // part of an history batch.
|
---|
1150 | func (dc *downstreamConn) messageSupportsHistory(msg *irc.Message) bool {
|
---|
1151 | // Don't replay all messages, because that would mess up client
|
---|
1152 | // state. For instance we just sent the list of users, sending
|
---|
1153 | // PART messages for one of these users would be incorrect.
|
---|
1154 | // TODO: add support for draft/event-playback
|
---|
1155 | switch msg.Command {
|
---|
1156 | case "PRIVMSG", "NOTICE":
|
---|
1157 | return true
|
---|
1158 | }
|
---|
1159 | return false
|
---|
1160 | }
|
---|
1161 |
|
---|
1162 | func (dc *downstreamConn) sendTargetBacklog(net *network, target, msgID string) {
|
---|
1163 | if dc.caps["draft/chathistory"] || dc.user.msgStore == nil {
|
---|
1164 | return
|
---|
1165 | }
|
---|
1166 |
|
---|
1167 | ch := net.channels.Value(target)
|
---|
1168 |
|
---|
1169 | limit := 4000
|
---|
1170 | targetCM := net.casemap(target)
|
---|
1171 | history, err := dc.user.msgStore.LoadLatestID(net, targetCM, msgID, limit)
|
---|
1172 | if err != nil {
|
---|
1173 | dc.logger.Printf("failed to send backlog for %q: %v", target, err)
|
---|
1174 | return
|
---|
1175 | }
|
---|
1176 |
|
---|
1177 | batchRef := "history"
|
---|
1178 | if dc.caps["batch"] {
|
---|
1179 | dc.SendMessage(&irc.Message{
|
---|
1180 | Prefix: dc.srv.prefix(),
|
---|
1181 | Command: "BATCH",
|
---|
1182 | Params: []string{"+" + batchRef, "chathistory", dc.marshalEntity(net, target)},
|
---|
1183 | })
|
---|
1184 | }
|
---|
1185 |
|
---|
1186 | for _, msg := range history {
|
---|
1187 | if !dc.messageSupportsHistory(msg) {
|
---|
1188 | continue
|
---|
1189 | }
|
---|
1190 |
|
---|
1191 | if ch != nil && ch.Detached {
|
---|
1192 | if net.detachedMessageNeedsRelay(ch, msg) {
|
---|
1193 | dc.relayDetachedMessage(net, msg)
|
---|
1194 | }
|
---|
1195 | } else {
|
---|
1196 | if dc.caps["batch"] {
|
---|
1197 | msg.Tags["batch"] = irc.TagValue(batchRef)
|
---|
1198 | }
|
---|
1199 | dc.SendMessage(dc.marshalMessage(msg, net))
|
---|
1200 | }
|
---|
1201 | }
|
---|
1202 |
|
---|
1203 | if dc.caps["batch"] {
|
---|
1204 | dc.SendMessage(&irc.Message{
|
---|
1205 | Prefix: dc.srv.prefix(),
|
---|
1206 | Command: "BATCH",
|
---|
1207 | Params: []string{"-" + batchRef},
|
---|
1208 | })
|
---|
1209 | }
|
---|
1210 | }
|
---|
1211 |
|
---|
1212 | func (dc *downstreamConn) relayDetachedMessage(net *network, msg *irc.Message) {
|
---|
1213 | if msg.Command != "PRIVMSG" && msg.Command != "NOTICE" {
|
---|
1214 | return
|
---|
1215 | }
|
---|
1216 |
|
---|
1217 | sender := msg.Prefix.Name
|
---|
1218 | target, text := msg.Params[0], msg.Params[1]
|
---|
1219 | if net.isHighlight(msg) {
|
---|
1220 | sendServiceNOTICE(dc, fmt.Sprintf("highlight in %v: <%v> %v", dc.marshalEntity(net, target), sender, text))
|
---|
1221 | } else {
|
---|
1222 | sendServiceNOTICE(dc, fmt.Sprintf("message in %v: <%v> %v", dc.marshalEntity(net, target), sender, text))
|
---|
1223 | }
|
---|
1224 | }
|
---|
1225 |
|
---|
1226 | func (dc *downstreamConn) runUntilRegistered() error {
|
---|
1227 | for !dc.registered {
|
---|
1228 | msg, err := dc.ReadMessage()
|
---|
1229 | if err != nil {
|
---|
1230 | return fmt.Errorf("failed to read IRC command: %v", err)
|
---|
1231 | }
|
---|
1232 |
|
---|
1233 | err = dc.handleMessage(msg)
|
---|
1234 | if ircErr, ok := err.(ircError); ok {
|
---|
1235 | ircErr.Message.Prefix = dc.srv.prefix()
|
---|
1236 | dc.SendMessage(ircErr.Message)
|
---|
1237 | } else if err != nil {
|
---|
1238 | return fmt.Errorf("failed to handle IRC command %q: %v", msg, err)
|
---|
1239 | }
|
---|
1240 | }
|
---|
1241 |
|
---|
1242 | return nil
|
---|
1243 | }
|
---|
1244 |
|
---|
1245 | func (dc *downstreamConn) handleMessageRegistered(msg *irc.Message) error {
|
---|
1246 | switch msg.Command {
|
---|
1247 | case "CAP":
|
---|
1248 | var subCmd string
|
---|
1249 | if err := parseMessageParams(msg, &subCmd); err != nil {
|
---|
1250 | return err
|
---|
1251 | }
|
---|
1252 | if err := dc.handleCapCommand(subCmd, msg.Params[1:]); err != nil {
|
---|
1253 | return err
|
---|
1254 | }
|
---|
1255 | case "PING":
|
---|
1256 | var source, destination string
|
---|
1257 | if err := parseMessageParams(msg, &source); err != nil {
|
---|
1258 | return err
|
---|
1259 | }
|
---|
1260 | if len(msg.Params) > 1 {
|
---|
1261 | destination = msg.Params[1]
|
---|
1262 | }
|
---|
1263 | if destination != "" && destination != dc.srv.Hostname {
|
---|
1264 | return ircError{&irc.Message{
|
---|
1265 | Command: irc.ERR_NOSUCHSERVER,
|
---|
1266 | Params: []string{dc.nick, destination, "No such server"},
|
---|
1267 | }}
|
---|
1268 | }
|
---|
1269 | dc.SendMessage(&irc.Message{
|
---|
1270 | Prefix: dc.srv.prefix(),
|
---|
1271 | Command: "PONG",
|
---|
1272 | Params: []string{dc.srv.Hostname, source},
|
---|
1273 | })
|
---|
1274 | return nil
|
---|
1275 | case "PONG":
|
---|
1276 | if len(msg.Params) == 0 {
|
---|
1277 | return newNeedMoreParamsError(msg.Command)
|
---|
1278 | }
|
---|
1279 | token := msg.Params[len(msg.Params)-1]
|
---|
1280 | dc.handlePong(token)
|
---|
1281 | case "USER":
|
---|
1282 | return ircError{&irc.Message{
|
---|
1283 | Command: irc.ERR_ALREADYREGISTERED,
|
---|
1284 | Params: []string{dc.nick, "You may not reregister"},
|
---|
1285 | }}
|
---|
1286 | case "NICK":
|
---|
1287 | var rawNick string
|
---|
1288 | if err := parseMessageParams(msg, &rawNick); err != nil {
|
---|
1289 | return err
|
---|
1290 | }
|
---|
1291 |
|
---|
1292 | nick := rawNick
|
---|
1293 | var upstream *upstreamConn
|
---|
1294 | if dc.upstream() == nil {
|
---|
1295 | uc, unmarshaledNick, err := dc.unmarshalEntity(nick)
|
---|
1296 | if err == nil { // NICK nick/network: NICK only on a specific upstream
|
---|
1297 | upstream = uc
|
---|
1298 | nick = unmarshaledNick
|
---|
1299 | }
|
---|
1300 | }
|
---|
1301 |
|
---|
1302 | if strings.ContainsAny(nick, illegalNickChars) {
|
---|
1303 | return ircError{&irc.Message{
|
---|
1304 | Command: irc.ERR_ERRONEUSNICKNAME,
|
---|
1305 | Params: []string{dc.nick, rawNick, "contains illegal characters"},
|
---|
1306 | }}
|
---|
1307 | }
|
---|
1308 | if casemapASCII(nick) == serviceNickCM {
|
---|
1309 | return ircError{&irc.Message{
|
---|
1310 | Command: irc.ERR_NICKNAMEINUSE,
|
---|
1311 | Params: []string{dc.nick, rawNick, "Nickname reserved for bouncer service"},
|
---|
1312 | }}
|
---|
1313 | }
|
---|
1314 |
|
---|
1315 | var err error
|
---|
1316 | dc.forEachNetwork(func(n *network) {
|
---|
1317 | if err != nil || (upstream != nil && upstream.network != n) {
|
---|
1318 | return
|
---|
1319 | }
|
---|
1320 | n.Nick = nick
|
---|
1321 | err = dc.srv.db.StoreNetwork(dc.user.ID, &n.Network)
|
---|
1322 | })
|
---|
1323 | if err != nil {
|
---|
1324 | return err
|
---|
1325 | }
|
---|
1326 |
|
---|
1327 | dc.forEachUpstream(func(uc *upstreamConn) {
|
---|
1328 | if upstream != nil && upstream != uc {
|
---|
1329 | return
|
---|
1330 | }
|
---|
1331 | uc.SendMessageLabeled(dc.id, &irc.Message{
|
---|
1332 | Command: "NICK",
|
---|
1333 | Params: []string{nick},
|
---|
1334 | })
|
---|
1335 | })
|
---|
1336 |
|
---|
1337 | if dc.upstream() == nil && upstream == nil && dc.nick != nick {
|
---|
1338 | dc.SendMessage(&irc.Message{
|
---|
1339 | Prefix: dc.prefix(),
|
---|
1340 | Command: "NICK",
|
---|
1341 | Params: []string{nick},
|
---|
1342 | })
|
---|
1343 | dc.nick = nick
|
---|
1344 | dc.nickCM = casemapASCII(dc.nick)
|
---|
1345 | }
|
---|
1346 | case "JOIN":
|
---|
1347 | var namesStr string
|
---|
1348 | if err := parseMessageParams(msg, &namesStr); err != nil {
|
---|
1349 | return err
|
---|
1350 | }
|
---|
1351 |
|
---|
1352 | var keys []string
|
---|
1353 | if len(msg.Params) > 1 {
|
---|
1354 | keys = strings.Split(msg.Params[1], ",")
|
---|
1355 | }
|
---|
1356 |
|
---|
1357 | for i, name := range strings.Split(namesStr, ",") {
|
---|
1358 | uc, upstreamName, err := dc.unmarshalEntity(name)
|
---|
1359 | if err != nil {
|
---|
1360 | return err
|
---|
1361 | }
|
---|
1362 |
|
---|
1363 | var key string
|
---|
1364 | if len(keys) > i {
|
---|
1365 | key = keys[i]
|
---|
1366 | }
|
---|
1367 |
|
---|
1368 | params := []string{upstreamName}
|
---|
1369 | if key != "" {
|
---|
1370 | params = append(params, key)
|
---|
1371 | }
|
---|
1372 | uc.SendMessageLabeled(dc.id, &irc.Message{
|
---|
1373 | Command: "JOIN",
|
---|
1374 | Params: params,
|
---|
1375 | })
|
---|
1376 |
|
---|
1377 | ch := uc.network.channels.Value(upstreamName)
|
---|
1378 | if ch != nil {
|
---|
1379 | // Don't clear the channel key if there's one set
|
---|
1380 | // TODO: add a way to unset the channel key
|
---|
1381 | if key != "" {
|
---|
1382 | ch.Key = key
|
---|
1383 | }
|
---|
1384 | uc.network.attach(ch)
|
---|
1385 | } else {
|
---|
1386 | ch = &Channel{
|
---|
1387 | Name: upstreamName,
|
---|
1388 | Key: key,
|
---|
1389 | }
|
---|
1390 | uc.network.channels.SetValue(upstreamName, ch)
|
---|
1391 | }
|
---|
1392 | if err := dc.srv.db.StoreChannel(uc.network.ID, ch); err != nil {
|
---|
1393 | dc.logger.Printf("failed to create or update channel %q: %v", upstreamName, err)
|
---|
1394 | }
|
---|
1395 | }
|
---|
1396 | case "PART":
|
---|
1397 | var namesStr string
|
---|
1398 | if err := parseMessageParams(msg, &namesStr); err != nil {
|
---|
1399 | return err
|
---|
1400 | }
|
---|
1401 |
|
---|
1402 | var reason string
|
---|
1403 | if len(msg.Params) > 1 {
|
---|
1404 | reason = msg.Params[1]
|
---|
1405 | }
|
---|
1406 |
|
---|
1407 | for _, name := range strings.Split(namesStr, ",") {
|
---|
1408 | uc, upstreamName, err := dc.unmarshalEntity(name)
|
---|
1409 | if err != nil {
|
---|
1410 | return err
|
---|
1411 | }
|
---|
1412 |
|
---|
1413 | if strings.EqualFold(reason, "detach") {
|
---|
1414 | ch := uc.network.channels.Value(upstreamName)
|
---|
1415 | if ch != nil {
|
---|
1416 | uc.network.detach(ch)
|
---|
1417 | } else {
|
---|
1418 | ch = &Channel{
|
---|
1419 | Name: name,
|
---|
1420 | Detached: true,
|
---|
1421 | }
|
---|
1422 | uc.network.channels.SetValue(upstreamName, ch)
|
---|
1423 | }
|
---|
1424 | if err := dc.srv.db.StoreChannel(uc.network.ID, ch); err != nil {
|
---|
1425 | dc.logger.Printf("failed to create or update channel %q: %v", upstreamName, err)
|
---|
1426 | }
|
---|
1427 | } else {
|
---|
1428 | params := []string{upstreamName}
|
---|
1429 | if reason != "" {
|
---|
1430 | params = append(params, reason)
|
---|
1431 | }
|
---|
1432 | uc.SendMessageLabeled(dc.id, &irc.Message{
|
---|
1433 | Command: "PART",
|
---|
1434 | Params: params,
|
---|
1435 | })
|
---|
1436 |
|
---|
1437 | if err := uc.network.deleteChannel(upstreamName); err != nil {
|
---|
1438 | dc.logger.Printf("failed to delete channel %q: %v", upstreamName, err)
|
---|
1439 | }
|
---|
1440 | }
|
---|
1441 | }
|
---|
1442 | case "KICK":
|
---|
1443 | var channelStr, userStr string
|
---|
1444 | if err := parseMessageParams(msg, &channelStr, &userStr); err != nil {
|
---|
1445 | return err
|
---|
1446 | }
|
---|
1447 |
|
---|
1448 | channels := strings.Split(channelStr, ",")
|
---|
1449 | users := strings.Split(userStr, ",")
|
---|
1450 |
|
---|
1451 | var reason string
|
---|
1452 | if len(msg.Params) > 2 {
|
---|
1453 | reason = msg.Params[2]
|
---|
1454 | }
|
---|
1455 |
|
---|
1456 | if len(channels) != 1 && len(channels) != len(users) {
|
---|
1457 | return ircError{&irc.Message{
|
---|
1458 | Command: irc.ERR_BADCHANMASK,
|
---|
1459 | Params: []string{dc.nick, channelStr, "Bad channel mask"},
|
---|
1460 | }}
|
---|
1461 | }
|
---|
1462 |
|
---|
1463 | for i, user := range users {
|
---|
1464 | var channel string
|
---|
1465 | if len(channels) == 1 {
|
---|
1466 | channel = channels[0]
|
---|
1467 | } else {
|
---|
1468 | channel = channels[i]
|
---|
1469 | }
|
---|
1470 |
|
---|
1471 | ucChannel, upstreamChannel, err := dc.unmarshalEntity(channel)
|
---|
1472 | if err != nil {
|
---|
1473 | return err
|
---|
1474 | }
|
---|
1475 |
|
---|
1476 | ucUser, upstreamUser, err := dc.unmarshalEntity(user)
|
---|
1477 | if err != nil {
|
---|
1478 | return err
|
---|
1479 | }
|
---|
1480 |
|
---|
1481 | if ucChannel != ucUser {
|
---|
1482 | return ircError{&irc.Message{
|
---|
1483 | Command: irc.ERR_USERNOTINCHANNEL,
|
---|
1484 | Params: []string{dc.nick, user, channel, "They are on another network"},
|
---|
1485 | }}
|
---|
1486 | }
|
---|
1487 | uc := ucChannel
|
---|
1488 |
|
---|
1489 | params := []string{upstreamChannel, upstreamUser}
|
---|
1490 | if reason != "" {
|
---|
1491 | params = append(params, reason)
|
---|
1492 | }
|
---|
1493 | uc.SendMessageLabeled(dc.id, &irc.Message{
|
---|
1494 | Command: "KICK",
|
---|
1495 | Params: params,
|
---|
1496 | })
|
---|
1497 | }
|
---|
1498 | case "MODE":
|
---|
1499 | var name string
|
---|
1500 | if err := parseMessageParams(msg, &name); err != nil {
|
---|
1501 | return err
|
---|
1502 | }
|
---|
1503 |
|
---|
1504 | var modeStr string
|
---|
1505 | if len(msg.Params) > 1 {
|
---|
1506 | modeStr = msg.Params[1]
|
---|
1507 | }
|
---|
1508 |
|
---|
1509 | if casemapASCII(name) == dc.nickCM {
|
---|
1510 | if modeStr != "" {
|
---|
1511 | dc.forEachUpstream(func(uc *upstreamConn) {
|
---|
1512 | uc.SendMessageLabeled(dc.id, &irc.Message{
|
---|
1513 | Command: "MODE",
|
---|
1514 | Params: []string{uc.nick, modeStr},
|
---|
1515 | })
|
---|
1516 | })
|
---|
1517 | } else {
|
---|
1518 | // TODO: only do this in multi-upstream mode
|
---|
1519 | dc.SendMessage(&irc.Message{
|
---|
1520 | Prefix: dc.srv.prefix(),
|
---|
1521 | Command: irc.RPL_UMODEIS,
|
---|
1522 | Params: []string{dc.nick, ""}, // TODO
|
---|
1523 | })
|
---|
1524 | }
|
---|
1525 | return nil
|
---|
1526 | }
|
---|
1527 |
|
---|
1528 | uc, upstreamName, err := dc.unmarshalEntity(name)
|
---|
1529 | if err != nil {
|
---|
1530 | return err
|
---|
1531 | }
|
---|
1532 |
|
---|
1533 | if !uc.isChannel(upstreamName) {
|
---|
1534 | return ircError{&irc.Message{
|
---|
1535 | Command: irc.ERR_USERSDONTMATCH,
|
---|
1536 | Params: []string{dc.nick, "Cannot change mode for other users"},
|
---|
1537 | }}
|
---|
1538 | }
|
---|
1539 |
|
---|
1540 | if modeStr != "" {
|
---|
1541 | params := []string{upstreamName, modeStr}
|
---|
1542 | params = append(params, msg.Params[2:]...)
|
---|
1543 | uc.SendMessageLabeled(dc.id, &irc.Message{
|
---|
1544 | Command: "MODE",
|
---|
1545 | Params: params,
|
---|
1546 | })
|
---|
1547 | } else {
|
---|
1548 | ch := uc.channels.Value(upstreamName)
|
---|
1549 | if ch == nil {
|
---|
1550 | return ircError{&irc.Message{
|
---|
1551 | Command: irc.ERR_NOSUCHCHANNEL,
|
---|
1552 | Params: []string{dc.nick, name, "No such channel"},
|
---|
1553 | }}
|
---|
1554 | }
|
---|
1555 |
|
---|
1556 | if ch.modes == nil {
|
---|
1557 | // we haven't received the initial RPL_CHANNELMODEIS yet
|
---|
1558 | // ignore the request, we will broadcast the modes later when we receive RPL_CHANNELMODEIS
|
---|
1559 | return nil
|
---|
1560 | }
|
---|
1561 |
|
---|
1562 | modeStr, modeParams := ch.modes.Format()
|
---|
1563 | params := []string{dc.nick, name, modeStr}
|
---|
1564 | params = append(params, modeParams...)
|
---|
1565 |
|
---|
1566 | dc.SendMessage(&irc.Message{
|
---|
1567 | Prefix: dc.srv.prefix(),
|
---|
1568 | Command: irc.RPL_CHANNELMODEIS,
|
---|
1569 | Params: params,
|
---|
1570 | })
|
---|
1571 | if ch.creationTime != "" {
|
---|
1572 | dc.SendMessage(&irc.Message{
|
---|
1573 | Prefix: dc.srv.prefix(),
|
---|
1574 | Command: rpl_creationtime,
|
---|
1575 | Params: []string{dc.nick, name, ch.creationTime},
|
---|
1576 | })
|
---|
1577 | }
|
---|
1578 | }
|
---|
1579 | case "TOPIC":
|
---|
1580 | var channel string
|
---|
1581 | if err := parseMessageParams(msg, &channel); err != nil {
|
---|
1582 | return err
|
---|
1583 | }
|
---|
1584 |
|
---|
1585 | uc, upstreamName, err := dc.unmarshalEntity(channel)
|
---|
1586 | if err != nil {
|
---|
1587 | return err
|
---|
1588 | }
|
---|
1589 |
|
---|
1590 | if len(msg.Params) > 1 { // setting topic
|
---|
1591 | topic := msg.Params[1]
|
---|
1592 | uc.SendMessageLabeled(dc.id, &irc.Message{
|
---|
1593 | Command: "TOPIC",
|
---|
1594 | Params: []string{upstreamName, topic},
|
---|
1595 | })
|
---|
1596 | } else { // getting topic
|
---|
1597 | ch := uc.channels.Value(upstreamName)
|
---|
1598 | if ch == nil {
|
---|
1599 | return ircError{&irc.Message{
|
---|
1600 | Command: irc.ERR_NOSUCHCHANNEL,
|
---|
1601 | Params: []string{dc.nick, upstreamName, "No such channel"},
|
---|
1602 | }}
|
---|
1603 | }
|
---|
1604 | sendTopic(dc, ch)
|
---|
1605 | }
|
---|
1606 | case "LIST":
|
---|
1607 | // TODO: support ELIST when supported by all upstreams
|
---|
1608 |
|
---|
1609 | pl := pendingLIST{
|
---|
1610 | downstreamID: dc.id,
|
---|
1611 | pendingCommands: make(map[int64]*irc.Message),
|
---|
1612 | }
|
---|
1613 | var upstream *upstreamConn
|
---|
1614 | var upstreamChannels map[int64][]string
|
---|
1615 | if len(msg.Params) > 0 {
|
---|
1616 | uc, upstreamMask, err := dc.unmarshalEntity(msg.Params[0])
|
---|
1617 | if err == nil && upstreamMask == "*" { // LIST */network: send LIST only to one network
|
---|
1618 | upstream = uc
|
---|
1619 | } else {
|
---|
1620 | upstreamChannels = make(map[int64][]string)
|
---|
1621 | channels := strings.Split(msg.Params[0], ",")
|
---|
1622 | for _, channel := range channels {
|
---|
1623 | uc, upstreamChannel, err := dc.unmarshalEntity(channel)
|
---|
1624 | if err != nil {
|
---|
1625 | return err
|
---|
1626 | }
|
---|
1627 | upstreamChannels[uc.network.ID] = append(upstreamChannels[uc.network.ID], upstreamChannel)
|
---|
1628 | }
|
---|
1629 | }
|
---|
1630 | }
|
---|
1631 |
|
---|
1632 | dc.user.pendingLISTs = append(dc.user.pendingLISTs, pl)
|
---|
1633 | dc.forEachUpstream(func(uc *upstreamConn) {
|
---|
1634 | if upstream != nil && upstream != uc {
|
---|
1635 | return
|
---|
1636 | }
|
---|
1637 | var params []string
|
---|
1638 | if upstreamChannels != nil {
|
---|
1639 | if channels, ok := upstreamChannels[uc.network.ID]; ok {
|
---|
1640 | params = []string{strings.Join(channels, ",")}
|
---|
1641 | } else {
|
---|
1642 | return
|
---|
1643 | }
|
---|
1644 | }
|
---|
1645 | pl.pendingCommands[uc.network.ID] = &irc.Message{
|
---|
1646 | Command: "LIST",
|
---|
1647 | Params: params,
|
---|
1648 | }
|
---|
1649 | uc.trySendLIST(dc.id)
|
---|
1650 | })
|
---|
1651 | case "NAMES":
|
---|
1652 | if len(msg.Params) == 0 {
|
---|
1653 | dc.SendMessage(&irc.Message{
|
---|
1654 | Prefix: dc.srv.prefix(),
|
---|
1655 | Command: irc.RPL_ENDOFNAMES,
|
---|
1656 | Params: []string{dc.nick, "*", "End of /NAMES list"},
|
---|
1657 | })
|
---|
1658 | return nil
|
---|
1659 | }
|
---|
1660 |
|
---|
1661 | channels := strings.Split(msg.Params[0], ",")
|
---|
1662 | for _, channel := range channels {
|
---|
1663 | uc, upstreamName, err := dc.unmarshalEntity(channel)
|
---|
1664 | if err != nil {
|
---|
1665 | return err
|
---|
1666 | }
|
---|
1667 |
|
---|
1668 | ch := uc.channels.Value(upstreamName)
|
---|
1669 | if ch != nil {
|
---|
1670 | sendNames(dc, ch)
|
---|
1671 | } else {
|
---|
1672 | // NAMES on a channel we have not joined, ask upstream
|
---|
1673 | uc.SendMessageLabeled(dc.id, &irc.Message{
|
---|
1674 | Command: "NAMES",
|
---|
1675 | Params: []string{upstreamName},
|
---|
1676 | })
|
---|
1677 | }
|
---|
1678 | }
|
---|
1679 | case "WHO":
|
---|
1680 | if len(msg.Params) == 0 {
|
---|
1681 | // TODO: support WHO without parameters
|
---|
1682 | dc.SendMessage(&irc.Message{
|
---|
1683 | Prefix: dc.srv.prefix(),
|
---|
1684 | Command: irc.RPL_ENDOFWHO,
|
---|
1685 | Params: []string{dc.nick, "*", "End of /WHO list"},
|
---|
1686 | })
|
---|
1687 | return nil
|
---|
1688 | }
|
---|
1689 |
|
---|
1690 | // TODO: support WHO masks
|
---|
1691 | entity := msg.Params[0]
|
---|
1692 | entityCM := casemapASCII(entity)
|
---|
1693 |
|
---|
1694 | if dc.network == nil && entityCM == dc.nickCM {
|
---|
1695 | // TODO: support AWAY (H/G) in self WHO reply
|
---|
1696 | dc.SendMessage(&irc.Message{
|
---|
1697 | Prefix: dc.srv.prefix(),
|
---|
1698 | Command: irc.RPL_WHOREPLY,
|
---|
1699 | Params: []string{dc.nick, "*", dc.user.Username, dc.hostname, dc.srv.Hostname, dc.nick, "H", "0 " + dc.realname},
|
---|
1700 | })
|
---|
1701 | dc.SendMessage(&irc.Message{
|
---|
1702 | Prefix: dc.srv.prefix(),
|
---|
1703 | Command: irc.RPL_ENDOFWHO,
|
---|
1704 | Params: []string{dc.nick, dc.nick, "End of /WHO list"},
|
---|
1705 | })
|
---|
1706 | return nil
|
---|
1707 | }
|
---|
1708 | if entityCM == serviceNickCM {
|
---|
1709 | dc.SendMessage(&irc.Message{
|
---|
1710 | Prefix: dc.srv.prefix(),
|
---|
1711 | Command: irc.RPL_WHOREPLY,
|
---|
1712 | Params: []string{serviceNick, "*", servicePrefix.User, servicePrefix.Host, dc.srv.Hostname, serviceNick, "H", "0 " + serviceRealname},
|
---|
1713 | })
|
---|
1714 | dc.SendMessage(&irc.Message{
|
---|
1715 | Prefix: dc.srv.prefix(),
|
---|
1716 | Command: irc.RPL_ENDOFWHO,
|
---|
1717 | Params: []string{dc.nick, serviceNick, "End of /WHO list"},
|
---|
1718 | })
|
---|
1719 | return nil
|
---|
1720 | }
|
---|
1721 |
|
---|
1722 | uc, upstreamName, err := dc.unmarshalEntity(entity)
|
---|
1723 | if err != nil {
|
---|
1724 | return err
|
---|
1725 | }
|
---|
1726 |
|
---|
1727 | var params []string
|
---|
1728 | if len(msg.Params) == 2 {
|
---|
1729 | params = []string{upstreamName, msg.Params[1]}
|
---|
1730 | } else {
|
---|
1731 | params = []string{upstreamName}
|
---|
1732 | }
|
---|
1733 |
|
---|
1734 | uc.SendMessageLabeled(dc.id, &irc.Message{
|
---|
1735 | Command: "WHO",
|
---|
1736 | Params: params,
|
---|
1737 | })
|
---|
1738 | case "WHOIS":
|
---|
1739 | if len(msg.Params) == 0 {
|
---|
1740 | return ircError{&irc.Message{
|
---|
1741 | Command: irc.ERR_NONICKNAMEGIVEN,
|
---|
1742 | Params: []string{dc.nick, "No nickname given"},
|
---|
1743 | }}
|
---|
1744 | }
|
---|
1745 |
|
---|
1746 | var target, mask string
|
---|
1747 | if len(msg.Params) == 1 {
|
---|
1748 | target = ""
|
---|
1749 | mask = msg.Params[0]
|
---|
1750 | } else {
|
---|
1751 | target = msg.Params[0]
|
---|
1752 | mask = msg.Params[1]
|
---|
1753 | }
|
---|
1754 | // TODO: support multiple WHOIS users
|
---|
1755 | if i := strings.IndexByte(mask, ','); i >= 0 {
|
---|
1756 | mask = mask[:i]
|
---|
1757 | }
|
---|
1758 |
|
---|
1759 | if dc.network == nil && casemapASCII(mask) == dc.nickCM {
|
---|
1760 | dc.SendMessage(&irc.Message{
|
---|
1761 | Prefix: dc.srv.prefix(),
|
---|
1762 | Command: irc.RPL_WHOISUSER,
|
---|
1763 | Params: []string{dc.nick, dc.nick, dc.user.Username, dc.hostname, "*", dc.realname},
|
---|
1764 | })
|
---|
1765 | dc.SendMessage(&irc.Message{
|
---|
1766 | Prefix: dc.srv.prefix(),
|
---|
1767 | Command: irc.RPL_WHOISSERVER,
|
---|
1768 | Params: []string{dc.nick, dc.nick, dc.srv.Hostname, "soju"},
|
---|
1769 | })
|
---|
1770 | dc.SendMessage(&irc.Message{
|
---|
1771 | Prefix: dc.srv.prefix(),
|
---|
1772 | Command: irc.RPL_ENDOFWHOIS,
|
---|
1773 | Params: []string{dc.nick, dc.nick, "End of /WHOIS list"},
|
---|
1774 | })
|
---|
1775 | return nil
|
---|
1776 | }
|
---|
1777 |
|
---|
1778 | // TODO: support WHOIS masks
|
---|
1779 | uc, upstreamNick, err := dc.unmarshalEntity(mask)
|
---|
1780 | if err != nil {
|
---|
1781 | return err
|
---|
1782 | }
|
---|
1783 |
|
---|
1784 | var params []string
|
---|
1785 | if target != "" {
|
---|
1786 | if target == mask { // WHOIS nick nick
|
---|
1787 | params = []string{upstreamNick, upstreamNick}
|
---|
1788 | } else {
|
---|
1789 | params = []string{target, upstreamNick}
|
---|
1790 | }
|
---|
1791 | } else {
|
---|
1792 | params = []string{upstreamNick}
|
---|
1793 | }
|
---|
1794 |
|
---|
1795 | uc.SendMessageLabeled(dc.id, &irc.Message{
|
---|
1796 | Command: "WHOIS",
|
---|
1797 | Params: params,
|
---|
1798 | })
|
---|
1799 | case "PRIVMSG":
|
---|
1800 | var targetsStr, text string
|
---|
1801 | if err := parseMessageParams(msg, &targetsStr, &text); err != nil {
|
---|
1802 | return err
|
---|
1803 | }
|
---|
1804 | tags := copyClientTags(msg.Tags)
|
---|
1805 |
|
---|
1806 | for _, name := range strings.Split(targetsStr, ",") {
|
---|
1807 | if dc.network == nil && casemapASCII(name) == dc.nickCM {
|
---|
1808 | dc.SendMessage(msg)
|
---|
1809 | continue
|
---|
1810 | }
|
---|
1811 |
|
---|
1812 | if casemapASCII(name) == serviceNickCM {
|
---|
1813 | if dc.caps["echo-message"] {
|
---|
1814 | echoTags := tags.Copy()
|
---|
1815 | echoTags["time"] = irc.TagValue(time.Now().UTC().Format(serverTimeLayout))
|
---|
1816 | dc.SendMessage(&irc.Message{
|
---|
1817 | Tags: echoTags,
|
---|
1818 | Prefix: dc.prefix(),
|
---|
1819 | Command: "PRIVMSG",
|
---|
1820 | Params: []string{name, text},
|
---|
1821 | })
|
---|
1822 | }
|
---|
1823 | handleServicePRIVMSG(dc, text)
|
---|
1824 | continue
|
---|
1825 | }
|
---|
1826 |
|
---|
1827 | uc, upstreamName, err := dc.unmarshalEntity(name)
|
---|
1828 | if err != nil {
|
---|
1829 | return err
|
---|
1830 | }
|
---|
1831 |
|
---|
1832 | if uc.network.casemap(upstreamName) == "nickserv" {
|
---|
1833 | dc.handleNickServPRIVMSG(uc, text)
|
---|
1834 | }
|
---|
1835 |
|
---|
1836 | unmarshaledText := text
|
---|
1837 | if uc.isChannel(upstreamName) {
|
---|
1838 | unmarshaledText = dc.unmarshalText(uc, text)
|
---|
1839 | }
|
---|
1840 | uc.SendMessageLabeled(dc.id, &irc.Message{
|
---|
1841 | Tags: tags,
|
---|
1842 | Command: "PRIVMSG",
|
---|
1843 | Params: []string{upstreamName, unmarshaledText},
|
---|
1844 | })
|
---|
1845 |
|
---|
1846 | echoTags := tags.Copy()
|
---|
1847 | echoTags["time"] = irc.TagValue(time.Now().UTC().Format(serverTimeLayout))
|
---|
1848 | echoMsg := &irc.Message{
|
---|
1849 | Tags: echoTags,
|
---|
1850 | Prefix: &irc.Prefix{
|
---|
1851 | Name: uc.nick,
|
---|
1852 | User: uc.username,
|
---|
1853 | },
|
---|
1854 | Command: "PRIVMSG",
|
---|
1855 | Params: []string{upstreamName, text},
|
---|
1856 | }
|
---|
1857 | uc.produce(upstreamName, echoMsg, dc)
|
---|
1858 |
|
---|
1859 | uc.updateChannelAutoDetach(upstreamName)
|
---|
1860 | }
|
---|
1861 | case "NOTICE":
|
---|
1862 | var targetsStr, text string
|
---|
1863 | if err := parseMessageParams(msg, &targetsStr, &text); err != nil {
|
---|
1864 | return err
|
---|
1865 | }
|
---|
1866 | tags := copyClientTags(msg.Tags)
|
---|
1867 |
|
---|
1868 | for _, name := range strings.Split(targetsStr, ",") {
|
---|
1869 | uc, upstreamName, err := dc.unmarshalEntity(name)
|
---|
1870 | if err != nil {
|
---|
1871 | return err
|
---|
1872 | }
|
---|
1873 |
|
---|
1874 | unmarshaledText := text
|
---|
1875 | if uc.isChannel(upstreamName) {
|
---|
1876 | unmarshaledText = dc.unmarshalText(uc, text)
|
---|
1877 | }
|
---|
1878 | uc.SendMessageLabeled(dc.id, &irc.Message{
|
---|
1879 | Tags: tags,
|
---|
1880 | Command: "NOTICE",
|
---|
1881 | Params: []string{upstreamName, unmarshaledText},
|
---|
1882 | })
|
---|
1883 |
|
---|
1884 | uc.updateChannelAutoDetach(upstreamName)
|
---|
1885 | }
|
---|
1886 | case "TAGMSG":
|
---|
1887 | var targetsStr string
|
---|
1888 | if err := parseMessageParams(msg, &targetsStr); err != nil {
|
---|
1889 | return err
|
---|
1890 | }
|
---|
1891 | tags := copyClientTags(msg.Tags)
|
---|
1892 |
|
---|
1893 | for _, name := range strings.Split(targetsStr, ",") {
|
---|
1894 | uc, upstreamName, err := dc.unmarshalEntity(name)
|
---|
1895 | if err != nil {
|
---|
1896 | return err
|
---|
1897 | }
|
---|
1898 | if _, ok := uc.caps["message-tags"]; !ok {
|
---|
1899 | continue
|
---|
1900 | }
|
---|
1901 |
|
---|
1902 | uc.SendMessageLabeled(dc.id, &irc.Message{
|
---|
1903 | Tags: tags,
|
---|
1904 | Command: "TAGMSG",
|
---|
1905 | Params: []string{upstreamName},
|
---|
1906 | })
|
---|
1907 |
|
---|
1908 | uc.updateChannelAutoDetach(upstreamName)
|
---|
1909 | }
|
---|
1910 | case "INVITE":
|
---|
1911 | var user, channel string
|
---|
1912 | if err := parseMessageParams(msg, &user, &channel); err != nil {
|
---|
1913 | return err
|
---|
1914 | }
|
---|
1915 |
|
---|
1916 | ucChannel, upstreamChannel, err := dc.unmarshalEntity(channel)
|
---|
1917 | if err != nil {
|
---|
1918 | return err
|
---|
1919 | }
|
---|
1920 |
|
---|
1921 | ucUser, upstreamUser, err := dc.unmarshalEntity(user)
|
---|
1922 | if err != nil {
|
---|
1923 | return err
|
---|
1924 | }
|
---|
1925 |
|
---|
1926 | if ucChannel != ucUser {
|
---|
1927 | return ircError{&irc.Message{
|
---|
1928 | Command: irc.ERR_USERNOTINCHANNEL,
|
---|
1929 | Params: []string{dc.nick, user, channel, "They are on another network"},
|
---|
1930 | }}
|
---|
1931 | }
|
---|
1932 | uc := ucChannel
|
---|
1933 |
|
---|
1934 | uc.SendMessageLabeled(dc.id, &irc.Message{
|
---|
1935 | Command: "INVITE",
|
---|
1936 | Params: []string{upstreamUser, upstreamChannel},
|
---|
1937 | })
|
---|
1938 | case "CHATHISTORY":
|
---|
1939 | var subcommand string
|
---|
1940 | if err := parseMessageParams(msg, &subcommand); err != nil {
|
---|
1941 | return err
|
---|
1942 | }
|
---|
1943 | var target, limitStr string
|
---|
1944 | var boundsStr [2]string
|
---|
1945 | switch subcommand {
|
---|
1946 | case "AFTER", "BEFORE":
|
---|
1947 | if err := parseMessageParams(msg, nil, &target, &boundsStr[0], &limitStr); err != nil {
|
---|
1948 | return err
|
---|
1949 | }
|
---|
1950 | case "BETWEEN":
|
---|
1951 | if err := parseMessageParams(msg, nil, &target, &boundsStr[0], &boundsStr[1], &limitStr); err != nil {
|
---|
1952 | return err
|
---|
1953 | }
|
---|
1954 | default:
|
---|
1955 | // TODO: support LATEST, AROUND
|
---|
1956 | return ircError{&irc.Message{
|
---|
1957 | Command: "FAIL",
|
---|
1958 | Params: []string{"CHATHISTORY", "INVALID_PARAMS", subcommand, "Unknown command"},
|
---|
1959 | }}
|
---|
1960 | }
|
---|
1961 |
|
---|
1962 | store, ok := dc.user.msgStore.(chatHistoryMessageStore)
|
---|
1963 | if !ok {
|
---|
1964 | return ircError{&irc.Message{
|
---|
1965 | Command: irc.ERR_UNKNOWNCOMMAND,
|
---|
1966 | Params: []string{dc.nick, "CHATHISTORY", "Unknown command"},
|
---|
1967 | }}
|
---|
1968 | }
|
---|
1969 |
|
---|
1970 | uc, entity, err := dc.unmarshalEntity(target)
|
---|
1971 | if err != nil {
|
---|
1972 | return err
|
---|
1973 | }
|
---|
1974 | entity = uc.network.casemap(entity)
|
---|
1975 |
|
---|
1976 | // TODO: support msgid criteria
|
---|
1977 | var bounds [2]time.Time
|
---|
1978 | bounds[0] = parseChatHistoryBound(boundsStr[0])
|
---|
1979 | if bounds[0].IsZero() {
|
---|
1980 | return ircError{&irc.Message{
|
---|
1981 | Command: "FAIL",
|
---|
1982 | Params: []string{"CHATHISTORY", "INVALID_PARAMS", subcommand, boundsStr[0], "Invalid first bound"},
|
---|
1983 | }}
|
---|
1984 | }
|
---|
1985 |
|
---|
1986 | if boundsStr[1] != "" {
|
---|
1987 | bounds[1] = parseChatHistoryBound(boundsStr[1])
|
---|
1988 | if bounds[1].IsZero() {
|
---|
1989 | return ircError{&irc.Message{
|
---|
1990 | Command: "FAIL",
|
---|
1991 | Params: []string{"CHATHISTORY", "INVALID_PARAMS", subcommand, boundsStr[1], "Invalid second bound"},
|
---|
1992 | }}
|
---|
1993 | }
|
---|
1994 | }
|
---|
1995 |
|
---|
1996 | limit, err := strconv.Atoi(limitStr)
|
---|
1997 | if err != nil || limit < 0 || limit > dc.srv.HistoryLimit {
|
---|
1998 | return ircError{&irc.Message{
|
---|
1999 | Command: "FAIL",
|
---|
2000 | Params: []string{"CHATHISTORY", "INVALID_PARAMS", subcommand, limitStr, "Invalid limit"},
|
---|
2001 | }}
|
---|
2002 | }
|
---|
2003 |
|
---|
2004 | var history []*irc.Message
|
---|
2005 | switch subcommand {
|
---|
2006 | case "BEFORE":
|
---|
2007 | history, err = store.LoadBeforeTime(uc.network, entity, bounds[0], time.Time{}, limit)
|
---|
2008 | case "AFTER":
|
---|
2009 | history, err = store.LoadAfterTime(uc.network, entity, bounds[0], time.Now(), limit)
|
---|
2010 | case "BETWEEN":
|
---|
2011 | if bounds[0].Before(bounds[1]) {
|
---|
2012 | history, err = store.LoadAfterTime(uc.network, entity, bounds[0], bounds[1], limit)
|
---|
2013 | } else {
|
---|
2014 | history, err = store.LoadBeforeTime(uc.network, entity, bounds[0], bounds[1], limit)
|
---|
2015 | }
|
---|
2016 | }
|
---|
2017 | if err != nil {
|
---|
2018 | dc.logger.Printf("failed fetching %q messages for chathistory: %v", target, err)
|
---|
2019 | return newChatHistoryError(subcommand, target)
|
---|
2020 | }
|
---|
2021 |
|
---|
2022 | batchRef := "history"
|
---|
2023 | dc.SendMessage(&irc.Message{
|
---|
2024 | Prefix: dc.srv.prefix(),
|
---|
2025 | Command: "BATCH",
|
---|
2026 | Params: []string{"+" + batchRef, "chathistory", target},
|
---|
2027 | })
|
---|
2028 |
|
---|
2029 | for _, msg := range history {
|
---|
2030 | msg.Tags["batch"] = irc.TagValue(batchRef)
|
---|
2031 | dc.SendMessage(dc.marshalMessage(msg, uc.network))
|
---|
2032 | }
|
---|
2033 |
|
---|
2034 | dc.SendMessage(&irc.Message{
|
---|
2035 | Prefix: dc.srv.prefix(),
|
---|
2036 | Command: "BATCH",
|
---|
2037 | Params: []string{"-" + batchRef},
|
---|
2038 | })
|
---|
2039 | case "BOUNCER":
|
---|
2040 | var subcommand string
|
---|
2041 | if err := parseMessageParams(msg, &subcommand); err != nil {
|
---|
2042 | return err
|
---|
2043 | }
|
---|
2044 |
|
---|
2045 | switch strings.ToUpper(subcommand) {
|
---|
2046 | case "LISTNETWORKS":
|
---|
2047 | dc.SendMessage(&irc.Message{
|
---|
2048 | Prefix: dc.srv.prefix(),
|
---|
2049 | Command: "BATCH",
|
---|
2050 | Params: []string{"+networks", "bouncer-networks"},
|
---|
2051 | })
|
---|
2052 | dc.user.forEachNetwork(func(network *network) {
|
---|
2053 | idStr := fmt.Sprintf("%v", network.ID)
|
---|
2054 | attrs := getNetworkAttrs(network)
|
---|
2055 | dc.SendMessage(&irc.Message{
|
---|
2056 | Tags: irc.Tags{"batch": irc.TagValue("networks")},
|
---|
2057 | Prefix: dc.srv.prefix(),
|
---|
2058 | Command: "BOUNCER",
|
---|
2059 | Params: []string{"NETWORK", idStr, attrs.String()},
|
---|
2060 | })
|
---|
2061 | })
|
---|
2062 | dc.SendMessage(&irc.Message{
|
---|
2063 | Prefix: dc.srv.prefix(),
|
---|
2064 | Command: "BATCH",
|
---|
2065 | Params: []string{"-networks"},
|
---|
2066 | })
|
---|
2067 | case "ADDNETWORK":
|
---|
2068 | var attrsStr string
|
---|
2069 | if err := parseMessageParams(msg, nil, &attrsStr); err != nil {
|
---|
2070 | return err
|
---|
2071 | }
|
---|
2072 | attrs := irc.ParseTags(attrsStr)
|
---|
2073 |
|
---|
2074 | host, ok := attrs.GetTag("host")
|
---|
2075 | if !ok {
|
---|
2076 | return ircError{&irc.Message{
|
---|
2077 | Command: "FAIL",
|
---|
2078 | Params: []string{"BOUNCER", "NEED_ATTRIBUTE", subcommand, "host", "Missing required host attribute"},
|
---|
2079 | }}
|
---|
2080 | }
|
---|
2081 |
|
---|
2082 | addr := host
|
---|
2083 | if port, ok := attrs.GetTag("port"); ok {
|
---|
2084 | addr += ":" + port
|
---|
2085 | }
|
---|
2086 |
|
---|
2087 | if tlsStr, ok := attrs.GetTag("tls"); ok && tlsStr == "0" {
|
---|
2088 | addr = "irc+insecure://" + tlsStr
|
---|
2089 | }
|
---|
2090 |
|
---|
2091 | nick, ok := attrs.GetTag("nickname")
|
---|
2092 | if !ok {
|
---|
2093 | nick = dc.nick
|
---|
2094 | }
|
---|
2095 |
|
---|
2096 | username, _ := attrs.GetTag("username")
|
---|
2097 | realname, _ := attrs.GetTag("realname")
|
---|
2098 | pass, _ := attrs.GetTag("pass")
|
---|
2099 |
|
---|
2100 | // TODO: reject unknown attributes
|
---|
2101 |
|
---|
2102 | record := &Network{
|
---|
2103 | Addr: addr,
|
---|
2104 | Nick: nick,
|
---|
2105 | Username: username,
|
---|
2106 | Realname: realname,
|
---|
2107 | Pass: pass,
|
---|
2108 | }
|
---|
2109 | network, err := dc.user.createNetwork(record)
|
---|
2110 | if err != nil {
|
---|
2111 | return ircError{&irc.Message{
|
---|
2112 | Command: "FAIL",
|
---|
2113 | Params: []string{"BOUNCER", "UNKNOWN_ERROR", subcommand, fmt.Sprintf("Failed to create network: %v", err)},
|
---|
2114 | }}
|
---|
2115 | }
|
---|
2116 |
|
---|
2117 | dc.SendMessage(&irc.Message{
|
---|
2118 | Prefix: dc.srv.prefix(),
|
---|
2119 | Command: "BOUNCER",
|
---|
2120 | Params: []string{"ADDNETWORK", fmt.Sprintf("%v", network.ID)},
|
---|
2121 | })
|
---|
2122 | case "CHANGENETWORK":
|
---|
2123 | var idStr, attrsStr string
|
---|
2124 | if err := parseMessageParams(msg, nil, &idStr, &attrsStr); err != nil {
|
---|
2125 | return err
|
---|
2126 | }
|
---|
2127 | id, err := parseBouncerNetID(subcommand, idStr)
|
---|
2128 | if err != nil {
|
---|
2129 | return err
|
---|
2130 | }
|
---|
2131 | attrs := irc.ParseTags(attrsStr)
|
---|
2132 |
|
---|
2133 | net := dc.user.getNetworkByID(id)
|
---|
2134 | if net == nil {
|
---|
2135 | return ircError{&irc.Message{
|
---|
2136 | Command: "FAIL",
|
---|
2137 | Params: []string{"BOUNCER", "INVALID_NETID", subcommand, idStr, "Invalid network ID"},
|
---|
2138 | }}
|
---|
2139 | }
|
---|
2140 |
|
---|
2141 | record := net.Network // copy network record because we'll mutate it
|
---|
2142 | for k, v := range attrs {
|
---|
2143 | s := string(v)
|
---|
2144 | switch k {
|
---|
2145 | // TODO: host, port, tls
|
---|
2146 | case "nickname":
|
---|
2147 | record.Nick = s
|
---|
2148 | case "username":
|
---|
2149 | record.Username = s
|
---|
2150 | case "realname":
|
---|
2151 | record.Realname = s
|
---|
2152 | case "pass":
|
---|
2153 | record.Pass = s
|
---|
2154 | default:
|
---|
2155 | return ircError{&irc.Message{
|
---|
2156 | Command: "FAIL",
|
---|
2157 | Params: []string{"BOUNCER", "UNKNOWN_ATTRIBUTE", subcommand, k, "Unknown attribute"},
|
---|
2158 | }}
|
---|
2159 | }
|
---|
2160 | }
|
---|
2161 |
|
---|
2162 | _, err = dc.user.updateNetwork(&record)
|
---|
2163 | if err != nil {
|
---|
2164 | return ircError{&irc.Message{
|
---|
2165 | Command: "FAIL",
|
---|
2166 | Params: []string{"BOUNCER", "UNKNOWN_ERROR", subcommand, fmt.Sprintf("Failed to update network: %v", err)},
|
---|
2167 | }}
|
---|
2168 | }
|
---|
2169 |
|
---|
2170 | dc.SendMessage(&irc.Message{
|
---|
2171 | Prefix: dc.srv.prefix(),
|
---|
2172 | Command: "BOUNCER",
|
---|
2173 | Params: []string{"CHANGENETWORK", idStr},
|
---|
2174 | })
|
---|
2175 | case "DELNETWORK":
|
---|
2176 | var idStr string
|
---|
2177 | if err := parseMessageParams(msg, nil, &idStr); err != nil {
|
---|
2178 | return err
|
---|
2179 | }
|
---|
2180 | id, err := parseBouncerNetID(subcommand, idStr)
|
---|
2181 | if err != nil {
|
---|
2182 | return err
|
---|
2183 | }
|
---|
2184 |
|
---|
2185 | net := dc.user.getNetworkByID(id)
|
---|
2186 | if net == nil {
|
---|
2187 | return ircError{&irc.Message{
|
---|
2188 | Command: "FAIL",
|
---|
2189 | Params: []string{"BOUNCER", "INVALID_NETID", subcommand, idStr, "Invalid network ID"},
|
---|
2190 | }}
|
---|
2191 | }
|
---|
2192 |
|
---|
2193 | if err := dc.user.deleteNetwork(net.ID); err != nil {
|
---|
2194 | return err
|
---|
2195 | }
|
---|
2196 |
|
---|
2197 | dc.SendMessage(&irc.Message{
|
---|
2198 | Prefix: dc.srv.prefix(),
|
---|
2199 | Command: "BOUNCER",
|
---|
2200 | Params: []string{"DELNETWORK", idStr},
|
---|
2201 | })
|
---|
2202 | default:
|
---|
2203 | return ircError{&irc.Message{
|
---|
2204 | Command: "FAIL",
|
---|
2205 | Params: []string{"BOUNCER", "UNKNOWN_COMMAND", subcommand, "Unknown subcommand"},
|
---|
2206 | }}
|
---|
2207 | }
|
---|
2208 | default:
|
---|
2209 | dc.logger.Printf("unhandled message: %v", msg)
|
---|
2210 | return newUnknownCommandError(msg.Command)
|
---|
2211 | }
|
---|
2212 | return nil
|
---|
2213 | }
|
---|
2214 |
|
---|
2215 | func (dc *downstreamConn) handleNickServPRIVMSG(uc *upstreamConn, text string) {
|
---|
2216 | username, password, ok := parseNickServCredentials(text, uc.nick)
|
---|
2217 | if !ok {
|
---|
2218 | return
|
---|
2219 | }
|
---|
2220 |
|
---|
2221 | // User may have e.g. EXTERNAL mechanism configured. We do not want to
|
---|
2222 | // automatically erase the key pair or any other credentials.
|
---|
2223 | if uc.network.SASL.Mechanism != "" && uc.network.SASL.Mechanism != "PLAIN" {
|
---|
2224 | return
|
---|
2225 | }
|
---|
2226 |
|
---|
2227 | dc.logger.Printf("auto-saving NickServ credentials with username %q", username)
|
---|
2228 | n := uc.network
|
---|
2229 | n.SASL.Mechanism = "PLAIN"
|
---|
2230 | n.SASL.Plain.Username = username
|
---|
2231 | n.SASL.Plain.Password = password
|
---|
2232 | if err := dc.srv.db.StoreNetwork(dc.user.ID, &n.Network); err != nil {
|
---|
2233 | dc.logger.Printf("failed to save NickServ credentials: %v", err)
|
---|
2234 | }
|
---|
2235 | }
|
---|
2236 |
|
---|
2237 | func parseNickServCredentials(text, nick string) (username, password string, ok bool) {
|
---|
2238 | fields := strings.Fields(text)
|
---|
2239 | if len(fields) < 2 {
|
---|
2240 | return "", "", false
|
---|
2241 | }
|
---|
2242 | cmd := strings.ToUpper(fields[0])
|
---|
2243 | params := fields[1:]
|
---|
2244 | switch cmd {
|
---|
2245 | case "REGISTER":
|
---|
2246 | username = nick
|
---|
2247 | password = params[0]
|
---|
2248 | case "IDENTIFY":
|
---|
2249 | if len(params) == 1 {
|
---|
2250 | username = nick
|
---|
2251 | password = params[0]
|
---|
2252 | } else {
|
---|
2253 | username = params[0]
|
---|
2254 | password = params[1]
|
---|
2255 | }
|
---|
2256 | case "SET":
|
---|
2257 | if len(params) == 2 && strings.EqualFold(params[0], "PASSWORD") {
|
---|
2258 | username = nick
|
---|
2259 | password = params[1]
|
---|
2260 | }
|
---|
2261 | default:
|
---|
2262 | return "", "", false
|
---|
2263 | }
|
---|
2264 | return username, password, true
|
---|
2265 | }
|
---|