Debian Codegraph @

mpd/internal/server/server.go

raw symbols SCIP
1 // Copyright 2013 The GoMPD Authors. All rights reserved.
2 // Use of this source code is governed by the MIT
3 // license that can be found in the LICENSE file
4
5 // Package server implements a fake MPD server that's used to test gompd client.
6 package server
7
8 import (
9 "fmt"
10 "io"
11 "log"
12 "net"
13 "net/textproto"
14 "os"
15 "sort"
16 "strconv"
17 "strings"
18 )
19
20 // attrs is a set of attributes returned by MPD.
21 type attrs map[string]string
22
23 const (
24 accErrorNoExist = 50
25 )
26
27 func unquote(line string, start int) (string, int) {
28 i := start
29 if line[i] != '"' {
30 for i < len(line) && (line[i] != ' ' && line[i] != '\t') {
31 i++
32 }
33 return line[start:i], i
34 }
35
36 i++ // beginning "
37 s := make([]byte, len(line[i:]))
38 n := 0
39 for i < len(line) {
40 if line[i] == '"' { // ending "
41 i++
42 break
43 }
44 if line[i] == '\\' && i+1 < len(line) {
45 i++
46 }
47 s[n] = line[i]
48 i++
49 n++
50 }
51 return string(s[:n]), i
52 }
53
54 func parseArgs(line string) (args []string) {
55 var s string
56 i := 0
57 for i < len(line) {
58 if line[i] == ' ' || line[i] == '\t' {
59 i++
60 continue
61 }
62 s, i = unquote(line, i)
63 args = append(args, s)
64 }
65 return
66 }
67
68 type playlistEntry struct {
69 song int
70 id int
71 }
72
73 type playlist struct {
74 songs []playlistEntry
75 maxid int
76 }
77
78 func newPlaylist() *playlist {
79 return &playlist{songs: make([]playlistEntry, 0), maxid: 0}
80 }
81
82 func (p *playlist) At(i int) int {
83 return p.songs[i].song
84 }
85
86 func (p *playlist) Len() int {
87 return len(p.songs)
88 }
89
90 func (p *playlist) Add(song int) int {
91 entry := playlistEntry{song: song, id: p.maxid}
92 p.songs = append(p.songs, entry)
93 p.maxid++
94 return entry.id
95 }
96
97 func (p *playlist) Delete(i int) {
98 if i < 0 || i >= len(p.songs) {
99 return
100 }
101 copy(p.songs[i:], p.songs[i+1:])
102 p.songs = p.songs[:len(p.songs)-1]
103 }
104
105 func (p *playlist) Clear() {
106 p.songs = p.songs[:0]
107 }
108
109 func (p *playlist) Append(q *playlist) {
110 // TODO: do at most one allocation
111 for i := 0; i < q.Len(); i++ {
112 p.Add(q.At(i))
113 }
114 }
115
116 type sticker struct {
117 Name, Value string
118 }
119
120 func newSticker(name, value string) *sticker {
121 return &sticker{
122 Name: name,
123 Value: value,
124 }
125 }
126
127 func (s *sticker) String() string {
128 return s.Name + "=" + s.Value
129 }
130
131 type stickers map[string]*sticker
132
133 func newStickers() stickers {
134 return make(stickers)
135 }
136
137 func (ss stickers) Set(name, value string) {
138 if _, ok := ss[name]; !ok {
139 ss[name] = newSticker(name, value)
140 return
141 }
142 ss[name].Value = value
143 }
144
145 func (ss stickers) Get(name string) *sticker {
146 return ss[name]
147 }
148
149 func (ss stickers) Delete(name string) {
150 delete(ss, name)
151 }
152
153 func (ss stickers) Sorted() []*sticker {
154 var v []*sticker
155 for _, s := range ss {
156 v = append(v, s)
157 }
158 sort.Slice(v, func(i, j int) bool {
159 return v[i].Name < v[j].Name
160 })
161 return v
162 }
163
164 type server struct {
165 state string
166 database []attrs // database of songs
167 index map[string]int // maps URI to database index
168 playlists map[string]*playlist
169 currentPlaylist *playlist
170 songStickers map[string]stickers
171 pos int // in currentPlaylist
172 artwork []byte
173 idleEventc chan string
174 idleStartc chan *idleRequest
175 idleEndc chan uint
176 }
177
178 func newServer() *server {
179 s := &server{
180 state: "stop",
181 database: make([]attrs, 100),
182 index: make(map[string]int, 100),
183 songStickers: make(map[string]stickers, 100),
184 playlists: make(map[string]*playlist),
185 currentPlaylist: newPlaylist(),
186 pos: 0,
187 artwork: []byte{0x01, 0x02, 0x03, 0x04, 0x05},
188 idleEventc: make(chan string),
189 idleStartc: make(chan *idleRequest),
190 idleEndc: make(chan uint),
191 }
192 for i := 0; i < len(s.database); i++ {
193 s.database[i] = make(attrs, 5)
194 filename := fmt.Sprintf("song%04d.ogg", i)
195 s.database[i]["file"] = filename
196 s.index[filename] = i
197 s.songStickers[filename] = newStickers()
198 }
199 return s
200 }
201
202 func writeBinaryChunk(p *textproto.Conn, data []byte, offset, length int) {
203 p.PrintfLine("size: %d", len(data))
204 if offset+length > len(data) {
205 length = len(data) - offset
206 }
207 p.PrintfLine("binary: %d", length)
208 // Can't use p.PrintfLine() for writing bytes since it'd terminate the data with \r\n instead of just \n
209 p.W.Write(data[offset : offset+length])
210 p.W.WriteByte('\n')
211 }
212
213 func (s *server) writeResponse(p *textproto.Conn, args []string, okLine string) (cmdOk, closed bool) {
214 if len(args) < 1 {
215 p.PrintfLine("No command given")
216 return
217 }
218 ack := func(format string, a ...interface{}) error {
219 return p.PrintfLine("ACK {"+args[0]+"} "+format, a...)
220 }
221 ackWithCode := func(code int, format string, a ...interface{}) error {
222 return p.PrintfLine(fmt.Sprintf("ACK [%d@0] {%s} %s", code, args[0], format), a...)
223 }
224 switch args[0] {
225 case "close":
226 closed = true
227 return
228 case "list":
229 if len(args) < 2 || args[1] == "" {
230 ack("too few arguments")
231 return
232 }
233 if args[1] == "file" {
234 for _, a := range s.database {
235 p.PrintfLine("file: %s", a["file"])
236 }
237 }
238 case "listallinfo":
239 if len(args) < 2 || args[1] == "" {
240 ack("too few arguments")
241 return
242 }
243 p.PrintfLine("OK")
244 case "lsinfo":
245 if len(args) < 2 || args[1] == "" {
246 ack("too few arguments")
247 return
248 }
249 for _, a := range s.database {
250 p.PrintfLine("file: %s", a["file"])
251 p.PrintfLine("Last-Modified: 2014-07-02T12:32:26Z")
252 p.PrintfLine("Artist: Newcleus")
253 p.PrintfLine("Title: Jam On It")
254 p.PrintfLine("Track: 02")
255 }
256 for _, a := range []string{
257 "music/Buck 65 - Dirtbike 1",
258 "music/Howlin' Wolf - Moanin' in the Moonlight",
259 } {
260 p.PrintfLine("directory: %s", a)
261 }
262 p.PrintfLine("playlist: BBC 6 Music.m3u")
263 case "readcomments":
264 if len(args) < 2 || args[1] == "" {
265 ack("too few arguments")
266 return
267 }
268
269 p.PrintfLine("TITLE: Jam On It")
270 p.PrintfLine("ARTIST: Newcleus")
271 p.PrintfLine("ALBUM: Jam on Revenge")
272 case "listplaylists":
273 for k := range s.playlists {
274 p.PrintfLine("playlist: %s", k)
275 }
276 case "playlistinfo":
277 var rng []string
278 var start int
279 end := s.currentPlaylist.Len()
280
281 if len(args) >= 2 {
282 rng = strings.Split(args[1], ":")
283 }
284
285 if len(rng) == 1 {
286 // Requesting a single song from the playlist at position i.
287 i, err := strconv.Atoi(rng[0])
288 if err != nil {
289 ack("invalid song position")
290 return
291 }
292 start = i
293 end = i + 1
294 } else if len(rng) == 2 {
295 // Requesting a range of the playlist from specified start/end positions.
296 var err error
297 start, err = strconv.Atoi(rng[0])
298 if err != nil {
299 ack("integer or range expected")
300 return
301 }
302 end, err := strconv.Atoi(rng[1])
303 if err != nil {
304 ack("integer or range expected")
305 return
306 }
307 if start < 0 || end < 0 {
308 ack("number is negative")
309 return
310 }
311 }
312
313 for i := start; i < end; i++ {
314 p.PrintfLine("file: %s", s.database[s.currentPlaylist.At(i)]["file"])
315 }
316 case "listplaylistinfo":
317 if len(args) < 2 {
318 ack("too few arguments")
319 return
320 }
321 pl, ok := s.playlists[args[1]]
322 if !ok {
323 ack("no such playlist")
324 return
325 }
326 for i := 0; i < pl.Len(); i++ {
327 p.PrintfLine("file: %s", s.database[pl.At(i)]["file"])
328 }
329 case "playlistadd":
330 if len(args) != 3 {
331 ack("wrong number of arguments")
332 return
333 }
334 name, uri := args[1], args[2]
335 i, ok := s.index[uri]
336 if !ok {
337 ack("URI not found")
338 return
339 }
340 if s.playlists[name] == nil {
341 s.playlists[name] = newPlaylist()
342 }
343 s.playlists[name].Add(i)
344 case "playlistdelete":
345 if len(args) != 3 {
346 ack("wrong number of arguments")
347 return
348 }
349 name := args[1]
350 pos, err := strconv.Atoi(args[2])
351 if err != nil {
352 ack("invalid position number")
353 return
354 }
355 pl, ok := s.playlists[name]
356 if !ok {
357 ack("playlist not found")
358 return
359 }
360 if pos < 0 || pos >= pl.Len() {
361 ack("invalid song position")
362 return
363 }
364 pl.Delete(pos)
365 case "playlistclear":
366 if len(args) != 2 {
367 ack("wrong number of arguments")
368 return
369 }
370 pl, ok := s.playlists[args[1]]
371 if !ok {
372 ack("playlist not found")
373 return
374 }
375 pl.Clear()
376 case "rm":
377 if len(args) != 2 {
378 ack("wrong number of arguments")
379 return
380 }
381 _, ok := s.playlists[args[1]]
382 if !ok {
383 ack("playlist not found")
384 return
385 }
386 delete(s.playlists, args[1])
387 case "rename":
388 if len(args) != 3 {
389 ack("wrong number of arguments")
390 return
391 }
392 old, new := args[1], args[2]
393 _, ok := s.playlists[old]
394 if !ok {
395 ack("playlist %s does not exist", old)
396 return
397 }
398 _, ok = s.playlists[new]
399 if ok {
400 ack("playlist %s already exists", new)
401 return
402 }
403 s.playlists[new] = s.playlists[old]
404 delete(s.playlists, old)
405 case "load":
406 if len(args) != 2 {
407 ack("wrong number of arguments")
408 return
409 }
410 pl, ok := s.playlists[args[1]]
411 if !ok {
412 ack("playlist %s does not exist", args[1])
413 return
414 }
415 s.currentPlaylist.Append(pl)
416 case "clear":
417 s.currentPlaylist.Clear()
418 case "add":
419 if len(args) != 2 {
420 ack("wrong number of arguments")
421 return
422 }
423 i, ok := s.index[args[1]]
424 if !ok {
425 ack("URI not found")
426 return
427 }
428 s.currentPlaylist.Add(i)
429 case "addid":
430 if len(args) < 2 || len(args) > 3 {
431 ack("wrong number of arguments")
432 return
433 }
434 i, ok := s.index[args[1]]
435 if !ok {
436 ack("URI not found")
437 return
438 }
439 id := s.currentPlaylist.Add(i)
440 p.PrintfLine("Id: %d", id)
441 case "prio":
442 if len(args) != 3 {
443 ack("wrong number of arguments")
444 return
445 }
446 rng := strings.Split(args[2], ":")
447 prio, err := strconv.Atoi(args[1])
448 if err != nil || prio < 0 || prio > 255 {
449 ack("invalid priority")
450 return
451 }
452
453 switch len(rng) {
454 case 1:
455 // Updating a single song from the playlist at position i.
456 i, err := strconv.Atoi(rng[0])
457 if err != nil {
458 ack("invalid song position")
459 return
460 }
461 // Note: we don't check end as it does not matter for our test case
462 if i < 0 {
463 ack("invalid song position")
464 }
465 case 2:
466 // Updating a range of the playlist from specified start/end positions.
467 start, err := strconv.Atoi(rng[0])
468 if err != nil {
469 ack("integer or range expected")
470 return
471 }
472 end, err := strconv.Atoi(rng[1])
473 if err != nil {
474 ack("integer or range expected")
475 return
476 }
477 if start < 0 || end < 0 {
478 ack("number is negative")
479 return
480 }
481 default:
482 ack("invalid range")
483 }
484 case "prioid":
485 if len(args) != 3 {
486 ack("wrong number of arguments")
487 return
488 }
489 prio, err := strconv.Atoi(args[1])
490 if err != nil || prio < 0 || prio > 255 {
491 ack("invalid priority")
492 return
493 }
494 id, err := strconv.Atoi(args[2])
495 if err != nil || id < 0 {
496 ack("invalid song ID")
497 return
498 }
499 case "delete":
500 if len(args) != 2 {
501 ack("wrong number of arguments")
502 return
503 }
504 i, err := strconv.Atoi(args[1])
505 if err != nil {
506 ack("invalid song position")
507 return
508 }
509 s.idleEventc <- "playlist"
510 if i < 0 || i >= s.currentPlaylist.Len() {
511 ack("invalid song position")
512 return
513 }
514 s.currentPlaylist.Delete(i)
515 case "deleteid":
516 if len(args) != 2 {
517 ack("wrong number of arguments")
518 return
519 }
520 id, err := strconv.Atoi(args[1])
521 if err != nil {
522 ack("invalid song ID")
523 return
524 }
525 s.idleEventc <- "playlist"
526 deleted := false
527 for i, song := range s.currentPlaylist.songs {
528 if song.id == id {
529 deleted = true
530 s.currentPlaylist.Delete(i)
531 break
532 }
533 }
534 if !deleted {
535 ackWithCode(accErrorNoExist, "No such song")
536 return
537 }
538 case "save":
539 if len(args) != 2 {
540 ack("wrong number of arguments")
541 return
542 }
543 name := args[1]
544 _, ok := s.playlists[name]
545 if ok {
546 ack("playlist %s already exists", name)
547 return
548 }
549 s.playlists[name] = newPlaylist()
550 s.playlists[name].Append(s.currentPlaylist)
551 case "play", "stop":
552 s.idleEventc <- "player"
553 s.state = args[0]
554 case "next":
555 s.idleEventc <- "player"
556 if s.pos < 0 || s.pos >= s.currentPlaylist.Len() {
557 s.pos = 0
558 break
559 }
560 s.pos = (s.pos + 1) % s.currentPlaylist.Len()
561 case "previous":
562 s.idleEventc <- "player"
563 if s.pos < 0 || s.pos >= s.currentPlaylist.Len() {
564 s.pos = 0
565 break
566 }
567 if s.pos == 0 {
568 s.pos = s.currentPlaylist.Len() - 1
569 break
570 }
571 s.pos--
572 case "pause":
573 if s.state != "stop" {
574 s.state = args[0]
575 }
576 case "status":
577 state := s.state
578 p.PrintfLine("state: %s", state)
579 case "update", "rescan":
580 if len(args) < 2 || args[1] == "" {
581 ack("too few arguments")
582 return
583 }
584 p.PrintfLine("updating_db: 1")
585 case "ping":
586 case "currentsong":
587 if s.currentPlaylist.Len() == 0 {
588 break
589 }
590 if s.pos >= s.currentPlaylist.Len() {
591 s.pos = 0
592 }
593 p.PrintfLine("file: %s", s.database[s.currentPlaylist.At(s.pos)]["file"])
594 case "albumart":
595 if len(args) < 2 || len(args) > 3 {
596 ack("wrong number of arguments")
597 return
598 }
599 artLen, offset := len(s.artwork), 0
600 var err error
601 if len(args) == 3 {
602 if offset, err = strconv.Atoi(args[2]); err != nil {
603 ack("invalid offset value: %v", err)
604 return
605 } else if offset >= artLen {
606 ack("offset beyond end of file")
607 return
608 }
609 }
610
611 switch args[1] {
612 case "/file/with/small-artwork":
613 // Give away the entire "file" at once
614 writeBinaryChunk(p, s.artwork, offset, len(s.artwork))
615 case "/file/with/huge-artwork":
616 // Give away the "file" 3 bytes at a time
617 writeBinaryChunk(p, s.artwork, offset, 3)
618 default:
619 ack("no artwork found")
620 }
621
622 case "readpicture":
623 if len(args) < 2 || len(args) > 3 {
624 ack("wrong number of arguments")
625 return
626 }
627 artLen, offset := len(s.artwork), 0
628 var err error
629 if len(args) == 3 {
630 if offset, err = strconv.Atoi(args[2]); err != nil {
631 ack("invalid offset value: %v", err)
632 return
633 } else if offset >= artLen {
634 ack("offset beyond end of file")
635 return
636 }
637 }
638
639 switch args[1] {
640 case "/file/with/small-artwork":
641 // Give away the entire "file" at once
642 writeBinaryChunk(p, s.artwork, offset, len(s.artwork))
643 case "/file/with/huge-artwork":
644 // Give away the "file" 3 bytes at a time
645 writeBinaryChunk(p, s.artwork, offset, 3)
646 default:
647 ack("no artwork found")
648 }
649
650 case "outputs":
651 p.PrintfLine("outputid: 0")
652 p.PrintfLine("outputenabled: 1")
653 p.PrintfLine("outputname: downstairs")
654 p.PrintfLine("outputid: 1")
655 p.PrintfLine("outputenabled: 0")
656 p.PrintfLine("outputname: upstairs")
657 case "disableoutput", "enableoutput":
658 case "sticker":
659 if len(args) < 4 {
660 ack("too few arguments")
661 return
662 }
663 if args[2] != "song" {
664 ack("Invalid object type %q", args[2])
665 return
666 }
667 uri := args[3]
668
669 switch args[1] {
670 case "get":
671 if len(args) < 5 {
672 ack("bad request")
673 return
674 }
675 name := args[4]
676 v, ok := s.songStickers[uri]
677 if !ok {
678 ack("No such song %q", uri)
679 return
680 }
681 stk := v.Get(name)
682 if stk == nil {
683 ack("no such sticker %q", name)
684 return
685 }
686 p.PrintfLine("sticker: %s", stk)
687
688 case "set":
689 if len(args) < 6 {
690 ack("bad request")
691 return
692 }
693 v, ok := s.songStickers[uri]
694 if !ok {
695 ack("No such song %q", uri)
696 return
697 }
698 v.Set(args[4], args[5])
699
700 case "delete":
701 if len(args) < 5 {
702 ack("bad request")
703 return
704 }
705 name := args[4]
706 v, ok := s.songStickers[uri]
707 if !ok {
708 ack("No such song %q", uri)
709 return
710 }
711 if stk := v.Get(name); stk == nil {
712 ack("No such sticker %q", name)
713 return
714 }
715 v.Delete(name)
716
717 case "list":
718 v, ok := s.songStickers[uri]
719 if !ok {
720 ack("No such song %q", uri)
721 return
722 }
723 for _, stk := range v.Sorted() {
724 p.PrintfLine("sticker: %s", stk)
725 }
726
727 case "find":
728 if len(args) < 5 {
729 ack("bad request")
730 return
731 }
732 name := args[4]
733
734 for file, v := range s.songStickers {
735 if stk := v.Get(name); stk != nil {
736 p.PrintfLine("file: %s", file)
737 p.PrintfLine("sticker: %s", stk)
738 }
739 }
740 }
741 default:
742 p.PrintfLine("ACK {} unknown command %q", args[0])
743 log.Printf("unknown command: %s\n", args[0])
744 return
745 }
746 cmdOk = true
747 p.PrintfLine(okLine)
748 return
749 }
750
751 type requestType int
752
753 const (
754 simple requestType = iota
755 commandListOk
756 idle
757 noIdle
758 )
759
760 type request struct {
761 typ requestType
762 args []string
763 cmdList [][]string
764 }
765
766 func (s *server) readRequest(p *textproto.Conn) (*request, error) {
767 line, err := p.ReadLine()
768 if err == io.EOF {
769 return nil, err
770 }
771 if err != nil {
772 log.Printf("reading request failed: %v\n", err)
773 return nil, err
774 }
775 args := parseArgs(line)
776 if len(args) == 0 {
777 return &request{typ: simple, args: args}, nil
778 }
779 switch args[0] {
780 case "command_list_ok_begin":
781 var cmdList [][]string
782 for {
783 line, err := p.ReadLine()
784 if err == io.EOF {
785 return nil, err
786 }
787 if err != nil {
788 log.Printf("reading request failed: %v\n", err)
789 return nil, err
790 }
791 args = parseArgs(line)
792 if len(args) > 0 && args[0] == "command_list_end" {
793 break
794 }
795 cmdList = append(cmdList, args)
796 }
797 return &request{typ: commandListOk, cmdList: cmdList}, nil
798
799 case "idle":
800 return &request{typ: idle, args: args}, nil
801
802 case "noidle":
803 return &request{typ: noIdle, args: args}, nil
804 }
805 return &request{typ: simple, args: args}, nil
806 }
807
808 type idleRequest struct {
809 endTokenc chan uint // for token used to end event broadcast
810 eventc chan string // for subsystem name
811 subsystems []string // subsystems to listen for changes
812 }
813
814 func (s *server) writeIdleResponse(p *textproto.Conn, id uint, quit chan bool, subsystems []string) {
815 p.StartResponse(id)
816 defer p.EndResponse(id)
817
818 req := &idleRequest{
819 endTokenc: make(chan uint),
820 eventc: make(chan string, 1),
821 subsystems: subsystems,
822 }
823 s.idleStartc <- req
824 token := <-req.endTokenc
825 select {
826 case name := <-req.eventc:
827 p.PrintfLine("changed: %s", name)
828 p.PrintfLine("OK")
829 <-quit
830 case <-quit:
831 p.PrintfLine("OK")
832 }
833 s.idleEndc <- token
834 }
835
836 func (s *server) handleConnection(p *textproto.Conn) {
837 id := p.Next()
838 p.StartRequest(id)
839 p.EndRequest(id)
840 p.StartResponse(id)
841 p.PrintfLine("OK MPD gompd0.1")
842 p.EndResponse(id)
843
844 endIdle := make(chan bool)
845 inIdle := false
846 defer p.Close()
847 for {
848 id := p.Next()
849 p.StartRequest(id)
850 req, err := s.readRequest(p)
851 if err != nil {
852 return
853 }
854 // We need to do this inside request because idle response
855 // may not have ended yet, but it will end after the following.
856 if inIdle {
857 endIdle <- true
858 }
859 p.EndRequest(id)
860
861 if req.typ == idle {
862 inIdle = true
863 go s.writeIdleResponse(p, id, endIdle, req.args[1:])
864 // writeIdleResponse does it's own StartResponse/EndResponse
865 continue
866 }
867
868 p.StartResponse(id)
869 if inIdle {
870 inIdle = false
871 }
872 switch req.typ {
873 case noIdle:
874 case commandListOk:
875 var ok, closed bool
876 ok = true
877 for _, args := range req.cmdList {
878 ok, closed = s.writeResponse(p, args, "list_OK")
879 if closed {
880 return
881 }
882 if !ok {
883 break
884 }
885 }
886 if ok {
887 p.PrintfLine("OK")
888 }
889 case simple:
890 if _, closed := s.writeResponse(p, req.args, "OK"); closed {
891 return
892 }
893 }
894 p.EndResponse(id)
895 }
896 }
897
898 var knownSubsystems = []string{
899 "database",
900 "update",
901 "stored_playlist",
902 "playlist",
903 "player",
904 "mixer",
905 "output",
906 "options",
907 }
908
909 func indexID(v []uint, id uint) int {
910 for i, n := range v {
911 if id == n {
912 return i
913 }
914 }
915 return -1
916 }
917
918 func deleteID(v []uint, id uint) []uint {
919 i := indexID(v, id)
920 if i < 0 {
921 return v
922 }
923 copy(v[i:], v[i+1:])
924 return v[:len(v)-1]
925 }
926
927 func (s *server) broadcastIdleEvents() {
928 clientChans := make(map[uint]chan string)
929 subsys := make(map[string][]uint)
930 for _, name := range knownSubsystems {
931 subsys[name] = make([]uint, 0)
932 }
933 token := uint(0)
934 for {
935 select {
936 case req := <-s.idleStartc:
937 clientChans[token] = req.eventc
938 names := req.subsystems
939 if len(req.subsystems) == 0 {
940 names = knownSubsystems
941 }
942 for _, name := range names {
943 if _, ok := subsys[name]; !ok {
944 subsys[name] = make([]uint, 0)
945 }
946 subsys[name] = append(subsys[name], token)
947 }
948 req.endTokenc <- token
949 token++
950
951 case client := <-s.idleEndc:
952 delete(clientChans, client)
953 for name := range subsys {
954 subsys[name] = deleteID(subsys[name], client)
955 }
956
957 case name := <-s.idleEventc:
958 if clients, ok := subsys[name]; ok {
959 for _, c := range clients {
960 select {
961 case clientChans[c] <- name:
962 default:
963 }
964 }
965 }
966 }
967 }
968 }
969
970 // Listen starts the server on the network network and address addr.
971 // Once the server has started, a value is sent to listening channel.
972 func Listen(network, addr string, listening chan bool) {
973 ln, err := net.Listen(network, addr)
974 if err != nil {
975 log.Fatalf("Listen failed: %v\n", err)
976 os.Exit(1)
977 }
978 s := newServer()
979 go s.broadcastIdleEvents()
980 listening <- true
981 for {
982 conn, err := ln.Accept()
983 if err != nil {
984 log.Printf("Accept failed: %v\n", err)
985 continue
986 }
987 go s.handleConnection(textproto.NewConn(conn))
988 }
989 }