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