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(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 | // TODO: send response in multiple chunks if >= 400 bytes
|
---|
623 | var respStr = "+"
|
---|
624 | if len(resp) != 0 {
|
---|
625 | respStr = base64.StdEncoding.EncodeToString(resp)
|
---|
626 | }
|
---|
627 |
|
---|
628 | uc.SendMessage(ctx, &irc.Message{
|
---|
629 | Command: "AUTHENTICATE",
|
---|
630 | Params: []string{respStr},
|
---|
631 | })
|
---|
632 | case irc.RPL_LOGGEDIN:
|
---|
633 | if err := parseMessageParams(msg, nil, nil, &uc.account); err != nil {
|
---|
634 | return err
|
---|
635 | }
|
---|
636 | uc.logger.Printf("logged in with account %q", uc.account)
|
---|
637 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
638 | dc.updateAccount()
|
---|
639 | })
|
---|
640 | case irc.RPL_LOGGEDOUT:
|
---|
641 | uc.account = ""
|
---|
642 | uc.logger.Printf("logged out")
|
---|
643 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
644 | dc.updateAccount()
|
---|
645 | })
|
---|
646 | case irc.ERR_NICKLOCKED, irc.RPL_SASLSUCCESS, irc.ERR_SASLFAIL, irc.ERR_SASLTOOLONG, irc.ERR_SASLABORTED:
|
---|
647 | var info string
|
---|
648 | if err := parseMessageParams(msg, nil, &info); err != nil {
|
---|
649 | return err
|
---|
650 | }
|
---|
651 | switch msg.Command {
|
---|
652 | case irc.ERR_NICKLOCKED:
|
---|
653 | uc.logger.Printf("invalid nick used with SASL authentication: %v", info)
|
---|
654 | case irc.ERR_SASLFAIL:
|
---|
655 | uc.logger.Printf("SASL authentication failed: %v", info)
|
---|
656 | case irc.ERR_SASLTOOLONG:
|
---|
657 | uc.logger.Printf("SASL message too long: %v", info)
|
---|
658 | }
|
---|
659 |
|
---|
660 | uc.saslClient = nil
|
---|
661 | uc.saslStarted = false
|
---|
662 |
|
---|
663 | if dc, _ := uc.dequeueCommand("AUTHENTICATE"); dc != nil && dc.sasl != nil {
|
---|
664 | if msg.Command == irc.RPL_SASLSUCCESS {
|
---|
665 | uc.network.autoSaveSASLPlain(ctx, dc.sasl.plainUsername, dc.sasl.plainPassword)
|
---|
666 | }
|
---|
667 |
|
---|
668 | dc.endSASL(msg)
|
---|
669 | }
|
---|
670 |
|
---|
671 | if !uc.registered {
|
---|
672 | uc.SendMessage(ctx, &irc.Message{
|
---|
673 | Command: "CAP",
|
---|
674 | Params: []string{"END"},
|
---|
675 | })
|
---|
676 | }
|
---|
677 | case "REGISTER", "VERIFY":
|
---|
678 | if dc, cmd := uc.dequeueCommand(msg.Command); dc != nil {
|
---|
679 | if msg.Command == "REGISTER" {
|
---|
680 | var account, password string
|
---|
681 | if err := parseMessageParams(msg, nil, &account); err != nil {
|
---|
682 | return err
|
---|
683 | }
|
---|
684 | if err := parseMessageParams(cmd, nil, nil, &password); err != nil {
|
---|
685 | return err
|
---|
686 | }
|
---|
687 | uc.network.autoSaveSASLPlain(ctx, account, password)
|
---|
688 | }
|
---|
689 |
|
---|
690 | dc.SendMessage(msg)
|
---|
691 | }
|
---|
692 | case irc.RPL_WELCOME:
|
---|
693 | if err := parseMessageParams(msg, &uc.nick); err != nil {
|
---|
694 | return err
|
---|
695 | }
|
---|
696 |
|
---|
697 | uc.registered = true
|
---|
698 | uc.nickCM = uc.network.casemap(uc.nick)
|
---|
699 | uc.logger.Printf("connection registered with nick %q", uc.nick)
|
---|
700 |
|
---|
701 | if uc.network.channels.Len() > 0 {
|
---|
702 | var channels, keys []string
|
---|
703 | for _, entry := range uc.network.channels.innerMap {
|
---|
704 | ch := entry.value.(*Channel)
|
---|
705 | channels = append(channels, ch.Name)
|
---|
706 | keys = append(keys, ch.Key)
|
---|
707 | }
|
---|
708 |
|
---|
709 | for _, msg := range join(channels, keys) {
|
---|
710 | uc.SendMessage(ctx, msg)
|
---|
711 | }
|
---|
712 | }
|
---|
713 | case irc.RPL_MYINFO:
|
---|
714 | if err := parseMessageParams(msg, nil, &uc.serverName, nil, &uc.availableUserModes, nil); err != nil {
|
---|
715 | return err
|
---|
716 | }
|
---|
717 | case irc.RPL_ISUPPORT:
|
---|
718 | if err := parseMessageParams(msg, nil, nil); err != nil {
|
---|
719 | return err
|
---|
720 | }
|
---|
721 |
|
---|
722 | var downstreamIsupport []string
|
---|
723 | for _, token := range msg.Params[1 : len(msg.Params)-1] {
|
---|
724 | parameter := token
|
---|
725 | var negate, hasValue bool
|
---|
726 | var value string
|
---|
727 | if strings.HasPrefix(token, "-") {
|
---|
728 | negate = true
|
---|
729 | token = token[1:]
|
---|
730 | } else if i := strings.IndexByte(token, '='); i >= 0 {
|
---|
731 | parameter = token[:i]
|
---|
732 | value = token[i+1:]
|
---|
733 | hasValue = true
|
---|
734 | }
|
---|
735 |
|
---|
736 | if hasValue {
|
---|
737 | uc.isupport[parameter] = &value
|
---|
738 | } else if !negate {
|
---|
739 | uc.isupport[parameter] = nil
|
---|
740 | } else {
|
---|
741 | delete(uc.isupport, parameter)
|
---|
742 | }
|
---|
743 |
|
---|
744 | var err error
|
---|
745 | switch parameter {
|
---|
746 | case "CASEMAPPING":
|
---|
747 | casemap, ok := parseCasemappingToken(value)
|
---|
748 | if !ok {
|
---|
749 | casemap = casemapRFC1459
|
---|
750 | }
|
---|
751 | uc.network.updateCasemapping(casemap)
|
---|
752 | uc.nickCM = uc.network.casemap(uc.nick)
|
---|
753 | uc.casemapIsSet = true
|
---|
754 | case "CHANMODES":
|
---|
755 | if !negate {
|
---|
756 | err = uc.handleChanModes(value)
|
---|
757 | } else {
|
---|
758 | uc.availableChannelModes = stdChannelModes
|
---|
759 | }
|
---|
760 | case "CHANTYPES":
|
---|
761 | if !negate {
|
---|
762 | uc.availableChannelTypes = value
|
---|
763 | } else {
|
---|
764 | uc.availableChannelTypes = stdChannelTypes
|
---|
765 | }
|
---|
766 | case "PREFIX":
|
---|
767 | if !negate {
|
---|
768 | err = uc.handleMemberships(value)
|
---|
769 | } else {
|
---|
770 | uc.availableMemberships = stdMemberships
|
---|
771 | }
|
---|
772 | }
|
---|
773 | if err != nil {
|
---|
774 | return err
|
---|
775 | }
|
---|
776 |
|
---|
777 | if passthroughIsupport[parameter] {
|
---|
778 | downstreamIsupport = append(downstreamIsupport, token)
|
---|
779 | }
|
---|
780 | }
|
---|
781 |
|
---|
782 | uc.updateMonitor()
|
---|
783 |
|
---|
784 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
785 | if dc.network == nil {
|
---|
786 | return
|
---|
787 | }
|
---|
788 | msgs := generateIsupport(dc.srv.prefix(), dc.nick, downstreamIsupport)
|
---|
789 | for _, msg := range msgs {
|
---|
790 | dc.SendMessage(msg)
|
---|
791 | }
|
---|
792 | })
|
---|
793 | case irc.ERR_NOMOTD, irc.RPL_ENDOFMOTD:
|
---|
794 | if !uc.casemapIsSet {
|
---|
795 | // upstream did not send any CASEMAPPING token, thus
|
---|
796 | // we assume it implements the old RFCs with rfc1459.
|
---|
797 | uc.casemapIsSet = true
|
---|
798 | uc.network.updateCasemapping(casemapRFC1459)
|
---|
799 | uc.nickCM = uc.network.casemap(uc.nick)
|
---|
800 | }
|
---|
801 |
|
---|
802 | if !uc.gotMotd {
|
---|
803 | // Ignore the initial MOTD upon connection, but forward
|
---|
804 | // subsequent MOTD messages downstream
|
---|
805 | uc.gotMotd = true
|
---|
806 | return nil
|
---|
807 | }
|
---|
808 |
|
---|
809 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
810 | dc.SendMessage(&irc.Message{
|
---|
811 | Prefix: uc.srv.prefix(),
|
---|
812 | Command: msg.Command,
|
---|
813 | Params: msg.Params,
|
---|
814 | })
|
---|
815 | })
|
---|
816 | case "BATCH":
|
---|
817 | var tag string
|
---|
818 | if err := parseMessageParams(msg, &tag); err != nil {
|
---|
819 | return err
|
---|
820 | }
|
---|
821 |
|
---|
822 | if strings.HasPrefix(tag, "+") {
|
---|
823 | tag = tag[1:]
|
---|
824 | if _, ok := uc.batches[tag]; ok {
|
---|
825 | return fmt.Errorf("unexpected BATCH reference tag: batch was already defined: %q", tag)
|
---|
826 | }
|
---|
827 | var batchType string
|
---|
828 | if err := parseMessageParams(msg, nil, &batchType); err != nil {
|
---|
829 | return err
|
---|
830 | }
|
---|
831 | label := label
|
---|
832 | if label == "" && msgBatch != nil {
|
---|
833 | label = msgBatch.Label
|
---|
834 | }
|
---|
835 | uc.batches[tag] = batch{
|
---|
836 | Type: batchType,
|
---|
837 | Params: msg.Params[2:],
|
---|
838 | Outer: msgBatch,
|
---|
839 | Label: label,
|
---|
840 | }
|
---|
841 | } else if strings.HasPrefix(tag, "-") {
|
---|
842 | tag = tag[1:]
|
---|
843 | if _, ok := uc.batches[tag]; !ok {
|
---|
844 | return fmt.Errorf("unknown BATCH reference tag: %q", tag)
|
---|
845 | }
|
---|
846 | delete(uc.batches, tag)
|
---|
847 | } else {
|
---|
848 | return fmt.Errorf("unexpected BATCH reference tag: missing +/- prefix: %q", tag)
|
---|
849 | }
|
---|
850 | case "NICK":
|
---|
851 | if msg.Prefix == nil {
|
---|
852 | return fmt.Errorf("expected a prefix")
|
---|
853 | }
|
---|
854 |
|
---|
855 | var newNick string
|
---|
856 | if err := parseMessageParams(msg, &newNick); err != nil {
|
---|
857 | return err
|
---|
858 | }
|
---|
859 |
|
---|
860 | me := false
|
---|
861 | if uc.isOurNick(msg.Prefix.Name) {
|
---|
862 | uc.logger.Printf("changed nick from %q to %q", uc.nick, newNick)
|
---|
863 | me = true
|
---|
864 | uc.nick = newNick
|
---|
865 | uc.nickCM = uc.network.casemap(uc.nick)
|
---|
866 | }
|
---|
867 |
|
---|
868 | for _, entry := range uc.channels.innerMap {
|
---|
869 | ch := entry.value.(*upstreamChannel)
|
---|
870 | memberships := ch.Members.Value(msg.Prefix.Name)
|
---|
871 | if memberships != nil {
|
---|
872 | ch.Members.Delete(msg.Prefix.Name)
|
---|
873 | ch.Members.SetValue(newNick, memberships)
|
---|
874 | uc.appendLog(ch.Name, msg)
|
---|
875 | }
|
---|
876 | }
|
---|
877 |
|
---|
878 | if !me {
|
---|
879 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
880 | dc.SendMessage(dc.marshalMessage(msg, uc.network))
|
---|
881 | })
|
---|
882 | } else {
|
---|
883 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
884 | dc.updateNick()
|
---|
885 | })
|
---|
886 | uc.updateMonitor()
|
---|
887 | }
|
---|
888 | case "SETNAME":
|
---|
889 | if msg.Prefix == nil {
|
---|
890 | return fmt.Errorf("expected a prefix")
|
---|
891 | }
|
---|
892 |
|
---|
893 | var newRealname string
|
---|
894 | if err := parseMessageParams(msg, &newRealname); err != nil {
|
---|
895 | return err
|
---|
896 | }
|
---|
897 |
|
---|
898 | // TODO: consider appending this message to logs
|
---|
899 |
|
---|
900 | if uc.isOurNick(msg.Prefix.Name) {
|
---|
901 | uc.logger.Printf("changed realname from %q to %q", uc.realname, newRealname)
|
---|
902 | uc.realname = newRealname
|
---|
903 |
|
---|
904 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
905 | dc.updateRealname()
|
---|
906 | })
|
---|
907 | } else {
|
---|
908 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
909 | dc.SendMessage(dc.marshalMessage(msg, uc.network))
|
---|
910 | })
|
---|
911 | }
|
---|
912 | case "JOIN":
|
---|
913 | if msg.Prefix == nil {
|
---|
914 | return fmt.Errorf("expected a prefix")
|
---|
915 | }
|
---|
916 |
|
---|
917 | var channels string
|
---|
918 | if err := parseMessageParams(msg, &channels); err != nil {
|
---|
919 | return err
|
---|
920 | }
|
---|
921 |
|
---|
922 | for _, ch := range strings.Split(channels, ",") {
|
---|
923 | if uc.isOurNick(msg.Prefix.Name) {
|
---|
924 | uc.logger.Printf("joined channel %q", ch)
|
---|
925 | members := membershipsCasemapMap{newCasemapMap(0)}
|
---|
926 | members.casemap = uc.network.casemap
|
---|
927 | uc.channels.SetValue(ch, &upstreamChannel{
|
---|
928 | Name: ch,
|
---|
929 | conn: uc,
|
---|
930 | Members: members,
|
---|
931 | })
|
---|
932 | uc.updateChannelAutoDetach(ch)
|
---|
933 |
|
---|
934 | uc.SendMessage(ctx, &irc.Message{
|
---|
935 | Command: "MODE",
|
---|
936 | Params: []string{ch},
|
---|
937 | })
|
---|
938 | } else {
|
---|
939 | ch, err := uc.getChannel(ch)
|
---|
940 | if err != nil {
|
---|
941 | return err
|
---|
942 | }
|
---|
943 | ch.Members.SetValue(msg.Prefix.Name, &memberships{})
|
---|
944 | }
|
---|
945 |
|
---|
946 | chMsg := msg.Copy()
|
---|
947 | chMsg.Params[0] = ch
|
---|
948 | uc.produce(ch, chMsg, nil)
|
---|
949 | }
|
---|
950 | case "PART":
|
---|
951 | if msg.Prefix == nil {
|
---|
952 | return fmt.Errorf("expected a prefix")
|
---|
953 | }
|
---|
954 |
|
---|
955 | var channels string
|
---|
956 | if err := parseMessageParams(msg, &channels); err != nil {
|
---|
957 | return err
|
---|
958 | }
|
---|
959 |
|
---|
960 | for _, ch := range strings.Split(channels, ",") {
|
---|
961 | if uc.isOurNick(msg.Prefix.Name) {
|
---|
962 | uc.logger.Printf("parted channel %q", ch)
|
---|
963 | uch := uc.channels.Value(ch)
|
---|
964 | if uch != nil {
|
---|
965 | uc.channels.Delete(ch)
|
---|
966 | uch.updateAutoDetach(0)
|
---|
967 | }
|
---|
968 | } else {
|
---|
969 | ch, err := uc.getChannel(ch)
|
---|
970 | if err != nil {
|
---|
971 | return err
|
---|
972 | }
|
---|
973 | ch.Members.Delete(msg.Prefix.Name)
|
---|
974 | }
|
---|
975 |
|
---|
976 | chMsg := msg.Copy()
|
---|
977 | chMsg.Params[0] = ch
|
---|
978 | uc.produce(ch, chMsg, nil)
|
---|
979 | }
|
---|
980 | case "KICK":
|
---|
981 | if msg.Prefix == nil {
|
---|
982 | return fmt.Errorf("expected a prefix")
|
---|
983 | }
|
---|
984 |
|
---|
985 | var channel, user string
|
---|
986 | if err := parseMessageParams(msg, &channel, &user); err != nil {
|
---|
987 | return err
|
---|
988 | }
|
---|
989 |
|
---|
990 | if uc.isOurNick(user) {
|
---|
991 | uc.logger.Printf("kicked from channel %q by %s", channel, msg.Prefix.Name)
|
---|
992 | uc.channels.Delete(channel)
|
---|
993 | } else {
|
---|
994 | ch, err := uc.getChannel(channel)
|
---|
995 | if err != nil {
|
---|
996 | return err
|
---|
997 | }
|
---|
998 | ch.Members.Delete(user)
|
---|
999 | }
|
---|
1000 |
|
---|
1001 | uc.produce(channel, msg, nil)
|
---|
1002 | case "QUIT":
|
---|
1003 | if msg.Prefix == nil {
|
---|
1004 | return fmt.Errorf("expected a prefix")
|
---|
1005 | }
|
---|
1006 |
|
---|
1007 | if uc.isOurNick(msg.Prefix.Name) {
|
---|
1008 | uc.logger.Printf("quit")
|
---|
1009 | }
|
---|
1010 |
|
---|
1011 | for _, entry := range uc.channels.innerMap {
|
---|
1012 | ch := entry.value.(*upstreamChannel)
|
---|
1013 | if ch.Members.Has(msg.Prefix.Name) {
|
---|
1014 | ch.Members.Delete(msg.Prefix.Name)
|
---|
1015 |
|
---|
1016 | uc.appendLog(ch.Name, msg)
|
---|
1017 | }
|
---|
1018 | }
|
---|
1019 |
|
---|
1020 | if msg.Prefix.Name != uc.nick {
|
---|
1021 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1022 | dc.SendMessage(dc.marshalMessage(msg, uc.network))
|
---|
1023 | })
|
---|
1024 | }
|
---|
1025 | case irc.RPL_TOPIC, irc.RPL_NOTOPIC:
|
---|
1026 | var name, topic string
|
---|
1027 | if err := parseMessageParams(msg, nil, &name, &topic); err != nil {
|
---|
1028 | return err
|
---|
1029 | }
|
---|
1030 | ch, err := uc.getChannel(name)
|
---|
1031 | if err != nil {
|
---|
1032 | return err
|
---|
1033 | }
|
---|
1034 | if msg.Command == irc.RPL_TOPIC {
|
---|
1035 | ch.Topic = topic
|
---|
1036 | } else {
|
---|
1037 | ch.Topic = ""
|
---|
1038 | }
|
---|
1039 | case "TOPIC":
|
---|
1040 | if msg.Prefix == nil {
|
---|
1041 | return fmt.Errorf("expected a prefix")
|
---|
1042 | }
|
---|
1043 |
|
---|
1044 | var name string
|
---|
1045 | if err := parseMessageParams(msg, &name); err != nil {
|
---|
1046 | return err
|
---|
1047 | }
|
---|
1048 | ch, err := uc.getChannel(name)
|
---|
1049 | if err != nil {
|
---|
1050 | return err
|
---|
1051 | }
|
---|
1052 | if len(msg.Params) > 1 {
|
---|
1053 | ch.Topic = msg.Params[1]
|
---|
1054 | ch.TopicWho = msg.Prefix.Copy()
|
---|
1055 | ch.TopicTime = time.Now() // TODO use msg.Tags["time"]
|
---|
1056 | } else {
|
---|
1057 | ch.Topic = ""
|
---|
1058 | }
|
---|
1059 | uc.produce(ch.Name, msg, nil)
|
---|
1060 | case "MODE":
|
---|
1061 | var name, modeStr string
|
---|
1062 | if err := parseMessageParams(msg, &name, &modeStr); err != nil {
|
---|
1063 | return err
|
---|
1064 | }
|
---|
1065 |
|
---|
1066 | if !uc.isChannel(name) { // user mode change
|
---|
1067 | if name != uc.nick {
|
---|
1068 | return fmt.Errorf("received MODE message for unknown nick %q", name)
|
---|
1069 | }
|
---|
1070 |
|
---|
1071 | if err := uc.modes.Apply(modeStr); err != nil {
|
---|
1072 | return err
|
---|
1073 | }
|
---|
1074 |
|
---|
1075 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1076 | if dc.upstream() == nil {
|
---|
1077 | return
|
---|
1078 | }
|
---|
1079 |
|
---|
1080 | dc.SendMessage(msg)
|
---|
1081 | })
|
---|
1082 | } else { // channel mode change
|
---|
1083 | ch, err := uc.getChannel(name)
|
---|
1084 | if err != nil {
|
---|
1085 | return err
|
---|
1086 | }
|
---|
1087 |
|
---|
1088 | needMarshaling, err := applyChannelModes(ch, modeStr, msg.Params[2:])
|
---|
1089 | if err != nil {
|
---|
1090 | return err
|
---|
1091 | }
|
---|
1092 |
|
---|
1093 | uc.appendLog(ch.Name, msg)
|
---|
1094 |
|
---|
1095 | c := uc.network.channels.Value(name)
|
---|
1096 | if c == nil || !c.Detached {
|
---|
1097 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1098 | params := make([]string, len(msg.Params))
|
---|
1099 | params[0] = dc.marshalEntity(uc.network, name)
|
---|
1100 | params[1] = modeStr
|
---|
1101 |
|
---|
1102 | copy(params[2:], msg.Params[2:])
|
---|
1103 | for i, modeParam := range params[2:] {
|
---|
1104 | if _, ok := needMarshaling[i]; ok {
|
---|
1105 | params[2+i] = dc.marshalEntity(uc.network, modeParam)
|
---|
1106 | }
|
---|
1107 | }
|
---|
1108 |
|
---|
1109 | dc.SendMessage(&irc.Message{
|
---|
1110 | Prefix: dc.marshalUserPrefix(uc.network, msg.Prefix),
|
---|
1111 | Command: "MODE",
|
---|
1112 | Params: params,
|
---|
1113 | })
|
---|
1114 | })
|
---|
1115 | }
|
---|
1116 | }
|
---|
1117 | case irc.RPL_UMODEIS:
|
---|
1118 | if err := parseMessageParams(msg, nil); err != nil {
|
---|
1119 | return err
|
---|
1120 | }
|
---|
1121 | modeStr := ""
|
---|
1122 | if len(msg.Params) > 1 {
|
---|
1123 | modeStr = msg.Params[1]
|
---|
1124 | }
|
---|
1125 |
|
---|
1126 | uc.modes = ""
|
---|
1127 | if err := uc.modes.Apply(modeStr); err != nil {
|
---|
1128 | return err
|
---|
1129 | }
|
---|
1130 |
|
---|
1131 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1132 | if dc.upstream() == nil {
|
---|
1133 | return
|
---|
1134 | }
|
---|
1135 |
|
---|
1136 | dc.SendMessage(msg)
|
---|
1137 | })
|
---|
1138 | case irc.RPL_CHANNELMODEIS:
|
---|
1139 | var channel string
|
---|
1140 | if err := parseMessageParams(msg, nil, &channel); err != nil {
|
---|
1141 | return err
|
---|
1142 | }
|
---|
1143 | modeStr := ""
|
---|
1144 | if len(msg.Params) > 2 {
|
---|
1145 | modeStr = msg.Params[2]
|
---|
1146 | }
|
---|
1147 |
|
---|
1148 | ch, err := uc.getChannel(channel)
|
---|
1149 | if err != nil {
|
---|
1150 | return err
|
---|
1151 | }
|
---|
1152 |
|
---|
1153 | firstMode := ch.modes == nil
|
---|
1154 | ch.modes = make(map[byte]string)
|
---|
1155 | if _, err := applyChannelModes(ch, modeStr, msg.Params[3:]); err != nil {
|
---|
1156 | return err
|
---|
1157 | }
|
---|
1158 | if firstMode {
|
---|
1159 | c := uc.network.channels.Value(channel)
|
---|
1160 | if c == nil || !c.Detached {
|
---|
1161 | modeStr, modeParams := ch.modes.Format()
|
---|
1162 |
|
---|
1163 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1164 | params := []string{dc.nick, dc.marshalEntity(uc.network, channel), modeStr}
|
---|
1165 | params = append(params, modeParams...)
|
---|
1166 |
|
---|
1167 | dc.SendMessage(&irc.Message{
|
---|
1168 | Prefix: dc.srv.prefix(),
|
---|
1169 | Command: irc.RPL_CHANNELMODEIS,
|
---|
1170 | Params: params,
|
---|
1171 | })
|
---|
1172 | })
|
---|
1173 | }
|
---|
1174 | }
|
---|
1175 | case rpl_creationtime:
|
---|
1176 | var channel, creationTime string
|
---|
1177 | if err := parseMessageParams(msg, nil, &channel, &creationTime); err != nil {
|
---|
1178 | return err
|
---|
1179 | }
|
---|
1180 |
|
---|
1181 | ch, err := uc.getChannel(channel)
|
---|
1182 | if err != nil {
|
---|
1183 | return err
|
---|
1184 | }
|
---|
1185 |
|
---|
1186 | firstCreationTime := ch.creationTime == ""
|
---|
1187 | ch.creationTime = creationTime
|
---|
1188 | if firstCreationTime {
|
---|
1189 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1190 | dc.SendMessage(&irc.Message{
|
---|
1191 | Prefix: dc.srv.prefix(),
|
---|
1192 | Command: rpl_creationtime,
|
---|
1193 | Params: []string{dc.nick, dc.marshalEntity(uc.network, ch.Name), creationTime},
|
---|
1194 | })
|
---|
1195 | })
|
---|
1196 | }
|
---|
1197 | case rpl_topicwhotime:
|
---|
1198 | var name, who, timeStr string
|
---|
1199 | if err := parseMessageParams(msg, nil, &name, &who, &timeStr); err != nil {
|
---|
1200 | return err
|
---|
1201 | }
|
---|
1202 | ch, err := uc.getChannel(name)
|
---|
1203 | if err != nil {
|
---|
1204 | return err
|
---|
1205 | }
|
---|
1206 | firstTopicWhoTime := ch.TopicWho == nil
|
---|
1207 | ch.TopicWho = irc.ParsePrefix(who)
|
---|
1208 | sec, err := strconv.ParseInt(timeStr, 10, 64)
|
---|
1209 | if err != nil {
|
---|
1210 | return fmt.Errorf("failed to parse topic time: %v", err)
|
---|
1211 | }
|
---|
1212 | ch.TopicTime = time.Unix(sec, 0)
|
---|
1213 | if firstTopicWhoTime {
|
---|
1214 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1215 | topicWho := dc.marshalUserPrefix(uc.network, ch.TopicWho)
|
---|
1216 | dc.SendMessage(&irc.Message{
|
---|
1217 | Prefix: dc.srv.prefix(),
|
---|
1218 | Command: rpl_topicwhotime,
|
---|
1219 | Params: []string{
|
---|
1220 | dc.nick,
|
---|
1221 | dc.marshalEntity(uc.network, ch.Name),
|
---|
1222 | topicWho.String(),
|
---|
1223 | timeStr,
|
---|
1224 | },
|
---|
1225 | })
|
---|
1226 | })
|
---|
1227 | }
|
---|
1228 | case irc.RPL_LIST:
|
---|
1229 | var channel, clients, topic string
|
---|
1230 | if err := parseMessageParams(msg, nil, &channel, &clients, &topic); err != nil {
|
---|
1231 | return err
|
---|
1232 | }
|
---|
1233 |
|
---|
1234 | dc, cmd := uc.currentPendingCommand("LIST")
|
---|
1235 | if cmd == nil {
|
---|
1236 | return fmt.Errorf("unexpected RPL_LIST: no matching pending LIST")
|
---|
1237 | } else if dc == nil {
|
---|
1238 | return nil
|
---|
1239 | }
|
---|
1240 |
|
---|
1241 | dc.SendMessage(&irc.Message{
|
---|
1242 | Prefix: dc.srv.prefix(),
|
---|
1243 | Command: irc.RPL_LIST,
|
---|
1244 | Params: []string{dc.nick, dc.marshalEntity(uc.network, channel), clients, topic},
|
---|
1245 | })
|
---|
1246 | case irc.RPL_LISTEND:
|
---|
1247 | dc, cmd := uc.dequeueCommand("LIST")
|
---|
1248 | if cmd == nil {
|
---|
1249 | return fmt.Errorf("unexpected RPL_LISTEND: no matching pending LIST")
|
---|
1250 | } else if dc == nil {
|
---|
1251 | return nil
|
---|
1252 | }
|
---|
1253 |
|
---|
1254 | dc.SendMessage(&irc.Message{
|
---|
1255 | Prefix: dc.srv.prefix(),
|
---|
1256 | Command: irc.RPL_LISTEND,
|
---|
1257 | Params: []string{dc.nick, "End of /LIST"},
|
---|
1258 | })
|
---|
1259 | case irc.RPL_NAMREPLY:
|
---|
1260 | var name, statusStr, members string
|
---|
1261 | if err := parseMessageParams(msg, nil, &statusStr, &name, &members); err != nil {
|
---|
1262 | return err
|
---|
1263 | }
|
---|
1264 |
|
---|
1265 | ch := uc.channels.Value(name)
|
---|
1266 | if ch == nil {
|
---|
1267 | // NAMES on a channel we have not joined, forward to downstream
|
---|
1268 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1269 | channel := dc.marshalEntity(uc.network, name)
|
---|
1270 | members := splitSpace(members)
|
---|
1271 | for i, member := range members {
|
---|
1272 | memberships, nick := uc.parseMembershipPrefix(member)
|
---|
1273 | members[i] = memberships.Format(dc) + dc.marshalEntity(uc.network, nick)
|
---|
1274 | }
|
---|
1275 | memberStr := strings.Join(members, " ")
|
---|
1276 |
|
---|
1277 | dc.SendMessage(&irc.Message{
|
---|
1278 | Prefix: dc.srv.prefix(),
|
---|
1279 | Command: irc.RPL_NAMREPLY,
|
---|
1280 | Params: []string{dc.nick, statusStr, channel, memberStr},
|
---|
1281 | })
|
---|
1282 | })
|
---|
1283 | return nil
|
---|
1284 | }
|
---|
1285 |
|
---|
1286 | status, err := parseChannelStatus(statusStr)
|
---|
1287 | if err != nil {
|
---|
1288 | return err
|
---|
1289 | }
|
---|
1290 | ch.Status = status
|
---|
1291 |
|
---|
1292 | for _, s := range splitSpace(members) {
|
---|
1293 | memberships, nick := uc.parseMembershipPrefix(s)
|
---|
1294 | ch.Members.SetValue(nick, memberships)
|
---|
1295 | }
|
---|
1296 | case irc.RPL_ENDOFNAMES:
|
---|
1297 | var name string
|
---|
1298 | if err := parseMessageParams(msg, nil, &name); err != nil {
|
---|
1299 | return err
|
---|
1300 | }
|
---|
1301 |
|
---|
1302 | ch := uc.channels.Value(name)
|
---|
1303 | if ch == nil {
|
---|
1304 | // NAMES on a channel we have not joined, forward to downstream
|
---|
1305 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1306 | channel := dc.marshalEntity(uc.network, name)
|
---|
1307 |
|
---|
1308 | dc.SendMessage(&irc.Message{
|
---|
1309 | Prefix: dc.srv.prefix(),
|
---|
1310 | Command: irc.RPL_ENDOFNAMES,
|
---|
1311 | Params: []string{dc.nick, channel, "End of /NAMES list"},
|
---|
1312 | })
|
---|
1313 | })
|
---|
1314 | return nil
|
---|
1315 | }
|
---|
1316 |
|
---|
1317 | if ch.complete {
|
---|
1318 | return fmt.Errorf("received unexpected RPL_ENDOFNAMES")
|
---|
1319 | }
|
---|
1320 | ch.complete = true
|
---|
1321 |
|
---|
1322 | c := uc.network.channels.Value(name)
|
---|
1323 | if c == nil || !c.Detached {
|
---|
1324 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1325 | forwardChannel(dc, ch)
|
---|
1326 | })
|
---|
1327 | }
|
---|
1328 | case irc.RPL_WHOREPLY:
|
---|
1329 | var channel, username, host, server, nick, mode, trailing string
|
---|
1330 | if err := parseMessageParams(msg, nil, &channel, &username, &host, &server, &nick, &mode, &trailing); err != nil {
|
---|
1331 | return err
|
---|
1332 | }
|
---|
1333 |
|
---|
1334 | dc, cmd := uc.currentPendingCommand("WHO")
|
---|
1335 | if cmd == nil {
|
---|
1336 | return fmt.Errorf("unexpected RPL_WHOREPLY: no matching pending WHO")
|
---|
1337 | } else if dc == nil {
|
---|
1338 | return nil
|
---|
1339 | }
|
---|
1340 |
|
---|
1341 | if channel != "*" {
|
---|
1342 | channel = dc.marshalEntity(uc.network, channel)
|
---|
1343 | }
|
---|
1344 | nick = dc.marshalEntity(uc.network, nick)
|
---|
1345 | dc.SendMessage(&irc.Message{
|
---|
1346 | Prefix: dc.srv.prefix(),
|
---|
1347 | Command: irc.RPL_WHOREPLY,
|
---|
1348 | Params: []string{dc.nick, channel, username, host, server, nick, mode, trailing},
|
---|
1349 | })
|
---|
1350 | case rpl_whospcrpl:
|
---|
1351 | dc, cmd := uc.currentPendingCommand("WHO")
|
---|
1352 | if cmd == nil {
|
---|
1353 | return fmt.Errorf("unexpected RPL_WHOSPCRPL: no matching pending WHO")
|
---|
1354 | } else if dc == nil {
|
---|
1355 | return nil
|
---|
1356 | }
|
---|
1357 |
|
---|
1358 | // Only supported in single-upstream mode, so forward as-is
|
---|
1359 | dc.SendMessage(msg)
|
---|
1360 | case irc.RPL_ENDOFWHO:
|
---|
1361 | var name string
|
---|
1362 | if err := parseMessageParams(msg, nil, &name); err != nil {
|
---|
1363 | return err
|
---|
1364 | }
|
---|
1365 |
|
---|
1366 | dc, cmd := uc.dequeueCommand("WHO")
|
---|
1367 | if cmd == nil {
|
---|
1368 | return fmt.Errorf("unexpected RPL_ENDOFWHO: no matching pending WHO")
|
---|
1369 | } else if dc == nil {
|
---|
1370 | return nil
|
---|
1371 | }
|
---|
1372 |
|
---|
1373 | mask := "*"
|
---|
1374 | if len(cmd.Params) > 0 {
|
---|
1375 | mask = cmd.Params[0]
|
---|
1376 | }
|
---|
1377 | dc.SendMessage(&irc.Message{
|
---|
1378 | Prefix: dc.srv.prefix(),
|
---|
1379 | Command: irc.RPL_ENDOFWHO,
|
---|
1380 | Params: []string{dc.nick, mask, "End of /WHO list"},
|
---|
1381 | })
|
---|
1382 | case irc.RPL_WHOISUSER:
|
---|
1383 | var nick, username, host, realname string
|
---|
1384 | if err := parseMessageParams(msg, nil, &nick, &username, &host, nil, &realname); err != nil {
|
---|
1385 | return err
|
---|
1386 | }
|
---|
1387 |
|
---|
1388 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1389 | nick := dc.marshalEntity(uc.network, nick)
|
---|
1390 | dc.SendMessage(&irc.Message{
|
---|
1391 | Prefix: dc.srv.prefix(),
|
---|
1392 | Command: irc.RPL_WHOISUSER,
|
---|
1393 | Params: []string{dc.nick, nick, username, host, "*", realname},
|
---|
1394 | })
|
---|
1395 | })
|
---|
1396 | case irc.RPL_WHOISSERVER:
|
---|
1397 | var nick, server, serverInfo string
|
---|
1398 | if err := parseMessageParams(msg, nil, &nick, &server, &serverInfo); err != nil {
|
---|
1399 | return err
|
---|
1400 | }
|
---|
1401 |
|
---|
1402 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1403 | nick := dc.marshalEntity(uc.network, nick)
|
---|
1404 | dc.SendMessage(&irc.Message{
|
---|
1405 | Prefix: dc.srv.prefix(),
|
---|
1406 | Command: irc.RPL_WHOISSERVER,
|
---|
1407 | Params: []string{dc.nick, nick, server, serverInfo},
|
---|
1408 | })
|
---|
1409 | })
|
---|
1410 | case irc.RPL_WHOISOPERATOR:
|
---|
1411 | var nick string
|
---|
1412 | if err := parseMessageParams(msg, nil, &nick); err != nil {
|
---|
1413 | return err
|
---|
1414 | }
|
---|
1415 |
|
---|
1416 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1417 | nick := dc.marshalEntity(uc.network, nick)
|
---|
1418 | dc.SendMessage(&irc.Message{
|
---|
1419 | Prefix: dc.srv.prefix(),
|
---|
1420 | Command: irc.RPL_WHOISOPERATOR,
|
---|
1421 | Params: []string{dc.nick, nick, "is an IRC operator"},
|
---|
1422 | })
|
---|
1423 | })
|
---|
1424 | case irc.RPL_WHOISIDLE:
|
---|
1425 | var nick string
|
---|
1426 | if err := parseMessageParams(msg, nil, &nick, nil); err != nil {
|
---|
1427 | return err
|
---|
1428 | }
|
---|
1429 |
|
---|
1430 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1431 | nick := dc.marshalEntity(uc.network, nick)
|
---|
1432 | params := []string{dc.nick, nick}
|
---|
1433 | params = append(params, msg.Params[2:]...)
|
---|
1434 | dc.SendMessage(&irc.Message{
|
---|
1435 | Prefix: dc.srv.prefix(),
|
---|
1436 | Command: irc.RPL_WHOISIDLE,
|
---|
1437 | Params: params,
|
---|
1438 | })
|
---|
1439 | })
|
---|
1440 | case irc.RPL_WHOISCHANNELS:
|
---|
1441 | var nick, channelList string
|
---|
1442 | if err := parseMessageParams(msg, nil, &nick, &channelList); err != nil {
|
---|
1443 | return err
|
---|
1444 | }
|
---|
1445 | channels := splitSpace(channelList)
|
---|
1446 |
|
---|
1447 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1448 | nick := dc.marshalEntity(uc.network, nick)
|
---|
1449 | channelList := make([]string, len(channels))
|
---|
1450 | for i, channel := range channels {
|
---|
1451 | prefix, channel := uc.parseMembershipPrefix(channel)
|
---|
1452 | channel = dc.marshalEntity(uc.network, channel)
|
---|
1453 | channelList[i] = prefix.Format(dc) + channel
|
---|
1454 | }
|
---|
1455 | channels := strings.Join(channelList, " ")
|
---|
1456 | dc.SendMessage(&irc.Message{
|
---|
1457 | Prefix: dc.srv.prefix(),
|
---|
1458 | Command: irc.RPL_WHOISCHANNELS,
|
---|
1459 | Params: []string{dc.nick, nick, channels},
|
---|
1460 | })
|
---|
1461 | })
|
---|
1462 | case irc.RPL_ENDOFWHOIS:
|
---|
1463 | var nick string
|
---|
1464 | if err := parseMessageParams(msg, nil, &nick); err != nil {
|
---|
1465 | return err
|
---|
1466 | }
|
---|
1467 |
|
---|
1468 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1469 | nick := dc.marshalEntity(uc.network, nick)
|
---|
1470 | dc.SendMessage(&irc.Message{
|
---|
1471 | Prefix: dc.srv.prefix(),
|
---|
1472 | Command: irc.RPL_ENDOFWHOIS,
|
---|
1473 | Params: []string{dc.nick, nick, "End of /WHOIS list"},
|
---|
1474 | })
|
---|
1475 | })
|
---|
1476 | case "INVITE":
|
---|
1477 | var nick, channel string
|
---|
1478 | if err := parseMessageParams(msg, &nick, &channel); err != nil {
|
---|
1479 | return err
|
---|
1480 | }
|
---|
1481 |
|
---|
1482 | weAreInvited := uc.isOurNick(nick)
|
---|
1483 |
|
---|
1484 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1485 | if !weAreInvited && !dc.caps["invite-notify"] {
|
---|
1486 | return
|
---|
1487 | }
|
---|
1488 | dc.SendMessage(&irc.Message{
|
---|
1489 | Prefix: dc.marshalUserPrefix(uc.network, msg.Prefix),
|
---|
1490 | Command: "INVITE",
|
---|
1491 | Params: []string{dc.marshalEntity(uc.network, nick), dc.marshalEntity(uc.network, channel)},
|
---|
1492 | })
|
---|
1493 | })
|
---|
1494 | case irc.RPL_INVITING:
|
---|
1495 | var nick, channel string
|
---|
1496 | if err := parseMessageParams(msg, nil, &nick, &channel); err != nil {
|
---|
1497 | return err
|
---|
1498 | }
|
---|
1499 |
|
---|
1500 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1501 | dc.SendMessage(&irc.Message{
|
---|
1502 | Prefix: dc.srv.prefix(),
|
---|
1503 | Command: irc.RPL_INVITING,
|
---|
1504 | Params: []string{dc.nick, dc.marshalEntity(uc.network, nick), dc.marshalEntity(uc.network, channel)},
|
---|
1505 | })
|
---|
1506 | })
|
---|
1507 | case irc.RPL_MONONLINE, irc.RPL_MONOFFLINE:
|
---|
1508 | var targetsStr string
|
---|
1509 | if err := parseMessageParams(msg, nil, &targetsStr); err != nil {
|
---|
1510 | return err
|
---|
1511 | }
|
---|
1512 | targets := strings.Split(targetsStr, ",")
|
---|
1513 |
|
---|
1514 | online := msg.Command == irc.RPL_MONONLINE
|
---|
1515 | for _, target := range targets {
|
---|
1516 | prefix := irc.ParsePrefix(target)
|
---|
1517 | uc.monitored.SetValue(prefix.Name, online)
|
---|
1518 | }
|
---|
1519 |
|
---|
1520 | // Check if the nick we want is now free
|
---|
1521 | wantNick := GetNick(&uc.user.User, &uc.network.Network)
|
---|
1522 | wantNickCM := uc.network.casemap(wantNick)
|
---|
1523 | if !online && uc.nickCM != wantNickCM {
|
---|
1524 | found := false
|
---|
1525 | for _, target := range targets {
|
---|
1526 | prefix := irc.ParsePrefix(target)
|
---|
1527 | if uc.network.casemap(prefix.Name) == wantNickCM {
|
---|
1528 | found = true
|
---|
1529 | break
|
---|
1530 | }
|
---|
1531 | }
|
---|
1532 | if found {
|
---|
1533 | uc.logger.Printf("desired nick %q is now available", wantNick)
|
---|
1534 | uc.SendMessage(ctx, &irc.Message{
|
---|
1535 | Command: "NICK",
|
---|
1536 | Params: []string{wantNick},
|
---|
1537 | })
|
---|
1538 | }
|
---|
1539 | }
|
---|
1540 |
|
---|
1541 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1542 | for _, target := range targets {
|
---|
1543 | prefix := irc.ParsePrefix(target)
|
---|
1544 | if dc.monitored.Has(prefix.Name) {
|
---|
1545 | dc.SendMessage(&irc.Message{
|
---|
1546 | Prefix: dc.srv.prefix(),
|
---|
1547 | Command: msg.Command,
|
---|
1548 | Params: []string{dc.nick, target},
|
---|
1549 | })
|
---|
1550 | }
|
---|
1551 | }
|
---|
1552 | })
|
---|
1553 | case irc.ERR_MONLISTFULL:
|
---|
1554 | var limit, targetsStr string
|
---|
1555 | if err := parseMessageParams(msg, nil, &limit, &targetsStr); err != nil {
|
---|
1556 | return err
|
---|
1557 | }
|
---|
1558 |
|
---|
1559 | targets := strings.Split(targetsStr, ",")
|
---|
1560 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1561 | for _, target := range targets {
|
---|
1562 | if dc.monitored.Has(target) {
|
---|
1563 | dc.SendMessage(&irc.Message{
|
---|
1564 | Prefix: dc.srv.prefix(),
|
---|
1565 | Command: msg.Command,
|
---|
1566 | Params: []string{dc.nick, limit, target},
|
---|
1567 | })
|
---|
1568 | }
|
---|
1569 | }
|
---|
1570 | })
|
---|
1571 | case irc.RPL_AWAY:
|
---|
1572 | var nick, reason string
|
---|
1573 | if err := parseMessageParams(msg, nil, &nick, &reason); err != nil {
|
---|
1574 | return err
|
---|
1575 | }
|
---|
1576 |
|
---|
1577 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1578 | dc.SendMessage(&irc.Message{
|
---|
1579 | Prefix: dc.srv.prefix(),
|
---|
1580 | Command: irc.RPL_AWAY,
|
---|
1581 | Params: []string{dc.nick, dc.marshalEntity(uc.network, nick), reason},
|
---|
1582 | })
|
---|
1583 | })
|
---|
1584 | case "AWAY", "ACCOUNT":
|
---|
1585 | if msg.Prefix == nil {
|
---|
1586 | return fmt.Errorf("expected a prefix")
|
---|
1587 | }
|
---|
1588 |
|
---|
1589 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1590 | dc.SendMessage(&irc.Message{
|
---|
1591 | Prefix: dc.marshalUserPrefix(uc.network, msg.Prefix),
|
---|
1592 | Command: msg.Command,
|
---|
1593 | Params: msg.Params,
|
---|
1594 | })
|
---|
1595 | })
|
---|
1596 | case irc.RPL_BANLIST, irc.RPL_INVITELIST, irc.RPL_EXCEPTLIST:
|
---|
1597 | var channel, mask string
|
---|
1598 | if err := parseMessageParams(msg, nil, &channel, &mask); err != nil {
|
---|
1599 | return err
|
---|
1600 | }
|
---|
1601 | var addNick, addTime string
|
---|
1602 | if len(msg.Params) >= 5 {
|
---|
1603 | addNick = msg.Params[3]
|
---|
1604 | addTime = msg.Params[4]
|
---|
1605 | }
|
---|
1606 |
|
---|
1607 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1608 | channel := dc.marshalEntity(uc.network, channel)
|
---|
1609 |
|
---|
1610 | var params []string
|
---|
1611 | if addNick != "" && addTime != "" {
|
---|
1612 | addNick := dc.marshalEntity(uc.network, addNick)
|
---|
1613 | params = []string{dc.nick, channel, mask, addNick, addTime}
|
---|
1614 | } else {
|
---|
1615 | params = []string{dc.nick, channel, mask}
|
---|
1616 | }
|
---|
1617 |
|
---|
1618 | dc.SendMessage(&irc.Message{
|
---|
1619 | Prefix: dc.srv.prefix(),
|
---|
1620 | Command: msg.Command,
|
---|
1621 | Params: params,
|
---|
1622 | })
|
---|
1623 | })
|
---|
1624 | case irc.RPL_ENDOFBANLIST, irc.RPL_ENDOFINVITELIST, irc.RPL_ENDOFEXCEPTLIST:
|
---|
1625 | var channel, trailing string
|
---|
1626 | if err := parseMessageParams(msg, nil, &channel, &trailing); err != nil {
|
---|
1627 | return err
|
---|
1628 | }
|
---|
1629 |
|
---|
1630 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1631 | upstreamChannel := dc.marshalEntity(uc.network, channel)
|
---|
1632 | dc.SendMessage(&irc.Message{
|
---|
1633 | Prefix: dc.srv.prefix(),
|
---|
1634 | Command: msg.Command,
|
---|
1635 | Params: []string{dc.nick, upstreamChannel, trailing},
|
---|
1636 | })
|
---|
1637 | })
|
---|
1638 | case irc.ERR_UNKNOWNCOMMAND, irc.RPL_TRYAGAIN:
|
---|
1639 | var command, reason string
|
---|
1640 | if err := parseMessageParams(msg, nil, &command, &reason); err != nil {
|
---|
1641 | return err
|
---|
1642 | }
|
---|
1643 |
|
---|
1644 | if dc, _ := uc.dequeueCommand(command); dc != nil && downstreamID == 0 {
|
---|
1645 | downstreamID = dc.id
|
---|
1646 | }
|
---|
1647 |
|
---|
1648 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1649 | dc.SendMessage(&irc.Message{
|
---|
1650 | Prefix: uc.srv.prefix(),
|
---|
1651 | Command: msg.Command,
|
---|
1652 | Params: []string{dc.nick, command, reason},
|
---|
1653 | })
|
---|
1654 | })
|
---|
1655 | case "FAIL":
|
---|
1656 | var command, code string
|
---|
1657 | if err := parseMessageParams(msg, &command, &code); err != nil {
|
---|
1658 | return err
|
---|
1659 | }
|
---|
1660 |
|
---|
1661 | if !uc.registered && command == "*" && code == "ACCOUNT_REQUIRED" {
|
---|
1662 | return registrationError{msg}
|
---|
1663 | }
|
---|
1664 |
|
---|
1665 | if dc, _ := uc.dequeueCommand(command); dc != nil && downstreamID == 0 {
|
---|
1666 | downstreamID = dc.id
|
---|
1667 | }
|
---|
1668 |
|
---|
1669 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1670 | dc.SendMessage(msg)
|
---|
1671 | })
|
---|
1672 | case "ACK":
|
---|
1673 | // Ignore
|
---|
1674 | case irc.RPL_NOWAWAY, irc.RPL_UNAWAY:
|
---|
1675 | // Ignore
|
---|
1676 | case irc.RPL_YOURHOST, irc.RPL_CREATED:
|
---|
1677 | // Ignore
|
---|
1678 | case irc.RPL_LUSERCLIENT, irc.RPL_LUSEROP, irc.RPL_LUSERUNKNOWN, irc.RPL_LUSERCHANNELS, irc.RPL_LUSERME:
|
---|
1679 | fallthrough
|
---|
1680 | case irc.RPL_STATSVLINE, rpl_statsping, irc.RPL_STATSBLINE, irc.RPL_STATSDLINE:
|
---|
1681 | fallthrough
|
---|
1682 | case rpl_localusers, rpl_globalusers:
|
---|
1683 | fallthrough
|
---|
1684 | case irc.RPL_MOTDSTART, irc.RPL_MOTD:
|
---|
1685 | // Ignore these messages if they're part of the initial registration
|
---|
1686 | // message burst. Forward them if the user explicitly asked for them.
|
---|
1687 | if !uc.gotMotd {
|
---|
1688 | return nil
|
---|
1689 | }
|
---|
1690 |
|
---|
1691 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1692 | dc.SendMessage(&irc.Message{
|
---|
1693 | Prefix: uc.srv.prefix(),
|
---|
1694 | Command: msg.Command,
|
---|
1695 | Params: msg.Params,
|
---|
1696 | })
|
---|
1697 | })
|
---|
1698 | case irc.RPL_LISTSTART:
|
---|
1699 | // Ignore
|
---|
1700 | case "ERROR":
|
---|
1701 | var text string
|
---|
1702 | if err := parseMessageParams(msg, &text); err != nil {
|
---|
1703 | return err
|
---|
1704 | }
|
---|
1705 | return fmt.Errorf("fatal server error: %v", text)
|
---|
1706 | case irc.ERR_NICKNAMEINUSE:
|
---|
1707 | // At this point, we haven't received ISUPPORT so we don't know the
|
---|
1708 | // maximum nickname length or whether the server supports MONITOR. Many
|
---|
1709 | // servers have NICKLEN=30 so let's just use that.
|
---|
1710 | if !uc.registered && len(uc.nick)+1 < 30 {
|
---|
1711 | uc.nick = uc.nick + "_"
|
---|
1712 | uc.nickCM = uc.network.casemap(uc.nick)
|
---|
1713 | uc.logger.Printf("desired nick is not available, falling back to %q", uc.nick)
|
---|
1714 | uc.SendMessage(ctx, &irc.Message{
|
---|
1715 | Command: "NICK",
|
---|
1716 | Params: []string{uc.nick},
|
---|
1717 | })
|
---|
1718 | return nil
|
---|
1719 | }
|
---|
1720 | fallthrough
|
---|
1721 | case irc.ERR_PASSWDMISMATCH, irc.ERR_ERRONEUSNICKNAME, irc.ERR_NICKCOLLISION, irc.ERR_UNAVAILRESOURCE, irc.ERR_NOPERMFORHOST, irc.ERR_YOUREBANNEDCREEP:
|
---|
1722 | if !uc.registered {
|
---|
1723 | return registrationError{msg}
|
---|
1724 | }
|
---|
1725 | fallthrough
|
---|
1726 | default:
|
---|
1727 | uc.logger.Printf("unhandled message: %v", msg)
|
---|
1728 |
|
---|
1729 | uc.forEachDownstreamByID(downstreamID, func(dc *downstreamConn) {
|
---|
1730 | // best effort marshaling for unknown messages, replies and errors:
|
---|
1731 | // most numerics start with the user nick, marshal it if that's the case
|
---|
1732 | // otherwise, conservately keep the params without marshaling
|
---|
1733 | params := msg.Params
|
---|
1734 | if _, err := strconv.Atoi(msg.Command); err == nil { // numeric
|
---|
1735 | if len(msg.Params) > 0 && isOurNick(uc.network, msg.Params[0]) {
|
---|
1736 | params[0] = dc.nick
|
---|
1737 | }
|
---|
1738 | }
|
---|
1739 | dc.SendMessage(&irc.Message{
|
---|
1740 | Prefix: uc.srv.prefix(),
|
---|
1741 | Command: msg.Command,
|
---|
1742 | Params: params,
|
---|
1743 | })
|
---|
1744 | })
|
---|
1745 | }
|
---|
1746 | return nil
|
---|
1747 | }
|
---|
1748 |
|
---|
1749 | func (uc *upstreamConn) handleDetachedMessage(ctx context.Context, ch *Channel, msg *irc.Message) {
|
---|
1750 | if uc.network.detachedMessageNeedsRelay(ch, msg) {
|
---|
1751 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
1752 | dc.relayDetachedMessage(uc.network, msg)
|
---|
1753 | })
|
---|
1754 | }
|
---|
1755 | if ch.ReattachOn == FilterMessage || (ch.ReattachOn == FilterHighlight && uc.network.isHighlight(msg)) {
|
---|
1756 | uc.network.attach(ch)
|
---|
1757 | if err := uc.srv.db.StoreChannel(ctx, uc.network.ID, ch); err != nil {
|
---|
1758 | uc.logger.Printf("failed to update channel %q: %v", ch.Name, err)
|
---|
1759 | }
|
---|
1760 | }
|
---|
1761 | }
|
---|
1762 |
|
---|
1763 | func (uc *upstreamConn) handleChanModes(s string) error {
|
---|
1764 | parts := strings.SplitN(s, ",", 5)
|
---|
1765 | if len(parts) < 4 {
|
---|
1766 | return fmt.Errorf("malformed ISUPPORT CHANMODES value: %v", s)
|
---|
1767 | }
|
---|
1768 | modes := make(map[byte]channelModeType)
|
---|
1769 | for i, mt := range []channelModeType{modeTypeA, modeTypeB, modeTypeC, modeTypeD} {
|
---|
1770 | for j := 0; j < len(parts[i]); j++ {
|
---|
1771 | mode := parts[i][j]
|
---|
1772 | modes[mode] = mt
|
---|
1773 | }
|
---|
1774 | }
|
---|
1775 | uc.availableChannelModes = modes
|
---|
1776 | return nil
|
---|
1777 | }
|
---|
1778 |
|
---|
1779 | func (uc *upstreamConn) handleMemberships(s string) error {
|
---|
1780 | if s == "" {
|
---|
1781 | uc.availableMemberships = nil
|
---|
1782 | return nil
|
---|
1783 | }
|
---|
1784 |
|
---|
1785 | if s[0] != '(' {
|
---|
1786 | return fmt.Errorf("malformed ISUPPORT PREFIX value: %v", s)
|
---|
1787 | }
|
---|
1788 | sep := strings.IndexByte(s, ')')
|
---|
1789 | if sep < 0 || len(s) != sep*2 {
|
---|
1790 | return fmt.Errorf("malformed ISUPPORT PREFIX value: %v", s)
|
---|
1791 | }
|
---|
1792 | memberships := make([]membership, len(s)/2-1)
|
---|
1793 | for i := range memberships {
|
---|
1794 | memberships[i] = membership{
|
---|
1795 | Mode: s[i+1],
|
---|
1796 | Prefix: s[sep+i+1],
|
---|
1797 | }
|
---|
1798 | }
|
---|
1799 | uc.availableMemberships = memberships
|
---|
1800 | return nil
|
---|
1801 | }
|
---|
1802 |
|
---|
1803 | func (uc *upstreamConn) handleSupportedCaps(capsStr string) {
|
---|
1804 | caps := strings.Fields(capsStr)
|
---|
1805 | for _, s := range caps {
|
---|
1806 | kv := strings.SplitN(s, "=", 2)
|
---|
1807 | k := strings.ToLower(kv[0])
|
---|
1808 | var v string
|
---|
1809 | if len(kv) == 2 {
|
---|
1810 | v = kv[1]
|
---|
1811 | }
|
---|
1812 | uc.supportedCaps[k] = v
|
---|
1813 | }
|
---|
1814 | }
|
---|
1815 |
|
---|
1816 | func (uc *upstreamConn) requestCaps() {
|
---|
1817 | var requestCaps []string
|
---|
1818 | for c := range permanentUpstreamCaps {
|
---|
1819 | if _, ok := uc.supportedCaps[c]; ok && !uc.caps[c] {
|
---|
1820 | requestCaps = append(requestCaps, c)
|
---|
1821 | }
|
---|
1822 | }
|
---|
1823 |
|
---|
1824 | if len(requestCaps) == 0 {
|
---|
1825 | return
|
---|
1826 | }
|
---|
1827 |
|
---|
1828 | uc.SendMessage(context.TODO(), &irc.Message{
|
---|
1829 | Command: "CAP",
|
---|
1830 | Params: []string{"REQ", strings.Join(requestCaps, " ")},
|
---|
1831 | })
|
---|
1832 | }
|
---|
1833 |
|
---|
1834 | func (uc *upstreamConn) supportsSASL(mech string) bool {
|
---|
1835 | v, ok := uc.supportedCaps["sasl"]
|
---|
1836 | if !ok {
|
---|
1837 | return false
|
---|
1838 | }
|
---|
1839 |
|
---|
1840 | if v == "" {
|
---|
1841 | return true
|
---|
1842 | }
|
---|
1843 |
|
---|
1844 | mechanisms := strings.Split(v, ",")
|
---|
1845 | for _, mech := range mechanisms {
|
---|
1846 | if strings.EqualFold(mech, mech) {
|
---|
1847 | return true
|
---|
1848 | }
|
---|
1849 | }
|
---|
1850 | return false
|
---|
1851 | }
|
---|
1852 |
|
---|
1853 | func (uc *upstreamConn) requestSASL() bool {
|
---|
1854 | if uc.network.SASL.Mechanism == "" {
|
---|
1855 | return false
|
---|
1856 | }
|
---|
1857 | return uc.supportsSASL(uc.network.SASL.Mechanism)
|
---|
1858 | }
|
---|
1859 |
|
---|
1860 | func (uc *upstreamConn) handleCapAck(name string, ok bool) error {
|
---|
1861 | uc.caps[name] = ok
|
---|
1862 |
|
---|
1863 | switch name {
|
---|
1864 | case "sasl":
|
---|
1865 | if !uc.requestSASL() {
|
---|
1866 | return nil
|
---|
1867 | }
|
---|
1868 | if !ok {
|
---|
1869 | uc.logger.Printf("server refused to acknowledge the SASL capability")
|
---|
1870 | return nil
|
---|
1871 | }
|
---|
1872 |
|
---|
1873 | auth := &uc.network.SASL
|
---|
1874 | switch auth.Mechanism {
|
---|
1875 | case "PLAIN":
|
---|
1876 | uc.logger.Printf("starting SASL PLAIN authentication with username %q", auth.Plain.Username)
|
---|
1877 | uc.saslClient = sasl.NewPlainClient("", auth.Plain.Username, auth.Plain.Password)
|
---|
1878 | case "EXTERNAL":
|
---|
1879 | uc.logger.Printf("starting SASL EXTERNAL authentication")
|
---|
1880 | uc.saslClient = sasl.NewExternalClient("")
|
---|
1881 | default:
|
---|
1882 | return fmt.Errorf("unsupported SASL mechanism %q", name)
|
---|
1883 | }
|
---|
1884 |
|
---|
1885 | uc.SendMessage(context.TODO(), &irc.Message{
|
---|
1886 | Command: "AUTHENTICATE",
|
---|
1887 | Params: []string{auth.Mechanism},
|
---|
1888 | })
|
---|
1889 | default:
|
---|
1890 | if permanentUpstreamCaps[name] {
|
---|
1891 | break
|
---|
1892 | }
|
---|
1893 | uc.logger.Printf("received CAP ACK/NAK for a cap we don't support: %v", name)
|
---|
1894 | }
|
---|
1895 | return nil
|
---|
1896 | }
|
---|
1897 |
|
---|
1898 | func splitSpace(s string) []string {
|
---|
1899 | return strings.FieldsFunc(s, func(r rune) bool {
|
---|
1900 | return r == ' '
|
---|
1901 | })
|
---|
1902 | }
|
---|
1903 |
|
---|
1904 | func (uc *upstreamConn) register() {
|
---|
1905 | ctx := context.TODO()
|
---|
1906 |
|
---|
1907 | uc.nick = GetNick(&uc.user.User, &uc.network.Network)
|
---|
1908 | uc.nickCM = uc.network.casemap(uc.nick)
|
---|
1909 | uc.username = GetUsername(&uc.user.User, &uc.network.Network)
|
---|
1910 | uc.realname = GetRealname(&uc.user.User, &uc.network.Network)
|
---|
1911 |
|
---|
1912 | uc.SendMessage(ctx, &irc.Message{
|
---|
1913 | Command: "CAP",
|
---|
1914 | Params: []string{"LS", "302"},
|
---|
1915 | })
|
---|
1916 |
|
---|
1917 | if uc.network.Pass != "" {
|
---|
1918 | uc.SendMessage(ctx, &irc.Message{
|
---|
1919 | Command: "PASS",
|
---|
1920 | Params: []string{uc.network.Pass},
|
---|
1921 | })
|
---|
1922 | }
|
---|
1923 |
|
---|
1924 | uc.SendMessage(ctx, &irc.Message{
|
---|
1925 | Command: "NICK",
|
---|
1926 | Params: []string{uc.nick},
|
---|
1927 | })
|
---|
1928 | uc.SendMessage(ctx, &irc.Message{
|
---|
1929 | Command: "USER",
|
---|
1930 | Params: []string{uc.username, "0", "*", uc.realname},
|
---|
1931 | })
|
---|
1932 | }
|
---|
1933 |
|
---|
1934 | func (uc *upstreamConn) ReadMessage() (*irc.Message, error) {
|
---|
1935 | msg, err := uc.conn.ReadMessage()
|
---|
1936 | if err != nil {
|
---|
1937 | return nil, err
|
---|
1938 | }
|
---|
1939 | uc.srv.metrics.upstreamInMessagesTotal.Inc()
|
---|
1940 | return msg, nil
|
---|
1941 | }
|
---|
1942 |
|
---|
1943 | func (uc *upstreamConn) runUntilRegistered() error {
|
---|
1944 | for !uc.registered {
|
---|
1945 | msg, err := uc.ReadMessage()
|
---|
1946 | if err != nil {
|
---|
1947 | return fmt.Errorf("failed to read message: %v", err)
|
---|
1948 | }
|
---|
1949 |
|
---|
1950 | if err := uc.handleMessage(context.TODO(), msg); err != nil {
|
---|
1951 | if _, ok := err.(registrationError); ok {
|
---|
1952 | return err
|
---|
1953 | } else {
|
---|
1954 | msg.Tags = nil // prevent message tags from cluttering logs
|
---|
1955 | return fmt.Errorf("failed to handle message %q: %v", msg, err)
|
---|
1956 | }
|
---|
1957 | }
|
---|
1958 | }
|
---|
1959 |
|
---|
1960 | for _, command := range uc.network.ConnectCommands {
|
---|
1961 | m, err := irc.ParseMessage(command)
|
---|
1962 | if err != nil {
|
---|
1963 | uc.logger.Printf("failed to parse connect command %q: %v", command, err)
|
---|
1964 | } else {
|
---|
1965 | uc.SendMessage(context.TODO(), m)
|
---|
1966 | }
|
---|
1967 | }
|
---|
1968 |
|
---|
1969 | return nil
|
---|
1970 | }
|
---|
1971 |
|
---|
1972 | func (uc *upstreamConn) readMessages(ch chan<- event) error {
|
---|
1973 | for {
|
---|
1974 | msg, err := uc.ReadMessage()
|
---|
1975 | if errors.Is(err, io.EOF) {
|
---|
1976 | break
|
---|
1977 | } else if err != nil {
|
---|
1978 | return fmt.Errorf("failed to read IRC command: %v", err)
|
---|
1979 | }
|
---|
1980 |
|
---|
1981 | ch <- eventUpstreamMessage{msg, uc}
|
---|
1982 | }
|
---|
1983 |
|
---|
1984 | return nil
|
---|
1985 | }
|
---|
1986 |
|
---|
1987 | func (uc *upstreamConn) SendMessage(ctx context.Context, msg *irc.Message) {
|
---|
1988 | if !uc.caps["message-tags"] {
|
---|
1989 | msg = msg.Copy()
|
---|
1990 | msg.Tags = nil
|
---|
1991 | }
|
---|
1992 |
|
---|
1993 | uc.srv.metrics.upstreamOutMessagesTotal.Inc()
|
---|
1994 | uc.conn.SendMessage(ctx, msg)
|
---|
1995 | }
|
---|
1996 |
|
---|
1997 | func (uc *upstreamConn) SendMessageLabeled(ctx context.Context, downstreamID uint64, msg *irc.Message) {
|
---|
1998 | if uc.caps["labeled-response"] {
|
---|
1999 | if msg.Tags == nil {
|
---|
2000 | msg.Tags = make(map[string]irc.TagValue)
|
---|
2001 | }
|
---|
2002 | msg.Tags["label"] = irc.TagValue(fmt.Sprintf("sd-%d-%d", downstreamID, uc.nextLabelID))
|
---|
2003 | uc.nextLabelID++
|
---|
2004 | }
|
---|
2005 | uc.SendMessage(ctx, msg)
|
---|
2006 | }
|
---|
2007 |
|
---|
2008 | // appendLog appends a message to the log file.
|
---|
2009 | //
|
---|
2010 | // The internal message ID is returned. If the message isn't recorded in the
|
---|
2011 | // log file, an empty string is returned.
|
---|
2012 | func (uc *upstreamConn) appendLog(entity string, msg *irc.Message) (msgID string) {
|
---|
2013 | if uc.user.msgStore == nil {
|
---|
2014 | return ""
|
---|
2015 | }
|
---|
2016 |
|
---|
2017 | // Don't store messages with a server mask target
|
---|
2018 | if strings.HasPrefix(entity, "$") {
|
---|
2019 | return ""
|
---|
2020 | }
|
---|
2021 |
|
---|
2022 | entityCM := uc.network.casemap(entity)
|
---|
2023 | if entityCM == "nickserv" {
|
---|
2024 | // The messages sent/received from NickServ may contain
|
---|
2025 | // security-related information (like passwords). Don't store these.
|
---|
2026 | return ""
|
---|
2027 | }
|
---|
2028 |
|
---|
2029 | if !uc.network.delivered.HasTarget(entity) {
|
---|
2030 | // This is the first message we receive from this target. Save the last
|
---|
2031 | // message ID in delivery receipts, so that we can send the new message
|
---|
2032 | // in the backlog if an offline client reconnects.
|
---|
2033 | lastID, err := uc.user.msgStore.LastMsgID(&uc.network.Network, entityCM, time.Now())
|
---|
2034 | if err != nil {
|
---|
2035 | uc.logger.Printf("failed to log message: failed to get last message ID: %v", err)
|
---|
2036 | return ""
|
---|
2037 | }
|
---|
2038 |
|
---|
2039 | uc.network.delivered.ForEachClient(func(clientName string) {
|
---|
2040 | uc.network.delivered.StoreID(entity, clientName, lastID)
|
---|
2041 | })
|
---|
2042 | }
|
---|
2043 |
|
---|
2044 | msgID, err := uc.user.msgStore.Append(&uc.network.Network, entityCM, msg)
|
---|
2045 | if err != nil {
|
---|
2046 | uc.logger.Printf("failed to append message to store: %v", err)
|
---|
2047 | return ""
|
---|
2048 | }
|
---|
2049 |
|
---|
2050 | return msgID
|
---|
2051 | }
|
---|
2052 |
|
---|
2053 | // produce appends a message to the logs and forwards it to connected downstream
|
---|
2054 | // connections.
|
---|
2055 | //
|
---|
2056 | // If origin is not nil and origin doesn't support echo-message, the message is
|
---|
2057 | // forwarded to all connections except origin.
|
---|
2058 | func (uc *upstreamConn) produce(target string, msg *irc.Message, origin *downstreamConn) {
|
---|
2059 | var msgID string
|
---|
2060 | if target != "" {
|
---|
2061 | msgID = uc.appendLog(target, msg)
|
---|
2062 | }
|
---|
2063 |
|
---|
2064 | // Don't forward messages if it's a detached channel
|
---|
2065 | ch := uc.network.channels.Value(target)
|
---|
2066 | detached := ch != nil && ch.Detached
|
---|
2067 |
|
---|
2068 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
2069 | if !detached && (dc != origin || dc.caps["echo-message"]) {
|
---|
2070 | dc.sendMessageWithID(dc.marshalMessage(msg, uc.network), msgID)
|
---|
2071 | } else {
|
---|
2072 | dc.advanceMessageWithID(msg, msgID)
|
---|
2073 | }
|
---|
2074 | })
|
---|
2075 | }
|
---|
2076 |
|
---|
2077 | func (uc *upstreamConn) updateAway() {
|
---|
2078 | ctx := context.TODO()
|
---|
2079 |
|
---|
2080 | away := true
|
---|
2081 | uc.forEachDownstream(func(*downstreamConn) {
|
---|
2082 | away = false
|
---|
2083 | })
|
---|
2084 | if away == uc.away {
|
---|
2085 | return
|
---|
2086 | }
|
---|
2087 | if away {
|
---|
2088 | uc.SendMessage(ctx, &irc.Message{
|
---|
2089 | Command: "AWAY",
|
---|
2090 | Params: []string{"Auto away"},
|
---|
2091 | })
|
---|
2092 | } else {
|
---|
2093 | uc.SendMessage(ctx, &irc.Message{
|
---|
2094 | Command: "AWAY",
|
---|
2095 | })
|
---|
2096 | }
|
---|
2097 | uc.away = away
|
---|
2098 | }
|
---|
2099 |
|
---|
2100 | func (uc *upstreamConn) updateChannelAutoDetach(name string) {
|
---|
2101 | uch := uc.channels.Value(name)
|
---|
2102 | if uch == nil {
|
---|
2103 | return
|
---|
2104 | }
|
---|
2105 | ch := uc.network.channels.Value(name)
|
---|
2106 | if ch == nil || ch.Detached {
|
---|
2107 | return
|
---|
2108 | }
|
---|
2109 | uch.updateAutoDetach(ch.DetachAfter)
|
---|
2110 | }
|
---|
2111 |
|
---|
2112 | func (uc *upstreamConn) updateMonitor() {
|
---|
2113 | if _, ok := uc.isupport["MONITOR"]; !ok {
|
---|
2114 | return
|
---|
2115 | }
|
---|
2116 |
|
---|
2117 | ctx := context.TODO()
|
---|
2118 |
|
---|
2119 | add := make(map[string]struct{})
|
---|
2120 | var addList []string
|
---|
2121 | seen := make(map[string]struct{})
|
---|
2122 | uc.forEachDownstream(func(dc *downstreamConn) {
|
---|
2123 | for targetCM := range dc.monitored.innerMap {
|
---|
2124 | if !uc.monitored.Has(targetCM) {
|
---|
2125 | if _, ok := add[targetCM]; !ok {
|
---|
2126 | addList = append(addList, targetCM)
|
---|
2127 | add[targetCM] = struct{}{}
|
---|
2128 | }
|
---|
2129 | } else {
|
---|
2130 | seen[targetCM] = struct{}{}
|
---|
2131 | }
|
---|
2132 | }
|
---|
2133 | })
|
---|
2134 |
|
---|
2135 | wantNick := GetNick(&uc.user.User, &uc.network.Network)
|
---|
2136 | wantNickCM := uc.network.casemap(wantNick)
|
---|
2137 | if _, ok := add[wantNickCM]; !ok && !uc.monitored.Has(wantNick) && !uc.isOurNick(wantNick) {
|
---|
2138 | addList = append(addList, wantNickCM)
|
---|
2139 | add[wantNickCM] = struct{}{}
|
---|
2140 | }
|
---|
2141 |
|
---|
2142 | removeAll := true
|
---|
2143 | var removeList []string
|
---|
2144 | for targetCM, entry := range uc.monitored.innerMap {
|
---|
2145 | if _, ok := seen[targetCM]; ok {
|
---|
2146 | removeAll = false
|
---|
2147 | } else {
|
---|
2148 | removeList = append(removeList, entry.originalKey)
|
---|
2149 | }
|
---|
2150 | }
|
---|
2151 |
|
---|
2152 | // TODO: better handle the case where len(uc.monitored) + len(addList)
|
---|
2153 | // exceeds the limit, probably by immediately sending ERR_MONLISTFULL?
|
---|
2154 |
|
---|
2155 | if removeAll && len(addList) == 0 && len(removeList) > 0 {
|
---|
2156 | // Optimization when the last MONITOR-aware downstream disconnects
|
---|
2157 | uc.SendMessage(ctx, &irc.Message{
|
---|
2158 | Command: "MONITOR",
|
---|
2159 | Params: []string{"C"},
|
---|
2160 | })
|
---|
2161 | } else {
|
---|
2162 | msgs := generateMonitor("-", removeList)
|
---|
2163 | msgs = append(msgs, generateMonitor("+", addList)...)
|
---|
2164 | for _, msg := range msgs {
|
---|
2165 | uc.SendMessage(ctx, msg)
|
---|
2166 | }
|
---|
2167 | }
|
---|
2168 |
|
---|
2169 | for _, target := range removeList {
|
---|
2170 | uc.monitored.Delete(target)
|
---|
2171 | }
|
---|
2172 | }
|
---|