~taiite/senpai

ref: 009982352f18c03c331aa7aee0a1c89822e32884 senpai/irc/tokens.go -rw-r--r-- 11.1 KiB
00998235delthas Send SASL PLAIN authentication on connect 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
package irc

import (
	"errors"
	"fmt"
	"strings"
	"time"
)

// CasemapASCII of name is the canonical representation of name according to the
// ascii casemapping.
func CasemapASCII(name string) string {
	var sb strings.Builder
	sb.Grow(len(name))
	for _, r := range name {
		if 'A' <= r && r <= 'Z' {
			r += 'a' - 'A'
		}
		sb.WriteRune(r)
	}
	return sb.String()
}

// CasemapRFC1459 of name is the canonical representation of name according to the
// rfc-1459 casemapping.
func CasemapRFC1459(name string) string {
	var sb strings.Builder
	sb.Grow(len(name))
	for _, r := range name {
		if 'A' <= r && r <= 'Z' {
			r += 'a' - 'A'
		} else if r == '[' {
			r = '{'
		} else if r == ']' {
			r = '}'
		} else if r == '\\' {
			r = '|'
		} else if r == '~' {
			r = '^'
		}
		sb.WriteRune(r)
	}
	return sb.String()
}

// word returns the first word of s and the rest of s.
func word(s string) (word, rest string) {
	split := strings.SplitN(s, " ", 2)
	if len(split) < 2 {
		word = split[0]
		rest = ""
	} else {
		word = split[0]
		rest = split[1]
	}
	return
}

// tagEscape returns the value of '\c' given c according to the message-tags
// specification.
func tagEscape(c rune) (escape rune) {
	switch c {
	case ':':
		escape = ';'
	case 's':
		escape = ' '
	case 'r':
		escape = '\r'
	case 'n':
		escape = '\n'
	default:
		escape = c
	}
	return
}

// unescapeTagValue removes escapes from the given string and replaces them with
// their meaningful values.
func unescapeTagValue(escaped string) string {
	var builder strings.Builder
	builder.Grow(len(escaped))
	escape := false

	for _, c := range escaped {
		if c == '\\' && !escape {
			escape = true
		} else {
			var cpp rune

			if escape {
				cpp = tagEscape(c)
			} else {
				cpp = c
			}

			builder.WriteRune(cpp)
			escape = false
		}
	}

	return builder.String()
}

// escapeTagValue does the inverse operation of unescapeTagValue.
func escapeTagValue(unescaped string) string {
	var sb strings.Builder
	sb.Grow(len(unescaped) * 2)

	for _, c := range unescaped {
		switch c {
		case ';':
			sb.WriteRune('\\')
			sb.WriteRune(':')
		case ' ':
			sb.WriteRune('\\')
			sb.WriteRune('s')
		case '\r':
			sb.WriteRune('\\')
			sb.WriteRune('r')
		case '\n':
			sb.WriteRune('\\')
			sb.WriteRune('n')
		case '\\':
			sb.WriteRune('\\')
			sb.WriteRune('\\')
		default:
			sb.WriteRune(c)
		}
	}

	return sb.String()
}

func parseTags(s string) (tags map[string]string) {
	tags = map[string]string{}

	for _, item := range strings.Split(s, ";") {
		if item == "" || item == "=" || item == "+" || item == "+=" {
			continue
		}

		kv := strings.SplitN(item, "=", 2)
		if len(kv) < 2 {
			tags[kv[0]] = ""
		} else {
			tags[kv[0]] = unescapeTagValue(kv[1])
		}
	}

	return
}

func formatTags(tags map[string]string) string {
	var sb strings.Builder
	for k, v := range tags {
		sb.WriteString(k)
		if v != "" {
			sb.WriteRune('=')
			sb.WriteString(escapeTagValue(v))
		}
		sb.WriteRune(';')
	}
	return sb.String()
}

var (
	errEmptyMessage      = errors.New("empty message")
	errIncompleteMessage = errors.New("message is incomplete")
	errMissingPrefix     = errors.New("missing message prefix")
)

type Prefix struct {
	Name string
	User string
	Host string
}

// ParsePrefix parses a "nick!user@host" combination (or a prefix) from the given
// string.
func ParsePrefix(s string) (p *Prefix) {
	if s == "" {
		return
	}

	p = &Prefix{}

	spl0 := strings.Split(s, "@")
	if 1 < len(spl0) {
		p.Host = spl0[1]
	}

	spl1 := strings.Split(spl0[0], "!")
	if 1 < len(spl1) {
		p.User = spl1[1]
	}

	p.Name = spl1[0]

	return
}

// Copy makes a copy of the prefix, but doesn't copy the internal strings.
func (p *Prefix) Copy() *Prefix {
	if p == nil {
		return nil
	}
	res := &Prefix{}
	*res = *p
	return res
}

// String returns the "nick!user@host" representation of the prefix.
func (p *Prefix) String() string {
	if p == nil {
		return ""
	}

	if p.User != "" && p.Host != "" {
		return p.Name + "!" + p.User + "@" + p.Host
	} else if p.User != "" {
		return p.Name + "!" + p.User
	} else if p.Host != "" {
		return p.Name + "@" + p.Host
	} else {
		return p.Name
	}
}

// Message is the representation of an IRC message.
type Message struct {
	Tags    map[string]string
	Prefix  *Prefix
	Command string
	Params  []string
}

func NewMessage(command string, params ...string) Message {
	return Message{Command: command, Params: params}
}

// ParseMessage parses the message from the given string, which must be trimmed
// of "\r\n" beforehand.
func ParseMessage(line string) (msg Message, err error) {
	line = strings.TrimLeft(line, " ")
	if line == "" {
		err = errEmptyMessage
		return
	}

	if line[0] == '@' {
		var tags string

		tags, line = word(line)
		msg.Tags = parseTags(tags[1:])
	}

	line = strings.TrimLeft(line, " ")
	if line == "" {
		err = errIncompleteMessage
		return
	}

	if line[0] == ':' {
		var prefix string

		prefix, line = word(line)
		msg.Prefix = ParsePrefix(prefix[1:])
	}

	line = strings.TrimLeft(line, " ")
	if line == "" {
		err = errIncompleteMessage
		return
	}

	msg.Command, line = word(line)
	msg.Command = strings.ToUpper(msg.Command)

	msg.Params = make([]string, 0, 15)
	for line != "" {
		if line[0] == ':' {
			msg.Params = append(msg.Params, line[1:])
			break
		}

		var param string
		param, line = word(line)
		msg.Params = append(msg.Params, param)
	}

	return
}

func (msg Message) WithTag(key, value string) Message {
	if msg.Tags == nil {
		msg.Tags = map[string]string{}
	}
	msg.Tags[key] = escapeTagValue(value)
	return msg
}

// IsReply reports whether the message command is a server reply.
func (msg *Message) IsReply() bool {
	if len(msg.Command) != 3 {
		return false
	}
	for _, r := range msg.Command {
		if !('0' <= r && r <= '9') {
			return false
		}
	}
	return true
}

// String returns the protocol representation of the message, without an ending
// "\r\n".
func (msg *Message) String() string {
	var sb strings.Builder

	if msg.Tags != nil {
		sb.WriteRune('@')
		sb.WriteString(formatTags(msg.Tags))
		sb.WriteRune(' ')
	}

	if msg.Prefix != nil {
		sb.WriteRune(':')
		sb.WriteString(msg.Prefix.String())
		sb.WriteRune(' ')
	}

	sb.WriteString(msg.Command)

	if len(msg.Params) != 0 {
		for _, p := range msg.Params[:len(msg.Params)-1] {
			sb.WriteRune(' ')
			sb.WriteString(p)
		}
		lastParam := msg.Params[len(msg.Params)-1]
		if !strings.ContainsRune(lastParam, ' ') && !strings.HasPrefix(lastParam, ":") {
			sb.WriteRune(' ')
			sb.WriteString(lastParam)
		} else {
			sb.WriteRune(' ')
			sb.WriteRune(':')
			sb.WriteString(lastParam)
		}
	}

	return sb.String()
}

func (msg *Message) errNotEnoughParams(expected int) error {
	return fmt.Errorf("expected at least %d params, got %d", expected, len(msg.Params))
}

func (msg *Message) ParseParams(out ...*string) error {
	if len(msg.Params) < len(out) {
		return msg.errNotEnoughParams(len(out))
	}
	for i := range out {
		if out[i] != nil {
			*out[i] = msg.Params[i]
		}
	}
	return nil
}

func parseTimestamp(timestamp string) (time.Time, bool) {
	var year, month, day, hour, minute, second, millis int

	timestamp = strings.TrimSuffix(timestamp, "Z")

	_, err := fmt.Sscanf(timestamp, "%4d-%2d-%2dT%2d:%2d:%2d.%3d", &year, &month, &day, &hour, &minute, &second, &millis)
	if err != nil || month < 1 || 12 < month {
		return time.Time{}, false
	}

	return time.Date(year, time.Month(month), day, hour, minute, second, millis*1e6, time.UTC), true
}

// Time returns the time when the message has been sent, if present.
func (msg *Message) Time() (t time.Time, ok bool) {
	tag, ok := msg.Tags["time"]
	if !ok {
		return time.Time{}, false
	}
	return parseTimestamp(tag)
}

// TimeOrNow returns the time when the message has been sent, or time.Now() if
// absent.
func (msg *Message) TimeOrNow() time.Time {
	t, ok := msg.Time()
	if ok {
		return t
	}
	return time.Now().UTC()
}

// Severity is the severity of a server reply.
type Severity int

const (
	SeverityNote Severity = iota
	SeverityWarn
	SeverityFail
)

// ReplySeverity returns the severity of a server reply.
func ReplySeverity(reply string) Severity {
	switch reply[0] {
	case '4', '5':
		if reply == "422" {
			return SeverityNote
		} else {
			return SeverityFail
		}
	case '9':
		switch reply[2] {
		case '2', '4', '5', '6', '7':
			return SeverityFail
		default:
			return SeverityNote
		}
	default:
		return SeverityNote
	}
}

// Cap is a capability token in "CAP" server responses.
type Cap struct {
	Name   string
	Value  string
	Enable bool
}

// ParseCaps parses the last argument (capability list) of "CAP LS/LIST/NEW/DEL"
// server responses.
func ParseCaps(caps string) (diff []Cap) {
	for _, c := range strings.Split(caps, " ") {
		if c == "" || c == "-" || c == "=" || c == "-=" {
			continue
		}

		var item Cap

		if strings.HasPrefix(c, "-") {
			item.Enable = false
			c = c[1:]
		} else {
			item.Enable = true
		}

		kv := strings.SplitN(c, "=", 2)
		item.Name = strings.ToLower(kv[0])
		if len(kv) > 1 {
			item.Value = kv[1]
		}

		diff = append(diff, item)
	}

	return
}

// Member is a token in RPL_NAMREPLY's last parameter.
type Member struct {
	PowerLevel   string
	Name         *Prefix
	Away         bool
	Disconnected bool
}

type members []Member

func (m members) Len() int {
	return len(m)
}

func (m members) Less(i, j int) bool {
	if m[i].PowerLevel != "" && m[j].PowerLevel == "" {
		return true
	} else if m[i].PowerLevel == "" && m[j].PowerLevel != "" {
		return false
	} else {
		return strings.ToLower(m[i].Name.Name) < strings.ToLower(m[j].Name.Name)
	}
}

func (m members) Swap(i, j int) {
	m[i], m[j] = m[j], m[i]
}

// ParseNameReply parses the last parameter of RPL_NAMREPLY, according to the
// membership prefixes of the server.
func ParseNameReply(trailing string, prefixes string) (names []Member) {
	for _, word := range strings.Split(trailing, " ") {
		if word == "" {
			continue
		}

		name := strings.TrimLeft(word, prefixes)
		names = append(names, Member{
			PowerLevel: word[:len(word)-len(name)],
			Name:       ParsePrefix(name),
		})
	}

	return
}

// Mode types available in the CHANMODES 005 token.
const (
	ModeTypeA int = iota
	ModeTypeB
	ModeTypeC
	ModeTypeD
)

type ModeChange struct {
	Enable bool
	Mode   byte
	Param  string
}

// ParseChannelMode parses a MODE message for a channel, according to the
// CHANMODES of the server.
func ParseChannelMode(mode string, params []string, chanmodes [4]string, membershipModes string) ([]ModeChange, error) {
	var changes []ModeChange
	enable := true
	paramIdx := 0
	for i := 0; i < len(mode); i++ {
		m := mode[i]
		if m == '+' || m == '-' {
			enable = m == '+'
			continue
		}
		modeType := -1
		for t := 0; t < 4; t++ {
			if 0 <= strings.IndexByte(chanmodes[t], m) {
				modeType = t
				break
			}
		}
		if 0 <= strings.IndexByte(membershipModes, m) {
			modeType = ModeTypeB
		} else if modeType == -1 {
			return nil, fmt.Errorf("unknown mode %c", m)
		}
		// ref: https://modern.ircdocs.horse/#mode-message
		if modeType == ModeTypeA || modeType == ModeTypeB || (enable && modeType == ModeTypeC) {
			if len(params) <= paramIdx {
				return nil, fmt.Errorf("missing mode params")
			}
			changes = append(changes, ModeChange{
				Enable: enable,
				Mode:   m,
				Param:  params[paramIdx],
			})
			paramIdx++
		} else {
			changes = append(changes, ModeChange{
				Enable: enable,
				Mode:   m,
			})
		}
	}
	return changes, nil
}