Blob


1 /*
2 * Copyright (c) 2022, 2023 Omar Polo <op@omarpolo.com>
3 * Copyright (c) 2015 Theo de Raadt <deraadt@openbsd.org>
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
18 #include "config.h"
20 #include <sys/socket.h>
21 #include <sys/un.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <limits.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <stdint.h>
29 #include <string.h>
30 #include <syslog.h>
31 #include <time.h>
32 #include <unistd.h>
34 #include "amused.h"
35 #include "log.h"
36 #include "playlist.h"
37 #include "xmalloc.h"
39 static struct imsgbuf *imsgbuf;
40 char cwd[PATH_MAX];
42 static int ctl_noarg(struct parse_result *, int, char **);
43 static int ctl_add(struct parse_result *, int, char **);
44 static int ctl_show(struct parse_result *, int, char **);
45 static int ctl_load(struct parse_result *, int, char **);
46 static int ctl_jump(struct parse_result *, int, char **);
47 static int ctl_repeat(struct parse_result *, int, char **);
48 static int ctl_consume(struct parse_result *, int, char **);
49 static int ctl_monitor(struct parse_result *, int, char **);
50 static int ctl_seek(struct parse_result *, int, char **);
51 static int ctl_status(struct parse_result *, int, char **);
53 struct ctl_command ctl_commands[] = {
54 { "add", ADD, ctl_add, "files..."},
55 { "consume", MODE, ctl_consume, "one|all"},
56 { "flush", FLUSH, ctl_noarg, ""},
57 { "jump", JUMP, ctl_jump, "pattern"},
58 { "load", LOAD, ctl_load, "[file]"},
59 { "monitor", MONITOR, ctl_monitor, "[events]"},
60 { "next", NEXT, ctl_noarg, ""},
61 { "pause", PAUSE, ctl_noarg, ""},
62 { "play", PLAY, ctl_noarg, ""},
63 { "prev", PREV, ctl_noarg, ""},
64 { "repeat", MODE, ctl_repeat, "one|all on|off"},
65 { "restart", RESTART, ctl_noarg, ""},
66 { "seek", SEEK, ctl_seek, "[+-]time[%]"},
67 { "show", SHOW, ctl_show, "[-p]"},
68 { "status", STATUS, ctl_status, "[-f fmt]"},
69 { "stop", STOP, ctl_noarg, ""},
70 { "toggle", TOGGLE, ctl_noarg, ""},
71 { NULL, 0, NULL, NULL},
72 };
74 __dead void
75 usage(void)
76 {
77 fprintf(stderr, "usage: %s [-dv] [-s socket]\n", getprogname());
78 exit(1);
79 }
81 static __dead void
82 ctl_usage(struct ctl_command *ctl)
83 {
84 fprintf(stderr, "usage: %s [-v] [-s socket] %s %s\n", getprogname(),
85 ctl->name, ctl->usage);
86 exit(1);
87 }
89 /* based on canonpath from kern_pledge.c */
90 static int
91 canonpath(const char *input, char *buf, size_t bufsize)
92 {
93 const char *p;
94 char *q, path[PATH_MAX];
95 int r;
97 if (input[0] != '/') {
98 r = snprintf(path, sizeof(path), "%s/%s", cwd, input);
99 if (r < 0 || (size_t)r >= sizeof(path)) {
100 errno = ENAMETOOLONG;
101 return -1;
103 input = path;
106 p = input;
107 q = buf;
108 while (*p && (q - buf < bufsize)) {
109 if (p[0] == '/' && (p[1] == '/' || p[1] == '\0')) {
110 p += 1;
112 } else if (p[0] == '/' && p[1] == '.' &&
113 (p[2] == '/' || p[2] == '\0')) {
114 p += 2;
116 } else if (p[0] == '/' && p[1] == '.' && p[2] == '.' &&
117 (p[3] == '/' || p[3] == '\0')) {
118 p += 3;
119 if (q != buf) /* "/../" at start of buf */
120 while (*--q != '/')
121 continue;
123 } else {
124 *q++ = *p++;
127 if ((*p == '\0') && (q - buf < bufsize)) {
128 *q = 0;
129 return 0;
130 } else {
131 errno = ENAMETOOLONG;
132 return -1;
136 static int
137 parse(struct parse_result *res, int argc, char **argv)
139 struct ctl_command *ctl = NULL;
140 const char *argv0;
141 int i, status;
143 if ((argv0 = argv[0]) == NULL)
144 argv0 = "status";
146 for (i = 0; ctl_commands[i].name != NULL; ++i) {
147 if (strncmp(ctl_commands[i].name, argv0, strlen(argv0))
148 == 0) {
149 if (ctl != NULL) {
150 fprintf(stderr,
151 "ambiguous argument: %s\n", argv0);
152 usage();
154 ctl = &ctl_commands[i];
158 if (ctl == NULL) {
159 fprintf(stderr, "unknown argument: %s\n", argv[0]);
160 usage();
163 res->action = ctl->action;
164 res->ctl = ctl;
166 status = ctl->main(res, argc, argv);
167 close(imsgbuf->fd);
168 free(imsgbuf);
169 return status;
172 static int
173 load_files(struct parse_result *res, int *ret)
175 const char *file;
176 char *line = NULL;
177 char path[PATH_MAX];
178 size_t linesize = 0, i = 0;
179 ssize_t linelen, curr = -1;
181 while ((linelen = getline(&line, &linesize, res->fp)) != -1) {
182 if (linelen == 0)
183 continue;
184 line[linelen-1] = '\0';
185 file = line;
186 if (!strncmp(file, "> ", 2)) {
187 file += 2;
188 curr = i;
189 } else if (!strncmp(file, " ", 2))
190 file += 2;
192 memset(path, 0, sizeof(path));
193 if (canonpath(file, path, sizeof(path)) == -1) {
194 log_warn("canonpath %s", file);
195 continue;
198 i++;
199 imsg_compose(imsgbuf, IMSG_CTL_ADD, 0, 0, -1,
200 path, sizeof(path));
203 free(line);
204 if (ferror(res->fp))
205 fatal("getline");
206 fclose(res->fp);
207 res->fp = NULL;
209 imsg_compose(imsgbuf, IMSG_CTL_COMMIT, 0, 0, -1,
210 &curr, sizeof(curr));
211 imsg_flush(imsgbuf);
212 return 0;
215 static const char *
216 imsg_strerror(struct imsg *imsg)
218 struct ibuf ibuf;
219 size_t datalen;
220 const char *msg;
222 if (imsg_get_ibuf(imsg, &ibuf) == -1 ||
223 (datalen = ibuf_size(&ibuf)) == 0 ||
224 (msg = ibuf_data(&ibuf)) == NULL ||
225 msg[datalen - 1] != '\0')
226 fatalx("malformed error message");
228 return msg;
231 static const char *
232 event_name(int type)
234 switch (type) {
235 case IMSG_CTL_PLAY:
236 return "play";
237 case IMSG_CTL_PAUSE:
238 return "pause";
239 case IMSG_CTL_STOP:
240 return "stop";
241 case IMSG_CTL_NEXT:
242 return "next";
243 case IMSG_CTL_PREV:
244 return "prev";
245 case IMSG_CTL_JUMP:
246 return "jump";
247 case IMSG_CTL_ADD:
248 return "add";
249 case IMSG_CTL_COMMIT:
250 return "load";
251 case IMSG_CTL_MODE:
252 return "mode";
253 case IMSG_CTL_SEEK:
254 return "seek";
255 default:
256 return "unknown";
260 static void
261 print_time(const char *label, int64_t seconds, const char *suffx)
263 int hours, minutes;
265 if (seconds < 0)
266 seconds = 0;
268 hours = seconds / 3600;
269 seconds -= hours * 3600;
271 minutes = seconds / 60;
272 seconds -= minutes * 60;
274 printf("%s", label);
275 if (hours != 0)
276 printf("%02d:", hours);
277 printf("%02d:%02lld%s", minutes, (long long)seconds, suffx);
280 static void
281 print_status(struct player_status *ps, const char *spec)
283 const char *status;
284 double percent;
285 char *dup, *tmp, *tok;
287 if (ps->status == STATE_STOPPED)
288 status = "stopped";
289 else if (ps->status == STATE_PLAYING)
290 status = "playing";
291 else if (ps->status == STATE_PAUSED)
292 status = "paused";
293 else
294 status = "unknown";
296 percent = 100.0 * (double)ps->position / (double)ps->duration;
298 tmp = dup = xstrdup(spec);
299 while ((tok = strsep(&tmp, ",")) != NULL) {
300 if (*tok == '\0')
301 continue;
303 if (!strcmp(tok, "path")) {
304 puts(ps->path);
305 } else if (!strcmp(tok, "mode:oneline")) {
306 printf("repeat one:%s ",
307 ps->mode.repeat_one ? "on" : "off");
308 printf("all:%s ", ps->mode.repeat_all ? "on" : "off");
309 printf("consume:%s\n", ps->mode.consume ? "on" : "off");
310 } else if (!strcmp(tok, "mode")) {
311 printf("repeat all %s\n",
312 ps->mode.repeat_all ? "on" : "off");
313 printf("repeat one %s\n",
314 ps->mode.repeat_one ? "on" : "off");
315 printf("consume %s\n",
316 ps->mode.consume ? "on" : "off");
317 } else if (!strcmp(tok, "status")) {
318 printf("%s %s\n", status, ps->path);
319 } else if (!strcmp(tok, "time:oneline")) {
320 print_time("time ", ps->position, " / ");
321 print_time("", ps->duration, "\n");
322 } else if (!strcmp(tok, "time:percentage")) {
323 printf("position %.2f%%\n", percent);
324 } else if (!strcmp(tok, "time:raw")) {
325 printf("position %lld\n", (long long)ps->position);
326 printf("duration %lld\n", (long long)ps->duration);
327 } else if (!strcmp(tok, "time")) {
328 print_time("position ", ps->position, "\n");
329 print_time("duration ", ps->duration, "\n");
333 free(dup);
336 static void
337 print_monitor_event(struct player_event *ev)
339 switch (ev->event) {
340 case IMSG_CTL_MODE:
341 printf("%s repeat one:%s all:%s consume:%s\n",
342 event_name(ev->event),
343 ev->mode.repeat_one ? "on" : "off",
344 ev->mode.repeat_all ? "on" : "off",
345 ev->mode.consume ? "on" : "off");
346 break;
347 case IMSG_CTL_SEEK:
348 printf("%s %lld %lld\n", event_name(ev->event),
349 (long long)ev->position, (long long)ev->duration);
350 break;
351 default:
352 puts(event_name(ev->event));
353 break;
356 fflush(stdout);
359 static int
360 ctlaction(struct parse_result *res)
362 char path[PATH_MAX];
363 struct imsg imsg;
364 struct player_status ps;
365 struct player_event ev;
366 ssize_t n;
367 int i, ret = 0, done = 1;
369 if (pledge("stdio", NULL) == -1)
370 fatal("pledge");
372 switch (res->action) {
373 case PLAY:
374 imsg_compose(imsgbuf, IMSG_CTL_PLAY, 0, 0, -1, NULL, 0);
375 if (verbose) {
376 imsg_compose(imsgbuf, IMSG_CTL_STATUS, 0, 0, -1,
377 NULL, 0);
378 done = 0;
380 break;
381 case PAUSE:
382 imsg_compose(imsgbuf, IMSG_CTL_PAUSE, 0, 0, -1, NULL, 0);
383 break;
384 case TOGGLE:
385 imsg_compose(imsgbuf, IMSG_CTL_TOGGLE_PLAY, 0, 0, -1, NULL, 0);
386 if (verbose) {
387 imsg_compose(imsgbuf, IMSG_CTL_STATUS, 0, 0, -1,
388 NULL, 0);
389 done = 0;
391 break;
392 case STOP:
393 imsg_compose(imsgbuf, IMSG_CTL_STOP, 0, 0, -1, NULL, 0);
394 break;
395 case ADD:
396 done = 0;
397 for (i = 0; res->files[i] != NULL; ++i) {
398 memset(path, 0, sizeof(path));
399 if (canonpath(res->files[i], path, sizeof(path))
400 == -1) {
401 log_warn("canonpath %s", res->files[i]);
402 continue;
405 imsg_compose(imsgbuf, IMSG_CTL_ADD, 0, 0, -1,
406 path, sizeof(path));
408 ret = i == 0;
409 break;
410 case FLUSH:
411 imsg_compose(imsgbuf, IMSG_CTL_FLUSH, 0, 0, -1, NULL, 0);
412 break;
413 case SHOW:
414 done = 0;
415 imsg_compose(imsgbuf, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
416 break;
417 case STATUS:
418 done = 0;
419 imsg_compose(imsgbuf, IMSG_CTL_STATUS, 0, 0, -1, NULL, 0);
420 break;
421 case NEXT:
422 imsg_compose(imsgbuf, IMSG_CTL_NEXT, 0, 0, -1, NULL, 0);
423 if (verbose) {
424 imsg_compose(imsgbuf, IMSG_CTL_STATUS, 0, 0, -1,
425 NULL, 0);
426 done = 0;
428 break;
429 case PREV:
430 imsg_compose(imsgbuf, IMSG_CTL_PREV, 0, 0, -1, NULL, 0);
431 if (verbose) {
432 imsg_compose(imsgbuf, IMSG_CTL_STATUS, 0, 0, -1,
433 NULL, 0);
434 done = 0;
436 break;
437 case LOAD:
438 done = 0;
439 imsg_compose(imsgbuf, IMSG_CTL_BEGIN, 0, 0, -1, NULL, 0);
440 break;
441 case JUMP:
442 done = 0;
443 memset(path, 0, sizeof(path));
444 strlcpy(path, res->files[0], sizeof(path));
445 imsg_compose(imsgbuf, IMSG_CTL_JUMP, 0, 0, -1,
446 path, sizeof(path));
447 break;
448 case MODE:
449 done = 0;
450 imsg_compose(imsgbuf, IMSG_CTL_MODE, 0, 0, -1,
451 &res->mode, sizeof(res->mode));
452 imsg_compose(imsgbuf, IMSG_CTL_STATUS, 0, 0, -1,
453 &res->mode, sizeof(res->mode));
454 res->status_format = "mode:oneline";
455 if (verbose)
456 res->status_format = "mode";
457 break;
458 case MONITOR:
459 done = 0;
460 imsg_compose(imsgbuf, IMSG_CTL_MONITOR, 0, 0, -1,
461 NULL, 0);
462 break;
463 case RESTART:
464 memset(&res->seek, 0, sizeof(res->seek));
465 /* fallthrough */
466 case SEEK:
467 imsg_compose(imsgbuf, IMSG_CTL_SEEK, 0, 0, -1, &res->seek,
468 sizeof(res->seek));
469 break;
470 case NONE:
471 /* action not expected */
472 fatalx("invalid action %u", res->action);
473 break;
476 if (ret != 0)
477 goto end;
479 imsg_flush(imsgbuf);
481 i = 0;
482 while (!done) {
483 if ((n = imsg_read(imsgbuf)) == -1 && errno != EAGAIN)
484 fatalx("imsg_read error");
485 if (n == 0)
486 fatalx("pipe closed");
488 while (!done) {
489 if ((n = imsg_get(imsgbuf, &imsg)) == -1)
490 fatalx("imsg_get error");
491 if (n == 0)
492 break;
494 if (imsg.hdr.type == IMSG_CTL_ERR) {
495 log_warnx("%s: %s", res->ctl->name,
496 imsg_strerror(&imsg));
497 ret = 1;
498 done = 1;
499 break;
502 switch (res->action) {
503 case ADD:
504 if (res->files[i] == NULL)
505 fatalx("received more replies than "
506 "files enqueued.");
508 if (imsg.hdr.type == IMSG_CTL_ADD)
509 log_debug("enqueued %s", res->files[i]);
510 else
511 fatalx("invalid message %d",
512 imsg.hdr.type);
513 i++;
514 done = res->files[i] == NULL;
515 break;
516 case SHOW:
517 if (imsg_get_len(&imsg) == 0) {
518 done = 1;
519 break;
521 if (imsg_get_data(&imsg, &ps, sizeof(ps))
522 == -1)
523 fatalx("data size mismatch");
524 if (ps.path[sizeof(ps.path) - 1] != '\0')
525 fatalx("received corrupted data");
526 if (res->pretty) {
527 char c = ' ';
528 if (ps.status == STATE_PLAYING)
529 c = '>';
530 printf("%c ", c);
532 puts(ps.path);
533 break;
534 case PLAY:
535 case TOGGLE:
536 case STATUS:
537 case NEXT:
538 case PREV:
539 case JUMP:
540 case MODE:
541 if (imsg.hdr.type != IMSG_CTL_STATUS)
542 fatalx("invalid message %d",
543 imsg.hdr.type);
545 if (imsg_get_data(&imsg, &ps, sizeof(ps))
546 == -1)
547 fatalx("data size mismatch");
548 if (ps.path[sizeof(ps.path) - 1] != '\0')
549 fatalx("received corrupted data");
551 print_status(&ps, res->status_format);
552 done = 1;
553 break;
554 case LOAD:
555 if (imsg.hdr.type == IMSG_CTL_ADD)
556 break;
557 if (imsg.hdr.type == IMSG_CTL_COMMIT) {
558 done = 1;
559 break;
562 if (imsg.hdr.type != IMSG_CTL_BEGIN)
563 fatalx("invalid message %d",
564 imsg.hdr.type);
566 load_files(res, &ret);
567 break;
568 case MONITOR:
569 if (imsg.hdr.type != IMSG_CTL_MONITOR)
570 fatalx("invalid message %d",
571 imsg.hdr.type);
573 if (imsg_get_data(&imsg, &ev, sizeof(ev))
574 == -1)
575 fatalx("data size mismatch");
577 if (ev.event < 0 || ev.event > IMSG__LAST)
578 fatalx("received corrupted data");
580 if (!res->monitor[ev.event])
581 break;
583 print_monitor_event(&ev);
584 break;
585 default:
586 done = 1;
587 break;
590 imsg_free(&imsg);
594 end:
595 return ret;
598 static int
599 ctl_noarg(struct parse_result *res, int argc, char **argv)
601 int ch;
603 while ((ch = getopt(argc, argv, "")) != -1)
604 ctl_usage(res->ctl);
605 argc -= optind;
606 argv += optind;
608 if (argc > 0)
609 ctl_usage(res->ctl);
611 return ctlaction(res);
614 static int
615 ctl_add(struct parse_result *res, int argc, char **argv)
617 int ch;
619 while ((ch = getopt(argc, argv, "")) != -1)
620 ctl_usage(res->ctl);
621 argc -= optind;
622 argv += optind;
624 if (argc == 0)
625 ctl_usage(res->ctl);
626 res->files = argv;
628 return ctlaction(res);
631 static int
632 ctl_show(struct parse_result *res, int argc, char **argv)
634 int ch;
636 while ((ch = getopt(argc, argv, "p")) != -1) {
637 switch (ch) {
638 case 'p':
639 res->pretty = 1;
640 break;
641 default:
642 ctl_usage(res->ctl);
646 return ctlaction(res);
649 static int
650 ctl_load(struct parse_result *res, int argc, char **argv)
652 int ch;
654 while ((ch = getopt(argc, argv, "")) != -1)
655 ctl_usage(res->ctl);
656 argc -= optind;
657 argv += optind;
659 if (argc > 1)
660 ctl_usage(res->ctl);
662 res->fp = stdin;
663 if (argc == 1) {
664 if ((res->fp = fopen(argv[0], "r")) == NULL)
665 fatal("can't open %s", argv[0]);
668 return ctlaction(res);
671 static int
672 ctl_jump(struct parse_result *res, int argc, char **argv)
674 int ch;
676 while ((ch = getopt(argc, argv, "")) != -1)
677 ctl_usage(res->ctl);
678 argc -= optind;
679 argv += optind;
681 if (argc != 1)
682 ctl_usage(res->ctl);
684 res->files = argv;
685 return ctlaction(res);
688 static int
689 parse_mode(struct parse_result *res, const char *v)
691 if (v == NULL)
692 return MODE_TOGGLE;
693 if (!strcmp(v, "on"))
694 return MODE_ON;
695 if (!strcmp(v, "off"))
696 return MODE_OFF;
697 ctl_usage(res->ctl);
700 static int
701 ctl_repeat(struct parse_result *res, int argc, char **argv)
703 int ch;
705 while ((ch = getopt(argc, argv, "")) != -1)
706 ctl_usage(res->ctl);
707 argc -= optind;
708 argv += optind;
710 if (argc != 1 && argc != 2)
711 ctl_usage(res->ctl);
713 if (!strcmp(argv[0], "one"))
714 res->mode.repeat_one = parse_mode(res, argv[1]);
715 else if (!strcmp(argv[0], "all"))
716 res->mode.repeat_all = parse_mode(res, argv[1]);
717 else
718 ctl_usage(res->ctl);
720 return ctlaction(res);
723 static int
724 ctl_consume(struct parse_result *res, int argc, char **argv)
726 int ch;
728 while ((ch = getopt(argc, argv, "")) != -1)
729 ctl_usage(res->ctl);
730 argc -= optind;
731 argv += optind;
733 if (argc > 1)
734 ctl_usage(res->ctl);
736 res->mode.consume = parse_mode(res, argv[0]);
737 return ctlaction(res);
740 static int
741 ctl_monitor(struct parse_result *res, int argc, char **argv)
743 int ch, n = 0;
744 const char *events;
745 char *dup, *tmp, *tok;
747 while ((ch = getopt(argc, argv, "")) != -1)
748 ctl_usage(res->ctl);
749 argc -= optind;
750 argv += optind;
752 if (argc > 1)
753 ctl_usage(res->ctl);
755 events = "play,pause,stop,next,prev,jump,mode,add,load,seek";
756 if (argc == 1)
757 events = *argv;
759 tmp = dup = xstrdup(events);
760 while ((tok = strsep(&tmp, ",")) != NULL) {
761 if (*tok == '\0')
762 continue;
764 n++;
765 if (!strcmp(tok, "play"))
766 res->monitor[IMSG_CTL_PLAY] = 1;
767 else if (!strcmp(tok, "pause"))
768 res->monitor[IMSG_CTL_PAUSE] = 1;
769 else if (!strcmp(tok, "stop"))
770 res->monitor[IMSG_CTL_STOP] = 1;
771 else if (!strcmp(tok, "next"))
772 res->monitor[IMSG_CTL_NEXT] = 1;
773 else if (!strcmp(tok, "prev"))
774 res->monitor[IMSG_CTL_PREV] = 1;
775 else if (!strcmp(tok, "jump"))
776 res->monitor[IMSG_CTL_JUMP] = 1;
777 else if (!strcmp(tok, "mode"))
778 res->monitor[IMSG_CTL_MODE] = 1;
779 else if (!strcmp(tok, "add"))
780 res->monitor[IMSG_CTL_ADD] = 1;
781 else if (!strcmp(tok, "load"))
782 res->monitor[IMSG_CTL_COMMIT] = 1;
783 else if (!strcmp(tok, "seek"))
784 res->monitor[IMSG_CTL_SEEK] = 1;
785 else {
786 log_warnx("unknown event \"%s\"", tok);
787 n--;
791 free(dup);
792 if (n == 0)
793 ctl_usage(res->ctl);
794 return ctlaction(res);
797 static int
798 ctl_seek(struct parse_result *res, int argc, char **argv)
800 const char *n;
801 char *ep;
802 int hours = 0, minutes = 0, seconds = 0;
803 int sign = 1;
805 if (argc > 0) {
806 /* skip the command name */
807 argc--;
808 argv++;
811 if (argc > 0 && !strcmp(*argv, "--")) {
812 argc--;
813 argv++;
816 if (argc != 1)
817 ctl_usage(res->ctl);
819 n = *argv;
820 if (*n == '-' || *n == '+')
821 res->seek.relative = 1;
822 if (*n == '-') {
823 n++;
824 sign = -1;
827 seconds = strtol(n, &ep, 10);
828 if (n[0] == '\0' ||
829 (*ep != '\0' && *ep != ':' && *ep != '%') ||
830 (*ep == '%' && ep[1] != '\0'))
831 fatalx("invalid offset: %s", argv[0]);
832 if (*ep == '\0' || *ep == '%') {
833 res->seek.percent = *ep == '%';
834 goto done;
837 n = ++ep;
838 minutes = seconds;
839 seconds = strtol(n, &ep, 10);
840 if (n[0] == '\0' || (*ep != '\0' && *ep != ':'))
841 fatalx("invalid offset: %s", argv[0]);
842 if (*ep == '\0')
843 goto done;
845 n = ++ep;
846 hours = minutes;
847 minutes = seconds;
848 seconds = strtol(n, &ep, 10);
849 if (n[0] == '\0' || *ep != '\0')
850 fatalx("invalid offset: %s", argv[0]);
852 done:
853 res->seek.offset = sign * (hours * 3600 + minutes * 60 + seconds);
854 return ctlaction(res);
857 static int
858 ctl_status(struct parse_result *res, int argc, char **argv)
860 int ch;
862 while ((ch = getopt(argc, argv, "f:")) != -1) {
863 switch (ch) {
864 case 'f':
865 res->status_format = optarg;
866 break;
867 default:
868 ctl_usage(res->ctl);
871 argc -= optind;
872 argv += optind;
874 if (argc > 0)
875 ctl_usage(res->ctl);
877 return ctlaction(res);
880 static int
881 ctl_get_lock(const char *lockfile)
883 int lockfd;
885 if ((lockfd = open(lockfile, O_WRONLY|O_CREAT, 0600)) == -1) {
886 log_debug("open failed: %s", strerror(errno));
887 return -1;
890 if (flock(lockfd, LOCK_EX|LOCK_NB) == -1) {
891 log_debug("flock failed: %s", strerror(errno));
892 if (errno != EAGAIN)
893 return -1;
894 while (flock(lockfd, LOCK_EX) == -1 && errno == EINTR)
895 /* nop */;
896 close(lockfd);
897 return -2;
899 log_debug("flock succeeded");
901 return lockfd;
904 static int
905 ctl_connect(void)
907 struct timespec ts = { 0, 50000000 }; /* 0.05 seconds */
908 struct sockaddr_un sa;
909 size_t size;
910 int fd, lockfd = -1, locked = 0, spawned = 0;
911 int attempt = 0;
912 char *lockfile = NULL;
914 memset(&sa, 0, sizeof(sa));
915 sa.sun_family = AF_UNIX;
916 size = strlcpy(sa.sun_path, csock, sizeof(sa.sun_path));
917 if (size >= sizeof(sa.sun_path)) {
918 errno = ENAMETOOLONG;
919 return -1;
922 retry:
923 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
924 return -1;
926 if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
927 log_debug("connection failed: %s", strerror(errno));
928 if (errno != ECONNREFUSED && errno != ENOENT)
929 goto failed;
930 if (attempt++ == 100)
931 goto failed;
932 close(fd);
934 if (!locked) {
935 xasprintf(&lockfile, "%s.lock", csock);
936 if ((lockfd = ctl_get_lock(lockfile)) < 0) {
937 log_debug("didn't get the lock (%d)", lockfd);
939 free(lockfile);
940 lockfile = NULL;
942 if (lockfd == -1)
943 goto retry;
946 /*
947 * Always retry at least once, even if we got
948 * the lock, because another client could have
949 * taken the lock, started the server and released
950 * the lock between our connect() and flock()
951 */
952 locked = 1;
953 goto retry;
956 if (!spawned) {
957 log_debug("spawning the daemon");
958 spawn_daemon();
959 spawned = 1;
962 nanosleep(&ts, NULL);
963 goto retry;
966 if (locked && lockfd >= 0) {
967 unlink(lockfile);
968 free(lockfile);
969 close(lockfd);
971 return fd;
973 failed:
974 if (locked) {
975 free(lockfile);
976 close(lockfd);
978 close(fd);
979 return -1;
982 __dead void
983 ctl(int argc, char **argv)
985 struct parse_result res;
986 const char *fmt;
987 int ctl_sock;
989 memset(&res, 0, sizeof(res));
990 if ((fmt = getenv("AMUSED_STATUS_FORMAT")) == NULL)
991 fmt = "status,time:oneline,mode:oneline";
992 res.status_format = fmt;
994 res.mode.consume = MODE_UNDEF;
995 res.mode.repeat_all = MODE_UNDEF;
996 res.mode.repeat_one = MODE_UNDEF;
998 log_init(1, LOG_DAEMON);
999 log_setverbose(verbose);
1001 if (getcwd(cwd, sizeof(cwd)) == NULL)
1002 fatal("getcwd");
1004 if ((ctl_sock = ctl_connect()) == -1)
1005 fatal("can't connect");
1007 imsgbuf = xmalloc(sizeof(*imsgbuf));
1008 imsg_init(imsgbuf, ctl_sock);
1010 optreset = 1;
1011 optind = 1;
1013 /* we'll drop rpath too later in ctlaction */
1014 if (pledge("stdio rpath", NULL) == -1)
1015 fatal("pledge");
1017 exit(parse(&res, argc, argv));