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