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