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