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