1 | package soju
|
---|
2 |
|
---|
3 | import (
|
---|
4 | "crypto"
|
---|
5 | "crypto/sha256"
|
---|
6 | "crypto/tls"
|
---|
7 | "crypto/x509"
|
---|
8 | "encoding/base64"
|
---|
9 | "errors"
|
---|
10 | "fmt"
|
---|
11 | "io"
|
---|
12 | "net"
|
---|
13 | "strconv"
|
---|
14 | "strings"
|
---|
15 | "time"
|
---|
16 |
|
---|
17 | "github.com/emersion/go-sasl"
|
---|
18 | "gopkg.in/irc.v3"
|
---|
19 | )
|
---|
20 |
|
---|
21 | // permanentUpstreamCaps is the static list of upstream capabilities always
|
---|
22 | // requested when supported.
|
---|
23 | var permanentUpstreamCaps = map[string]bool{
|
---|
24 | "away-notify": true,
|
---|
25 | "batch": true,
|
---|
26 | "extended-join": true,
|
---|
27 | "invite-notify": true,
|
---|
28 | "labeled-response": true,
|
---|
29 | "message-tags": true,
|
---|
30 | "multi-prefix": true,
|
---|
31 | "server-time": true,
|
---|
32 | "setname": true,
|
---|
33 | }
|
---|
34 |
|
---|
35 | type registrationError string
|
---|
36 |
|
---|
37 | func (err registrationError) Error() string {
|
---|
38 | return fmt.Sprintf("registration error: %v", string(err))
|
---|
39 | }
|
---|
40 |
|
---|
41 | type upstreamChannel struct {
|
---|
42 | Name string
|
---|
43 | conn *upstreamConn
|
---|
44 | Topic string
|
---|
45 | TopicWho *irc.Prefix
|
---|
46 | TopicTime time.Time
|
---|
47 | Status channelStatus
|
---|
48 | modes channelModes
|
---|
49 | creationTime string
|
---|
50 | Members membershipsCasemapMap
|
---|
51 | complete bool
|
---|
52 | detachTimer *time.Timer
|
---|
53 | }
|
---|
54 |
|
---|
55 | func (uc *upstreamChannel) updateAutoDetach(dur time.Duration) {
|
---|
56 | if uc.detachTimer != nil {
|
---|
57 | uc.detachTimer.Stop()
|
---|
58 | uc.detachTimer = nil
|
---|
59 | }
|
---|
60 |
|
---|
61 | if dur == 0 {
|
---|
62 | return
|
---|
63 | }
|
---|
64 |
|
---|
65 | uc.detachTimer = time.AfterFunc(dur, func() {
|
---|
66 | uc.conn.network.user.events <- eventChannelDetach{
|
---|
67 | uc: uc.conn,
|
---|
68 | name: uc.Name,
|
---|
69 | }
|
---|
70 | })
|
---|
71 | }
|
---|
72 |
|
---|
73 | type upstreamConn struct {
|
---|
74 | conn
|
---|
75 |
|
---|
76 | network *network
|
---|
77 | user *user
|
---|
78 |
|
---|
79 | serverName string
|
---|
80 | availableUserModes string
|
---|
81 | availableChannelModes map[byte]channelModeType
|
---|
82 | availableChannelTypes string
|
---|
83 | availableMemberships []membership
|
---|
84 | isupport map[string]*string
|
---|
85 |
|
---|
86 | registered bool
|
---|
87 | nick string
|
---|
88 | nickCM string
|
---|
89 | username string
|
---|
90 | realname string
|
---|
91 | modes userModes
|
---|
92 | channels upstreamChannelCasemapMap
|
---|
93 | supportedCaps map[string]string
|
---|
94 | caps map[string]bool
|
---|
95 | batches map[string]batch
|
---|
96 | away bool
|
---|
97 | nextLabelID uint64
|
---|
98 |
|
---|
99 | saslClient sasl.Client
|
---|
100 | saslStarted bool
|
---|
101 |
|
---|
102 | casemapIsSet bool
|
---|
103 |
|
---|
104 | // set of LIST commands in progress, per downstream
|
---|
105 | pendingLISTDownstreamSet map[uint64]struct{}
|
---|
106 | }
|
---|
107 |
|
---|
108 | func connectToUpstream(network *network) (*upstreamConn, error) {
|
---|
109 | logger := &prefixLogger{network.user.logger, fmt.Sprintf("upstream %q: ", network.GetName())}
|
---|
110 |
|
---|
111 | dialer := net.Dialer{Timeout: connectTimeout}
|
---|
112 |
|
---|
113 | u, err := network.URL()
|
---|
114 | if err != nil {
|
---|
115 | return nil, err
|
---|
116 | }
|
---|
117 |
|
---|
118 | var netConn net.Conn
|
---|
119 | switch u.Scheme {
|
---|
120 | case "ircs":
|
---|
121 | addr := u.Host
|
---|
122 | host, _, err := net.SplitHostPort(u.Host)
|
---|
123 | if err != nil {
|
---|
124 | host = u.Host
|
---|
125 | addr = u.Host + ":6697"
|
---|
126 | }
|
---|
127 |
|
---|
128 | logger.Printf("connecting to TLS server at address %q", addr)
|
---|
129 |
|
---|
130 | tlsConfig := &tls.Config{ServerName: host, NextProtos: []string{"irc"}}
|
---|
131 | if network.SASL.Mechanism == "EXTERNAL" {
|
---|
132 | if network.SASL.External.CertBlob == nil {
|
---|
133 | return nil, fmt.Errorf("missing certificate for authentication")
|
---|
134 | }
|
---|
135 | if network.SASL.External.PrivKeyBlob == nil {
|
---|
136 | return nil, fmt.Errorf("missing private key for authentication")
|
---|
137 | }
|
---|
138 | key, err := x509.ParsePKCS8PrivateKey(network.SASL.External.PrivKeyBlob)
|
---|
139 | if err != nil {
|
---|
140 | return nil, fmt.Errorf("failed to parse private key: %v", err)
|
---|
141 | }
|
---|
142 | tlsConfig.Certificates = []tls.Certificate{
|
---|
143 | {
|
---|
144 | Certificate: [][]byte{network.SASL.External.CertBlob},
|
---|
145 | PrivateKey: key.(crypto.PrivateKey),
|
---|
146 | },
|
---|
147 | }
|
---|
148 | logger.Printf("using TLS client certificate %x", sha256.Sum256(network.SASL.External.CertBlob))
|
---|
149 | }
|
---|
150 |
|
---|
151 | netConn, err = dialer.Dial("tcp", addr)
|
---|
152 | if err != nil {
|
---|
153 | return nil, fmt.Errorf("failed to dial %q: %v", addr, err)
|
---|
154 | }
|
---|
155 |
|
---|
156 | // Don't do the TLS handshake immediately, because we need to register
|
---|
157 | // the new connection with identd ASAP. See:
|
---|
158 | // https://todo.sr.ht/~emersion/soju/69#event-41859
|
---|
159 | netConn = tls.Client(netConn, tlsConfig)
|
---|
160 | case "irc+insecure":
|
---|
161 | addr := u.Host
|
---|
162 | if _, _, err := net.SplitHostPort(addr); err != nil {
|
---|
163 | addr = addr + ":6667"
|
---|
164 | }
|
---|
165 |
|
---|
166 | logger.Printf("connecting to plain-text server at address %q", addr)
|
---|
167 | netConn, err = dialer.Dial("tcp", addr)
|
---|
168 | if err != nil {
|
---|
169 | return nil, fmt.Errorf("failed to dial %q: %v", addr, err)
|
---|
170 | }
|
---|
171 | case "irc+unix", "unix":
|
---|
172 | logger.Printf("connecting to Unix socket at path %q", u.Path)
|
---|
173 | netConn, err = dialer.Dial("unix", u.Path)
|
---|
174 | if err != nil {
|
---|
175 | return nil, fmt.Errorf("failed to connect to Unix socket %q: %v", u.Path, err)
|
---|
176 | }
|
---|
177 | default:
|
---|
178 | return nil, fmt.Errorf("failed to dial %q: unknown scheme: %v", network.Addr, u.Scheme)
|
---|
179 | }
|
---|
180 |
|
---|
181 | options := connOptions{
|
---|
182 | Logger: logger,
|
---|
183 | RateLimitDelay: upstreamMessageDelay,
|
---|
184 | RateLimitBurst: upstreamMessageBurst,
|
---|
185 | }
|
---|
186 |
|
---|
187 | uc := &upstreamConn{
|
---|
188 | conn: *newConn(network.user.srv, newNetIRCConn(netConn), &options),
|
---|
189 | network: network,
|
---|
190 | user: network.user,
|
---|
191 | channels: upstreamChannelCasemapMap{newCasemapMap(0)},
|
---|
192 | supportedCaps: make(map[string]string),
|
---|
193 | caps: make(map[string]bool),
|
---|
194 | batches: make(map[string]batch),
|
---|
195 | availableChannelTypes: stdChannelTypes,
|
---|
196 | availableChannelModes: stdChannelModes,
|
---|
197 | availableMemberships: stdMemberships,
|
---|
198 | isupport: make(map[string]*string),
|
---|
199 | pendingLISTDownstreamSet: make(map[uint64]struct{}),
|
---|
200 | }
|
---|
201 | return uc, nil
|
---|
202 | }
|
---|
203 |
|
---|
204 | func (uc *upstreamConn) forEachDownstream(f func(*downstreamConn)) {
|
---|
205 | uc.network.forEachDownstream(f)
|
---|
206 | }
|
---|
207 |
|
---|
208 | func (uc *upstreamConn) forEachDownstreamByID(id uint64, f func(*downstreamConn)) {
|
---|
209 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
210 | if id != 0 && id != dc.id {
|
---|
211 | return
|
---|
212 | }
|
---|
213 | f(dc)
|
---|
214 | })
|
---|
215 | }
|
---|
216 |
|
---|
217 | func (uc *upstreamConn) getChannel(name string) (*upstreamChannel, error) {
|
---|
218 | ch := uc.channels.Value(name)
|
---|
219 | if ch == nil {
|
---|
220 | return nil, fmt.Errorf("unknown channel %q", name)
|
---|
221 | }
|
---|
222 | return ch, nil
|
---|
223 | }
|
---|
224 |
|
---|
225 | func (uc *upstreamConn) isChannel(entity string) bool {
|
---|
226 | return strings.ContainsRune(uc.availableChannelTypes, rune(entity[0]))
|
---|
227 | }
|
---|
228 |
|
---|
229 | func (uc *upstreamConn) isOurNick(nick string) bool {
|
---|
230 | return uc.nickCM == uc.network.casemap(nick)
|
---|
231 | }
|
---|
232 |
|
---|
233 | func (uc *upstreamConn) getPendingLIST() *pendingLIST {
|
---|
234 | for _, pl := range uc.user.pendingLISTs {
|
---|
235 | if _, ok := pl.pendingCommands[uc.network.ID]; !ok {
|
---|
236 | continue
|
---|
237 | }
|
---|
238 | return &pl
|
---|
239 | }
|
---|
240 | return nil
|
---|
241 | }
|
---|
242 |
|
---|
243 | func (uc *upstreamConn) endPendingLISTs(all bool) (found bool) {
|
---|
244 | found = false
|
---|
245 | for i := 0; i < len(uc.user.pendingLISTs); i++ {
|
---|
246 | pl := uc.user.pendingLISTs[i]
|
---|
247 | if _, ok := pl.pendingCommands[uc.network.ID]; !ok {
|
---|
248 | continue
|
---|
249 | }
|
---|
250 | delete(pl.pendingCommands, uc.network.ID)
|
---|
251 | if len(pl.pendingCommands) == 0 {
|
---|
252 | uc.user.pendingLISTs = append(uc.user.pendingLISTs[:i], uc.user.pendingLISTs[i+1:]...)
|
---|
253 | i--
|
---|
254 | uc.forEachDownstreamByID(pl.downstreamID, func(dc *downstreamConn) {
|
---|
255 | dc.SendMessage(&irc.Message{
|
---|
256 | Prefix: dc.srv.prefix(),
|
---|
257 | Command: irc.RPL_LISTEND,
|
---|
258 | Params: []string{dc.nick, "End of /LIST"},
|
---|
259 | })
|
---|
260 | })
|
---|
261 | }
|
---|
262 | found = true
|
---|
263 | if !all {
|
---|
264 | delete(uc.pendingLISTDownstreamSet, pl.downstreamID)
|
---|
265 | uc.user.forEachUpstream(func(uc *upstreamConn) {
|
---|
266 | uc.trySendLIST(pl.downstreamID)
|
---|
267 | })
|
---|
268 | return
|
---|
269 | }
|
---|
270 | }
|
---|
271 | return
|
---|
272 | }
|
---|
273 |
|
---|
274 | func (uc *upstreamConn) trySendLIST(downstreamID uint64) {
|
---|
275 | if _, ok := uc.pendingLISTDownstreamSet[downstreamID]; ok {
|
---|
276 | // a LIST command is already pending
|
---|
277 | // we will try again when that command is completed
|
---|
278 | return
|
---|
279 | }
|
---|
280 |
|
---|
281 | for _, pl := range uc.user.pendingLISTs {
|
---|
282 | if pl.downstreamID != downstreamID {
|
---|
283 | continue
|
---|
284 | }
|
---|
285 | // this is the first pending LIST command list of the downstream
|
---|
286 | listCommand, ok := pl.pendingCommands[uc.network.ID]
|
---|
287 | if !ok {
|
---|
288 | // there is no command for this upstream in these LIST commands
|
---|
289 | // do not send anything
|
---|
290 | continue
|
---|
291 | }
|
---|
292 | // there is a command for this upstream in these LIST commands
|
---|
293 | // send it now
|
---|
294 |
|
---|
295 | uc.SendMessageLabeled(downstreamID, listCommand)
|
---|
296 |
|
---|
297 | uc.pendingLISTDownstreamSet[downstreamID] = struct{}{}
|
---|
298 | return
|
---|
299 | }
|
---|
300 | }
|
---|
301 |
|
---|
302 | func (uc *upstreamConn) parseMembershipPrefix(s string) (ms *memberships, nick string) {
|
---|
303 | memberships := make(memberships, 0, 4)
|
---|
304 | i := 0
|
---|
305 | for _, m := range uc.availableMemberships {
|
---|
306 | if i >= len(s) {
|
---|
307 | break
|
---|
308 | }
|
---|
309 | if s[i] == m.Prefix {
|
---|
310 | memberships = append(memberships, m)
|
---|
311 | i++
|
---|
312 | }
|
---|
313 | }
|
---|
314 | return &memberships, s[i:]
|
---|
315 | }
|
---|
316 |
|
---|
317 | func (uc *upstreamConn) handleMessage(msg *irc.Message) error {
|
---|
318 | var label string
|
---|
319 | if l, ok := msg.GetTag("label"); ok {
|
---|
320 | label = l
|
---|
321 | delete(msg.Tags, "label")
|
---|
322 | }
|
---|
323 |
|
---|
324 | var msgBatch *batch
|
---|
325 | if batchName, ok := msg.GetTag("batch"); ok {
|
---|
326 | b, ok := uc.batches[batchName]
|
---|
327 | if !ok {
|
---|
328 | return fmt.Errorf("unexpected batch reference: batch was not defined: %q", batchName)
|
---|
329 | }
|
---|
330 | msgBatch = &b
|
---|
331 | if label == "" {
|
---|
332 | label = msgBatch.Label
|
---|
333 | }
|
---|
334 | delete(msg.Tags, "batch")
|
---|
335 | }
|
---|
336 |
|
---|
337 | var downstreamID uint64 = 0
|
---|
338 | if label != "" {
|
---|
339 | var labelOffset uint64
|
---|
340 | n, err := fmt.Sscanf(label, "sd-%d-%d", &downstreamID, &labelOffset)
|
---|
341 | if err == nil && n < 2 {
|
---|
342 | err = errors.New("not enough arguments")
|
---|
343 | }
|
---|
344 | if err != nil {
|
---|
345 | return fmt.Errorf("unexpected message label: invalid downstream reference for label %q: %v", label, err)
|
---|
346 | }
|
---|
347 | }
|
---|
348 |
|
---|
349 | if _, ok := msg.Tags["time"]; !ok {
|
---|
350 | msg.Tags["time"] = irc.TagValue(time.Now().UTC().Format(serverTimeLayout))
|
---|
351 | }
|
---|
352 |
|
---|
353 | switch msg.Command {
|
---|
354 | case "PING":
|
---|
355 | uc.SendMessage(&irc.Message{
|
---|
356 | Command: "PONG",
|
---|
357 | Params: msg.Params,
|
---|
358 | })
|
---|
359 | return nil
|
---|
360 | case "NOTICE", "PRIVMSG", "TAGMSG":
|
---|
361 | if msg.Prefix == nil {
|
---|
362 | return fmt.Errorf("expected a prefix")
|
---|
363 | }
|
---|
364 |
|
---|
365 | var entity, text string
|
---|
366 | if msg.Command != "TAGMSG" {
|
---|
367 | if err := parseMessageParams(msg, &entity, &text); err != nil {
|
---|
368 | return err
|
---|
369 | }
|
---|
370 | } else {
|
---|
371 | if err := parseMessageParams(msg, &entity); err != nil {
|
---|
372 | return err
|
---|
373 | }
|
---|
374 | }
|
---|
375 |
|
---|
376 | if msg.Prefix.Name == serviceNick {
|
---|
377 | uc.logger.Printf("skipping %v from soju's service: %v", msg.Command, msg)
|
---|
378 | break
|
---|
379 | }
|
---|
380 | if entity == serviceNick {
|
---|
381 | uc.logger.Printf("skipping %v to soju's service: %v", msg.Command, msg)
|
---|
382 | break
|
---|
383 | }
|
---|
384 |
|
---|
385 | if msg.Prefix.User == "" && msg.Prefix.Host == "" { // server message
|
---|
386 | uc.produce("", msg, nil)
|
---|
387 | } else { // regular user message
|
---|
388 | target := entity
|
---|
389 | if uc.isOurNick(target) {
|
---|
390 | target = msg.Prefix.Name
|
---|
391 | }
|
---|
392 |
|
---|
393 | ch := uc.network.channels.Value(target)
|
---|
394 | if ch != nil && msg.Command != "TAGMSG" {
|
---|
395 | if ch.Detached {
|
---|
396 | uc.handleDetachedMessage(ch, msg)
|
---|
397 | }
|
---|
398 |
|
---|
399 | highlight := uc.network.isHighlight(msg)
|
---|
400 | if ch.DetachOn == FilterMessage || ch.DetachOn == FilterDefault || (ch.DetachOn == FilterHighlight && highlight) {
|
---|
401 | uc.updateChannelAutoDetach(target)
|
---|
402 | }
|
---|
403 | }
|
---|
404 |
|
---|
405 | uc.produce(target, msg, nil)
|
---|
406 | }
|
---|
407 | case "CAP":
|
---|
408 | var subCmd string
|
---|
409 | if err := parseMessageParams(msg, nil, &subCmd); err != nil {
|
---|
410 | return err
|
---|
411 | }
|
---|
412 | subCmd = strings.ToUpper(subCmd)
|
---|
413 | subParams := msg.Params[2:]
|
---|
414 | switch subCmd {
|
---|
415 | case "LS":
|
---|
416 | if len(subParams) < 1 {
|
---|
417 | return newNeedMoreParamsError(msg.Command)
|
---|
418 | }
|
---|
419 | caps := subParams[len(subParams)-1]
|
---|
420 | more := len(subParams) >= 2 && msg.Params[len(subParams)-2] == "*"
|
---|
421 |
|
---|
422 | uc.handleSupportedCaps(caps)
|
---|
423 |
|
---|
424 | if more {
|
---|
425 | break // wait to receive all capabilities
|
---|
426 | }
|
---|
427 |
|
---|
428 | uc.requestCaps()
|
---|
429 |
|
---|
430 | if uc.requestSASL() {
|
---|
431 | break // we'll send CAP END after authentication is completed
|
---|
432 | }
|
---|
433 |
|
---|
434 | uc.SendMessage(&irc.Message{
|
---|
435 | Command: "CAP",
|
---|
436 | Params: []string{"END"},
|
---|
437 | })
|
---|
438 | case "ACK", "NAK":
|
---|
439 | if len(subParams) < 1 {
|
---|
440 | return newNeedMoreParamsError(msg.Command)
|
---|
441 | }
|
---|
442 | caps := strings.Fields(subParams[0])
|
---|
443 |
|
---|
444 | for _, name := range caps {
|
---|
445 | if err := uc.handleCapAck(strings.ToLower(name), subCmd == "ACK"); err != nil {
|
---|
446 | return err
|
---|
447 | }
|
---|
448 | }
|
---|
449 |
|
---|
450 | if uc.registered {
|
---|
451 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
452 | dc.updateSupportedCaps()
|
---|
453 | })
|
---|
454 | }
|
---|
455 | case "NEW":
|
---|
456 | if len(subParams) < 1 {
|
---|
457 | return newNeedMoreParamsError(msg.Command)
|
---|
458 | }
|
---|
459 | uc.handleSupportedCaps(subParams[0])
|
---|
460 | uc.requestCaps()
|
---|
461 | case "DEL":
|
---|
462 | if len(subParams) < 1 {
|
---|
463 | return newNeedMoreParamsError(msg.Command)
|
---|
464 | }
|
---|
465 | caps := strings.Fields(subParams[0])
|
---|
466 |
|
---|
467 | for _, c := range caps {
|
---|
468 | delete(uc.supportedCaps, c)
|
---|
469 | delete(uc.caps, c)
|
---|
470 | }
|
---|
471 |
|
---|
472 | if uc.registered {
|
---|
473 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
474 | dc.updateSupportedCaps()
|
---|
475 | })
|
---|
476 | }
|
---|
477 | default:
|
---|
478 | uc.logger.Printf("unhandled message: %v", msg)
|
---|
479 | }
|
---|
480 | case "AUTHENTICATE":
|
---|
481 | if uc.saslClient == nil {
|
---|
482 | return fmt.Errorf("received unexpected AUTHENTICATE message")
|
---|
483 | }
|
---|
484 |
|
---|
485 | // TODO: if a challenge is 400 bytes long, buffer it
|
---|
486 | var challengeStr string
|
---|
487 | if err := parseMessageParams(msg, &challengeStr); err != nil {
|
---|
488 | uc.SendMessage(&irc.Message{
|
---|
489 | Command: "AUTHENTICATE",
|
---|
490 | Params: []string{"*"},
|
---|
491 | })
|
---|
492 | return err
|
---|
493 | }
|
---|
494 |
|
---|
495 | var challenge []byte
|
---|
496 | if challengeStr != "+" {
|
---|
497 | var err error
|
---|
498 | challenge, err = base64.StdEncoding.DecodeString(challengeStr)
|
---|
499 | if err != nil {
|
---|
500 | uc.SendMessage(&irc.Message{
|
---|
501 | Command: "AUTHENTICATE",
|
---|
502 | Params: []string{"*"},
|
---|
503 | })
|
---|
504 | return err
|
---|
505 | }
|
---|
506 | }
|
---|
507 |
|
---|
508 | var resp []byte
|
---|
509 | var err error
|
---|
510 | if !uc.saslStarted {
|
---|
511 | _, resp, err = uc.saslClient.Start()
|
---|
512 | uc.saslStarted = true
|
---|
513 | } else {
|
---|
514 | resp, err = uc.saslClient.Next(challenge)
|
---|
515 | }
|
---|
516 | if err != nil {
|
---|
517 | uc.SendMessage(&irc.Message{
|
---|
518 | Command: "AUTHENTICATE",
|
---|
519 | Params: []string{"*"},
|
---|
520 | })
|
---|
521 | return err
|
---|
522 | }
|
---|
523 |
|
---|
524 | // TODO: send response in multiple chunks if >= 400 bytes
|
---|
525 | var respStr = "+"
|
---|
526 | if len(resp) != 0 {
|
---|
527 | respStr = base64.StdEncoding.EncodeToString(resp)
|
---|
528 | }
|
---|
529 |
|
---|
530 | uc.SendMessage(&irc.Message{
|
---|
531 | Command: "AUTHENTICATE",
|
---|
532 | Params: []string{respStr},
|
---|
533 | })
|
---|
534 | case irc.RPL_LOGGEDIN:
|
---|
535 | var account string
|
---|
536 | if err := parseMessageParams(msg, nil, nil, &account); err != nil {
|
---|
537 | return err
|
---|
538 | }
|
---|
539 | uc.logger.Printf("logged in with account %q", account)
|
---|
540 | case irc.RPL_LOGGEDOUT:
|
---|
541 | uc.logger.Printf("logged out")
|
---|
542 | case irc.ERR_NICKLOCKED, irc.RPL_SASLSUCCESS, irc.ERR_SASLFAIL, irc.ERR_SASLTOOLONG, irc.ERR_SASLABORTED:
|
---|
543 | var info string
|
---|
544 | if err := parseMessageParams(msg, nil, &info); err != nil {
|
---|
545 | return err
|
---|
546 | }
|
---|
547 | switch msg.Command {
|
---|
548 | case irc.ERR_NICKLOCKED:
|
---|
549 | uc.logger.Printf("invalid nick used with SASL authentication: %v", info)
|
---|
550 | case irc.ERR_SASLFAIL:
|
---|
551 | uc.logger.Printf("SASL authentication failed: %v", info)
|
---|
552 | case irc.ERR_SASLTOOLONG:
|
---|
553 | uc.logger.Printf("SASL message too long: %v", info)
|
---|
554 | }
|
---|
555 |
|
---|
556 | uc.saslClient = nil
|
---|
557 | uc.saslStarted = false
|
---|
558 |
|
---|
559 | uc.SendMessage(&irc.Message{
|
---|
560 | Command: "CAP",
|
---|
561 | Params: []string{"END"},
|
---|
562 | })
|
---|
563 | case irc.RPL_WELCOME:
|
---|
564 | uc.registered = true
|
---|
565 | uc.logger.Printf("connection registered")
|
---|
566 |
|
---|
567 | if uc.network.channels.Len() > 0 {
|
---|
568 | var channels, keys []string
|
---|
569 | for _, entry := range uc.network.channels.innerMap {
|
---|
570 | ch := entry.value.(*Channel)
|
---|
571 | channels = append(channels, ch.Name)
|
---|
572 | keys = append(keys, ch.Key)
|
---|
573 | }
|
---|
574 |
|
---|
575 | for _, msg := range join(channels, keys) {
|
---|
576 | uc.SendMessage(msg)
|
---|
577 | }
|
---|
578 | }
|
---|
579 | case irc.RPL_MYINFO:
|
---|
580 | if err := parseMessageParams(msg, nil, &uc.serverName, nil, &uc.availableUserModes, nil); err != nil {
|
---|
581 | return err
|
---|
582 | }
|
---|
583 | case irc.RPL_ISUPPORT:
|
---|
584 | if err := parseMessageParams(msg, nil, nil); err != nil {
|
---|
585 | return err
|
---|
586 | }
|
---|
587 |
|
---|
588 | var downstreamIsupport []string
|
---|
589 | for _, token := range msg.Params[1 : len(msg.Params)-1] {
|
---|
590 | parameter := token
|
---|
591 | var negate, hasValue bool
|
---|
592 | var value string
|
---|
593 | if strings.HasPrefix(token, "-") {
|
---|
594 | negate = true
|
---|
595 | token = token[1:]
|
---|
596 | } else if i := strings.IndexByte(token, '='); i >= 0 {
|
---|
597 | parameter = token[:i]
|
---|
598 | value = token[i+1:]
|
---|
599 | hasValue = true
|
---|
600 | }
|
---|
601 |
|
---|
602 | if hasValue {
|
---|
603 | uc.isupport[parameter] = &value
|
---|
604 | } else if !negate {
|
---|
605 | uc.isupport[parameter] = nil
|
---|
606 | } else {
|
---|
607 | delete(uc.isupport, parameter)
|
---|
608 | }
|
---|
609 |
|
---|
610 | var err error
|
---|
611 | switch parameter {
|
---|
612 | case "CASEMAPPING":
|
---|
613 | casemap, ok := parseCasemappingToken(value)
|
---|
614 | if !ok {
|
---|
615 | casemap = casemapRFC1459
|
---|
616 | }
|
---|
617 | uc.network.updateCasemapping(casemap)
|
---|
618 | uc.nickCM = uc.network.casemap(uc.nick)
|
---|
619 | uc.casemapIsSet = true
|
---|
620 | case "CHANMODES":
|
---|
621 | if !negate {
|
---|
622 | err = uc.handleChanModes(value)
|
---|
623 | } else {
|
---|
624 | uc.availableChannelModes = stdChannelModes
|
---|
625 | }
|
---|
626 | case "CHANTYPES":
|
---|
627 | if !negate {
|
---|
628 | uc.availableChannelTypes = value
|
---|
629 | } else {
|
---|
630 | uc.availableChannelTypes = stdChannelTypes
|
---|
631 | }
|
---|
632 | case "PREFIX":
|
---|
633 | if !negate {
|
---|
634 | err = uc.handleMemberships(value)
|
---|
635 | } else {
|
---|
636 | uc.availableMemberships = stdMemberships
|
---|
637 | }
|
---|
638 | }
|
---|
639 | if err != nil {
|
---|
640 | return err
|
---|
641 | }
|
---|
642 |
|
---|
643 | if passthroughIsupport[parameter] {
|
---|
644 | downstreamIsupport = append(downstreamIsupport, token)
|
---|
645 | }
|
---|
646 | }
|
---|
647 |
|
---|
648 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
649 | if dc.network == nil {
|
---|
650 | return
|
---|
651 | }
|
---|
652 | msgs := generateIsupport(dc.srv.prefix(), dc.nick, downstreamIsupport)
|
---|
653 | for _, msg := range msgs {
|
---|
654 | dc.SendMessage(msg)
|
---|
655 | }
|
---|
656 | })
|
---|
657 | case irc.ERR_NOMOTD, irc.RPL_ENDOFMOTD:
|
---|
658 | if !uc.casemapIsSet {
|
---|
659 | // upstream did not send any CASEMAPPING token, thus
|
---|
660 | // we assume it implements the old RFCs with rfc1459.
|
---|
661 | uc.casemapIsSet = true
|
---|
662 | uc.network.updateCasemapping(casemapRFC1459)
|
---|
663 | uc.nickCM = uc.network.casemap(uc.nick)
|
---|
664 | }
|
---|
665 | case "BATCH":
|
---|
666 | var tag string
|
---|
667 | if err := parseMessageParams(msg, &tag); err != nil {
|
---|
668 | return err
|
---|
669 | }
|
---|
670 |
|
---|
671 | if strings.HasPrefix(tag, "+") {
|
---|
672 | tag = tag[1:]
|
---|
673 | if _, ok := uc.batches[tag]; ok {
|
---|
674 | return fmt.Errorf("unexpected BATCH reference tag: batch was already defined: %q", tag)
|
---|
675 | }
|
---|
676 | var batchType string
|
---|
677 | if err := parseMessageParams(msg, nil, &batchType); err != nil {
|
---|
678 | return err
|
---|
679 | }
|
---|
680 | label := label
|
---|
681 | if label == "" && msgBatch != nil {
|
---|
682 | label = msgBatch.Label
|
---|
683 | }
|
---|
684 | uc.batches[tag] = batch{
|
---|
685 | Type: batchType,
|
---|
686 | Params: msg.Params[2:],
|
---|
687 | Outer: msgBatch,
|
---|
688 | Label: label,
|
---|
689 | }
|
---|
690 | } else if strings.HasPrefix(tag, "-") {
|
---|
691 | tag = tag[1:]
|
---|
692 | if _, ok := uc.batches[tag]; !ok {
|
---|
693 | return fmt.Errorf("unknown BATCH reference tag: %q", tag)
|
---|
694 | }
|
---|
695 | delete(uc.batches, tag)
|
---|
696 | } else {
|
---|
697 | return fmt.Errorf("unexpected BATCH reference tag: missing +/- prefix: %q", tag)
|
---|
698 | }
|
---|
699 | case "NICK":
|
---|
700 | if msg.Prefix == nil {
|
---|
701 | return fmt.Errorf("expected a prefix")
|
---|
702 | }
|
---|
703 |
|
---|
704 | var newNick string
|
---|
705 | if err := parseMessageParams(msg, &newNick); err != nil {
|
---|
706 | return err
|
---|
707 | }
|
---|
708 |
|
---|
709 | me := false
|
---|
710 | if uc.isOurNick(msg.Prefix.Name) {
|
---|
711 | uc.logger.Printf("changed nick from %q to %q", uc.nick, newNick)
|
---|
712 | me = true
|
---|
713 | uc.nick = newNick
|
---|
714 | uc.nickCM = uc.network.casemap(uc.nick)
|
---|
715 | }
|
---|
716 |
|
---|
717 | for _, entry := range uc.channels.innerMap {
|
---|
718 | ch := entry.value.(*upstreamChannel)
|
---|
719 | memberships := ch.Members.Value(msg.Prefix.Name)
|
---|
720 | if memberships != nil {
|
---|
721 | ch.Members.Delete(msg.Prefix.Name)
|
---|
722 | ch.Members.SetValue(newNick, memberships)
|
---|
723 | uc.appendLog(ch.Name, msg)
|
---|
724 | }
|
---|
725 | }
|
---|
726 |
|
---|
727 | if !me {
|
---|
728 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
729 | dc.SendMessage(dc.marshalMessage(msg, uc.network))
|
---|
730 | })
|
---|
731 | } else {
|
---|
732 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
733 | dc.updateNick()
|
---|
734 | })
|
---|
735 | }
|
---|
736 | case "SETNAME":
|
---|
737 | if msg.Prefix == nil {
|
---|
738 | return fmt.Errorf("expected a prefix")
|
---|
739 | }
|
---|
740 |
|
---|
741 | var newRealname string
|
---|
742 | if err := parseMessageParams(msg, &newRealname); err != nil {
|
---|
743 | return err
|
---|
744 | }
|
---|
745 |
|
---|
746 | // TODO: consider appending this message to logs
|
---|
747 |
|
---|
748 | if uc.isOurNick(msg.Prefix.Name) {
|
---|
749 | uc.logger.Printf("changed realname from %q to %q", uc.realname, newRealname)
|
---|
750 | uc.realname = newRealname
|
---|
751 |
|
---|
752 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
753 | dc.updateRealname()
|
---|
754 | })
|
---|
755 | } else {
|
---|
756 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
757 | dc.SendMessage(dc.marshalMessage(msg, uc.network))
|
---|
758 | })
|
---|
759 | }
|
---|
760 | case "JOIN":
|
---|
761 | if msg.Prefix == nil {
|
---|
762 | return fmt.Errorf("expected a prefix")
|
---|
763 | }
|
---|
764 |
|
---|
765 | var channels string
|
---|
766 | if err := parseMessageParams(msg, &channels); err != nil {
|
---|
767 | return err
|
---|
768 | }
|
---|
769 |
|
---|
770 | for _, ch := range strings.Split(channels, ",") {
|
---|
771 | if uc.isOurNick(msg.Prefix.Name) {
|
---|
772 | uc.logger.Printf("joined channel %q", ch)
|
---|
773 | members := membershipsCasemapMap{newCasemapMap(0)}
|
---|
774 | members.casemap = uc.network.casemap
|
---|
775 | uc.channels.SetValue(ch, &upstreamChannel{
|
---|
776 | Name: ch,
|
---|
777 | conn: uc,
|
---|
778 | Members: members,
|
---|
779 | })
|
---|
780 | uc.updateChannelAutoDetach(ch)
|
---|
781 |
|
---|
782 | uc.SendMessage(&irc.Message{
|
---|
783 | Command: "MODE",
|
---|
784 | Params: []string{ch},
|
---|
785 | })
|
---|
786 | } else {
|
---|
787 | ch, err := uc.getChannel(ch)
|
---|
788 | if err != nil {
|
---|
789 | return err
|
---|
790 | }
|
---|
791 | ch.Members.SetValue(msg.Prefix.Name, &memberships{})
|
---|
792 | }
|
---|
793 |
|
---|
794 | chMsg := msg.Copy()
|
---|
795 | chMsg.Params[0] = ch
|
---|
796 | uc.produce(ch, chMsg, nil)
|
---|
797 | }
|
---|
798 | case "PART":
|
---|
799 | if msg.Prefix == nil {
|
---|
800 | return fmt.Errorf("expected a prefix")
|
---|
801 | }
|
---|
802 |
|
---|
803 | var channels string
|
---|
804 | if err := parseMessageParams(msg, &channels); err != nil {
|
---|
805 | return err
|
---|
806 | }
|
---|
807 |
|
---|
808 | for _, ch := range strings.Split(channels, ",") {
|
---|
809 | if uc.isOurNick(msg.Prefix.Name) {
|
---|
810 | uc.logger.Printf("parted channel %q", ch)
|
---|
811 | uch := uc.channels.Value(ch)
|
---|
812 | if uch != nil {
|
---|
813 | uc.channels.Delete(ch)
|
---|
814 | uch.updateAutoDetach(0)
|
---|
815 | }
|
---|
816 | } else {
|
---|
817 | ch, err := uc.getChannel(ch)
|
---|
818 | if err != nil {
|
---|
819 | return err
|
---|
820 | }
|
---|
821 | ch.Members.Delete(msg.Prefix.Name)
|
---|
822 | }
|
---|
823 |
|
---|
824 | chMsg := msg.Copy()
|
---|
825 | chMsg.Params[0] = ch
|
---|
826 | uc.produce(ch, chMsg, nil)
|
---|
827 | }
|
---|
828 | case "KICK":
|
---|
829 | if msg.Prefix == nil {
|
---|
830 | return fmt.Errorf("expected a prefix")
|
---|
831 | }
|
---|
832 |
|
---|
833 | var channel, user string
|
---|
834 | if err := parseMessageParams(msg, &channel, &user); err != nil {
|
---|
835 | return err
|
---|
836 | }
|
---|
837 |
|
---|
838 | if uc.isOurNick(user) {
|
---|
839 | uc.logger.Printf("kicked from channel %q by %s", channel, msg.Prefix.Name)
|
---|
840 | uc.channels.Delete(channel)
|
---|
841 | } else {
|
---|
842 | ch, err := uc.getChannel(channel)
|
---|
843 | if err != nil {
|
---|
844 | return err
|
---|
845 | }
|
---|
846 | ch.Members.Delete(user)
|
---|
847 | }
|
---|
848 |
|
---|
849 | uc.produce(channel, msg, nil)
|
---|
850 | case "QUIT":
|
---|
851 | if msg.Prefix == nil {
|
---|
852 | return fmt.Errorf("expected a prefix")
|
---|
853 | }
|
---|
854 |
|
---|
855 | if uc.isOurNick(msg.Prefix.Name) {
|
---|
856 | uc.logger.Printf("quit")
|
---|
857 | }
|
---|
858 |
|
---|
859 | for _, entry := range uc.channels.innerMap {
|
---|
860 | ch := entry.value.(*upstreamChannel)
|
---|
861 | if ch.Members.Has(msg.Prefix.Name) {
|
---|
862 | ch.Members.Delete(msg.Prefix.Name)
|
---|
863 |
|
---|
864 | uc.appendLog(ch.Name, msg)
|
---|
865 | }
|
---|
866 | }
|
---|
867 |
|
---|
868 | if msg.Prefix.Name != uc.nick {
|
---|
869 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
870 | dc.SendMessage(dc.marshalMessage(msg, uc.network))
|
---|
871 | })
|
---|
872 | }
|
---|
873 | case irc.RPL_TOPIC, irc.RPL_NOTOPIC:
|
---|
874 | var name, topic string
|
---|
875 | if err := parseMessageParams(msg, nil, &name, &topic); err != nil {
|
---|
876 | return err
|
---|
877 | }
|
---|
878 | ch, err := uc.getChannel(name)
|
---|
879 | if err != nil {
|
---|
880 | return err
|
---|
881 | }
|
---|
882 | if msg.Command == irc.RPL_TOPIC {
|
---|
883 | ch.Topic = topic
|
---|
884 | } else {
|
---|
885 | ch.Topic = ""
|
---|
886 | }
|
---|
887 | case "TOPIC":
|
---|
888 | if msg.Prefix == nil {
|
---|
889 | return fmt.Errorf("expected a prefix")
|
---|
890 | }
|
---|
891 |
|
---|
892 | var name string
|
---|
893 | if err := parseMessageParams(msg, &name); err != nil {
|
---|
894 | return err
|
---|
895 | }
|
---|
896 | ch, err := uc.getChannel(name)
|
---|
897 | if err != nil {
|
---|
898 | return err
|
---|
899 | }
|
---|
900 | if len(msg.Params) > 1 {
|
---|
901 | ch.Topic = msg.Params[1]
|
---|
902 | ch.TopicWho = msg.Prefix.Copy()
|
---|
903 | ch.TopicTime = time.Now() // TODO use msg.Tags["time"]
|
---|
904 | } else {
|
---|
905 | ch.Topic = ""
|
---|
906 | }
|
---|
907 | uc.produce(ch.Name, msg, nil)
|
---|
908 | case "MODE":
|
---|
909 | var name, modeStr string
|
---|
910 | if err := parseMessageParams(msg, &name, &modeStr); err != nil {
|
---|
911 | return err
|
---|
912 | }
|
---|
913 |
|
---|
914 | if !uc.isChannel(name) { // user mode change
|
---|
915 | if name != uc.nick {
|
---|
916 | return fmt.Errorf("received MODE message for unknown nick %q", name)
|
---|
917 | }
|
---|
918 | return uc.modes.Apply(modeStr)
|
---|
919 | // TODO: notify downstreams about user mode change?
|
---|
920 | } else { // channel mode change
|
---|
921 | ch, err := uc.getChannel(name)
|
---|
922 | if err != nil {
|
---|
923 | return err
|
---|
924 | }
|
---|
925 |
|
---|
926 | needMarshaling, err := applyChannelModes(ch, modeStr, msg.Params[2:])
|
---|
927 | if err != nil {
|
---|
928 | return err
|
---|
929 | }
|
---|
930 |
|
---|
931 | uc.appendLog(ch.Name, msg)
|
---|
932 |
|
---|
933 | c := uc.network.channels.Value(name)
|
---|
934 | if c == nil || !c.Detached {
|
---|
935 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
936 | params := make([]string, len(msg.Params))
|
---|
937 | params[0] = dc.marshalEntity(uc.network, name)
|
---|
938 | params[1] = modeStr
|
---|
939 |
|
---|
940 | copy(params[2:], msg.Params[2:])
|
---|
941 | for i, modeParam := range params[2:] {
|
---|
942 | if _, ok := needMarshaling[i]; ok {
|
---|
943 | params[2+i] = dc.marshalEntity(uc.network, modeParam)
|
---|
944 | }
|
---|
945 | }
|
---|
946 |
|
---|
947 | dc.SendMessage(&irc.Message{
|
---|
948 | Prefix: dc.marshalUserPrefix(uc.network, msg.Prefix),
|
---|
949 | Command: "MODE",
|
---|
950 | Params: params,
|
---|
951 | })
|
---|
952 | })
|
---|
953 | }
|
---|
954 | }
|
---|
955 | case irc.RPL_UMODEIS:
|
---|
956 | if err := parseMessageParams(msg, nil); err != nil {
|
---|
957 | return err
|
---|
958 | }
|
---|
959 | modeStr := ""
|
---|
960 | if len(msg.Params) > 1 {
|
---|
961 | modeStr = msg.Params[1]
|
---|
962 | }
|
---|
963 |
|
---|
964 | uc.modes = ""
|
---|
965 | if err := uc.modes.Apply(modeStr); err != nil {
|
---|
966 | return err
|
---|
967 | }
|
---|
968 | // TODO: send RPL_UMODEIS to downstream connections when applicable
|
---|
969 | case irc.RPL_CHANNELMODEIS:
|
---|
970 | var channel string
|
---|
971 | if err := parseMessageParams(msg, nil, &channel); err != nil {
|
---|
972 | return err
|
---|
973 | }
|
---|
974 | modeStr := ""
|
---|
975 | if len(msg.Params) > 2 {
|
---|
976 | modeStr = msg.Params[2]
|
---|
977 | }
|
---|
978 |
|
---|
979 | ch, err := uc.getChannel(channel)
|
---|
980 | if err != nil {
|
---|
981 | return err
|
---|
982 | }
|
---|
983 |
|
---|
984 | firstMode := ch.modes == nil
|
---|
985 | ch.modes = make(map[byte]string)
|
---|
986 | if _, err := applyChannelModes(ch, modeStr, msg.Params[3:]); err != nil {
|
---|
987 | return err
|
---|
988 | }
|
---|
989 | if firstMode {
|
---|
990 | c := uc.network.channels.Value(channel)
|
---|
991 | if c == nil || !c.Detached {
|
---|
992 | modeStr, modeParams := ch.modes.Format()
|
---|
993 |
|
---|
994 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
995 | params := []string{dc.nick, dc.marshalEntity(uc.network, channel), modeStr}
|
---|
996 | params = append(params, modeParams...)
|
---|
997 |
|
---|
998 | dc.SendMessage(&irc.Message{
|
---|
999 | Prefix: dc.srv.prefix(),
|
---|
1000 | Command: irc.RPL_CHANNELMODEIS,
|
---|
1001 | Params: params,
|
---|
1002 | })
|
---|
1003 | })
|
---|
1004 | }
|
---|
1005 | }
|
---|
1006 | case rpl_creationtime:
|
---|
1007 | var channel, creationTime string
|
---|
1008 | if err := parseMessageParams(msg, nil, &channel, &creationTime); err != nil {
|
---|
1009 | return err
|
---|
1010 | }
|
---|
1011 |
|
---|
1012 | ch, err := uc.getChannel(channel)
|
---|
1013 | if err != nil {
|
---|
1014 | return err
|
---|
1015 | }
|
---|
1016 |
|
---|
1017 | firstCreationTime := ch.creationTime == ""
|
---|
1018 | ch.creationTime = creationTime
|
---|
1019 | if firstCreationTime {
|
---|
1020 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1021 | dc.SendMessage(&irc.Message{
|
---|
1022 | Prefix: dc.srv.prefix(),
|
---|
1023 | Command: rpl_creationtime,
|
---|
1024 | Params: []string{dc.nick, dc.marshalEntity(uc.network, ch.Name), creationTime},
|
---|
1025 | })
|
---|
1026 | })
|
---|
1027 | }
|
---|
1028 | case rpl_topicwhotime:
|
---|
1029 | var name, who, timeStr string
|
---|
1030 | if err := parseMessageParams(msg, nil, &name, &who, &timeStr); err != nil {
|
---|
1031 | return err
|
---|
1032 | }
|
---|
1033 | ch, err := uc.getChannel(name)
|
---|
1034 | if err != nil {
|
---|
1035 | return err
|
---|
1036 | }
|
---|
1037 | firstTopicWhoTime := ch.TopicWho == nil
|
---|
1038 | ch.TopicWho = irc.ParsePrefix(who)
|
---|
1039 | sec, err := strconv.ParseInt(timeStr, 10, 64)
|
---|
1040 | if err != nil {
|
---|
1041 | return fmt.Errorf("failed to parse topic time: %v", err)
|
---|
1042 | }
|
---|
1043 | ch.TopicTime = time.Unix(sec, 0)
|
---|
1044 | if firstTopicWhoTime {
|
---|
1045 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1046 | topicWho := dc.marshalUserPrefix(uc.network, ch.TopicWho)
|
---|
1047 | dc.SendMessage(&irc.Message{
|
---|
1048 | Prefix: dc.srv.prefix(),
|
---|
1049 | Command: rpl_topicwhotime,
|
---|
1050 | Params: []string{
|
---|
1051 | dc.nick,
|
---|
1052 | dc.marshalEntity(uc.network, ch.Name),
|
---|
1053 | topicWho.String(),
|
---|
1054 | timeStr,
|
---|
1055 | },
|
---|
1056 | })
|
---|
1057 | })
|
---|
1058 | }
|
---|
1059 | case irc.RPL_LIST:
|
---|
1060 | var channel, clients, topic string
|
---|
1061 | if err := parseMessageParams(msg, nil, &channel, &clients, &topic); err != nil {
|
---|
1062 | return err
|
---|
1063 | }
|
---|
1064 |
|
---|
1065 | pl := uc.getPendingLIST()
|
---|
1066 | if pl == nil {
|
---|
1067 | return fmt.Errorf("unexpected RPL_LIST: no matching pending LIST")
|
---|
1068 | }
|
---|
1069 |
|
---|
1070 | uc.forEachDownstreamByID(pl.downstreamID, func(dc *downstreamConn) {
|
---|
1071 | dc.SendMessage(&irc.Message{
|
---|
1072 | Prefix: dc.srv.prefix(),
|
---|
1073 | Command: irc.RPL_LIST,
|
---|
1074 | Params: []string{dc.nick, dc.marshalEntity(uc.network, channel), clients, topic},
|
---|
1075 | })
|
---|
1076 | })
|
---|
1077 | case irc.RPL_LISTEND:
|
---|
1078 | ok := uc.endPendingLISTs(false)
|
---|
1079 | if !ok {
|
---|
1080 | return fmt.Errorf("unexpected RPL_LISTEND: no matching pending LIST")
|
---|
1081 | }
|
---|
1082 | case irc.RPL_NAMREPLY:
|
---|
1083 | var name, statusStr, members string
|
---|
1084 | if err := parseMessageParams(msg, nil, &statusStr, &name, &members); err != nil {
|
---|
1085 | return err
|
---|
1086 | }
|
---|
1087 |
|
---|
1088 | ch := uc.channels.Value(name)
|
---|
1089 | if ch == nil {
|
---|
1090 | // NAMES on a channel we have not joined, forward to downstream
|
---|
1091 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1092 | channel := dc.marshalEntity(uc.network, name)
|
---|
1093 | members := splitSpace(members)
|
---|
1094 | for i, member := range members {
|
---|
1095 | memberships, nick := uc.parseMembershipPrefix(member)
|
---|
1096 | members[i] = memberships.Format(dc) + dc.marshalEntity(uc.network, nick)
|
---|
1097 | }
|
---|
1098 | memberStr := strings.Join(members, " ")
|
---|
1099 |
|
---|
1100 | dc.SendMessage(&irc.Message{
|
---|
1101 | Prefix: dc.srv.prefix(),
|
---|
1102 | Command: irc.RPL_NAMREPLY,
|
---|
1103 | Params: []string{dc.nick, statusStr, channel, memberStr},
|
---|
1104 | })
|
---|
1105 | })
|
---|
1106 | return nil
|
---|
1107 | }
|
---|
1108 |
|
---|
1109 | status, err := parseChannelStatus(statusStr)
|
---|
1110 | if err != nil {
|
---|
1111 | return err
|
---|
1112 | }
|
---|
1113 | ch.Status = status
|
---|
1114 |
|
---|
1115 | for _, s := range splitSpace(members) {
|
---|
1116 | memberships, nick := uc.parseMembershipPrefix(s)
|
---|
1117 | ch.Members.SetValue(nick, memberships)
|
---|
1118 | }
|
---|
1119 | case irc.RPL_ENDOFNAMES:
|
---|
1120 | var name string
|
---|
1121 | if err := parseMessageParams(msg, nil, &name); err != nil {
|
---|
1122 | return err
|
---|
1123 | }
|
---|
1124 |
|
---|
1125 | ch := uc.channels.Value(name)
|
---|
1126 | if ch == nil {
|
---|
1127 | // NAMES on a channel we have not joined, forward to downstream
|
---|
1128 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1129 | channel := dc.marshalEntity(uc.network, name)
|
---|
1130 |
|
---|
1131 | dc.SendMessage(&irc.Message{
|
---|
1132 | Prefix: dc.srv.prefix(),
|
---|
1133 | Command: irc.RPL_ENDOFNAMES,
|
---|
1134 | Params: []string{dc.nick, channel, "End of /NAMES list"},
|
---|
1135 | })
|
---|
1136 | })
|
---|
1137 | return nil
|
---|
1138 | }
|
---|
1139 |
|
---|
1140 | if ch.complete {
|
---|
1141 | return fmt.Errorf("received unexpected RPL_ENDOFNAMES")
|
---|
1142 | }
|
---|
1143 | ch.complete = true
|
---|
1144 |
|
---|
1145 | c := uc.network.channels.Value(name)
|
---|
1146 | if c == nil || !c.Detached {
|
---|
1147 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1148 | forwardChannel(dc, ch)
|
---|
1149 | })
|
---|
1150 | }
|
---|
1151 | case irc.RPL_WHOREPLY:
|
---|
1152 | var channel, username, host, server, nick, mode, trailing string
|
---|
1153 | if err := parseMessageParams(msg, nil, &channel, &username, &host, &server, &nick, &mode, &trailing); err != nil {
|
---|
1154 | return err
|
---|
1155 | }
|
---|
1156 |
|
---|
1157 | parts := strings.SplitN(trailing, " ", 2)
|
---|
1158 | if len(parts) != 2 {
|
---|
1159 | return fmt.Errorf("received malformed RPL_WHOREPLY: wrong trailing parameter: %s", trailing)
|
---|
1160 | }
|
---|
1161 | realname := parts[1]
|
---|
1162 | hops, err := strconv.Atoi(parts[0])
|
---|
1163 | if err != nil {
|
---|
1164 | return fmt.Errorf("received malformed RPL_WHOREPLY: wrong hop count: %s", parts[0])
|
---|
1165 | }
|
---|
1166 | hops++
|
---|
1167 |
|
---|
1168 | trailing = strconv.Itoa(hops) + " " + realname
|
---|
1169 |
|
---|
1170 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1171 | channel := channel
|
---|
1172 | if channel != "*" {
|
---|
1173 | channel = dc.marshalEntity(uc.network, channel)
|
---|
1174 | }
|
---|
1175 | nick := dc.marshalEntity(uc.network, nick)
|
---|
1176 | dc.SendMessage(&irc.Message{
|
---|
1177 | Prefix: dc.srv.prefix(),
|
---|
1178 | Command: irc.RPL_WHOREPLY,
|
---|
1179 | Params: []string{dc.nick, channel, username, host, server, nick, mode, trailing},
|
---|
1180 | })
|
---|
1181 | })
|
---|
1182 | case irc.RPL_ENDOFWHO:
|
---|
1183 | var name string
|
---|
1184 | if err := parseMessageParams(msg, nil, &name); err != nil {
|
---|
1185 | return err
|
---|
1186 | }
|
---|
1187 |
|
---|
1188 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1189 | name := name
|
---|
1190 | if name != "*" {
|
---|
1191 | // TODO: support WHO masks
|
---|
1192 | name = dc.marshalEntity(uc.network, name)
|
---|
1193 | }
|
---|
1194 | dc.SendMessage(&irc.Message{
|
---|
1195 | Prefix: dc.srv.prefix(),
|
---|
1196 | Command: irc.RPL_ENDOFWHO,
|
---|
1197 | Params: []string{dc.nick, name, "End of /WHO list"},
|
---|
1198 | })
|
---|
1199 | })
|
---|
1200 | case irc.RPL_WHOISUSER:
|
---|
1201 | var nick, username, host, realname string
|
---|
1202 | if err := parseMessageParams(msg, nil, &nick, &username, &host, nil, &realname); err != nil {
|
---|
1203 | return err
|
---|
1204 | }
|
---|
1205 |
|
---|
1206 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1207 | nick := dc.marshalEntity(uc.network, nick)
|
---|
1208 | dc.SendMessage(&irc.Message{
|
---|
1209 | Prefix: dc.srv.prefix(),
|
---|
1210 | Command: irc.RPL_WHOISUSER,
|
---|
1211 | Params: []string{dc.nick, nick, username, host, "*", realname},
|
---|
1212 | })
|
---|
1213 | })
|
---|
1214 | case irc.RPL_WHOISSERVER:
|
---|
1215 | var nick, server, serverInfo string
|
---|
1216 | if err := parseMessageParams(msg, nil, &nick, &server, &serverInfo); err != nil {
|
---|
1217 | return err
|
---|
1218 | }
|
---|
1219 |
|
---|
1220 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1221 | nick := dc.marshalEntity(uc.network, nick)
|
---|
1222 | dc.SendMessage(&irc.Message{
|
---|
1223 | Prefix: dc.srv.prefix(),
|
---|
1224 | Command: irc.RPL_WHOISSERVER,
|
---|
1225 | Params: []string{dc.nick, nick, server, serverInfo},
|
---|
1226 | })
|
---|
1227 | })
|
---|
1228 | case irc.RPL_WHOISOPERATOR:
|
---|
1229 | var nick string
|
---|
1230 | if err := parseMessageParams(msg, nil, &nick); err != nil {
|
---|
1231 | return err
|
---|
1232 | }
|
---|
1233 |
|
---|
1234 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1235 | nick := dc.marshalEntity(uc.network, nick)
|
---|
1236 | dc.SendMessage(&irc.Message{
|
---|
1237 | Prefix: dc.srv.prefix(),
|
---|
1238 | Command: irc.RPL_WHOISOPERATOR,
|
---|
1239 | Params: []string{dc.nick, nick, "is an IRC operator"},
|
---|
1240 | })
|
---|
1241 | })
|
---|
1242 | case irc.RPL_WHOISIDLE:
|
---|
1243 | var nick string
|
---|
1244 | if err := parseMessageParams(msg, nil, &nick, nil); err != nil {
|
---|
1245 | return err
|
---|
1246 | }
|
---|
1247 |
|
---|
1248 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1249 | nick := dc.marshalEntity(uc.network, nick)
|
---|
1250 | params := []string{dc.nick, nick}
|
---|
1251 | params = append(params, msg.Params[2:]...)
|
---|
1252 | dc.SendMessage(&irc.Message{
|
---|
1253 | Prefix: dc.srv.prefix(),
|
---|
1254 | Command: irc.RPL_WHOISIDLE,
|
---|
1255 | Params: params,
|
---|
1256 | })
|
---|
1257 | })
|
---|
1258 | case irc.RPL_WHOISCHANNELS:
|
---|
1259 | var nick, channelList string
|
---|
1260 | if err := parseMessageParams(msg, nil, &nick, &channelList); err != nil {
|
---|
1261 | return err
|
---|
1262 | }
|
---|
1263 | channels := splitSpace(channelList)
|
---|
1264 |
|
---|
1265 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1266 | nick := dc.marshalEntity(uc.network, nick)
|
---|
1267 | channelList := make([]string, len(channels))
|
---|
1268 | for i, channel := range channels {
|
---|
1269 | prefix, channel := uc.parseMembershipPrefix(channel)
|
---|
1270 | channel = dc.marshalEntity(uc.network, channel)
|
---|
1271 | channelList[i] = prefix.Format(dc) + channel
|
---|
1272 | }
|
---|
1273 | channels := strings.Join(channelList, " ")
|
---|
1274 | dc.SendMessage(&irc.Message{
|
---|
1275 | Prefix: dc.srv.prefix(),
|
---|
1276 | Command: irc.RPL_WHOISCHANNELS,
|
---|
1277 | Params: []string{dc.nick, nick, channels},
|
---|
1278 | })
|
---|
1279 | })
|
---|
1280 | case irc.RPL_ENDOFWHOIS:
|
---|
1281 | var nick string
|
---|
1282 | if err := parseMessageParams(msg, nil, &nick); err != nil {
|
---|
1283 | return err
|
---|
1284 | }
|
---|
1285 |
|
---|
1286 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1287 | nick := dc.marshalEntity(uc.network, nick)
|
---|
1288 | dc.SendMessage(&irc.Message{
|
---|
1289 | Prefix: dc.srv.prefix(),
|
---|
1290 | Command: irc.RPL_ENDOFWHOIS,
|
---|
1291 | Params: []string{dc.nick, nick, "End of /WHOIS list"},
|
---|
1292 | })
|
---|
1293 | })
|
---|
1294 | case "INVITE":
|
---|
1295 | var nick, channel string
|
---|
1296 | if err := parseMessageParams(msg, &nick, &channel); err != nil {
|
---|
1297 | return err
|
---|
1298 | }
|
---|
1299 |
|
---|
1300 | weAreInvited := uc.isOurNick(nick)
|
---|
1301 |
|
---|
1302 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1303 | if !weAreInvited && !dc.caps["invite-notify"] {
|
---|
1304 | return
|
---|
1305 | }
|
---|
1306 | dc.SendMessage(&irc.Message{
|
---|
1307 | Prefix: dc.marshalUserPrefix(uc.network, msg.Prefix),
|
---|
1308 | Command: "INVITE",
|
---|
1309 | Params: []string{dc.marshalEntity(uc.network, nick), dc.marshalEntity(uc.network, channel)},
|
---|
1310 | })
|
---|
1311 | })
|
---|
1312 | case irc.RPL_INVITING:
|
---|
1313 | var nick, channel string
|
---|
1314 | if err := parseMessageParams(msg, nil, &nick, &channel); err != nil {
|
---|
1315 | return err
|
---|
1316 | }
|
---|
1317 |
|
---|
1318 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1319 | dc.SendMessage(&irc.Message{
|
---|
1320 | Prefix: dc.srv.prefix(),
|
---|
1321 | Command: irc.RPL_INVITING,
|
---|
1322 | Params: []string{dc.nick, dc.marshalEntity(uc.network, nick), dc.marshalEntity(uc.network, channel)},
|
---|
1323 | })
|
---|
1324 | })
|
---|
1325 | case irc.RPL_AWAY:
|
---|
1326 | var nick, reason string
|
---|
1327 | if err := parseMessageParams(msg, nil, &nick, &reason); err != nil {
|
---|
1328 | return err
|
---|
1329 | }
|
---|
1330 |
|
---|
1331 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1332 | dc.SendMessage(&irc.Message{
|
---|
1333 | Prefix: dc.srv.prefix(),
|
---|
1334 | Command: irc.RPL_AWAY,
|
---|
1335 | Params: []string{dc.nick, dc.marshalEntity(uc.network, nick), reason},
|
---|
1336 | })
|
---|
1337 | })
|
---|
1338 | case "AWAY":
|
---|
1339 | if msg.Prefix == nil {
|
---|
1340 | return fmt.Errorf("expected a prefix")
|
---|
1341 | }
|
---|
1342 |
|
---|
1343 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1344 | if !dc.caps["away-notify"] {
|
---|
1345 | return
|
---|
1346 | }
|
---|
1347 | dc.SendMessage(&irc.Message{
|
---|
1348 | Prefix: dc.marshalUserPrefix(uc.network, msg.Prefix),
|
---|
1349 | Command: "AWAY",
|
---|
1350 | Params: msg.Params,
|
---|
1351 | })
|
---|
1352 | })
|
---|
1353 | case irc.RPL_BANLIST, irc.RPL_INVITELIST, irc.RPL_EXCEPTLIST:
|
---|
1354 | var channel, mask string
|
---|
1355 | if err := parseMessageParams(msg, nil, &channel, &mask); err != nil {
|
---|
1356 | return err
|
---|
1357 | }
|
---|
1358 | var addNick, addTime string
|
---|
1359 | if len(msg.Params) >= 5 {
|
---|
1360 | addNick = msg.Params[3]
|
---|
1361 | addTime = msg.Params[4]
|
---|
1362 | }
|
---|
1363 |
|
---|
1364 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1365 | channel := dc.marshalEntity(uc.network, channel)
|
---|
1366 |
|
---|
1367 | var params []string
|
---|
1368 | if addNick != "" && addTime != "" {
|
---|
1369 | addNick := dc.marshalEntity(uc.network, addNick)
|
---|
1370 | params = []string{dc.nick, channel, mask, addNick, addTime}
|
---|
1371 | } else {
|
---|
1372 | params = []string{dc.nick, channel, mask}
|
---|
1373 | }
|
---|
1374 |
|
---|
1375 | dc.SendMessage(&irc.Message{
|
---|
1376 | Prefix: dc.srv.prefix(),
|
---|
1377 | Command: msg.Command,
|
---|
1378 | Params: params,
|
---|
1379 | })
|
---|
1380 | })
|
---|
1381 | case irc.RPL_ENDOFBANLIST, irc.RPL_ENDOFINVITELIST, irc.RPL_ENDOFEXCEPTLIST:
|
---|
1382 | var channel, trailing string
|
---|
1383 | if err := parseMessageParams(msg, nil, &channel, &trailing); err != nil {
|
---|
1384 | return err
|
---|
1385 | }
|
---|
1386 |
|
---|
1387 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1388 | upstreamChannel := dc.marshalEntity(uc.network, channel)
|
---|
1389 | dc.SendMessage(&irc.Message{
|
---|
1390 | Prefix: dc.srv.prefix(),
|
---|
1391 | Command: msg.Command,
|
---|
1392 | Params: []string{dc.nick, upstreamChannel, trailing},
|
---|
1393 | })
|
---|
1394 | })
|
---|
1395 | case irc.ERR_UNKNOWNCOMMAND, irc.RPL_TRYAGAIN:
|
---|
1396 | var command, reason string
|
---|
1397 | if err := parseMessageParams(msg, nil, &command, &reason); err != nil {
|
---|
1398 | return err
|
---|
1399 | }
|
---|
1400 |
|
---|
1401 | if command == "LIST" {
|
---|
1402 | ok := uc.endPendingLISTs(false)
|
---|
1403 | if !ok {
|
---|
1404 | return fmt.Errorf("unexpected response for LIST: %q: no matching pending LIST", msg.Command)
|
---|
1405 | }
|
---|
1406 | }
|
---|
1407 |
|
---|
1408 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1409 | dc.SendMessage(&irc.Message{
|
---|
1410 | Prefix: uc.srv.prefix(),
|
---|
1411 | Command: msg.Command,
|
---|
1412 | Params: []string{dc.nick, command, reason},
|
---|
1413 | })
|
---|
1414 | })
|
---|
1415 | case "ACK":
|
---|
1416 | // Ignore
|
---|
1417 | case irc.RPL_NOWAWAY, irc.RPL_UNAWAY:
|
---|
1418 | // Ignore
|
---|
1419 | case irc.RPL_YOURHOST, irc.RPL_CREATED:
|
---|
1420 | // Ignore
|
---|
1421 | case irc.RPL_LUSERCLIENT, irc.RPL_LUSEROP, irc.RPL_LUSERUNKNOWN, irc.RPL_LUSERCHANNELS, irc.RPL_LUSERME:
|
---|
1422 | // Ignore
|
---|
1423 | case irc.RPL_MOTDSTART, irc.RPL_MOTD:
|
---|
1424 | // Ignore
|
---|
1425 | case irc.RPL_LISTSTART:
|
---|
1426 | // Ignore
|
---|
1427 | case rpl_localusers, rpl_globalusers:
|
---|
1428 | // Ignore
|
---|
1429 | case irc.RPL_STATSVLINE, rpl_statsping, irc.RPL_STATSBLINE, irc.RPL_STATSDLINE:
|
---|
1430 | // Ignore
|
---|
1431 | case "ERROR":
|
---|
1432 | var text string
|
---|
1433 | if err := parseMessageParams(msg, &text); err != nil {
|
---|
1434 | return err
|
---|
1435 | }
|
---|
1436 | return fmt.Errorf("fatal server error: %v", text)
|
---|
1437 | case irc.ERR_PASSWDMISMATCH, irc.ERR_ERRONEUSNICKNAME, irc.ERR_NICKNAMEINUSE, irc.ERR_NICKCOLLISION, irc.ERR_UNAVAILRESOURCE, irc.ERR_NOPERMFORHOST, irc.ERR_YOUREBANNEDCREEP:
|
---|
1438 | if !uc.registered {
|
---|
1439 | text := msg.Params[len(msg.Params)-1]
|
---|
1440 | return registrationError(text)
|
---|
1441 | }
|
---|
1442 | fallthrough
|
---|
1443 | default:
|
---|
1444 | uc.logger.Printf("unhandled message: %v", msg)
|
---|
1445 |
|
---|
1446 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1447 | // best effort marshaling for unknown messages, replies and errors:
|
---|
1448 | // most numerics start with the user nick, marshal it if that's the case
|
---|
1449 | // otherwise, conservately keep the params without marshaling
|
---|
1450 | params := msg.Params
|
---|
1451 | if _, err := strconv.Atoi(msg.Command); err == nil { // numeric
|
---|
1452 | if len(msg.Params) > 0 && isOurNick(uc.network, msg.Params[0]) {
|
---|
1453 | params[0] = dc.nick
|
---|
1454 | }
|
---|
1455 | }
|
---|
1456 | dc.SendMessage(&irc.Message{
|
---|
1457 | Prefix: uc.srv.prefix(),
|
---|
1458 | Command: msg.Command,
|
---|
1459 | Params: params,
|
---|
1460 | })
|
---|
1461 | })
|
---|
1462 | }
|
---|
1463 | return nil
|
---|
1464 | }
|
---|
1465 |
|
---|
1466 | func (uc *upstreamConn) handleDetachedMessage(ch *Channel, msg *irc.Message) {
|
---|
1467 | if uc.network.detachedMessageNeedsRelay(ch, msg) {
|
---|
1468 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1469 | dc.relayDetachedMessage(uc.network, msg)
|
---|
1470 | })
|
---|
1471 | }
|
---|
1472 | if ch.ReattachOn == FilterMessage || (ch.ReattachOn == FilterHighlight && uc.network.isHighlight(msg)) {
|
---|
1473 | uc.network.attach(ch)
|
---|
1474 | if err := uc.srv.db.StoreChannel(uc.network.ID, ch); err != nil {
|
---|
1475 | uc.logger.Printf("failed to update channel %q: %v", ch.Name, err)
|
---|
1476 | }
|
---|
1477 | }
|
---|
1478 | }
|
---|
1479 |
|
---|
1480 | func (uc *upstreamConn) handleChanModes(s string) error {
|
---|
1481 | parts := strings.SplitN(s, ",", 5)
|
---|
1482 | if len(parts) < 4 {
|
---|
1483 | return fmt.Errorf("malformed ISUPPORT CHANMODES value: %v", s)
|
---|
1484 | }
|
---|
1485 | modes := make(map[byte]channelModeType)
|
---|
1486 | for i, mt := range []channelModeType{modeTypeA, modeTypeB, modeTypeC, modeTypeD} {
|
---|
1487 | for j := 0; j < len(parts[i]); j++ {
|
---|
1488 | mode := parts[i][j]
|
---|
1489 | modes[mode] = mt
|
---|
1490 | }
|
---|
1491 | }
|
---|
1492 | uc.availableChannelModes = modes
|
---|
1493 | return nil
|
---|
1494 | }
|
---|
1495 |
|
---|
1496 | func (uc *upstreamConn) handleMemberships(s string) error {
|
---|
1497 | if s == "" {
|
---|
1498 | uc.availableMemberships = nil
|
---|
1499 | return nil
|
---|
1500 | }
|
---|
1501 |
|
---|
1502 | if s[0] != '(' {
|
---|
1503 | return fmt.Errorf("malformed ISUPPORT PREFIX value: %v", s)
|
---|
1504 | }
|
---|
1505 | sep := strings.IndexByte(s, ')')
|
---|
1506 | if sep < 0 || len(s) != sep*2 {
|
---|
1507 | return fmt.Errorf("malformed ISUPPORT PREFIX value: %v", s)
|
---|
1508 | }
|
---|
1509 | memberships := make([]membership, len(s)/2-1)
|
---|
1510 | for i := range memberships {
|
---|
1511 | memberships[i] = membership{
|
---|
1512 | Mode: s[i+1],
|
---|
1513 | Prefix: s[sep+i+1],
|
---|
1514 | }
|
---|
1515 | }
|
---|
1516 | uc.availableMemberships = memberships
|
---|
1517 | return nil
|
---|
1518 | }
|
---|
1519 |
|
---|
1520 | func (uc *upstreamConn) handleSupportedCaps(capsStr string) {
|
---|
1521 | caps := strings.Fields(capsStr)
|
---|
1522 | for _, s := range caps {
|
---|
1523 | kv := strings.SplitN(s, "=", 2)
|
---|
1524 | k := strings.ToLower(kv[0])
|
---|
1525 | var v string
|
---|
1526 | if len(kv) == 2 {
|
---|
1527 | v = kv[1]
|
---|
1528 | }
|
---|
1529 | uc.supportedCaps[k] = v
|
---|
1530 | }
|
---|
1531 | }
|
---|
1532 |
|
---|
1533 | func (uc *upstreamConn) requestCaps() {
|
---|
1534 | var requestCaps []string
|
---|
1535 | for c := range permanentUpstreamCaps {
|
---|
1536 | if _, ok := uc.supportedCaps[c]; ok && !uc.caps[c] {
|
---|
1537 | requestCaps = append(requestCaps, c)
|
---|
1538 | }
|
---|
1539 | }
|
---|
1540 |
|
---|
1541 | if uc.requestSASL() && !uc.caps["sasl"] {
|
---|
1542 | requestCaps = append(requestCaps, "sasl")
|
---|
1543 | }
|
---|
1544 |
|
---|
1545 | if len(requestCaps) == 0 {
|
---|
1546 | return
|
---|
1547 | }
|
---|
1548 |
|
---|
1549 | uc.SendMessage(&irc.Message{
|
---|
1550 | Command: "CAP",
|
---|
1551 | Params: []string{"REQ", strings.Join(requestCaps, " ")},
|
---|
1552 | })
|
---|
1553 | }
|
---|
1554 |
|
---|
1555 | func (uc *upstreamConn) requestSASL() bool {
|
---|
1556 | if uc.network.SASL.Mechanism == "" {
|
---|
1557 | return false
|
---|
1558 | }
|
---|
1559 |
|
---|
1560 | v, ok := uc.supportedCaps["sasl"]
|
---|
1561 | if !ok {
|
---|
1562 | return false
|
---|
1563 | }
|
---|
1564 | if v != "" {
|
---|
1565 | mechanisms := strings.Split(v, ",")
|
---|
1566 | found := false
|
---|
1567 | for _, mech := range mechanisms {
|
---|
1568 | if strings.EqualFold(mech, uc.network.SASL.Mechanism) {
|
---|
1569 | found = true
|
---|
1570 | break
|
---|
1571 | }
|
---|
1572 | }
|
---|
1573 | if !found {
|
---|
1574 | return false
|
---|
1575 | }
|
---|
1576 | }
|
---|
1577 |
|
---|
1578 | return true
|
---|
1579 | }
|
---|
1580 |
|
---|
1581 | func (uc *upstreamConn) handleCapAck(name string, ok bool) error {
|
---|
1582 | uc.caps[name] = ok
|
---|
1583 |
|
---|
1584 | switch name {
|
---|
1585 | case "sasl":
|
---|
1586 | if !ok {
|
---|
1587 | uc.logger.Printf("server refused to acknowledge the SASL capability")
|
---|
1588 | return nil
|
---|
1589 | }
|
---|
1590 |
|
---|
1591 | auth := &uc.network.SASL
|
---|
1592 | switch auth.Mechanism {
|
---|
1593 | case "PLAIN":
|
---|
1594 | uc.logger.Printf("starting SASL PLAIN authentication with username %q", auth.Plain.Username)
|
---|
1595 | uc.saslClient = sasl.NewPlainClient("", auth.Plain.Username, auth.Plain.Password)
|
---|
1596 | case "EXTERNAL":
|
---|
1597 | uc.logger.Printf("starting SASL EXTERNAL authentication")
|
---|
1598 | uc.saslClient = sasl.NewExternalClient("")
|
---|
1599 | default:
|
---|
1600 | return fmt.Errorf("unsupported SASL mechanism %q", name)
|
---|
1601 | }
|
---|
1602 |
|
---|
1603 | uc.SendMessage(&irc.Message{
|
---|
1604 | Command: "AUTHENTICATE",
|
---|
1605 | Params: []string{auth.Mechanism},
|
---|
1606 | })
|
---|
1607 | default:
|
---|
1608 | if permanentUpstreamCaps[name] {
|
---|
1609 | break
|
---|
1610 | }
|
---|
1611 | uc.logger.Printf("received CAP ACK/NAK for a cap we don't support: %v", name)
|
---|
1612 | }
|
---|
1613 | return nil
|
---|
1614 | }
|
---|
1615 |
|
---|
1616 | func splitSpace(s string) []string {
|
---|
1617 | return strings.FieldsFunc(s, func(r rune) bool {
|
---|
1618 | return r == ' '
|
---|
1619 | })
|
---|
1620 | }
|
---|
1621 |
|
---|
1622 | func (uc *upstreamConn) register() {
|
---|
1623 | uc.nick = uc.network.Nick
|
---|
1624 | uc.nickCM = uc.network.casemap(uc.nick)
|
---|
1625 | uc.username = uc.network.GetUsername()
|
---|
1626 | uc.realname = uc.network.GetRealname()
|
---|
1627 |
|
---|
1628 | uc.SendMessage(&irc.Message{
|
---|
1629 | Command: "CAP",
|
---|
1630 | Params: []string{"LS", "302"},
|
---|
1631 | })
|
---|
1632 |
|
---|
1633 | if uc.network.Pass != "" {
|
---|
1634 | uc.SendMessage(&irc.Message{
|
---|
1635 | Command: "PASS",
|
---|
1636 | Params: []string{uc.network.Pass},
|
---|
1637 | })
|
---|
1638 | }
|
---|
1639 |
|
---|
1640 | uc.SendMessage(&irc.Message{
|
---|
1641 | Command: "NICK",
|
---|
1642 | Params: []string{uc.nick},
|
---|
1643 | })
|
---|
1644 | uc.SendMessage(&irc.Message{
|
---|
1645 | Command: "USER",
|
---|
1646 | Params: []string{uc.username, "0", "*", uc.realname},
|
---|
1647 | })
|
---|
1648 | }
|
---|
1649 |
|
---|
1650 | func (uc *upstreamConn) runUntilRegistered() error {
|
---|
1651 | for !uc.registered {
|
---|
1652 | msg, err := uc.ReadMessage()
|
---|
1653 | if err != nil {
|
---|
1654 | return fmt.Errorf("failed to read message: %v", err)
|
---|
1655 | }
|
---|
1656 |
|
---|
1657 | if err := uc.handleMessage(msg); err != nil {
|
---|
1658 | if _, ok := err.(registrationError); ok {
|
---|
1659 | return err
|
---|
1660 | } else {
|
---|
1661 | msg.Tags = nil // prevent message tags from cluttering logs
|
---|
1662 | return fmt.Errorf("failed to handle message %q: %v", msg, err)
|
---|
1663 | }
|
---|
1664 | }
|
---|
1665 | }
|
---|
1666 |
|
---|
1667 | for _, command := range uc.network.ConnectCommands {
|
---|
1668 | m, err := irc.ParseMessage(command)
|
---|
1669 | if err != nil {
|
---|
1670 | uc.logger.Printf("failed to parse connect command %q: %v", command, err)
|
---|
1671 | } else {
|
---|
1672 | uc.SendMessage(m)
|
---|
1673 | }
|
---|
1674 | }
|
---|
1675 |
|
---|
1676 | return nil
|
---|
1677 | }
|
---|
1678 |
|
---|
1679 | func (uc *upstreamConn) readMessages(ch chan<- event) error {
|
---|
1680 | for {
|
---|
1681 | msg, err := uc.ReadMessage()
|
---|
1682 | if err == io.EOF {
|
---|
1683 | break
|
---|
1684 | } else if err != nil {
|
---|
1685 | return fmt.Errorf("failed to read IRC command: %v", err)
|
---|
1686 | }
|
---|
1687 |
|
---|
1688 | ch <- eventUpstreamMessage{msg, uc}
|
---|
1689 | }
|
---|
1690 |
|
---|
1691 | return nil
|
---|
1692 | }
|
---|
1693 |
|
---|
1694 | func (uc *upstreamConn) SendMessage(msg *irc.Message) {
|
---|
1695 | if !uc.caps["message-tags"] {
|
---|
1696 | msg = msg.Copy()
|
---|
1697 | msg.Tags = nil
|
---|
1698 | }
|
---|
1699 |
|
---|
1700 | uc.conn.SendMessage(msg)
|
---|
1701 | }
|
---|
1702 |
|
---|
1703 | func (uc *upstreamConn) SendMessageLabeled(downstreamID uint64, msg *irc.Message) {
|
---|
1704 | if uc.caps["labeled-response"] {
|
---|
1705 | if msg.Tags == nil {
|
---|
1706 | msg.Tags = make(map[string]irc.TagValue)
|
---|
1707 | }
|
---|
1708 | msg.Tags["label"] = irc.TagValue(fmt.Sprintf("sd-%d-%d", downstreamID, uc.nextLabelID))
|
---|
1709 | uc.nextLabelID++
|
---|
1710 | }
|
---|
1711 | uc.SendMessage(msg)
|
---|
1712 | }
|
---|
1713 |
|
---|
1714 | // appendLog appends a message to the log file.
|
---|
1715 | //
|
---|
1716 | // The internal message ID is returned. If the message isn't recorded in the
|
---|
1717 | // log file, an empty string is returned.
|
---|
1718 | func (uc *upstreamConn) appendLog(entity string, msg *irc.Message) (msgID string) {
|
---|
1719 | if uc.user.msgStore == nil {
|
---|
1720 | return ""
|
---|
1721 | }
|
---|
1722 |
|
---|
1723 | entityCM := uc.network.casemap(entity)
|
---|
1724 | if entityCM == "nickserv" {
|
---|
1725 | // The messages sent/received from NickServ may contain
|
---|
1726 | // security-related information (like passwords). Don't store these.
|
---|
1727 | return ""
|
---|
1728 | }
|
---|
1729 |
|
---|
1730 | if !uc.network.delivered.HasTarget(entity) {
|
---|
1731 | // This is the first message we receive from this target. Save the last
|
---|
1732 | // message ID in delivery receipts, so that we can send the new message
|
---|
1733 | // in the backlog if an offline client reconnects.
|
---|
1734 | lastID, err := uc.user.msgStore.LastMsgID(uc.network, entityCM, time.Now())
|
---|
1735 | if err != nil {
|
---|
1736 | uc.logger.Printf("failed to log message: failed to get last message ID: %v", err)
|
---|
1737 | return ""
|
---|
1738 | }
|
---|
1739 |
|
---|
1740 | uc.network.delivered.ForEachClient(func(clientName string) {
|
---|
1741 | uc.network.delivered.StoreID(entity, clientName, lastID)
|
---|
1742 | })
|
---|
1743 | }
|
---|
1744 |
|
---|
1745 | msgID, err := uc.user.msgStore.Append(uc.network, entityCM, msg)
|
---|
1746 | if err != nil {
|
---|
1747 | uc.logger.Printf("failed to log message: %v", err)
|
---|
1748 | return ""
|
---|
1749 | }
|
---|
1750 |
|
---|
1751 | return msgID
|
---|
1752 | }
|
---|
1753 |
|
---|
1754 | // produce appends a message to the logs and forwards it to connected downstream
|
---|
1755 | // connections.
|
---|
1756 | //
|
---|
1757 | // If origin is not nil and origin doesn't support echo-message, the message is
|
---|
1758 | // forwarded to all connections except origin.
|
---|
1759 | func (uc *upstreamConn) produce(target string, msg *irc.Message, origin *downstreamConn) {
|
---|
1760 | var msgID string
|
---|
1761 | if target != "" {
|
---|
1762 | msgID = uc.appendLog(target, msg)
|
---|
1763 | }
|
---|
1764 |
|
---|
1765 | // Don't forward messages if it's a detached channel
|
---|
1766 | ch := uc.network.channels.Value(target)
|
---|
1767 | detached := ch != nil && ch.Detached
|
---|
1768 |
|
---|
1769 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1770 | if !detached && (dc != origin || dc.caps["echo-message"]) {
|
---|
1771 | dc.sendMessageWithID(dc.marshalMessage(msg, uc.network), msgID)
|
---|
1772 | } else {
|
---|
1773 | dc.advanceMessageWithID(msg, msgID)
|
---|
1774 | }
|
---|
1775 | })
|
---|
1776 | }
|
---|
1777 |
|
---|
1778 | func (uc *upstreamConn) updateAway() {
|
---|
1779 | away := true
|
---|
1780 | uc.forEachDownstream(func(*downstreamConn) {
|
---|
1781 | away = false
|
---|
1782 | })
|
---|
1783 | if away == uc.away {
|
---|
1784 | return
|
---|
1785 | }
|
---|
1786 | if away {
|
---|
1787 | uc.SendMessage(&irc.Message{
|
---|
1788 | Command: "AWAY",
|
---|
1789 | Params: []string{"Auto away"},
|
---|
1790 | })
|
---|
1791 | } else {
|
---|
1792 | uc.SendMessage(&irc.Message{
|
---|
1793 | Command: "AWAY",
|
---|
1794 | })
|
---|
1795 | }
|
---|
1796 | uc.away = away
|
---|
1797 | }
|
---|
1798 |
|
---|
1799 | func (uc *upstreamConn) updateChannelAutoDetach(name string) {
|
---|
1800 | uch := uc.channels.Value(name)
|
---|
1801 | if uch == nil {
|
---|
1802 | return
|
---|
1803 | }
|
---|
1804 | ch := uc.network.channels.Value(name)
|
---|
1805 | if ch == nil || ch.Detached {
|
---|
1806 | return
|
---|
1807 | }
|
---|
1808 | uch.updateAutoDetach(ch.DetachAfter)
|
---|
1809 | }
|
---|