1 | package soju
|
---|
2 |
|
---|
3 | import (
|
---|
4 | "context"
|
---|
5 | "crypto/sha1"
|
---|
6 | "crypto/sha256"
|
---|
7 | "crypto/sha512"
|
---|
8 | "encoding/hex"
|
---|
9 | "errors"
|
---|
10 | "flag"
|
---|
11 | "fmt"
|
---|
12 | "io/ioutil"
|
---|
13 | "sort"
|
---|
14 | "strconv"
|
---|
15 | "strings"
|
---|
16 | "time"
|
---|
17 | "unicode"
|
---|
18 |
|
---|
19 | "golang.org/x/crypto/bcrypt"
|
---|
20 | "gopkg.in/irc.v3"
|
---|
21 | )
|
---|
22 |
|
---|
23 | const serviceNick = "BouncerServ"
|
---|
24 | const serviceNickCM = "bouncerserv"
|
---|
25 | const serviceRealname = "soju bouncer service"
|
---|
26 |
|
---|
27 | // maxRSABits is the maximum number of RSA key bits used when generating a new
|
---|
28 | // private key.
|
---|
29 | const maxRSABits = 8192
|
---|
30 |
|
---|
31 | var servicePrefix = &irc.Prefix{
|
---|
32 | Name: serviceNick,
|
---|
33 | User: serviceNick,
|
---|
34 | Host: serviceNick,
|
---|
35 | }
|
---|
36 |
|
---|
37 | type serviceCommandSet map[string]*serviceCommand
|
---|
38 |
|
---|
39 | type serviceCommand struct {
|
---|
40 | usage string
|
---|
41 | desc string
|
---|
42 | handle func(ctx context.Context, dc *downstreamConn, params []string) error
|
---|
43 | children serviceCommandSet
|
---|
44 | admin bool
|
---|
45 | }
|
---|
46 |
|
---|
47 | func sendServiceNOTICE(dc *downstreamConn, text string) {
|
---|
48 | dc.SendMessage(&irc.Message{
|
---|
49 | Prefix: servicePrefix,
|
---|
50 | Command: "NOTICE",
|
---|
51 | Params: []string{dc.nick, text},
|
---|
52 | })
|
---|
53 | }
|
---|
54 |
|
---|
55 | func sendServicePRIVMSG(dc *downstreamConn, text string) {
|
---|
56 | dc.SendMessage(&irc.Message{
|
---|
57 | Prefix: servicePrefix,
|
---|
58 | Command: "PRIVMSG",
|
---|
59 | Params: []string{dc.nick, text},
|
---|
60 | })
|
---|
61 | }
|
---|
62 |
|
---|
63 | func splitWords(s string) ([]string, error) {
|
---|
64 | var words []string
|
---|
65 | var lastWord strings.Builder
|
---|
66 | escape := false
|
---|
67 | prev := ' '
|
---|
68 | wordDelim := ' '
|
---|
69 |
|
---|
70 | for _, r := range s {
|
---|
71 | if escape {
|
---|
72 | // last char was a backslash, write the byte as-is.
|
---|
73 | lastWord.WriteRune(r)
|
---|
74 | escape = false
|
---|
75 | } else if r == '\\' {
|
---|
76 | escape = true
|
---|
77 | } else if wordDelim == ' ' && unicode.IsSpace(r) {
|
---|
78 | // end of last word
|
---|
79 | if !unicode.IsSpace(prev) {
|
---|
80 | words = append(words, lastWord.String())
|
---|
81 | lastWord.Reset()
|
---|
82 | }
|
---|
83 | } else if r == wordDelim {
|
---|
84 | // wordDelim is either " or ', switch back to
|
---|
85 | // space-delimited words.
|
---|
86 | wordDelim = ' '
|
---|
87 | } else if r == '"' || r == '\'' {
|
---|
88 | if wordDelim == ' ' {
|
---|
89 | // start of (double-)quoted word
|
---|
90 | wordDelim = r
|
---|
91 | } else {
|
---|
92 | // either wordDelim is " and r is ' or vice-versa
|
---|
93 | lastWord.WriteRune(r)
|
---|
94 | }
|
---|
95 | } else {
|
---|
96 | lastWord.WriteRune(r)
|
---|
97 | }
|
---|
98 |
|
---|
99 | prev = r
|
---|
100 | }
|
---|
101 |
|
---|
102 | if !unicode.IsSpace(prev) {
|
---|
103 | words = append(words, lastWord.String())
|
---|
104 | }
|
---|
105 |
|
---|
106 | if wordDelim != ' ' {
|
---|
107 | return nil, fmt.Errorf("unterminated quoted string")
|
---|
108 | }
|
---|
109 | if escape {
|
---|
110 | return nil, fmt.Errorf("unterminated backslash sequence")
|
---|
111 | }
|
---|
112 |
|
---|
113 | return words, nil
|
---|
114 | }
|
---|
115 |
|
---|
116 | func handleServicePRIVMSG(ctx context.Context, dc *downstreamConn, text string) {
|
---|
117 | words, err := splitWords(text)
|
---|
118 | if err != nil {
|
---|
119 | sendServicePRIVMSG(dc, fmt.Sprintf(`error: failed to parse command: %v`, err))
|
---|
120 | return
|
---|
121 | }
|
---|
122 |
|
---|
123 | cmd, params, err := serviceCommands.Get(words)
|
---|
124 | if err != nil {
|
---|
125 | sendServicePRIVMSG(dc, fmt.Sprintf(`error: %v (type "help" for a list of commands)`, err))
|
---|
126 | return
|
---|
127 | }
|
---|
128 | if cmd.admin && !dc.user.Admin {
|
---|
129 | sendServicePRIVMSG(dc, "error: you must be an admin to use this command")
|
---|
130 | return
|
---|
131 | }
|
---|
132 |
|
---|
133 | if cmd.handle == nil {
|
---|
134 | if len(cmd.children) > 0 {
|
---|
135 | var l []string
|
---|
136 | appendServiceCommandSetHelp(cmd.children, words, dc.user.Admin, &l)
|
---|
137 | sendServicePRIVMSG(dc, "available commands: "+strings.Join(l, ", "))
|
---|
138 | } else {
|
---|
139 | // Pretend the command does not exist if it has neither children nor handler.
|
---|
140 | // This is obviously a bug but it is better to not die anyway.
|
---|
141 | dc.logger.Printf("command without handler and subcommands invoked:", words[0])
|
---|
142 | sendServicePRIVMSG(dc, fmt.Sprintf("command %q not found", words[0]))
|
---|
143 | }
|
---|
144 | return
|
---|
145 | }
|
---|
146 |
|
---|
147 | if err := cmd.handle(ctx, dc, params); err != nil {
|
---|
148 | sendServicePRIVMSG(dc, fmt.Sprintf("error: %v", err))
|
---|
149 | }
|
---|
150 | }
|
---|
151 |
|
---|
152 | func (cmds serviceCommandSet) Get(params []string) (*serviceCommand, []string, error) {
|
---|
153 | if len(params) == 0 {
|
---|
154 | return nil, nil, fmt.Errorf("no command specified")
|
---|
155 | }
|
---|
156 |
|
---|
157 | name := params[0]
|
---|
158 | params = params[1:]
|
---|
159 |
|
---|
160 | cmd, ok := cmds[name]
|
---|
161 | if !ok {
|
---|
162 | for k := range cmds {
|
---|
163 | if !strings.HasPrefix(k, name) {
|
---|
164 | continue
|
---|
165 | }
|
---|
166 | if cmd != nil {
|
---|
167 | return nil, params, fmt.Errorf("command %q is ambiguous", name)
|
---|
168 | }
|
---|
169 | cmd = cmds[k]
|
---|
170 | }
|
---|
171 | }
|
---|
172 | if cmd == nil {
|
---|
173 | return nil, params, fmt.Errorf("command %q not found", name)
|
---|
174 | }
|
---|
175 |
|
---|
176 | if len(params) == 0 || len(cmd.children) == 0 {
|
---|
177 | return cmd, params, nil
|
---|
178 | }
|
---|
179 | return cmd.children.Get(params)
|
---|
180 | }
|
---|
181 |
|
---|
182 | func (cmds serviceCommandSet) Names() []string {
|
---|
183 | l := make([]string, 0, len(cmds))
|
---|
184 | for name := range cmds {
|
---|
185 | l = append(l, name)
|
---|
186 | }
|
---|
187 | sort.Strings(l)
|
---|
188 | return l
|
---|
189 | }
|
---|
190 |
|
---|
191 | var serviceCommands serviceCommandSet
|
---|
192 |
|
---|
193 | func init() {
|
---|
194 | serviceCommands = serviceCommandSet{
|
---|
195 | "help": {
|
---|
196 | usage: "[command]",
|
---|
197 | desc: "print help message",
|
---|
198 | handle: handleServiceHelp,
|
---|
199 | },
|
---|
200 | "network": {
|
---|
201 | children: serviceCommandSet{
|
---|
202 | "create": {
|
---|
203 | usage: "-addr <addr> [-name name] [-username username] [-pass pass] [-realname realname] [-nick nick] [-enabled enabled] [-connect-command command]...",
|
---|
204 | desc: "add a new network",
|
---|
205 | handle: handleServiceNetworkCreate,
|
---|
206 | },
|
---|
207 | "status": {
|
---|
208 | desc: "show a list of saved networks and their current status",
|
---|
209 | handle: handleServiceNetworkStatus,
|
---|
210 | },
|
---|
211 | "update": {
|
---|
212 | usage: "<name> [-addr addr] [-name name] [-username username] [-pass pass] [-realname realname] [-nick nick] [-enabled enabled] [-connect-command command]...",
|
---|
213 | desc: "update a network",
|
---|
214 | handle: handleServiceNetworkUpdate,
|
---|
215 | },
|
---|
216 | "delete": {
|
---|
217 | usage: "<name>",
|
---|
218 | desc: "delete a network",
|
---|
219 | handle: handleServiceNetworkDelete,
|
---|
220 | },
|
---|
221 | "quote": {
|
---|
222 | usage: "<name> <command>",
|
---|
223 | desc: "send a raw line to a network",
|
---|
224 | handle: handleServiceNetworkQuote,
|
---|
225 | },
|
---|
226 | },
|
---|
227 | },
|
---|
228 | "certfp": {
|
---|
229 | children: serviceCommandSet{
|
---|
230 | "generate": {
|
---|
231 | usage: "[-key-type rsa|ecdsa|ed25519] [-bits N] <network name>",
|
---|
232 | desc: "generate a new self-signed certificate, defaults to using RSA-3072 key",
|
---|
233 | handle: handleServiceCertFPGenerate,
|
---|
234 | },
|
---|
235 | "fingerprint": {
|
---|
236 | usage: "<network name>",
|
---|
237 | desc: "show fingerprints of certificate associated with the network",
|
---|
238 | handle: handleServiceCertFPFingerprints,
|
---|
239 | },
|
---|
240 | },
|
---|
241 | },
|
---|
242 | "sasl": {
|
---|
243 | children: serviceCommandSet{
|
---|
244 | "set-plain": {
|
---|
245 | usage: "<network name> <username> <password>",
|
---|
246 | desc: "set SASL PLAIN credentials",
|
---|
247 | handle: handleServiceSASLSetPlain,
|
---|
248 | },
|
---|
249 | "reset": {
|
---|
250 | usage: "<network name>",
|
---|
251 | desc: "disable SASL authentication and remove stored credentials",
|
---|
252 | handle: handleServiceSASLReset,
|
---|
253 | },
|
---|
254 | },
|
---|
255 | },
|
---|
256 | "user": {
|
---|
257 | children: serviceCommandSet{
|
---|
258 | "create": {
|
---|
259 | usage: "-username <username> -password <password> [-realname <realname>] [-admin]",
|
---|
260 | desc: "create a new soju user",
|
---|
261 | handle: handleUserCreate,
|
---|
262 | admin: true,
|
---|
263 | },
|
---|
264 | "update": {
|
---|
265 | usage: "[-password <password>] [-realname <realname>]",
|
---|
266 | desc: "update the current user",
|
---|
267 | handle: handleUserUpdate,
|
---|
268 | },
|
---|
269 | "delete": {
|
---|
270 | usage: "<username>",
|
---|
271 | desc: "delete a user",
|
---|
272 | handle: handleUserDelete,
|
---|
273 | admin: true,
|
---|
274 | },
|
---|
275 | },
|
---|
276 | },
|
---|
277 | "channel": {
|
---|
278 | children: serviceCommandSet{
|
---|
279 | "status": {
|
---|
280 | usage: "[-network name]",
|
---|
281 | desc: "show a list of saved channels and their current status",
|
---|
282 | handle: handleServiceChannelStatus,
|
---|
283 | },
|
---|
284 | "update": {
|
---|
285 | usage: "<name> [-relay-detached <default|none|highlight|message>] [-reattach-on <default|none|highlight|message>] [-detach-after <duration>] [-detach-on <default|none|highlight|message>]",
|
---|
286 | desc: "update a channel",
|
---|
287 | handle: handleServiceChannelUpdate,
|
---|
288 | },
|
---|
289 | },
|
---|
290 | },
|
---|
291 | "server": {
|
---|
292 | children: serviceCommandSet{
|
---|
293 | "status": {
|
---|
294 | desc: "show server statistics",
|
---|
295 | handle: handleServiceServerStatus,
|
---|
296 | admin: true,
|
---|
297 | },
|
---|
298 | "notice": {
|
---|
299 | desc: "broadcast a notice to all connected bouncer users",
|
---|
300 | handle: handleServiceServerNotice,
|
---|
301 | admin: true,
|
---|
302 | },
|
---|
303 | },
|
---|
304 | admin: true,
|
---|
305 | },
|
---|
306 | }
|
---|
307 | }
|
---|
308 |
|
---|
309 | func appendServiceCommandSetHelp(cmds serviceCommandSet, prefix []string, admin bool, l *[]string) {
|
---|
310 | for _, name := range cmds.Names() {
|
---|
311 | cmd := cmds[name]
|
---|
312 | if cmd.admin && !admin {
|
---|
313 | continue
|
---|
314 | }
|
---|
315 | words := append(prefix, name)
|
---|
316 | if len(cmd.children) == 0 {
|
---|
317 | s := strings.Join(words, " ")
|
---|
318 | *l = append(*l, s)
|
---|
319 | } else {
|
---|
320 | appendServiceCommandSetHelp(cmd.children, words, admin, l)
|
---|
321 | }
|
---|
322 | }
|
---|
323 | }
|
---|
324 |
|
---|
325 | func handleServiceHelp(ctx context.Context, dc *downstreamConn, params []string) error {
|
---|
326 | if len(params) > 0 {
|
---|
327 | cmd, rest, err := serviceCommands.Get(params)
|
---|
328 | if err != nil {
|
---|
329 | return err
|
---|
330 | }
|
---|
331 | words := params[:len(params)-len(rest)]
|
---|
332 |
|
---|
333 | if len(cmd.children) > 0 {
|
---|
334 | var l []string
|
---|
335 | appendServiceCommandSetHelp(cmd.children, words, dc.user.Admin, &l)
|
---|
336 | sendServicePRIVMSG(dc, "available commands: "+strings.Join(l, ", "))
|
---|
337 | } else {
|
---|
338 | text := strings.Join(words, " ")
|
---|
339 | if cmd.usage != "" {
|
---|
340 | text += " " + cmd.usage
|
---|
341 | }
|
---|
342 | text += ": " + cmd.desc
|
---|
343 |
|
---|
344 | sendServicePRIVMSG(dc, text)
|
---|
345 | }
|
---|
346 | } else {
|
---|
347 | var l []string
|
---|
348 | appendServiceCommandSetHelp(serviceCommands, nil, dc.user.Admin, &l)
|
---|
349 | sendServicePRIVMSG(dc, "available commands: "+strings.Join(l, ", "))
|
---|
350 | }
|
---|
351 | return nil
|
---|
352 | }
|
---|
353 |
|
---|
354 | func newFlagSet() *flag.FlagSet {
|
---|
355 | fs := flag.NewFlagSet("", flag.ContinueOnError)
|
---|
356 | fs.SetOutput(ioutil.Discard)
|
---|
357 | return fs
|
---|
358 | }
|
---|
359 |
|
---|
360 | type stringSliceFlag []string
|
---|
361 |
|
---|
362 | func (v *stringSliceFlag) String() string {
|
---|
363 | return fmt.Sprint([]string(*v))
|
---|
364 | }
|
---|
365 |
|
---|
366 | func (v *stringSliceFlag) Set(s string) error {
|
---|
367 | *v = append(*v, s)
|
---|
368 | return nil
|
---|
369 | }
|
---|
370 |
|
---|
371 | // stringPtrFlag is a flag value populating a string pointer. This allows to
|
---|
372 | // disambiguate between a flag that hasn't been set and a flag that has been
|
---|
373 | // set to an empty string.
|
---|
374 | type stringPtrFlag struct {
|
---|
375 | ptr **string
|
---|
376 | }
|
---|
377 |
|
---|
378 | func (f stringPtrFlag) String() string {
|
---|
379 | if f.ptr == nil || *f.ptr == nil {
|
---|
380 | return ""
|
---|
381 | }
|
---|
382 | return **f.ptr
|
---|
383 | }
|
---|
384 |
|
---|
385 | func (f stringPtrFlag) Set(s string) error {
|
---|
386 | *f.ptr = &s
|
---|
387 | return nil
|
---|
388 | }
|
---|
389 |
|
---|
390 | type boolPtrFlag struct {
|
---|
391 | ptr **bool
|
---|
392 | }
|
---|
393 |
|
---|
394 | func (f boolPtrFlag) String() string {
|
---|
395 | if f.ptr == nil || *f.ptr == nil {
|
---|
396 | return "<nil>"
|
---|
397 | }
|
---|
398 | return strconv.FormatBool(**f.ptr)
|
---|
399 | }
|
---|
400 |
|
---|
401 | func (f boolPtrFlag) Set(s string) error {
|
---|
402 | v, err := strconv.ParseBool(s)
|
---|
403 | if err != nil {
|
---|
404 | return err
|
---|
405 | }
|
---|
406 | *f.ptr = &v
|
---|
407 | return nil
|
---|
408 | }
|
---|
409 |
|
---|
410 | type networkFlagSet struct {
|
---|
411 | *flag.FlagSet
|
---|
412 | Addr, Name, Nick, Username, Pass, Realname *string
|
---|
413 | Enabled *bool
|
---|
414 | ConnectCommands []string
|
---|
415 | }
|
---|
416 |
|
---|
417 | func newNetworkFlagSet() *networkFlagSet {
|
---|
418 | fs := &networkFlagSet{FlagSet: newFlagSet()}
|
---|
419 | fs.Var(stringPtrFlag{&fs.Addr}, "addr", "")
|
---|
420 | fs.Var(stringPtrFlag{&fs.Name}, "name", "")
|
---|
421 | fs.Var(stringPtrFlag{&fs.Nick}, "nick", "")
|
---|
422 | fs.Var(stringPtrFlag{&fs.Username}, "username", "")
|
---|
423 | fs.Var(stringPtrFlag{&fs.Pass}, "pass", "")
|
---|
424 | fs.Var(stringPtrFlag{&fs.Realname}, "realname", "")
|
---|
425 | fs.Var(boolPtrFlag{&fs.Enabled}, "enabled", "")
|
---|
426 | fs.Var((*stringSliceFlag)(&fs.ConnectCommands), "connect-command", "")
|
---|
427 | return fs
|
---|
428 | }
|
---|
429 |
|
---|
430 | func (fs *networkFlagSet) update(network *Network) error {
|
---|
431 | if fs.Addr != nil {
|
---|
432 | if addrParts := strings.SplitN(*fs.Addr, "://", 2); len(addrParts) == 2 {
|
---|
433 | scheme := addrParts[0]
|
---|
434 | switch scheme {
|
---|
435 | case "ircs", "irc+insecure", "unix":
|
---|
436 | default:
|
---|
437 | return fmt.Errorf("unknown scheme %q (supported schemes: ircs, irc+insecure, unix)", scheme)
|
---|
438 | }
|
---|
439 | }
|
---|
440 | network.Addr = *fs.Addr
|
---|
441 | }
|
---|
442 | if fs.Name != nil {
|
---|
443 | network.Name = *fs.Name
|
---|
444 | }
|
---|
445 | if fs.Nick != nil {
|
---|
446 | network.Nick = *fs.Nick
|
---|
447 | }
|
---|
448 | if fs.Username != nil {
|
---|
449 | network.Username = *fs.Username
|
---|
450 | }
|
---|
451 | if fs.Pass != nil {
|
---|
452 | network.Pass = *fs.Pass
|
---|
453 | }
|
---|
454 | if fs.Realname != nil {
|
---|
455 | network.Realname = *fs.Realname
|
---|
456 | }
|
---|
457 | if fs.Enabled != nil {
|
---|
458 | network.Enabled = *fs.Enabled
|
---|
459 | }
|
---|
460 | if fs.ConnectCommands != nil {
|
---|
461 | if len(fs.ConnectCommands) == 1 && fs.ConnectCommands[0] == "" {
|
---|
462 | network.ConnectCommands = nil
|
---|
463 | } else {
|
---|
464 | for _, command := range fs.ConnectCommands {
|
---|
465 | _, err := irc.ParseMessage(command)
|
---|
466 | if err != nil {
|
---|
467 | return fmt.Errorf("flag -connect-command must be a valid raw irc command string: %q: %v", command, err)
|
---|
468 | }
|
---|
469 | }
|
---|
470 | network.ConnectCommands = fs.ConnectCommands
|
---|
471 | }
|
---|
472 | }
|
---|
473 | return nil
|
---|
474 | }
|
---|
475 |
|
---|
476 | func handleServiceNetworkCreate(ctx context.Context, dc *downstreamConn, params []string) error {
|
---|
477 | fs := newNetworkFlagSet()
|
---|
478 | if err := fs.Parse(params); err != nil {
|
---|
479 | return err
|
---|
480 | }
|
---|
481 | if fs.Addr == nil {
|
---|
482 | return fmt.Errorf("flag -addr is required")
|
---|
483 | }
|
---|
484 |
|
---|
485 | record := &Network{
|
---|
486 | Addr: *fs.Addr,
|
---|
487 | Enabled: true,
|
---|
488 | }
|
---|
489 | if err := fs.update(record); err != nil {
|
---|
490 | return err
|
---|
491 | }
|
---|
492 |
|
---|
493 | network, err := dc.user.createNetwork(ctx, record)
|
---|
494 | if err != nil {
|
---|
495 | return fmt.Errorf("could not create network: %v", err)
|
---|
496 | }
|
---|
497 |
|
---|
498 | sendServicePRIVMSG(dc, fmt.Sprintf("created network %q", network.GetName()))
|
---|
499 | return nil
|
---|
500 | }
|
---|
501 |
|
---|
502 | func handleServiceNetworkStatus(ctx context.Context, dc *downstreamConn, params []string) error {
|
---|
503 | n := 0
|
---|
504 | dc.user.forEachNetwork(func(net *network) {
|
---|
505 | var statuses []string
|
---|
506 | var details string
|
---|
507 | if uc := net.conn; uc != nil {
|
---|
508 | if dc.nick != uc.nick {
|
---|
509 | statuses = append(statuses, "connected as "+uc.nick)
|
---|
510 | } else {
|
---|
511 | statuses = append(statuses, "connected")
|
---|
512 | }
|
---|
513 | details = fmt.Sprintf("%v channels", uc.channels.Len())
|
---|
514 | } else if !net.Enabled {
|
---|
515 | statuses = append(statuses, "disabled")
|
---|
516 | } else {
|
---|
517 | statuses = append(statuses, "disconnected")
|
---|
518 | if net.lastError != nil {
|
---|
519 | details = net.lastError.Error()
|
---|
520 | }
|
---|
521 | }
|
---|
522 |
|
---|
523 | if net == dc.network {
|
---|
524 | statuses = append(statuses, "current")
|
---|
525 | }
|
---|
526 |
|
---|
527 | name := net.GetName()
|
---|
528 | if name != net.Addr {
|
---|
529 | name = fmt.Sprintf("%v (%v)", name, net.Addr)
|
---|
530 | }
|
---|
531 |
|
---|
532 | s := fmt.Sprintf("%v [%v]", name, strings.Join(statuses, ", "))
|
---|
533 | if details != "" {
|
---|
534 | s += ": " + details
|
---|
535 | }
|
---|
536 | sendServicePRIVMSG(dc, s)
|
---|
537 |
|
---|
538 | n++
|
---|
539 | })
|
---|
540 |
|
---|
541 | if n == 0 {
|
---|
542 | sendServicePRIVMSG(dc, `No network configured, add one with "network create".`)
|
---|
543 | }
|
---|
544 |
|
---|
545 | return nil
|
---|
546 | }
|
---|
547 |
|
---|
548 | func handleServiceNetworkUpdate(ctx context.Context, dc *downstreamConn, params []string) error {
|
---|
549 | if len(params) < 1 {
|
---|
550 | return fmt.Errorf("expected at least one argument")
|
---|
551 | }
|
---|
552 |
|
---|
553 | fs := newNetworkFlagSet()
|
---|
554 | if err := fs.Parse(params[1:]); err != nil {
|
---|
555 | return err
|
---|
556 | }
|
---|
557 |
|
---|
558 | net := dc.user.getNetwork(params[0])
|
---|
559 | if net == nil {
|
---|
560 | return fmt.Errorf("unknown network %q", params[0])
|
---|
561 | }
|
---|
562 |
|
---|
563 | record := net.Network // copy network record because we'll mutate it
|
---|
564 | if err := fs.update(&record); err != nil {
|
---|
565 | return err
|
---|
566 | }
|
---|
567 |
|
---|
568 | network, err := dc.user.updateNetwork(ctx, &record)
|
---|
569 | if err != nil {
|
---|
570 | return fmt.Errorf("could not update network: %v", err)
|
---|
571 | }
|
---|
572 |
|
---|
573 | sendServicePRIVMSG(dc, fmt.Sprintf("updated network %q", network.GetName()))
|
---|
574 | return nil
|
---|
575 | }
|
---|
576 |
|
---|
577 | func handleServiceNetworkDelete(ctx context.Context, dc *downstreamConn, params []string) error {
|
---|
578 | if len(params) != 1 {
|
---|
579 | return fmt.Errorf("expected exactly one argument")
|
---|
580 | }
|
---|
581 |
|
---|
582 | net := dc.user.getNetwork(params[0])
|
---|
583 | if net == nil {
|
---|
584 | return fmt.Errorf("unknown network %q", params[0])
|
---|
585 | }
|
---|
586 |
|
---|
587 | if err := dc.user.deleteNetwork(ctx, net.ID); err != nil {
|
---|
588 | return err
|
---|
589 | }
|
---|
590 |
|
---|
591 | sendServicePRIVMSG(dc, fmt.Sprintf("deleted network %q", net.GetName()))
|
---|
592 | return nil
|
---|
593 | }
|
---|
594 |
|
---|
595 | func handleServiceNetworkQuote(ctx context.Context, dc *downstreamConn, params []string) error {
|
---|
596 | if len(params) != 2 {
|
---|
597 | return fmt.Errorf("expected exactly two arguments")
|
---|
598 | }
|
---|
599 |
|
---|
600 | net := dc.user.getNetwork(params[0])
|
---|
601 | if net == nil {
|
---|
602 | return fmt.Errorf("unknown network %q", params[0])
|
---|
603 | }
|
---|
604 |
|
---|
605 | uc := net.conn
|
---|
606 | if uc == nil {
|
---|
607 | return fmt.Errorf("network %q is not currently connected", params[0])
|
---|
608 | }
|
---|
609 |
|
---|
610 | m, err := irc.ParseMessage(params[1])
|
---|
611 | if err != nil {
|
---|
612 | return fmt.Errorf("failed to parse command %q: %v", params[1], err)
|
---|
613 | }
|
---|
614 | uc.SendMessage(m)
|
---|
615 |
|
---|
616 | sendServicePRIVMSG(dc, fmt.Sprintf("sent command to %q", net.GetName()))
|
---|
617 | return nil
|
---|
618 | }
|
---|
619 |
|
---|
620 | func sendCertfpFingerprints(dc *downstreamConn, cert []byte) {
|
---|
621 | sha1Sum := sha1.Sum(cert)
|
---|
622 | sendServicePRIVMSG(dc, "SHA-1 fingerprint: "+hex.EncodeToString(sha1Sum[:]))
|
---|
623 | sha256Sum := sha256.Sum256(cert)
|
---|
624 | sendServicePRIVMSG(dc, "SHA-256 fingerprint: "+hex.EncodeToString(sha256Sum[:]))
|
---|
625 | sha512Sum := sha512.Sum512(cert)
|
---|
626 | sendServicePRIVMSG(dc, "SHA-512 fingerprint: "+hex.EncodeToString(sha512Sum[:]))
|
---|
627 | }
|
---|
628 |
|
---|
629 | func handleServiceCertFPGenerate(ctx context.Context, dc *downstreamConn, params []string) error {
|
---|
630 | fs := newFlagSet()
|
---|
631 | keyType := fs.String("key-type", "rsa", "key type to generate (rsa, ecdsa, ed25519)")
|
---|
632 | bits := fs.Int("bits", 3072, "size of key to generate, meaningful only for RSA")
|
---|
633 |
|
---|
634 | if err := fs.Parse(params); err != nil {
|
---|
635 | return err
|
---|
636 | }
|
---|
637 |
|
---|
638 | if len(fs.Args()) != 1 {
|
---|
639 | return errors.New("exactly one argument is required")
|
---|
640 | }
|
---|
641 |
|
---|
642 | net := dc.user.getNetwork(fs.Arg(0))
|
---|
643 | if net == nil {
|
---|
644 | return fmt.Errorf("unknown network %q", fs.Arg(0))
|
---|
645 | }
|
---|
646 |
|
---|
647 | if *bits <= 0 || *bits > maxRSABits {
|
---|
648 | return fmt.Errorf("invalid value for -bits")
|
---|
649 | }
|
---|
650 |
|
---|
651 | privKey, cert, err := generateCertFP(*keyType, *bits)
|
---|
652 | if err != nil {
|
---|
653 | return err
|
---|
654 | }
|
---|
655 |
|
---|
656 | net.SASL.External.CertBlob = cert
|
---|
657 | net.SASL.External.PrivKeyBlob = privKey
|
---|
658 | net.SASL.Mechanism = "EXTERNAL"
|
---|
659 |
|
---|
660 | if err := dc.srv.db.StoreNetwork(ctx, dc.user.ID, &net.Network); err != nil {
|
---|
661 | return err
|
---|
662 | }
|
---|
663 |
|
---|
664 | sendServicePRIVMSG(dc, "certificate generated")
|
---|
665 | sendCertfpFingerprints(dc, cert)
|
---|
666 | return nil
|
---|
667 | }
|
---|
668 |
|
---|
669 | func handleServiceCertFPFingerprints(ctx context.Context, dc *downstreamConn, params []string) error {
|
---|
670 | if len(params) != 1 {
|
---|
671 | return fmt.Errorf("expected exactly one argument")
|
---|
672 | }
|
---|
673 |
|
---|
674 | net := dc.user.getNetwork(params[0])
|
---|
675 | if net == nil {
|
---|
676 | return fmt.Errorf("unknown network %q", params[0])
|
---|
677 | }
|
---|
678 |
|
---|
679 | if net.SASL.Mechanism != "EXTERNAL" {
|
---|
680 | return fmt.Errorf("CertFP not set up")
|
---|
681 | }
|
---|
682 |
|
---|
683 | sendCertfpFingerprints(dc, net.SASL.External.CertBlob)
|
---|
684 | return nil
|
---|
685 | }
|
---|
686 |
|
---|
687 | func handleServiceSASLSetPlain(ctx context.Context, dc *downstreamConn, params []string) error {
|
---|
688 | if len(params) != 3 {
|
---|
689 | return fmt.Errorf("expected exactly 3 arguments")
|
---|
690 | }
|
---|
691 |
|
---|
692 | net := dc.user.getNetwork(params[0])
|
---|
693 | if net == nil {
|
---|
694 | return fmt.Errorf("unknown network %q", params[0])
|
---|
695 | }
|
---|
696 |
|
---|
697 | net.SASL.Plain.Username = params[1]
|
---|
698 | net.SASL.Plain.Password = params[2]
|
---|
699 | net.SASL.Mechanism = "PLAIN"
|
---|
700 |
|
---|
701 | if err := dc.srv.db.StoreNetwork(ctx, dc.user.ID, &net.Network); err != nil {
|
---|
702 | return err
|
---|
703 | }
|
---|
704 |
|
---|
705 | sendServicePRIVMSG(dc, "credentials saved")
|
---|
706 | return nil
|
---|
707 | }
|
---|
708 |
|
---|
709 | func handleServiceSASLReset(ctx context.Context, dc *downstreamConn, params []string) error {
|
---|
710 | if len(params) != 1 {
|
---|
711 | return fmt.Errorf("expected exactly one argument")
|
---|
712 | }
|
---|
713 |
|
---|
714 | net := dc.user.getNetwork(params[0])
|
---|
715 | if net == nil {
|
---|
716 | return fmt.Errorf("unknown network %q", params[0])
|
---|
717 | }
|
---|
718 |
|
---|
719 | net.SASL.Plain.Username = ""
|
---|
720 | net.SASL.Plain.Password = ""
|
---|
721 | net.SASL.External.CertBlob = nil
|
---|
722 | net.SASL.External.PrivKeyBlob = nil
|
---|
723 | net.SASL.Mechanism = ""
|
---|
724 |
|
---|
725 | if err := dc.srv.db.StoreNetwork(ctx, dc.user.ID, &net.Network); err != nil {
|
---|
726 | return err
|
---|
727 | }
|
---|
728 |
|
---|
729 | sendServicePRIVMSG(dc, "credentials reset")
|
---|
730 | return nil
|
---|
731 | }
|
---|
732 |
|
---|
733 | func handleUserCreate(ctx context.Context, dc *downstreamConn, params []string) error {
|
---|
734 | fs := newFlagSet()
|
---|
735 | username := fs.String("username", "", "")
|
---|
736 | password := fs.String("password", "", "")
|
---|
737 | realname := fs.String("realname", "", "")
|
---|
738 | admin := fs.Bool("admin", false, "")
|
---|
739 |
|
---|
740 | if err := fs.Parse(params); err != nil {
|
---|
741 | return err
|
---|
742 | }
|
---|
743 | if *username == "" {
|
---|
744 | return fmt.Errorf("flag -username is required")
|
---|
745 | }
|
---|
746 | if *password == "" {
|
---|
747 | return fmt.Errorf("flag -password is required")
|
---|
748 | }
|
---|
749 |
|
---|
750 | hashed, err := bcrypt.GenerateFromPassword([]byte(*password), bcrypt.DefaultCost)
|
---|
751 | if err != nil {
|
---|
752 | return fmt.Errorf("failed to hash password: %v", err)
|
---|
753 | }
|
---|
754 |
|
---|
755 | user := &User{
|
---|
756 | Username: *username,
|
---|
757 | Password: string(hashed),
|
---|
758 | Realname: *realname,
|
---|
759 | Admin: *admin,
|
---|
760 | }
|
---|
761 | if _, err := dc.srv.createUser(ctx, user); err != nil {
|
---|
762 | return fmt.Errorf("could not create user: %v", err)
|
---|
763 | }
|
---|
764 |
|
---|
765 | sendServicePRIVMSG(dc, fmt.Sprintf("created user %q", *username))
|
---|
766 | return nil
|
---|
767 | }
|
---|
768 |
|
---|
769 | func popArg(params []string) (string, []string) {
|
---|
770 | if len(params) > 0 && !strings.HasPrefix(params[0], "-") {
|
---|
771 | return params[0], params[1:]
|
---|
772 | }
|
---|
773 | return "", params
|
---|
774 | }
|
---|
775 |
|
---|
776 | func handleUserUpdate(ctx context.Context, dc *downstreamConn, params []string) error {
|
---|
777 | var password, realname *string
|
---|
778 | var admin *bool
|
---|
779 | fs := newFlagSet()
|
---|
780 | fs.Var(stringPtrFlag{&password}, "password", "")
|
---|
781 | fs.Var(stringPtrFlag{&realname}, "realname", "")
|
---|
782 | fs.Var(boolPtrFlag{&admin}, "admin", "")
|
---|
783 |
|
---|
784 | username, params := popArg(params)
|
---|
785 | if err := fs.Parse(params); err != nil {
|
---|
786 | return err
|
---|
787 | }
|
---|
788 | if len(fs.Args()) > 0 {
|
---|
789 | return fmt.Errorf("unexpected argument")
|
---|
790 | }
|
---|
791 |
|
---|
792 | var hashed *string
|
---|
793 | if password != nil {
|
---|
794 | hashedBytes, err := bcrypt.GenerateFromPassword([]byte(*password), bcrypt.DefaultCost)
|
---|
795 | if err != nil {
|
---|
796 | return fmt.Errorf("failed to hash password: %v", err)
|
---|
797 | }
|
---|
798 | hashedStr := string(hashedBytes)
|
---|
799 | hashed = &hashedStr
|
---|
800 | }
|
---|
801 |
|
---|
802 | if username != "" && username != dc.user.Username {
|
---|
803 | if !dc.user.Admin {
|
---|
804 | return fmt.Errorf("you must be an admin to update other users")
|
---|
805 | }
|
---|
806 | if realname != nil {
|
---|
807 | return fmt.Errorf("cannot update -realname of other user")
|
---|
808 | }
|
---|
809 |
|
---|
810 | u := dc.srv.getUser(username)
|
---|
811 | if u == nil {
|
---|
812 | return fmt.Errorf("unknown username %q", username)
|
---|
813 | }
|
---|
814 |
|
---|
815 | done := make(chan error, 1)
|
---|
816 | event := eventUserUpdate{
|
---|
817 | password: hashed,
|
---|
818 | admin: admin,
|
---|
819 | done: done,
|
---|
820 | }
|
---|
821 | select {
|
---|
822 | case <-ctx.Done():
|
---|
823 | return ctx.Err()
|
---|
824 | case u.events <- event:
|
---|
825 | }
|
---|
826 | // TODO: send context to the other side
|
---|
827 | if err := <-done; err != nil {
|
---|
828 | return err
|
---|
829 | }
|
---|
830 |
|
---|
831 | sendServicePRIVMSG(dc, fmt.Sprintf("updated user %q", username))
|
---|
832 | } else {
|
---|
833 | // copy the user record because we'll mutate it
|
---|
834 | record := dc.user.User
|
---|
835 |
|
---|
836 | if hashed != nil {
|
---|
837 | record.Password = *hashed
|
---|
838 | }
|
---|
839 | if realname != nil {
|
---|
840 | record.Realname = *realname
|
---|
841 | }
|
---|
842 | if admin != nil {
|
---|
843 | return fmt.Errorf("cannot update -admin of own user")
|
---|
844 | }
|
---|
845 |
|
---|
846 | if err := dc.user.updateUser(ctx, &record); err != nil {
|
---|
847 | return err
|
---|
848 | }
|
---|
849 |
|
---|
850 | sendServicePRIVMSG(dc, fmt.Sprintf("updated user %q", dc.user.Username))
|
---|
851 | }
|
---|
852 |
|
---|
853 | return nil
|
---|
854 | }
|
---|
855 |
|
---|
856 | func handleUserDelete(ctx context.Context, dc *downstreamConn, params []string) error {
|
---|
857 | if len(params) != 1 {
|
---|
858 | return fmt.Errorf("expected exactly one argument")
|
---|
859 | }
|
---|
860 | username := params[0]
|
---|
861 |
|
---|
862 | u := dc.srv.getUser(username)
|
---|
863 | if u == nil {
|
---|
864 | return fmt.Errorf("unknown username %q", username)
|
---|
865 | }
|
---|
866 |
|
---|
867 | u.stop()
|
---|
868 |
|
---|
869 | if err := dc.srv.db.DeleteUser(ctx, u.ID); err != nil {
|
---|
870 | return fmt.Errorf("failed to delete user: %v", err)
|
---|
871 | }
|
---|
872 |
|
---|
873 | sendServicePRIVMSG(dc, fmt.Sprintf("deleted user %q", username))
|
---|
874 | return nil
|
---|
875 | }
|
---|
876 |
|
---|
877 | func handleServiceChannelStatus(ctx context.Context, dc *downstreamConn, params []string) error {
|
---|
878 | var defaultNetworkName string
|
---|
879 | if dc.network != nil {
|
---|
880 | defaultNetworkName = dc.network.GetName()
|
---|
881 | }
|
---|
882 |
|
---|
883 | fs := newFlagSet()
|
---|
884 | networkName := fs.String("network", defaultNetworkName, "")
|
---|
885 |
|
---|
886 | if err := fs.Parse(params); err != nil {
|
---|
887 | return err
|
---|
888 | }
|
---|
889 |
|
---|
890 | n := 0
|
---|
891 |
|
---|
892 | sendNetwork := func(net *network) {
|
---|
893 | var channels []*Channel
|
---|
894 | for _, entry := range net.channels.innerMap {
|
---|
895 | channels = append(channels, entry.value.(*Channel))
|
---|
896 | }
|
---|
897 |
|
---|
898 | sort.Slice(channels, func(i, j int) bool {
|
---|
899 | return strings.ReplaceAll(channels[i].Name, "#", "") <
|
---|
900 | strings.ReplaceAll(channels[j].Name, "#", "")
|
---|
901 | })
|
---|
902 |
|
---|
903 | for _, ch := range channels {
|
---|
904 | var uch *upstreamChannel
|
---|
905 | if net.conn != nil {
|
---|
906 | uch = net.conn.channels.Value(ch.Name)
|
---|
907 | }
|
---|
908 |
|
---|
909 | name := ch.Name
|
---|
910 | if *networkName == "" {
|
---|
911 | name += "/" + net.GetName()
|
---|
912 | }
|
---|
913 |
|
---|
914 | var status string
|
---|
915 | if uch != nil {
|
---|
916 | status = "joined"
|
---|
917 | } else if net.conn != nil {
|
---|
918 | status = "parted"
|
---|
919 | } else {
|
---|
920 | status = "disconnected"
|
---|
921 | }
|
---|
922 |
|
---|
923 | if ch.Detached {
|
---|
924 | status += ", detached"
|
---|
925 | }
|
---|
926 |
|
---|
927 | s := fmt.Sprintf("%v [%v]", name, status)
|
---|
928 | sendServicePRIVMSG(dc, s)
|
---|
929 |
|
---|
930 | n++
|
---|
931 | }
|
---|
932 | }
|
---|
933 |
|
---|
934 | if *networkName == "" {
|
---|
935 | dc.user.forEachNetwork(sendNetwork)
|
---|
936 | } else {
|
---|
937 | net := dc.user.getNetwork(*networkName)
|
---|
938 | if net == nil {
|
---|
939 | return fmt.Errorf("unknown network %q", *networkName)
|
---|
940 | }
|
---|
941 | sendNetwork(net)
|
---|
942 | }
|
---|
943 |
|
---|
944 | if n == 0 {
|
---|
945 | sendServicePRIVMSG(dc, "No channel configured.")
|
---|
946 | }
|
---|
947 |
|
---|
948 | return nil
|
---|
949 | }
|
---|
950 |
|
---|
951 | type channelFlagSet struct {
|
---|
952 | *flag.FlagSet
|
---|
953 | RelayDetached, ReattachOn, DetachAfter, DetachOn *string
|
---|
954 | }
|
---|
955 |
|
---|
956 | func newChannelFlagSet() *channelFlagSet {
|
---|
957 | fs := &channelFlagSet{FlagSet: newFlagSet()}
|
---|
958 | fs.Var(stringPtrFlag{&fs.RelayDetached}, "relay-detached", "")
|
---|
959 | fs.Var(stringPtrFlag{&fs.ReattachOn}, "reattach-on", "")
|
---|
960 | fs.Var(stringPtrFlag{&fs.DetachAfter}, "detach-after", "")
|
---|
961 | fs.Var(stringPtrFlag{&fs.DetachOn}, "detach-on", "")
|
---|
962 | return fs
|
---|
963 | }
|
---|
964 |
|
---|
965 | func (fs *channelFlagSet) update(channel *Channel) error {
|
---|
966 | if fs.RelayDetached != nil {
|
---|
967 | filter, err := parseFilter(*fs.RelayDetached)
|
---|
968 | if err != nil {
|
---|
969 | return err
|
---|
970 | }
|
---|
971 | channel.RelayDetached = filter
|
---|
972 | }
|
---|
973 | if fs.ReattachOn != nil {
|
---|
974 | filter, err := parseFilter(*fs.ReattachOn)
|
---|
975 | if err != nil {
|
---|
976 | return err
|
---|
977 | }
|
---|
978 | channel.ReattachOn = filter
|
---|
979 | }
|
---|
980 | if fs.DetachAfter != nil {
|
---|
981 | dur, err := time.ParseDuration(*fs.DetachAfter)
|
---|
982 | if err != nil || dur < 0 {
|
---|
983 | return fmt.Errorf("unknown duration for -detach-after %q (duration format: 0, 300s, 22h30m, ...)", *fs.DetachAfter)
|
---|
984 | }
|
---|
985 | channel.DetachAfter = dur
|
---|
986 | }
|
---|
987 | if fs.DetachOn != nil {
|
---|
988 | filter, err := parseFilter(*fs.DetachOn)
|
---|
989 | if err != nil {
|
---|
990 | return err
|
---|
991 | }
|
---|
992 | channel.DetachOn = filter
|
---|
993 | }
|
---|
994 | return nil
|
---|
995 | }
|
---|
996 |
|
---|
997 | func handleServiceChannelUpdate(ctx context.Context, dc *downstreamConn, params []string) error {
|
---|
998 | if len(params) < 1 {
|
---|
999 | return fmt.Errorf("expected at least one argument")
|
---|
1000 | }
|
---|
1001 | name := params[0]
|
---|
1002 |
|
---|
1003 | fs := newChannelFlagSet()
|
---|
1004 | if err := fs.Parse(params[1:]); err != nil {
|
---|
1005 | return err
|
---|
1006 | }
|
---|
1007 |
|
---|
1008 | uc, upstreamName, err := dc.unmarshalEntity(name)
|
---|
1009 | if err != nil {
|
---|
1010 | return fmt.Errorf("unknown channel %q", name)
|
---|
1011 | }
|
---|
1012 |
|
---|
1013 | ch := uc.network.channels.Value(upstreamName)
|
---|
1014 | if ch == nil {
|
---|
1015 | return fmt.Errorf("unknown channel %q", name)
|
---|
1016 | }
|
---|
1017 |
|
---|
1018 | if err := fs.update(ch); err != nil {
|
---|
1019 | return err
|
---|
1020 | }
|
---|
1021 |
|
---|
1022 | uc.updateChannelAutoDetach(upstreamName)
|
---|
1023 |
|
---|
1024 | if err := dc.srv.db.StoreChannel(ctx, uc.network.ID, ch); err != nil {
|
---|
1025 | return fmt.Errorf("failed to update channel: %v", err)
|
---|
1026 | }
|
---|
1027 |
|
---|
1028 | sendServicePRIVMSG(dc, fmt.Sprintf("updated channel %q", name))
|
---|
1029 | return nil
|
---|
1030 | }
|
---|
1031 |
|
---|
1032 | func handleServiceServerStatus(ctx context.Context, dc *downstreamConn, params []string) error {
|
---|
1033 | dbStats, err := dc.user.srv.db.Stats(ctx)
|
---|
1034 | if err != nil {
|
---|
1035 | return err
|
---|
1036 | }
|
---|
1037 | serverStats := dc.user.srv.Stats()
|
---|
1038 | sendServicePRIVMSG(dc, fmt.Sprintf("%v/%v users, %v downstreams, %v networks, %v channels", serverStats.Users, dbStats.Users, serverStats.Downstreams, dbStats.Networks, dbStats.Channels))
|
---|
1039 | return nil
|
---|
1040 | }
|
---|
1041 |
|
---|
1042 | func handleServiceServerNotice(ctx context.Context, dc *downstreamConn, params []string) error {
|
---|
1043 | if len(params) != 1 {
|
---|
1044 | return fmt.Errorf("expected exactly one argument")
|
---|
1045 | }
|
---|
1046 | text := params[0]
|
---|
1047 |
|
---|
1048 | dc.logger.Printf("broadcasting bouncer-wide NOTICE: %v", text)
|
---|
1049 |
|
---|
1050 | broadcastMsg := &irc.Message{
|
---|
1051 | Prefix: servicePrefix,
|
---|
1052 | Command: "NOTICE",
|
---|
1053 | Params: []string{"$" + dc.srv.Hostname, text},
|
---|
1054 | }
|
---|
1055 | var err error
|
---|
1056 | dc.srv.forEachUser(func(u *user) {
|
---|
1057 | select {
|
---|
1058 | case <-ctx.Done():
|
---|
1059 | err = ctx.Err()
|
---|
1060 | case u.events <- eventBroadcast{broadcastMsg}:
|
---|
1061 | }
|
---|
1062 | })
|
---|
1063 | return err
|
---|
1064 | }
|
---|