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