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 *ibuf;
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(ibuf->fd);
168 free(ibuf);
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(ibuf, 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(ibuf, IMSG_CTL_COMMIT, 0, 0, -1,
210 &curr, sizeof(curr));
211 imsg_flush(ibuf);
212 return 0;
215 static const char *
216 imsg_strerror(struct imsg *imsg)
218 size_t datalen;
219 const char *msg;
221 datalen = IMSG_DATA_SIZE(*imsg);
222 msg = imsg->data;
223 if (datalen == 0 || msg[datalen-1] != '\0')
224 fatalx("malformed error message");
226 return msg;
229 static const char *
230 event_name(int type)
232 switch (type) {
233 case IMSG_CTL_PLAY:
234 return "play";
235 case IMSG_CTL_PAUSE:
236 return "pause";
237 case IMSG_CTL_STOP:
238 return "stop";
239 case IMSG_CTL_NEXT:
240 return "next";
241 case IMSG_CTL_PREV:
242 return "prev";
243 case IMSG_CTL_JUMP:
244 return "jump";
245 case IMSG_CTL_ADD:
246 return "add";
247 case IMSG_CTL_COMMIT:
248 return "load";
249 case IMSG_CTL_MODE:
250 return "mode";
251 case IMSG_CTL_SEEK:
252 return "seek";
253 default:
254 return "unknown";
258 static void
259 print_time(const char *label, int64_t seconds, const char *suffx)
261 int hours, minutes;
263 if (seconds < 0)
264 seconds = 0;
266 hours = seconds / 3600;
267 seconds -= hours * 3600;
269 minutes = seconds / 60;
270 seconds -= minutes * 60;
272 printf("%s", label);
273 if (hours != 0)
274 printf("%02d:", hours);
275 printf("%02d:%02lld%s", minutes, (long long)seconds, suffx);
278 static void
279 print_status(struct player_status *ps, const char *spec)
281 const char *status;
282 double percent;
283 char *dup, *tmp, *tok;
285 if (ps->status == STATE_STOPPED)
286 status = "stopped";
287 else if (ps->status == STATE_PLAYING)
288 status = "playing";
289 else if (ps->status == STATE_PAUSED)
290 status = "paused";
291 else
292 status = "unknown";
294 percent = 100.0 * (double)ps->position / (double)ps->duration;
296 tmp = dup = xstrdup(spec);
297 while ((tok = strsep(&tmp, ",")) != NULL) {
298 if (*tok == '\0')
299 continue;
301 if (!strcmp(tok, "path")) {
302 puts(ps->path);
303 } else if (!strcmp(tok, "mode:oneline")) {
304 printf("repeat one:%s ",
305 ps->mode.repeat_one ? "on" : "off");
306 printf("all:%s ", ps->mode.repeat_all ? "on" : "off");
307 printf("consume:%s\n", ps->mode.consume ? "on" : "off");
308 } else if (!strcmp(tok, "mode")) {
309 printf("repeat all %s\n",
310 ps->mode.repeat_all ? "on" : "off");
311 printf("repeat one %s\n",
312 ps->mode.repeat_one ? "on" : "off");
313 printf("consume %s\n",
314 ps->mode.consume ? "on" : "off");
315 } else if (!strcmp(tok, "status")) {
316 printf("%s %s\n", status, ps->path);
317 } else if (!strcmp(tok, "time:oneline")) {
318 print_time("time ", ps->position, " / ");
319 print_time("", ps->duration, "\n");
320 } else if (!strcmp(tok, "time:percentage")) {
321 printf("position %.2f%%\n", percent);
322 } else if (!strcmp(tok, "time:raw")) {
323 printf("position %lld\n", (long long)ps->position);
324 printf("duration %lld\n", (long long)ps->duration);
325 } else if (!strcmp(tok, "time")) {
326 print_time("position ", ps->position, "\n");
327 print_time("duration ", ps->duration, "\n");
331 free(dup);
334 static void
335 print_monitor_event(struct player_event *ev)
337 switch (ev->event) {
338 case IMSG_CTL_MODE:
339 printf("%s repeat one:%s all:%s consume:%s\n",
340 event_name(ev->event),
341 ev->mode.repeat_one ? "on" : "off",
342 ev->mode.repeat_all ? "on" : "off",
343 ev->mode.consume ? "on" : "off");
344 break;
345 case IMSG_CTL_SEEK:
346 printf("%s %lld %lld\n", event_name(ev->event),
347 (long long)ev->position, (long long)ev->duration);
348 break;
349 default:
350 puts(event_name(ev->event));
351 break;
354 fflush(stdout);
357 static int
358 ctlaction(struct parse_result *res)
360 char path[PATH_MAX];
361 struct imsg imsg;
362 struct player_status ps;
363 struct player_event ev;
364 size_t datalen;
365 ssize_t n;
366 int i, ret = 0, done = 1;
368 if (pledge("stdio", NULL) == -1)
369 fatal("pledge");
371 switch (res->action) {
372 case PLAY:
373 imsg_compose(ibuf, IMSG_CTL_PLAY, 0, 0, -1, NULL, 0);
374 if (verbose) {
375 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
376 NULL, 0);
377 done = 0;
379 break;
380 case PAUSE:
381 imsg_compose(ibuf, IMSG_CTL_PAUSE, 0, 0, -1, NULL, 0);
382 break;
383 case TOGGLE:
384 imsg_compose(ibuf, IMSG_CTL_TOGGLE_PLAY, 0, 0, -1, NULL, 0);
385 if (verbose) {
386 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
387 NULL, 0);
388 done = 0;
390 break;
391 case STOP:
392 imsg_compose(ibuf, IMSG_CTL_STOP, 0, 0, -1, NULL, 0);
393 break;
394 case ADD:
395 done = 0;
396 for (i = 0; res->files[i] != NULL; ++i) {
397 memset(path, 0, sizeof(path));
398 if (canonpath(res->files[i], path, sizeof(path))
399 == -1) {
400 log_warn("canonpath %s", res->files[i]);
401 continue;
404 imsg_compose(ibuf, IMSG_CTL_ADD, 0, 0, -1,
405 path, sizeof(path));
407 ret = i == 0;
408 break;
409 case FLUSH:
410 imsg_compose(ibuf, IMSG_CTL_FLUSH, 0, 0, -1, NULL, 0);
411 break;
412 case SHOW:
413 done = 0;
414 imsg_compose(ibuf, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
415 break;
416 case STATUS:
417 done = 0;
418 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1, NULL, 0);
419 break;
420 case NEXT:
421 imsg_compose(ibuf, IMSG_CTL_NEXT, 0, 0, -1, NULL, 0);
422 if (verbose) {
423 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
424 NULL, 0);
425 done = 0;
427 break;
428 case PREV:
429 imsg_compose(ibuf, IMSG_CTL_PREV, 0, 0, -1, NULL, 0);
430 if (verbose) {
431 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
432 NULL, 0);
433 done = 0;
435 break;
436 case LOAD:
437 done = 0;
438 imsg_compose(ibuf, IMSG_CTL_BEGIN, 0, 0, -1, NULL, 0);
439 break;
440 case JUMP:
441 done = 0;
442 memset(path, 0, sizeof(path));
443 strlcpy(path, res->files[0], sizeof(path));
444 imsg_compose(ibuf, IMSG_CTL_JUMP, 0, 0, -1,
445 path, sizeof(path));
446 break;
447 case MODE:
448 done = 0;
449 imsg_compose(ibuf, IMSG_CTL_MODE, 0, 0, -1,
450 &res->mode, sizeof(res->mode));
451 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
452 &res->mode, sizeof(res->mode));
453 res->status_format = "mode:oneline";
454 if (verbose)
455 res->status_format = "mode";
456 break;
457 case MONITOR:
458 done = 0;
459 imsg_compose(ibuf, IMSG_CTL_MONITOR, 0, 0, -1,
460 NULL, 0);
461 break;
462 case RESTART:
463 memset(&res->seek, 0, sizeof(res->seek));
464 /* fallthrough */
465 case SEEK:
466 imsg_compose(ibuf, IMSG_CTL_SEEK, 0, 0, -1, &res->seek,
467 sizeof(res->seek));
468 break;
469 case NONE:
470 /* action not expected */
471 fatalx("invalid action %u", res->action);
472 break;
475 if (ret != 0)
476 goto end;
478 imsg_flush(ibuf);
480 i = 0;
481 while (!done) {
482 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
483 fatalx("imsg_read error");
484 if (n == 0)
485 fatalx("pipe closed");
487 while (!done) {
488 if ((n = imsg_get(ibuf, &imsg)) == -1)
489 fatalx("imsg_get error");
490 if (n == 0)
491 break;
493 if (imsg.hdr.type == IMSG_CTL_ERR) {
494 log_warnx("%s: %s", res->ctl->name,
495 imsg_strerror(&imsg));
496 ret = 1;
497 done = 1;
498 break;
501 datalen = IMSG_DATA_SIZE(imsg);
503 switch (res->action) {
504 case ADD:
505 if (res->files[i] == NULL)
506 fatalx("received more replies than "
507 "files enqueued.");
509 if (imsg.hdr.type == IMSG_CTL_ADD)
510 log_debug("enqueued %s", res->files[i]);
511 else
512 fatalx("invalid message %d",
513 imsg.hdr.type);
514 i++;
515 done = res->files[i] == NULL;
516 break;
517 case SHOW:
518 if (datalen == 0) {
519 done = 1;
520 break;
522 if (datalen != sizeof(ps))
523 fatalx("data size mismatch");
524 memcpy(&ps, imsg.data, sizeof(ps));
525 if (ps.path[sizeof(ps.path) - 1] != '\0')
526 fatalx("received corrupted data");
527 if (res->pretty) {
528 char c = ' ';
529 if (ps.status == STATE_PLAYING)
530 c = '>';
531 printf("%c ", c);
533 puts(ps.path);
534 break;
535 case PLAY:
536 case TOGGLE:
537 case STATUS:
538 case NEXT:
539 case PREV:
540 case JUMP:
541 case MODE:
542 if (imsg.hdr.type != IMSG_CTL_STATUS)
543 fatalx("invalid message %d",
544 imsg.hdr.type);
546 if (datalen != sizeof(ps))
547 fatalx("data size mismatch");
548 memcpy(&ps, imsg.data, sizeof(ps));
549 if (ps.path[sizeof(ps.path) - 1] != '\0')
550 fatalx("received corrupted data");
552 print_status(&ps, res->status_format);
553 done = 1;
554 break;
555 case LOAD:
556 if (imsg.hdr.type == IMSG_CTL_ADD)
557 break;
558 if (imsg.hdr.type == IMSG_CTL_COMMIT) {
559 done = 1;
560 break;
563 if (imsg.hdr.type != IMSG_CTL_BEGIN)
564 fatalx("invalid message %d",
565 imsg.hdr.type);
567 load_files(res, &ret);
568 break;
569 case MONITOR:
570 if (imsg.hdr.type != IMSG_CTL_MONITOR)
571 fatalx("invalid message %d",
572 imsg.hdr.type);
574 if (datalen != sizeof(ev))
575 fatalx("data size mismatch");
577 memcpy(&ev, imsg.data, sizeof(ev));
578 if (ev.event < 0 || ev.event > IMSG__LAST)
579 fatalx("received corrupted data");
581 if (!res->monitor[ev.event])
582 break;
584 print_monitor_event(&ev);
585 break;
586 default:
587 done = 1;
588 break;
591 imsg_free(&imsg);
595 end:
596 return ret;
599 static int
600 ctl_noarg(struct parse_result *res, int argc, char **argv)
602 int ch;
604 while ((ch = getopt(argc, argv, "")) != -1)
605 ctl_usage(res->ctl);
606 argc -= optind;
607 argv += optind;
609 if (argc > 0)
610 ctl_usage(res->ctl);
612 return ctlaction(res);
615 static int
616 ctl_add(struct parse_result *res, int argc, char **argv)
618 int ch;
620 while ((ch = getopt(argc, argv, "")) != -1)
621 ctl_usage(res->ctl);
622 argc -= optind;
623 argv += optind;
625 if (argc == 0)
626 ctl_usage(res->ctl);
627 res->files = argv;
629 return ctlaction(res);
632 static int
633 ctl_show(struct parse_result *res, int argc, char **argv)
635 int ch;
637 while ((ch = getopt(argc, argv, "p")) != -1) {
638 switch (ch) {
639 case 'p':
640 res->pretty = 1;
641 break;
642 default:
643 ctl_usage(res->ctl);
647 return ctlaction(res);
650 static int
651 ctl_load(struct parse_result *res, int argc, char **argv)
653 int ch;
655 while ((ch = getopt(argc, argv, "")) != -1)
656 ctl_usage(res->ctl);
657 argc -= optind;
658 argv += optind;
660 if (argc > 1)
661 ctl_usage(res->ctl);
663 res->fp = stdin;
664 if (argc == 1) {
665 if ((res->fp = fopen(argv[0], "r")) == NULL)
666 fatal("can't open %s", argv[0]);
669 return ctlaction(res);
672 static int
673 ctl_jump(struct parse_result *res, int argc, char **argv)
675 int ch;
677 while ((ch = getopt(argc, argv, "")) != -1)
678 ctl_usage(res->ctl);
679 argc -= optind;
680 argv += optind;
682 if (argc != 1)
683 ctl_usage(res->ctl);
685 res->files = argv;
686 return ctlaction(res);
689 static int
690 parse_mode(struct parse_result *res, const char *v)
692 if (v == NULL)
693 return MODE_TOGGLE;
694 if (!strcmp(v, "on"))
695 return MODE_ON;
696 if (!strcmp(v, "off"))
697 return MODE_OFF;
698 ctl_usage(res->ctl);
701 static int
702 ctl_repeat(struct parse_result *res, int argc, char **argv)
704 int ch;
706 while ((ch = getopt(argc, argv, "")) != -1)
707 ctl_usage(res->ctl);
708 argc -= optind;
709 argv += optind;
711 if (argc != 1 && argc != 2)
712 ctl_usage(res->ctl);
714 if (!strcmp(argv[0], "one"))
715 res->mode.repeat_one = parse_mode(res, argv[1]);
716 else if (!strcmp(argv[0], "all"))
717 res->mode.repeat_all = parse_mode(res, argv[1]);
718 else
719 ctl_usage(res->ctl);
721 return ctlaction(res);
724 static int
725 ctl_consume(struct parse_result *res, int argc, char **argv)
727 int ch;
729 while ((ch = getopt(argc, argv, "")) != -1)
730 ctl_usage(res->ctl);
731 argc -= optind;
732 argv += optind;
734 if (argc > 1)
735 ctl_usage(res->ctl);
737 res->mode.consume = parse_mode(res, argv[0]);
738 return ctlaction(res);
741 static int
742 ctl_monitor(struct parse_result *res, int argc, char **argv)
744 int ch, n = 0;
745 const char *events;
746 char *dup, *tmp, *tok;
748 while ((ch = getopt(argc, argv, "")) != -1)
749 ctl_usage(res->ctl);
750 argc -= optind;
751 argv += optind;
753 if (argc > 1)
754 ctl_usage(res->ctl);
756 events = "play,pause,stop,next,prev,jump,mode,add,load,seek";
757 if (argc == 1)
758 events = *argv;
760 tmp = dup = xstrdup(events);
761 while ((tok = strsep(&tmp, ",")) != NULL) {
762 if (*tok == '\0')
763 continue;
765 n++;
766 if (!strcmp(tok, "play"))
767 res->monitor[IMSG_CTL_PLAY] = 1;
768 else if (!strcmp(tok, "pause"))
769 res->monitor[IMSG_CTL_PAUSE] = 1;
770 else if (!strcmp(tok, "stop"))
771 res->monitor[IMSG_CTL_STOP] = 1;
772 else if (!strcmp(tok, "next"))
773 res->monitor[IMSG_CTL_NEXT] = 1;
774 else if (!strcmp(tok, "prev"))
775 res->monitor[IMSG_CTL_PREV] = 1;
776 else if (!strcmp(tok, "jump"))
777 res->monitor[IMSG_CTL_JUMP] = 1;
778 else if (!strcmp(tok, "mode"))
779 res->monitor[IMSG_CTL_MODE] = 1;
780 else if (!strcmp(tok, "add"))
781 res->monitor[IMSG_CTL_ADD] = 1;
782 else if (!strcmp(tok, "load"))
783 res->monitor[IMSG_CTL_COMMIT] = 1;
784 else if (!strcmp(tok, "seek"))
785 res->monitor[IMSG_CTL_SEEK] = 1;
786 else {
787 log_warnx("unknown event \"%s\"", tok);
788 n--;
792 free(dup);
793 if (n == 0)
794 ctl_usage(res->ctl);
795 return ctlaction(res);
798 static int
799 ctl_seek(struct parse_result *res, int argc, char **argv)
801 const char *n;
802 char *ep;
803 int hours = 0, minutes = 0, seconds = 0;
804 int sign = 1;
806 if (argc > 0) {
807 /* skip the command name */
808 argc--;
809 argv++;
812 if (argc > 0 && !strcmp(*argv, "--")) {
813 argc--;
814 argv++;
817 if (argc != 1)
818 ctl_usage(res->ctl);
820 n = *argv;
821 if (*n == '-' || *n == '+')
822 res->seek.relative = 1;
823 if (*n == '-') {
824 n++;
825 sign = -1;
828 seconds = strtol(n, &ep, 10);
829 if (n[0] == '\0' ||
830 (*ep != '\0' && *ep != ':' && *ep != '%') ||
831 (*ep == '%' && ep[1] != '\0'))
832 fatalx("invalid offset: %s", argv[0]);
833 if (*ep == '\0' || *ep == '%') {
834 res->seek.percent = *ep == '%';
835 goto done;
838 n = ++ep;
839 minutes = seconds;
840 seconds = strtol(n, &ep, 10);
841 if (n[0] == '\0' || (*ep != '\0' && *ep != ':'))
842 fatalx("invalid offset: %s", argv[0]);
843 if (*ep == '\0')
844 goto done;
846 n = ++ep;
847 hours = minutes;
848 minutes = seconds;
849 seconds = strtol(n, &ep, 10);
850 if (n[0] == '\0' || *ep != '\0')
851 fatalx("invalid offset: %s", argv[0]);
853 done:
854 res->seek.offset = sign * (hours * 3600 + minutes * 60 + seconds);
855 return ctlaction(res);
858 static int
859 ctl_status(struct parse_result *res, int argc, char **argv)
861 int ch;
863 while ((ch = getopt(argc, argv, "f:")) != -1) {
864 switch (ch) {
865 case 'f':
866 res->status_format = optarg;
867 break;
868 default:
869 ctl_usage(res->ctl);
872 argc -= optind;
873 argv += optind;
875 if (argc > 0)
876 ctl_usage(res->ctl);
878 return ctlaction(res);
881 static int
882 ctl_get_lock(const char *lockfile)
884 int lockfd;
886 if ((lockfd = open(lockfile, O_WRONLY|O_CREAT, 0600)) == -1) {
887 log_debug("open failed: %s", strerror(errno));
888 return -1;
891 if (flock(lockfd, LOCK_EX|LOCK_NB) == -1) {
892 log_debug("flock failed: %s", strerror(errno));
893 if (errno != EAGAIN)
894 return -1;
895 while (flock(lockfd, LOCK_EX) == -1 && errno == EINTR)
896 /* nop */;
897 close(lockfd);
898 return -2;
900 log_debug("flock succeeded");
902 return lockfd;
905 static int
906 ctl_connect(void)
908 struct timespec ts = { 0, 50000000 }; /* 0.05 seconds */
909 struct sockaddr_un sa;
910 size_t size;
911 int fd, lockfd = -1, locked = 0, spawned = 0;
912 int attempt = 0;
913 char *lockfile = NULL;
915 memset(&sa, 0, sizeof(sa));
916 sa.sun_family = AF_UNIX;
917 size = strlcpy(sa.sun_path, csock, sizeof(sa.sun_path));
918 if (size >= sizeof(sa.sun_path)) {
919 errno = ENAMETOOLONG;
920 return -1;
923 retry:
924 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
925 return -1;
927 if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
928 log_debug("connection failed: %s", strerror(errno));
929 if (errno != ECONNREFUSED && errno != ENOENT)
930 goto failed;
931 if (attempt++ == 100)
932 goto failed;
933 close(fd);
935 if (!locked) {
936 xasprintf(&lockfile, "%s.lock", csock);
937 if ((lockfd = ctl_get_lock(lockfile)) < 0) {
938 log_debug("didn't get the lock (%d)", lockfd);
940 free(lockfile);
941 lockfile = NULL;
943 if (lockfd == -1)
944 goto retry;
947 /*
948 * Always retry at least once, even if we got
949 * the lock, because another client could have
950 * taken the lock, started the server and released
951 * the lock between our connect() and flock()
952 */
953 locked = 1;
954 goto retry;
957 if (!spawned) {
958 log_debug("spawning the daemon");
959 spawn_daemon();
960 spawned = 1;
963 nanosleep(&ts, NULL);
964 goto retry;
967 if (locked && lockfd >= 0) {
968 unlink(lockfile);
969 free(lockfile);
970 close(lockfd);
972 return fd;
974 failed:
975 if (locked) {
976 free(lockfile);
977 close(lockfd);
979 close(fd);
980 return -1;
983 __dead void
984 ctl(int argc, char **argv)
986 struct parse_result res;
987 const char *fmt;
988 int ctl_sock;
990 memset(&res, 0, sizeof(res));
991 if ((fmt = getenv("AMUSED_STATUS_FORMAT")) == NULL)
992 fmt = "status,time:oneline,mode:oneline";
993 res.status_format = fmt;
995 res.mode.consume = MODE_UNDEF;
996 res.mode.repeat_all = MODE_UNDEF;
997 res.mode.repeat_one = MODE_UNDEF;
999 log_init(1, LOG_DAEMON);
1000 log_setverbose(verbose);
1002 if (getcwd(cwd, sizeof(cwd)) == NULL)
1003 fatal("getcwd");
1005 if ((ctl_sock = ctl_connect()) == -1)
1006 fatal("can't connect");
1008 ibuf = xmalloc(sizeof(*ibuf));
1009 imsg_init(ibuf, ctl_sock);
1011 optreset = 1;
1012 optind = 1;
1014 /* we'll drop rpath too later in ctlaction */
1015 if (pledge("stdio rpath", NULL) == -1)
1016 fatal("pledge");
1018 exit(parse(&res, argc, argv));