chiark / gitweb /
Provide for a network initialization step
[disorder] / clients / disorder.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2004-2013 Richard Kettlewell
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 /** @file clients/disorder.c
19  * @brief Command-line client
20  */
21
22 #include "common.h"
23
24 #include <getopt.h>
25 #include <sys/types.h>
26 #if HAVE_SYS_SOCKET_H
27 # include <sys/socket.h>
28 #endif
29 #if HAVE_SYS_UN_H
30 # include <sys/un.h>
31 #endif
32 #include <errno.h>
33 #include <locale.h>
34 #include <time.h>
35 #include <stddef.h>
36 #if HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
39 #if HAVE_PCRE_H
40 # include <pcre.h>
41 #endif
42 #include <ctype.h>
43 #if HAVE_GCRYPT_H
44 # include <gcrypt.h>
45 #endif
46 #if HAVE_LANGINFO_H
47 # include <langinfo.h>
48 #endif
49
50 #include "configuration.h"
51 #include "syscalls.h"
52 #include "log.h"
53 #include "queue.h"
54 #include "client.h"
55 #include "wstat.h"
56 #include "table.h"
57 #include "charset.h"
58 #include "kvp.h"
59 #include "split.h"
60 #include "sink.h"
61 #include "mem.h"
62 #include "defs.h"
63 #include "authorize.h"
64 #include "vector.h"
65 #include "version.h"
66 #include "dateparse.h"
67 #include "inputline.h"
68
69 static disorder_client *client;
70
71 static const struct option options[] = {
72   { "help", no_argument, 0, 'h' },
73   { "version", no_argument, 0, 'V' },
74   { "config", required_argument, 0, 'c' },
75   { "debug", no_argument, 0, 'd' },
76   { "local", no_argument, 0, 'l' },
77   { "no-per-user-config", no_argument, 0, 'N' },
78   { "help-commands", no_argument, 0, 'H' },
79   { "user", required_argument, 0, 'u' },
80   { "password", required_argument, 0, 'p' },
81   { 0, 0, 0, 0 }
82 };
83
84 /* display usage message and terminate */
85 static void help(void) {
86   xprintf("Usage:\n"
87           "  disorder [OPTIONS] COMMAND ...\n"
88           "Options:\n"
89           "  --help, -h              Display usage message\n"
90           "  --help-commands, -H     List commands\n"
91           "  --version, -V           Display version number\n"
92           "  --config PATH, -c PATH  Set configuration file\n"
93           "  --local, -l             Force connection to local server\n"
94           "  --debug, -d             Turn on debugging\n");
95   xfclose(stdout);
96   exit(0);
97 }
98
99 static disorder_client *getclient(void) {
100   if(!client) {
101     if(!(client = disorder_new(1))) exit(EXIT_FAILURE);
102     if(disorder_connect(client)) exit(EXIT_FAILURE);
103   }
104   return client;
105 }
106
107 static void cf_version(char attribute((unused)) **argv) {
108   char *v;
109
110   if(disorder_version(getclient(), &v)) exit(EXIT_FAILURE);
111   v = nullcheck(utf82mb_f(v));
112   xprintf("%s\n", v);
113   xfree(v);
114 }
115
116 static void print_queue_entry(const struct queue_entry *q) {
117   if(q->track) xprintf("track %s\n", nullcheck(utf82mb(q->track)));
118   if(q->id) xprintf("  id %s\n", nullcheck(utf82mb(q->id)));
119   switch(q->origin) {
120   case origin_adopted:
121   case origin_picked:
122   case origin_scheduled:
123     xprintf("  %s by %s at %s",
124             track_origins[q->origin],
125             nullcheck(utf82mb(q->submitter)), ctime(&q->when));
126     break;
127   default:
128     break;
129   }
130   if(q->played) xprintf("  played at %s", ctime(&q->played));
131   if(q->state == playing_started
132      || q->state == playing_paused) xprintf("  %lds so far",  q->sofar);
133   else if(q->expected) xprintf("  might start at %s", ctime(&q->expected));
134   if(q->scratched) xprintf("  scratched by %s\n",
135                            nullcheck(utf82mb(q->scratched)));
136   else xprintf("  %s\n", playing_states[q->state]);
137   if(q->wstat) xprintf("  %s\n", wstat(q->wstat));
138 }
139
140 static void cf_playing(char attribute((unused)) **argv) {
141   struct queue_entry *q;
142
143   if(disorder_playing(getclient(), &q)) exit(EXIT_FAILURE);
144   if(q)
145     print_queue_entry(q);
146   else
147     xprintf("nothing\n");
148 }
149
150 static void cf_play(char **argv) {
151   char *id;
152   while(*argv)
153     if(disorder_play(getclient(), *argv++, &id)) exit(EXIT_FAILURE);
154 }
155
156 static void cf_remove(char **argv) {
157   if(disorder_remove(getclient(), argv[0])) exit(EXIT_FAILURE);
158 }
159
160 static void cf_disable(char attribute((unused)) **argv) {
161   if(disorder_disable(getclient())) exit(EXIT_FAILURE);
162 }
163
164 static void cf_enable(char attribute((unused)) **argv) {
165   if(disorder_enable(getclient())) exit(EXIT_FAILURE);
166 }
167
168 static void cf_scratch(char **argv) {
169   if(disorder_scratch(getclient(), argv[0])) exit(EXIT_FAILURE);
170 }
171
172 static void cf_shutdown(char attribute((unused)) **argv) {
173   if(disorder_shutdown(getclient())) exit(EXIT_FAILURE);
174 }
175
176 static void cf_reconfigure(char attribute((unused)) **argv) {
177   /* Re-check configuration for server */
178   if(config_read(1, NULL))
179     disorder_fatal(0, "cannot read configuration");
180   if(disorder_reconfigure(getclient())) exit(EXIT_FAILURE);
181 }
182
183 static void cf_rescan(char attribute((unused)) **argv) {
184   if(disorder_rescan(getclient())) exit(EXIT_FAILURE);
185 }
186
187 static void cf_somequeue(int (*fn)(disorder_client *c,
188                                    struct queue_entry **qp)) {
189   struct queue_entry *q, *qbase;
190
191   if(fn(getclient(), &qbase)) exit(EXIT_FAILURE);
192   for(q = qbase; q; q = q->next)
193     print_queue_entry(q);
194   queue_free(qbase, 1);
195 }
196
197 static void cf_recent(char attribute((unused)) **argv) {
198   cf_somequeue(disorder_recent);
199 }
200
201 static void cf_queue(char attribute((unused)) **argv) {
202   cf_somequeue(disorder_queue);
203 }
204
205 static void cf_quack(char attribute((unused)) **argv) {
206   if(!strcasecmp(nl_langinfo(CODESET), "utf-8")) {
207 #define TL "\xE2\x95\xAD"
208 #define TR "\xE2\x95\xAE"
209 #define BR "\xE2\x95\xAF"
210 #define BL "\xE2\x95\xB0"
211 #define H "\xE2\x94\x80"
212 #define V "\xE2\x94\x82"
213 #define T "\xE2\x94\xAC"
214     xprintf("\n"
215             " "TL H H H H H H H H H H H H H H H H H H TR"\n"
216             " "V" Naath is a babe! "V"\n"
217             " "BL H H H H H H H H H T H H H H H H H H BR"\n"
218             "            \\\n"
219             "              >0\n"
220             "               (<)'\n"
221             "~~~~~~~~~~~~~~~~~~~~~~\n"
222             "\n");
223   } else {
224     xprintf("\n"
225             " .------------------.\n"
226             " | Naath is a babe! |\n"
227             " `---------+--------'\n"
228             "            \\\n"
229             "              >0\n"
230             "               (<)'\n"
231             "~~~~~~~~~~~~~~~~~~~~~~\n"
232             "\n");
233   }
234 }
235
236 static void cf_somelist(char **argv,
237                         int (*fn)(disorder_client *c,
238                                   const char *arg, const char *re,
239                                   char ***vecp, int *nvecp)) {
240   char **vec, **base;
241   const char *re;
242
243   if(argv[1])
244     re = xstrdup(argv[1] + 1);
245   else
246     re = 0;
247   if(fn(getclient(), argv[0], re, &base, 0)) exit(EXIT_FAILURE);
248   for(vec = base; *vec; ++vec)
249     xprintf("%s\n", nullcheck(utf82mb_f(*vec)));
250   xfree(base);
251 }
252
253 static int isarg_regexp(const char *s) {
254   return s[0] == '~';
255 }
256
257 static void cf_dirs(char **argv) {
258   cf_somelist(argv, disorder_dirs);
259 }
260
261 static void cf_files(char **argv) {
262   cf_somelist(argv, disorder_files);
263 }
264
265 static void cf_allfiles(char **argv) {
266   cf_somelist(argv, disorder_allfiles);
267 }
268
269 static void cf_get(char **argv) {
270   char *value;
271
272   if(disorder_get(getclient(), argv[0], argv[1], &value)) exit(EXIT_FAILURE);
273   xprintf("%s\n", nullcheck(utf82mb_f(value)));
274 }
275
276 static void cf_length(char **argv) {
277   long length;
278
279   if(disorder_length(getclient(), argv[0], &length)) exit(EXIT_FAILURE);
280   xprintf("%ld\n", length);
281 }
282
283 static void cf_set(char **argv) {
284   if(disorder_set(getclient(), argv[0], argv[1], argv[2])) exit(EXIT_FAILURE);
285 }
286
287 static void cf_unset(char **argv) {
288   if(disorder_unset(getclient(), argv[0], argv[1])) exit(EXIT_FAILURE);
289 }
290
291 static void cf_prefs(char **argv) {
292   struct kvp *k, *base;
293
294   if(disorder_prefs(getclient(), argv[0], &base)) exit(EXIT_FAILURE);
295   for(k = base; k; k = k->next)
296     xprintf("%s = %s\n",
297             nullcheck(utf82mb(k->name)), nullcheck(utf82mb(k->value)));
298   kvp_free(base);
299 }
300
301 static void cf_search(char **argv) {
302   char **results;
303   int nresults, n;
304
305   if(disorder_search(getclient(), *argv, &results, &nresults)) exit(EXIT_FAILURE);
306   for(n = 0; n < nresults; ++n)
307     xprintf("%s\n", nullcheck(utf82mb(results[n])));
308   free_strings(nresults, results);
309 }
310
311 static void cf_random_disable(char attribute((unused)) **argv) {
312   if(disorder_random_disable(getclient())) exit(EXIT_FAILURE);
313 }
314
315 static void cf_random_enable(char attribute((unused)) **argv) {
316   if(disorder_random_enable(getclient())) exit(EXIT_FAILURE);
317 }
318
319 static void cf_stats(char attribute((unused)) **argv) {
320   char **vec;
321   int nvec;
322   int n;
323
324   if(disorder_stats(getclient(), &vec, &nvec)) exit(EXIT_FAILURE);
325   for(n = 0; n < nvec; ++n)
326     xprintf("%s\n", nullcheck(utf82mb(vec[n])));
327   free_strings(nvec, vec);
328 }
329
330 static void cf_get_volume(char attribute((unused)) **argv) {
331   long l, r;
332
333   if(disorder_get_volume(getclient(), &l, &r)) exit(EXIT_FAILURE);
334   xprintf("%ld %ld\n", l, r);
335 }
336
337 static void cf_set_volume(char **argv) {
338   if(disorder_set_volume(getclient(), atoi(argv[0]), atoi(argv[1]))) exit(EXIT_FAILURE);
339 }
340
341 static void cf_log(char attribute((unused)) **argv) {
342   if(disorder_log(getclient(), sink_stdio("stdout", stdout))) exit(EXIT_FAILURE);
343 }
344
345 static void cf_move(char **argv) {
346   long n;
347   int e;
348   
349   if((e = xstrtol(&n, argv[1], 0, 10)))
350     disorder_fatal(e, "cannot convert '%s'", argv[1]);
351   if(n > INT_MAX || n < INT_MIN)
352     disorder_fatal(e, "%ld out of range", n);
353   if(disorder_move(getclient(), argv[0], (int)n)) exit(EXIT_FAILURE);
354 }
355
356 static void cf_part(char **argv) {
357   char *s;
358
359   if(disorder_part(getclient(), argv[0], argv[1], argv[2], &s)) exit(EXIT_FAILURE);
360   xprintf("%s\n", nullcheck(utf82mb_f(s)));
361 }
362
363 static int isarg_filename(const char *s) {
364   return s[0] == '/';
365 }
366
367 static void cf_authorize(char **argv) {
368   authorize(getclient(), argv[0], argv[1]);
369 }
370
371 static void cf_resolve(char **argv) {
372   char *track;
373
374   if(disorder_resolve(getclient(), argv[0], &track)) exit(EXIT_FAILURE);
375   xprintf("%s\n", nullcheck(utf82mb_f(track)));
376 }
377
378 static void cf_pause(char attribute((unused)) **argv) {
379   if(disorder_pause(getclient())) exit(EXIT_FAILURE);
380 }
381
382 static void cf_resume(char attribute((unused)) **argv) {
383   if(disorder_resume(getclient())) exit(EXIT_FAILURE);
384 }
385
386 static void cf_tags(char attribute((unused)) **argv) {
387   char **vec;
388
389   if(disorder_tags(getclient(), &vec, 0)) exit(EXIT_FAILURE);
390   while(*vec)
391       xprintf("%s\n", nullcheck(utf82mb(*vec++)));
392 }
393
394 static void cf_users(char attribute((unused)) **argv) {
395   char **vec;
396
397   if(disorder_users(getclient(), &vec, 0)) exit(EXIT_FAILURE);
398   while(*vec)
399     xprintf("%s\n", nullcheck(utf82mb(*vec++)));
400 }
401
402 static void cf_get_global(char **argv) {
403   char *value;
404
405   if(disorder_get_global(getclient(), argv[0], &value)) exit(EXIT_FAILURE);
406   xprintf("%s\n", nullcheck(utf82mb_f(value)));
407 }
408
409 static void cf_set_global(char **argv) {
410   if(disorder_set_global(getclient(), argv[0], argv[1])) exit(EXIT_FAILURE);
411 }
412
413 static void cf_unset_global(char **argv) {
414   if(disorder_unset_global(getclient(), argv[0])) exit(EXIT_FAILURE);
415 }
416
417 static int isarg_integer(const char *s) {
418   if(!*s) return 0;
419   while(*s) {
420     if(!isdigit((unsigned char)*s))
421       return 0;
422     ++s;
423   }
424   return 1;
425 }
426
427 static void cf_new(char **argv) {
428   char **vec;
429
430   if(disorder_new_tracks(getclient(), argv[0] ? atol(argv[0]) : 0, &vec, 0))
431     exit(EXIT_FAILURE);
432   while(*vec)
433     xprintf("%s\n", nullcheck(utf82mb(*vec++)));
434 }
435
436 static void cf_rtp_address(char attribute((unused)) **argv) {
437   char *address, *port;
438
439   if(disorder_rtp_address(getclient(), &address, &port)) exit(EXIT_FAILURE);
440   xprintf("address: %s\nport: %s\n", address, port);
441 }
442
443 static int isarg_rights(const char *arg) {
444   return strchr(arg, ',') || !parse_rights(arg, 0, 0);
445 }
446
447 static void cf_adduser(char **argv) {
448   if(disorder_adduser(getclient(), argv[0], argv[1], argv[2]))
449     exit(EXIT_FAILURE);
450 }
451
452 static void cf_deluser(char **argv) {
453   if(disorder_deluser(getclient(), argv[0]))
454     exit(EXIT_FAILURE);
455 }
456
457 static void cf_edituser(char **argv) {
458   if(disorder_edituser(getclient(), argv[0], argv[1], argv[2]))
459     exit(EXIT_FAILURE);
460 }
461
462 static void cf_userinfo(char **argv) {
463   char *s;
464
465   if(disorder_userinfo(getclient(), argv[0], argv[1], &s))
466     exit(EXIT_FAILURE);
467   xprintf("%s\n", nullcheck(utf82mb_f(s)));
468 }
469
470 static int isarg_option(const char *arg) {
471   return arg[0] == '-';
472 }
473
474 static int argvlen(char **argv) {
475   char **start = argv;
476   
477   while(*argv)
478     ++argv;
479   return argv - start;
480 }
481
482 static const struct option setup_guest_options[] = {
483   { "help", no_argument, 0, 'h' },
484   { "online-registration", no_argument, 0, 'r' },
485   { "no-online-registration", no_argument, 0, 'R' },
486   { 0, 0, 0, 0 }
487 };
488
489 static void help_setup_guest(void) {
490   xprintf("Usage:\n"
491           "  disorder setup-guest [OPTIONS]\n"
492           "Options:\n"
493           "  --help, -h                Display usage message\n"
494           "  --online-registration     Enable online registration (default)\n"
495           "  --no-online-registration  Disable online registration\n");
496   xfclose(stdout);
497   exit(0);
498 }
499
500 static void cf_setup_guest(char **argv) {
501   int n, online_registration = 1;
502   
503   while((n = getopt_long(argvlen(argv) + 1, argv - 1,
504                          "hrR", setup_guest_options, 0)) >= 0) {
505     switch(n) {
506     case 'h': help_setup_guest();
507     case 'r': online_registration = 1; break;
508     case 'R': online_registration = 0; break;
509     default: disorder_fatal(0, "invalid option");
510     }
511   }
512   if(online_registration && !config->mail_sender)
513     disorder_fatal(0, "you MUST set mail_sender if you want online registration");
514   if(disorder_adduser(getclient(), "guest", "",
515                       online_registration ? "read,register" : "read"))
516     exit(EXIT_FAILURE);
517 }
518
519 /** @brief A scheduled event read from the server */
520 struct scheduled_event {
521   /** @brief When event should occur */
522   time_t when;
523
524   /** @brief Details of action */
525   struct kvp *actiondata;
526
527   /** @brief Event ID */
528   char *id;
529 };
530
531 static int compare_event(const void *av, const void *bv) {
532   struct scheduled_event *a = (void *)av, *b = (void *)bv;
533
534   /* Primary sort key is the trigger time */
535   if(a->when < b->when)
536     return -1;
537   else if(a->when > b->when)
538     return 1;
539   /* For events that go off at the same time just sort by ID */
540   return strcmp(a->id, b->id);
541 }
542
543 static void cf_schedule_list(char attribute((unused)) **argv) {
544   char **ids;
545   int nids, n;
546   struct scheduled_event *events;
547   char tb[128];
548   const char *action, *key, *value, *priority;
549   int prichar;
550
551   /* Get all known events */
552   if(disorder_schedule_list(getclient(), &ids, &nids))
553     exit(EXIT_FAILURE);
554   events = xcalloc(nids, sizeof *events);
555   for(n = 0; n < nids; ++n) {
556     events[n].id = ids[n];
557     if(disorder_schedule_get(getclient(), ids[n], &events[n].actiondata))
558       exit(EXIT_FAILURE);
559     events[n].when = atoll(kvp_get(events[n].actiondata, "when"));
560   }
561   /* Sort by trigger time */
562   qsort(events, nids, sizeof *events, compare_event);
563   /* Display them */
564   for(n = 0; n < nids; ++n) {
565     strftime(tb, sizeof tb, "%Y-%m-%d %H:%M:%S %Z", localtime(&events[n].when));
566     action = kvp_get(events[n].actiondata, "action");
567     priority = kvp_get(events[n].actiondata, "priority");
568     if(!strcmp(priority, "junk"))
569       prichar = 'J';
570     else if(!strcmp(priority, "normal"))
571       prichar = 'N';
572     else
573       prichar = '?';
574     xprintf("%11s %-25s %c %-8s %s",
575             events[n].id, tb, prichar, kvp_get(events[n].actiondata, "who"),
576             action);
577     if(!strcmp(action, "play"))
578       xprintf(" %s",
579               nullcheck(utf82mb(kvp_get(events[n].actiondata, "track"))));
580     else if(!strcmp(action, "set-global")) {
581       key = kvp_get(events[n].actiondata, "key");
582       value = kvp_get(events[n].actiondata, "value");
583       if(value)
584         xprintf(" %s=%s",
585                 nullcheck(utf82mb(key)),
586                 nullcheck(utf82mb(value)));
587       else
588         xprintf(" %s unset",
589                 nullcheck(utf82mb(key)));
590     }
591     xprintf("\n");
592   }
593 }
594
595 static void cf_schedule_del(char **argv) {
596   if(disorder_schedule_del(getclient(), argv[0]))
597     exit(EXIT_FAILURE);
598 }
599
600 static void cf_schedule_play(char **argv) {
601   if(disorder_schedule_add_play(getclient(),
602                                 dateparse(argv[0]),
603                                 argv[1],
604                                 argv[2]))
605     exit(EXIT_FAILURE);
606 }
607
608 static void cf_schedule_set_global(char **argv) {
609   if(disorder_schedule_add_set_global(getclient(),
610                                       dateparse(argv[0]),
611                                       argv[1],
612                                       argv[2],
613                                       argv[3]))
614     exit(EXIT_FAILURE);
615 }
616
617 static void cf_schedule_unset_global(char **argv) {
618   if(disorder_schedule_add_unset_global(getclient(),
619                                         dateparse(argv[0]),
620                                         argv[1],
621                                         argv[2]))
622     exit(EXIT_FAILURE);
623 }
624
625 static void cf_adopt(char **argv) {
626   if(disorder_adopt(getclient(), argv[0]))
627     exit(EXIT_FAILURE);
628 }
629
630 static void cf_playlists(char attribute((unused)) **argv) {
631   char **vec;
632   int nvec;
633   int n;
634
635   if(disorder_playlists(getclient(), &vec, &nvec))
636     exit(EXIT_FAILURE);
637   for(n = 0; n < nvec; ++n)
638     xprintf("%s\n", nullcheck(utf82mb(vec[n])));
639   free_strings(nvec, vec);
640 }
641
642 static void cf_playlist_del(char **argv) {
643   if(disorder_playlist_delete(getclient(), argv[0]))
644     exit(EXIT_FAILURE);
645 }
646
647 static void cf_playlist_get(char **argv) {
648   char **vec;
649   int nvec;
650   int n;
651
652   if(disorder_playlist_get(getclient(), argv[0], &vec, &nvec))
653     exit(EXIT_FAILURE);
654   for(n = 0; n < nvec; ++n)
655     xprintf("%s\n", nullcheck(utf82mb(vec[n])));
656   free_strings(nvec, vec);
657 }
658
659 static void cf_playlist_set(char **argv) {
660   struct vector v[1];
661   FILE *input;
662   const char *tag;
663   char *l;
664
665   if(argv[1]) {
666     // Read track list from file
667     if(!(input = fopen(argv[1], "r")))
668       disorder_fatal(errno, "opening %s", argv[1]);
669     tag = argv[1];
670   } else {
671     // Read track list from standard input
672     input = stdin;
673     tag = "stdin";
674   }
675   vector_init(v);
676   while(!inputline(tag, input, &l, '\n')) {
677     if(!strcmp(l, "."))
678       break;
679     vector_append(v, l);
680   }
681   if(ferror(input))
682     disorder_fatal(errno, "reading %s", tag);
683   if(input != stdin)
684     fclose(input);
685   if(disorder_playlist_lock(getclient(), argv[0])
686      || disorder_playlist_set(getclient(), argv[0], v->vec, v->nvec)
687      || disorder_playlist_unlock(getclient()))
688     exit(EXIT_FAILURE);
689 }
690
691 /** @brief Command-line client's definition of a command */
692 static const struct client_command {
693   /** @brief Command name */
694   const char *name;
695
696   /** @brief Minimum number of argument */
697   int min;
698
699   /** @brief Maximum number of argument */
700   int max;
701
702   /** @brief Pointer to function implementing command */
703   void (*fn)(char **);
704
705   /** @brief Function to recognize a valid argument, or NULL */
706   int (*isarg)(const char *);
707
708   /** @brief Summary of arguments */
709   const char *argstr;
710
711   /** @brief Description */
712   const char *desc;
713 } commands[] = {
714   { "adduser",        2, 3, cf_adduser, isarg_rights, "USERNAME PASSWORD [RIGHTS]",
715                       "Create a new user" },
716   { "adopt",          1, 1, cf_adopt, 0, "ID",
717                       "Adopt a randomly picked track" },
718   { "allfiles",       1, 2, cf_allfiles, isarg_regexp, "DIR [~REGEXP]",
719                       "List all files and directories in DIR" },
720   { "authorize",      1, 2, cf_authorize, isarg_rights, "USERNAME [RIGHTS]",
721                       "Authorize user USERNAME to connect" },
722   { "deluser",        1, 1, cf_deluser, 0, "USERNAME",
723                       "Delete user USERNAME" },
724   { "dirs",           1, 2, cf_dirs, isarg_regexp, "DIR [~REGEXP]",
725                       "List directories in DIR" },
726   { "disable",        0, 0, cf_disable, 0, "",
727                       "Disable play" },
728   { "disable-random", 0, 0, cf_random_disable, 0, "",
729                       "Disable random play" },
730   { "edituser",       3, 3, cf_edituser, 0, "USERNAME PROPERTY VALUE",
731                       "Set a property of user USERNAME" },
732   { "enable",         0, 0, cf_enable, 0, "",
733                       "Enable play" },
734   { "enable-random",  0, 0, cf_random_enable, 0, "",
735                       "Enable random play" },
736   { "files",          1, 2, cf_files, isarg_regexp, "DIR [~REGEXP]",
737                       "List files in DIR" },
738   { "get",            2, 2, cf_get, 0, "TRACK NAME",
739                       "Get a preference value" },
740   { "get-global",     1, 1, cf_get_global, 0, "NAME",
741                       "Get a global preference value" },
742   { "get-volume",     0, 0, cf_get_volume, 0, "",
743                       "Get the current volume" },
744   { "length",         1, 1, cf_length, 0, "TRACK",
745                       "Get the length of TRACK in seconds" },
746   { "log",            0, 0, cf_log, 0, "",
747                       "Copy event log to stdout" },
748   { "move",           2, 2, cf_move, 0, "TRACK DELTA",
749                       "Move a track in the queue" },
750   { "new",            0, 1, cf_new, isarg_integer, "[MAX]",
751                       "Get the most recently added MAX tracks" },
752   { "part",           3, 3, cf_part, 0, "TRACK CONTEXT PART",
753                       "Find a track name part" },
754   { "pause",          0, 0, cf_pause, 0, "",
755                       "Pause the currently playing track" },
756   { "play",           1, INT_MAX, cf_play, isarg_filename, "TRACKS...",
757                       "Add TRACKS to the end of the queue" },
758   { "playing",        0, 0, cf_playing, 0, "",
759                       "Report the playing track" },
760   { "playlist-del",   1, 1, cf_playlist_del, 0, "PLAYLIST",
761                       "Delete a playlist" },
762   { "playlist-get",   1, 1, cf_playlist_get, 0, "PLAYLIST",
763                       "Get the contents of a playlist" },
764   { "playlist-set",   1, 2, cf_playlist_set, isarg_filename, "PLAYLIST [PATH]",
765                       "Set the contents of a playlist" },
766   { "playlists",      0, 0, cf_playlists, 0, "",
767                       "List playlists" },
768   { "prefs",          1, 1, cf_prefs, 0, "TRACK",
769                       "Display all the preferences for TRACK" },
770   { "quack",          0, 0, cf_quack, 0, 0, 0 },
771   { "queue",          0, 0, cf_queue, 0, "",
772                       "Display the current queue" },
773   { "random-disable", 0, 0, cf_random_disable, 0, "",
774                       "Disable random play" },
775   { "random-enable",  0, 0, cf_random_enable, 0, "",
776                       "Enable random play" },
777   { "recent",         0, 0, cf_recent, 0, "",
778                       "Display recently played track" },
779   { "reconfigure",    0, 0, cf_reconfigure, 0, "",
780                       "Reconfigure the daemon" },
781   { "remove",         1, 1, cf_remove, 0, "TRACK",
782                       "Remove a track from the queue" },
783   { "rescan",         0, 0, cf_rescan, 0, "",
784                       "Rescan for new tracks" },
785   { "resolve",        1, 1, cf_resolve, 0, "TRACK",
786                       "Resolve alias for TRACK" },
787   { "resume",         0, 0, cf_resume, 0, "",
788                       "Resume after a pause" },
789   { "rtp-address",    0, 0, cf_rtp_address, 0, "",
790                       "Report server's broadcast address" },
791   { "schedule-del",   1, 1, cf_schedule_del, 0, "EVENT",
792                       "Delete a scheduled event" },
793   { "schedule-list",  0, 0, cf_schedule_list, 0, "",
794                       "List scheduled events" },
795   { "schedule-play",  3, 3, cf_schedule_play, 0, "WHEN PRI TRACK",
796                       "Play TRACK later" },
797   { "schedule-set-global", 4, 4, cf_schedule_set_global, 0, "WHEN PRI NAME VAL",
798                       "Set a global preference later" },
799   { "schedule-unset-global", 3, 3, cf_schedule_unset_global, 0, "WHEN PRI NAME",
800                       "Unset a global preference later" },
801   { "scratch",        0, 0, cf_scratch, 0, "",
802                       "Scratch the currently playing track" },
803   { "scratch-id",     1, 1, cf_scratch, 0, "ID",
804                       "Scratch the currently playing track" },
805   { "search",         1, 1, cf_search, 0, "WORDS",
806                       "Display tracks matching all the words" },
807   { "set",            3, 3, cf_set, 0, "TRACK NAME VALUE",
808                       "Set a preference value" },
809   { "set-global",     2, 2, cf_set_global, 0, "NAME VALUE",
810                       "Set a global preference value" },
811   { "set-volume",     2, 2, cf_set_volume, 0, "LEFT RIGHT",
812                       "Set the volume" },
813   { "setup-guest",    0, INT_MAX, cf_setup_guest, isarg_option, "[OPTIONS]",
814                       "Create the guest login" },
815   { "shutdown",       0, 0, cf_shutdown, 0, "",
816                       "Shut down the daemon" },
817   { "stats",          0, 0, cf_stats, 0, "",
818                       "Display server statistics" },
819   { "tags",           0, 0, cf_tags, 0, "",
820                       "List known tags" },
821   { "unset",          2, 2, cf_unset, 0, "TRACK NAME",
822                       "Unset a preference" },
823   { "unset-global",   1, 1, cf_unset_global, 0, "NAME",
824                       "Unset a global preference" },
825   { "userinfo",       2, 2, cf_userinfo, 0, "USERNAME PROPERTY",
826                       "Get a property of a user" },
827   { "users",          0, 0, cf_users, 0, "",
828                       "List all users" },
829   { "version",        0, 0, cf_version, 0, "",
830                       "Display the server version" },
831 };
832
833 static void help_commands(void) {
834   unsigned n, max = 0, l;
835
836   xprintf("Command summary:\n");
837   for(n = 0; n < sizeof commands / sizeof *commands; ++n) {
838     if(!commands[n].desc) continue;
839     l = strlen(commands[n].name);
840     if(*commands[n].argstr)
841       l += strlen(commands[n].argstr) + 1;
842     if(l > max)
843       max = l;
844   }
845   for(n = 0; n < sizeof commands / sizeof *commands; ++n) {
846     if(!commands[n].desc) continue;
847     l = strlen(commands[n].name);
848     if(*commands[n].argstr)
849       l += strlen(commands[n].argstr) + 1;
850     xprintf("  %s%s%s%*s  %s\n", commands[n].name,
851             *commands[n].argstr ? " " : "",
852             commands[n].argstr,
853             max - l, "",
854             commands[n].desc);
855   }
856   xfclose(stdout);
857   exit(0);
858 }
859
860 int main(int argc, char **argv) {
861   int n, i, j, local = 0;
862   int status = 0;
863   struct vector args;
864   const char *user = 0, *password = 0;
865
866   mem_init();
867   network_init();
868 #if HAVE_PCRE_H
869   /* garbage-collect PCRE's memory */
870   pcre_malloc = xmalloc;
871   pcre_free = xfree;
872 #endif
873   if(!setlocale(LC_CTYPE, "")) disorder_fatal(errno, "error calling setlocale");
874   if(!setlocale(LC_TIME, "")) disorder_fatal(errno, "error calling setlocale");
875   while((n = getopt_long(argc, argv, "+hVc:dHlNu:p:", options, 0)) >= 0) {
876     switch(n) {
877     case 'h': help();
878     case 'H': help_commands();
879     case 'V': version("disorder");
880     case 'c': configfile = optarg; break;
881     case 'd': debugging = 1; break;
882     case 'l': local = 1; break;
883     case 'N': config_per_user = 0; break;
884     case 'u': user = optarg; break;
885     case 'p': password = optarg; break;
886     default: disorder_fatal(0, "invalid option");
887     }
888   }
889   if(config_read(0, NULL)) disorder_fatal(0, "cannot read configuration");
890   if(user) {
891     xfree(config->username);
892     config->username = xstrdup(user);
893     config->password = 0;
894   }
895   if(password) {
896     xfree(config->password);
897     config->password = xstrdup(password);
898   }
899   if(local)
900     config->connect.af = -1;
901   n = optind;
902   optind = 1;                           /* for subsequent getopt calls */
903 #if HAVE_GCRYPT_H
904   /* gcrypt initialization */
905   if(!gcry_check_version(NULL))
906     disorder_fatal(0, "gcry_check_version failed");
907   gcry_control(GCRYCTL_INIT_SECMEM, 0);
908   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
909 #endif
910   /* accumulate command args */
911   while(n < argc) {
912     if((i = TABLE_FIND(commands, name, argv[n])) < 0)
913       disorder_fatal(0, "unknown command '%s'", argv[n]);
914     if(n + commands[i].min >= argc)
915       disorder_fatal(0, "missing arguments to '%s'", argv[n]);
916     vector_init(&args);
917     /* Include the command name in the args, but at element -1, for
918      * the benefit of subcommand getopt calls */
919     vector_append(&args, xstrdup(argv[n]));
920     n++;
921     for(j = 0; j < commands[i].min; ++j)
922       vector_append(&args, nullcheck(mb2utf8(argv[n + j])));
923     for(; j < commands[i].max
924           && n + j < argc
925           && commands[i].isarg(argv[n + j]); ++j)
926       vector_append(&args, nullcheck(mb2utf8(argv[n + j])));
927     vector_terminate(&args);
928     commands[i].fn(args.vec + 1);
929     vector_clear(&args);
930     n += j;
931   }
932   if(client && disorder_close(client)) exit(EXIT_FAILURE);
933   if(fclose(stdout) < 0) disorder_fatal(errno, "error closing stdout");
934   config_free(config);
935   xfree(client);
936   return status;
937 }
938
939 /*
940 Local Variables:
941 c-basic-offset:2
942 comment-column:40
943 End:
944 */