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