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