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 <unistd.h>
33 #include "amused.h"
34 #include "log.h"
35 #include "playlist.h"
36 #include "xmalloc.h"
38 static struct imsgbuf *ibuf;
39 char cwd[PATH_MAX];
41 static int ctl_noarg(struct parse_result *, int, char **);
42 static int ctl_add(struct parse_result *, int, char **);
43 static int ctl_show(struct parse_result *, int, char **);
44 static int ctl_load(struct parse_result *, int, char **);
45 static int ctl_jump(struct parse_result *, int, char **);
46 static int ctl_repeat(struct parse_result *, int, char **);
47 static int ctl_consume(struct parse_result *, int, char **);
48 static int ctl_monitor(struct parse_result *, int, char **);
49 static int ctl_seek(struct parse_result *, int, char **);
50 static int ctl_status(struct parse_result *, int, char **);
52 struct ctl_command ctl_commands[] = {
53 { "add", ADD, ctl_add, "files..."},
54 { "consume", MODE, ctl_consume, "one|all"},
55 { "flush", FLUSH, ctl_noarg, ""},
56 { "jump", JUMP, ctl_jump, "pattern"},
57 { "load", LOAD, ctl_load, "[file]"},
58 { "monitor", MONITOR, ctl_monitor, "[events]"},
59 { "next", NEXT, ctl_noarg, ""},
60 { "pause", PAUSE, ctl_noarg, ""},
61 { "play", PLAY, ctl_noarg, ""},
62 { "prev", PREV, ctl_noarg, ""},
63 { "repeat", MODE, ctl_repeat, "one|all on|off"},
64 { "restart", RESTART, ctl_noarg, ""},
65 { "seek", SEEK, ctl_seek, "[+-]time[%]"},
66 { "show", SHOW, ctl_show, "[-p]"},
67 { "status", STATUS, ctl_status, "[-f fmt]"},
68 { "stop", STOP, ctl_noarg, ""},
69 { "toggle", TOGGLE, ctl_noarg, ""},
70 { NULL, 0, NULL, NULL},
71 };
73 __dead void
74 usage(void)
75 {
76 fprintf(stderr, "usage: %s [-dv] [-s socket]\n", getprogname());
77 exit(1);
78 }
80 static __dead void
81 ctl_usage(struct ctl_command *ctl)
82 {
83 fprintf(stderr, "usage: %s [-v] [-s socket] %s %s\n", getprogname(),
84 ctl->name, ctl->usage);
85 exit(1);
86 }
88 /* based on canonpath from kern_pledge.c */
89 static int
90 canonpath(const char *input, char *buf, size_t bufsize)
91 {
92 const char *p;
93 char *q, path[PATH_MAX];
94 int r;
96 if (input[0] != '/') {
97 r = snprintf(path, sizeof(path), "%s/%s", cwd, input);
98 if (r < 0 || (size_t)r >= sizeof(path)) {
99 errno = ENAMETOOLONG;
100 return -1;
102 input = path;
105 p = input;
106 q = buf;
107 while (*p && (q - buf < bufsize)) {
108 if (p[0] == '/' && (p[1] == '/' || p[1] == '\0')) {
109 p += 1;
111 } else if (p[0] == '/' && p[1] == '.' &&
112 (p[2] == '/' || p[2] == '\0')) {
113 p += 2;
115 } else if (p[0] == '/' && p[1] == '.' && p[2] == '.' &&
116 (p[3] == '/' || p[3] == '\0')) {
117 p += 3;
118 if (q != buf) /* "/../" at start of buf */
119 while (*--q != '/')
120 continue;
122 } else {
123 *q++ = *p++;
126 if ((*p == '\0') && (q - buf < bufsize)) {
127 *q = 0;
128 return 0;
129 } else {
130 errno = ENAMETOOLONG;
131 return -1;
135 static int
136 parse(struct parse_result *res, int argc, char **argv)
138 struct ctl_command *ctl = NULL;
139 const char *argv0;
140 int i, status;
142 if ((argv0 = argv[0]) == NULL)
143 argv0 = "status";
145 for (i = 0; ctl_commands[i].name != NULL; ++i) {
146 if (strncmp(ctl_commands[i].name, argv0, strlen(argv0))
147 == 0) {
148 if (ctl != NULL) {
149 fprintf(stderr,
150 "ambiguous argument: %s\n", argv0);
151 usage();
153 ctl = &ctl_commands[i];
157 if (ctl == NULL) {
158 fprintf(stderr, "unknown argument: %s\n", argv[0]);
159 usage();
162 res->action = ctl->action;
163 res->ctl = ctl;
165 status = ctl->main(res, argc, argv);
166 close(ibuf->fd);
167 free(ibuf);
168 return status;
171 static int
172 load_files(struct parse_result *res, int *ret)
174 const char *file;
175 char *line = NULL;
176 char path[PATH_MAX];
177 size_t linesize = 0, i = 0;
178 ssize_t linelen, curr = -1;
180 while ((linelen = getline(&line, &linesize, res->fp)) != -1) {
181 if (linelen == 0)
182 continue;
183 line[linelen-1] = '\0';
184 file = line;
185 if (!strncmp(file, "> ", 2)) {
186 file += 2;
187 curr = i;
188 } else if (!strncmp(file, " ", 2))
189 file += 2;
191 memset(path, 0, sizeof(path));
192 if (canonpath(file, path, sizeof(path)) == -1) {
193 log_warn("canonpath %s", file);
194 continue;
197 i++;
198 imsg_compose(ibuf, IMSG_CTL_ADD, 0, 0, -1,
199 path, sizeof(path));
202 free(line);
203 if (ferror(res->fp))
204 fatal("getline");
205 fclose(res->fp);
206 res->fp = NULL;
208 imsg_compose(ibuf, IMSG_CTL_COMMIT, 0, 0, -1,
209 &curr, sizeof(curr));
210 imsg_flush(ibuf);
211 return 0;
214 static const char *
215 imsg_strerror(struct imsg *imsg)
217 size_t datalen;
218 const char *msg;
220 datalen = IMSG_DATA_SIZE(*imsg);
221 msg = imsg->data;
222 if (datalen == 0 || msg[datalen-1] != '\0')
223 fatalx("malformed error message");
225 return msg;
228 static const char *
229 event_name(int type)
231 switch (type) {
232 case IMSG_CTL_PLAY:
233 return "play";
234 case IMSG_CTL_PAUSE:
235 return "pause";
236 case IMSG_CTL_STOP:
237 return "stop";
238 case IMSG_CTL_NEXT:
239 return "next";
240 case IMSG_CTL_PREV:
241 return "prev";
242 case IMSG_CTL_JUMP:
243 return "jump";
244 case IMSG_CTL_ADD:
245 return "add";
246 case IMSG_CTL_COMMIT:
247 return "load";
248 case IMSG_CTL_MODE:
249 return "mode";
250 case IMSG_CTL_SEEK:
251 return "seek";
252 default:
253 return "unknown";
257 static void
258 print_time(const char *label, int64_t seconds, const char *suffx)
260 int hours, minutes;
262 if (seconds < 0)
263 seconds = 0;
265 hours = seconds / 3600;
266 seconds -= hours * 3600;
268 minutes = seconds / 60;
269 seconds -= minutes * 60;
271 printf("%s", label);
272 if (hours != 0)
273 printf("%02d:", hours);
274 printf("%02d:%02lld%s", minutes, (long long)seconds, suffx);
277 static void
278 print_status(struct player_status *ps, const char *spec)
280 const char *status;
281 double percent;
282 char *dup, *tmp, *tok;
284 if (ps->status == STATE_STOPPED)
285 status = "stopped";
286 else if (ps->status == STATE_PLAYING)
287 status = "playing";
288 else if (ps->status == STATE_PAUSED)
289 status = "paused";
290 else
291 status = "unknown";
293 percent = 100.0 * (double)ps->position / (double)ps->duration;
295 tmp = dup = xstrdup(spec);
296 while ((tok = strsep(&tmp, ",")) != NULL) {
297 if (*tok == '\0')
298 continue;
300 if (!strcmp(tok, "path")) {
301 puts(ps->path);
302 } else if (!strcmp(tok, "mode:oneline")) {
303 printf("repeat one:%s ",
304 ps->mode.repeat_one ? "on" : "off");
305 printf("all:%s ", ps->mode.repeat_all ? "on" : "off");
306 printf("consume:%s\n", ps->mode.consume ? "on" : "off");
307 } else if (!strcmp(tok, "mode")) {
308 printf("repeat all %s\n",
309 ps->mode.repeat_all ? "on" : "off");
310 printf("repeat one %s\n",
311 ps->mode.repeat_one ? "on" : "off");
312 printf("consume %s\n",
313 ps->mode.consume ? "on" : "off");
314 } else if (!strcmp(tok, "status")) {
315 printf("%s %s\n", status, ps->path);
316 } else if (!strcmp(tok, "time:oneline")) {
317 print_time("time ", ps->position, " / ");
318 print_time("", ps->duration, "\n");
319 } else if (!strcmp(tok, "time:percentage")) {
320 printf("position %.2f%%\n", percent);
321 } else if (!strcmp(tok, "time:raw")) {
322 printf("position %lld\n", (long long)ps->position);
323 printf("duration %lld\n", (long long)ps->duration);
324 } else if (!strcmp(tok, "time")) {
325 print_time("position ", ps->position, "\n");
326 print_time("duration ", ps->duration, "\n");
330 free(dup);
333 static void
334 print_monitor_event(struct player_event *ev)
336 switch (ev->event) {
337 case IMSG_CTL_MODE:
338 printf("%s repeat one:%s all:%s consume:%s\n",
339 event_name(ev->event),
340 ev->mode.repeat_one ? "on" : "off",
341 ev->mode.repeat_all ? "on" : "off",
342 ev->mode.consume ? "on" : "off");
343 break;
344 case IMSG_CTL_SEEK:
345 printf("%s %lld %lld\n", event_name(ev->event),
346 (long long)ev->position, (long long)ev->duration);
347 break;
348 default:
349 puts(event_name(ev->event));
350 break;
353 fflush(stdout);
356 static int
357 ctlaction(struct parse_result *res)
359 char path[PATH_MAX];
360 struct imsg imsg;
361 struct player_status ps;
362 struct player_event ev;
363 size_t datalen;
364 ssize_t n;
365 int i, ret = 0, done = 1;
367 if (pledge("stdio", NULL) == -1)
368 fatal("pledge");
370 switch (res->action) {
371 case PLAY:
372 imsg_compose(ibuf, IMSG_CTL_PLAY, 0, 0, -1, NULL, 0);
373 if (verbose) {
374 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
375 NULL, 0);
376 done = 0;
378 break;
379 case PAUSE:
380 imsg_compose(ibuf, IMSG_CTL_PAUSE, 0, 0, -1, NULL, 0);
381 break;
382 case TOGGLE:
383 imsg_compose(ibuf, IMSG_CTL_TOGGLE_PLAY, 0, 0, -1, NULL, 0);
384 if (verbose) {
385 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
386 NULL, 0);
387 done = 0;
389 break;
390 case STOP:
391 imsg_compose(ibuf, IMSG_CTL_STOP, 0, 0, -1, NULL, 0);
392 break;
393 case ADD:
394 done = 0;
395 for (i = 0; res->files[i] != NULL; ++i) {
396 memset(path, 0, sizeof(path));
397 if (canonpath(res->files[i], path, sizeof(path))
398 == -1) {
399 log_warn("canonpath %s", res->files[i]);
400 continue;
403 imsg_compose(ibuf, IMSG_CTL_ADD, 0, 0, -1,
404 path, sizeof(path));
406 ret = i == 0;
407 break;
408 case FLUSH:
409 imsg_compose(ibuf, IMSG_CTL_FLUSH, 0, 0, -1, NULL, 0);
410 break;
411 case SHOW:
412 done = 0;
413 imsg_compose(ibuf, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
414 break;
415 case STATUS:
416 done = 0;
417 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1, NULL, 0);
418 break;
419 case NEXT:
420 imsg_compose(ibuf, IMSG_CTL_NEXT, 0, 0, -1, NULL, 0);
421 if (verbose) {
422 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
423 NULL, 0);
424 done = 0;
426 break;
427 case PREV:
428 imsg_compose(ibuf, IMSG_CTL_PREV, 0, 0, -1, NULL, 0);
429 if (verbose) {
430 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
431 NULL, 0);
432 done = 0;
434 break;
435 case LOAD:
436 done = 0;
437 imsg_compose(ibuf, IMSG_CTL_BEGIN, 0, 0, -1, NULL, 0);
438 break;
439 case JUMP:
440 done = 0;
441 memset(path, 0, sizeof(path));
442 strlcpy(path, res->files[0], sizeof(path));
443 imsg_compose(ibuf, IMSG_CTL_JUMP, 0, 0, -1,
444 path, sizeof(path));
445 break;
446 case MODE:
447 done = 0;
448 imsg_compose(ibuf, IMSG_CTL_MODE, 0, 0, -1,
449 &res->mode, sizeof(res->mode));
450 res->status_format = "mode:oneline";
451 if (verbose)
452 res->status_format = "mode";
453 break;
454 case MONITOR:
455 done = 0;
456 imsg_compose(ibuf, IMSG_CTL_MONITOR, 0, 0, -1,
457 NULL, 0);
458 break;
459 case RESTART:
460 memset(&res->seek, 0, sizeof(res->seek));
461 /* fallthrough */
462 case SEEK:
463 imsg_compose(ibuf, IMSG_CTL_SEEK, 0, 0, -1, &res->seek,
464 sizeof(res->seek));
465 break;
466 case NONE:
467 /* action not expected */
468 fatalx("invalid action %u", res->action);
469 break;
472 if (ret != 0)
473 goto end;
475 imsg_flush(ibuf);
477 i = 0;
478 while (!done) {
479 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
480 fatalx("imsg_read error");
481 if (n == 0)
482 fatalx("pipe closed");
484 while (!done) {
485 if ((n = imsg_get(ibuf, &imsg)) == -1)
486 fatalx("imsg_get error");
487 if (n == 0)
488 break;
490 if (imsg.hdr.type == IMSG_CTL_ERR) {
491 log_warnx("%s: %s", res->ctl->name,
492 imsg_strerror(&imsg));
493 ret = 1;
494 done = 1;
495 break;
498 datalen = IMSG_DATA_SIZE(imsg);
500 switch (res->action) {
501 case ADD:
502 if (res->files[i] == NULL)
503 fatalx("received more replies than "
504 "files enqueued.");
506 if (imsg.hdr.type == IMSG_CTL_ADD)
507 log_debug("enqueued %s", res->files[i]);
508 else
509 fatalx("invalid message %d",
510 imsg.hdr.type);
511 i++;
512 done = res->files[i] == NULL;
513 break;
514 case SHOW:
515 if (datalen == 0) {
516 done = 1;
517 break;
519 if (datalen != sizeof(ps))
520 fatalx("data size mismatch");
521 memcpy(&ps, imsg.data, sizeof(ps));
522 if (ps.path[sizeof(ps.path) - 1] != '\0')
523 fatalx("received corrupted data");
524 if (res->pretty) {
525 char c = ' ';
526 if (ps.status == STATE_PLAYING)
527 c = '>';
528 printf("%c ", c);
530 puts(ps.path);
531 break;
532 case PLAY:
533 case TOGGLE:
534 case STATUS:
535 case NEXT:
536 case PREV:
537 case JUMP:
538 case MODE:
539 if (imsg.hdr.type != IMSG_CTL_STATUS)
540 fatalx("invalid message %d",
541 imsg.hdr.type);
543 if (datalen != sizeof(ps))
544 fatalx("data size mismatch");
545 memcpy(&ps, imsg.data, sizeof(ps));
546 if (ps.path[sizeof(ps.path) - 1] != '\0')
547 fatalx("received corrupted data");
549 print_status(&ps, res->status_format);
550 done = 1;
551 break;
552 case LOAD:
553 if (imsg.hdr.type == IMSG_CTL_ADD)
554 break;
555 if (imsg.hdr.type == IMSG_CTL_COMMIT) {
556 done = 1;
557 break;
560 if (imsg.hdr.type != IMSG_CTL_BEGIN)
561 fatalx("invalid message %d",
562 imsg.hdr.type);
564 load_files(res, &ret);
565 break;
566 case MONITOR:
567 if (imsg.hdr.type != IMSG_CTL_MONITOR)
568 fatalx("invalid message %d",
569 imsg.hdr.type);
571 if (datalen != sizeof(ev))
572 fatalx("data size mismatch");
574 memcpy(&ev, imsg.data, sizeof(ev));
575 if (ev.event < 0 || ev.event > IMSG__LAST)
576 fatalx("received corrupted data");
578 if (!res->monitor[ev.event])
579 break;
581 print_monitor_event(&ev);
582 break;
583 default:
584 done = 1;
585 break;
588 imsg_free(&imsg);
592 end:
593 return ret;
596 static int
597 ctl_noarg(struct parse_result *res, int argc, char **argv)
599 int ch;
601 while ((ch = getopt(argc, argv, "")) != -1)
602 ctl_usage(res->ctl);
603 argc -= optind;
604 argv += optind;
606 if (argc > 0)
607 ctl_usage(res->ctl);
609 return ctlaction(res);
612 static int
613 ctl_add(struct parse_result *res, int argc, char **argv)
615 int ch;
617 while ((ch = getopt(argc, argv, "")) != -1)
618 ctl_usage(res->ctl);
619 argc -= optind;
620 argv += optind;
622 if (argc == 0)
623 ctl_usage(res->ctl);
624 res->files = argv;
626 return ctlaction(res);
629 static int
630 ctl_show(struct parse_result *res, int argc, char **argv)
632 int ch;
634 while ((ch = getopt(argc, argv, "p")) != -1) {
635 switch (ch) {
636 case 'p':
637 res->pretty = 1;
638 break;
639 default:
640 ctl_usage(res->ctl);
644 return ctlaction(res);
647 static int
648 ctl_load(struct parse_result *res, int argc, char **argv)
650 int ch;
652 while ((ch = getopt(argc, argv, "")) != -1)
653 ctl_usage(res->ctl);
654 argc -= optind;
655 argv += optind;
657 if (argc > 1)
658 ctl_usage(res->ctl);
660 res->fp = stdin;
661 if (argc == 1) {
662 if ((res->fp = fopen(argv[0], "r")) == NULL)
663 fatal("can't open %s", argv[0]);
666 return ctlaction(res);
669 static int
670 ctl_jump(struct parse_result *res, int argc, char **argv)
672 int ch;
674 while ((ch = getopt(argc, argv, "")) != -1)
675 ctl_usage(res->ctl);
676 argc -= optind;
677 argv += optind;
679 if (argc != 1)
680 ctl_usage(res->ctl);
682 res->files = argv;
683 return ctlaction(res);
686 static int
687 parse_mode(struct parse_result *res, const char *v)
689 if (v == NULL)
690 return MODE_TOGGLE;
691 if (!strcmp(v, "on"))
692 return MODE_ON;
693 if (!strcmp(v, "off"))
694 return MODE_OFF;
695 ctl_usage(res->ctl);
698 static int
699 ctl_repeat(struct parse_result *res, int argc, char **argv)
701 int ch;
703 while ((ch = getopt(argc, argv, "")) != -1)
704 ctl_usage(res->ctl);
705 argc -= optind;
706 argv += optind;
708 if (argc != 1 && argc != 2)
709 ctl_usage(res->ctl);
711 if (!strcmp(argv[0], "one"))
712 res->mode.repeat_one = parse_mode(res, argv[1]);
713 else if (!strcmp(argv[0], "all"))
714 res->mode.repeat_all = parse_mode(res, argv[1]);
715 else
716 ctl_usage(res->ctl);
718 return ctlaction(res);
721 static int
722 ctl_consume(struct parse_result *res, int argc, char **argv)
724 int ch;
726 while ((ch = getopt(argc, argv, "")) != -1)
727 ctl_usage(res->ctl);
728 argc -= optind;
729 argv += optind;
731 if (argc > 1)
732 ctl_usage(res->ctl);
734 res->mode.consume = parse_mode(res, argv[0]);
735 return ctlaction(res);
738 static int
739 ctl_monitor(struct parse_result *res, int argc, char **argv)
741 int ch, n = 0;
742 const char *events;
743 char *dup, *tmp, *tok;
745 while ((ch = getopt(argc, argv, "")) != -1)
746 ctl_usage(res->ctl);
747 argc -= optind;
748 argv += optind;
750 if (argc > 1)
751 ctl_usage(res->ctl);
753 events = "play,pause,stop,next,prev,jump,mode,add,load,seek";
754 if (argc == 1)
755 events = *argv;
757 tmp = dup = xstrdup(events);
758 while ((tok = strsep(&tmp, ",")) != NULL) {
759 if (*tok == '\0')
760 continue;
762 n++;
763 if (!strcmp(tok, "play"))
764 res->monitor[IMSG_CTL_PLAY] = 1;
765 else if (!strcmp(tok, "pause"))
766 res->monitor[IMSG_CTL_PAUSE] = 1;
767 else if (!strcmp(tok, "stop"))
768 res->monitor[IMSG_CTL_STOP] = 1;
769 else if (!strcmp(tok, "next"))
770 res->monitor[IMSG_CTL_NEXT] = 1;
771 else if (!strcmp(tok, "prev"))
772 res->monitor[IMSG_CTL_PREV] = 1;
773 else if (!strcmp(tok, "jump"))
774 res->monitor[IMSG_CTL_JUMP] = 1;
775 else if (!strcmp(tok, "mode"))
776 res->monitor[IMSG_CTL_MODE] = 1;
777 else if (!strcmp(tok, "add"))
778 res->monitor[IMSG_CTL_ADD] = 1;
779 else if (!strcmp(tok, "load"))
780 res->monitor[IMSG_CTL_COMMIT] = 1;
781 else if (!strcmp(tok, "seek"))
782 res->monitor[IMSG_CTL_SEEK] = 1;
783 else {
784 log_warnx("unknown event \"%s\"", tok);
785 n--;
789 free(dup);
790 if (n == 0)
791 ctl_usage(res->ctl);
792 return ctlaction(res);
795 static int
796 ctl_seek(struct parse_result *res, int argc, char **argv)
798 const char *n;
799 char *ep;
800 int hours = 0, minutes = 0, seconds = 0;
801 int sign = 1;
803 if (argc > 0) {
804 /* skip the command name */
805 argc--;
806 argv++;
809 if (argc > 0 && !strcmp(*argv, "--")) {
810 argc--;
811 argv++;
814 if (argc != 1)
815 ctl_usage(res->ctl);
817 n = *argv;
818 if (*n == '-' || *n == '+')
819 res->seek.relative = 1;
820 if (*n == '-') {
821 n++;
822 sign = -1;
825 seconds = strtol(n, &ep, 10);
826 if (n[0] == '\0' ||
827 (*ep != '\0' && *ep != ':' && *ep != '%') ||
828 (*ep == '%' && ep[1] != '\0'))
829 fatalx("invalid offset: %s", argv[0]);
830 if (*ep == '\0' || *ep == '%') {
831 res->seek.percent = *ep == '%';
832 goto done;
835 n = ++ep;
836 minutes = seconds;
837 seconds = strtol(n, &ep, 10);
838 if (n[0] == '\0' || (*ep != '\0' && *ep != ':'))
839 fatalx("invalid offset: %s", argv[0]);
840 if (*ep == '\0')
841 goto done;
843 n = ++ep;
844 hours = minutes;
845 minutes = seconds;
846 seconds = strtol(n, &ep, 10);
847 if (n[0] == '\0' || *ep != '\0')
848 fatalx("invalid offset: %s", argv[0]);
850 done:
851 res->seek.offset = sign * (hours * 3600 + minutes * 60 + seconds);
852 return ctlaction(res);
855 static int
856 ctl_status(struct parse_result *res, int argc, char **argv)
858 int ch;
860 while ((ch = getopt(argc, argv, "f:")) != -1) {
861 switch (ch) {
862 case 'f':
863 res->status_format = optarg;
864 break;
865 default:
866 ctl_usage(res->ctl);
869 argc -= optind;
870 argv += optind;
872 if (argc > 0)
873 ctl_usage(res->ctl);
875 return ctlaction(res);
878 static int
879 ctl_get_lock(const char *lockfile)
881 int lockfd;
883 if ((lockfd = open(lockfile, O_WRONLY|O_CREAT, 0600)) == -1) {
884 log_debug("open failed: %s", strerror(errno));
885 return -1;
888 if (flock(lockfd, LOCK_EX|LOCK_NB) == -1) {
889 log_debug("flock failed: %s", strerror(errno));
890 if (errno != EAGAIN)
891 return -1;
892 while (flock(lockfd, LOCK_EX) == -1 && errno == EINTR)
893 /* nop */;
894 close(lockfd);
895 return -2;
897 log_debug("flock succeeded");
899 return lockfd;
902 static int
903 ctl_connect(void)
905 struct timespec ts = { 0, 50000000 }; /* 0.05 seconds */
906 struct sockaddr_un sa;
907 size_t size;
908 int fd, lockfd = -1, locked = 0, spawned = 0;
909 int attempt = 0;
910 char *lockfile = NULL;
912 memset(&sa, 0, sizeof(sa));
913 sa.sun_family = AF_UNIX;
914 size = strlcpy(sa.sun_path, csock, sizeof(sa.sun_path));
915 if (size >= sizeof(sa.sun_path)) {
916 errno = ENAMETOOLONG;
917 return -1;
920 retry:
921 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
922 return -1;
924 if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
925 log_debug("connection failed: %s", strerror(errno));
926 if (errno != ECONNREFUSED && errno != ENOENT)
927 goto failed;
928 if (attempt++ == 100)
929 goto failed;
930 close(fd);
932 if (!locked) {
933 xasprintf(&lockfile, "%s.lock", csock);
934 if ((lockfd = ctl_get_lock(lockfile)) < 0) {
935 log_debug("didn't get the lock (%d)", lockfd);
937 free(lockfile);
938 lockfile = NULL;
940 if (lockfd == -1)
941 goto retry;
944 /*
945 * Always retry at least once, even if we got
946 * the lock, because another client could have
947 * taken the lock, started the server and released
948 * the lock between our connect() and flock()
949 */
950 locked = 1;
951 goto retry;
954 if (!spawned) {
955 log_debug("spawning the daemon");
956 spawn_daemon();
957 spawned = 1;
960 nanosleep(&ts, NULL);
961 goto retry;
964 if (locked && lockfd >= 0) {
965 unlink(lockfile);
966 free(lockfile);
967 close(lockfd);
969 return fd;
971 failed:
972 if (locked) {
973 free(lockfile);
974 close(lockfd);
976 close(fd);
977 return -1;
980 __dead void
981 ctl(int argc, char **argv)
983 struct parse_result res;
984 const char *fmt;
985 int ctl_sock;
987 memset(&res, 0, sizeof(res));
988 if ((fmt = getenv("AMUSED_STATUS_FORMAT")) == NULL)
989 fmt = "status,time:oneline,mode:oneline";
990 res.status_format = fmt;
992 res.mode.consume = MODE_UNDEF;
993 res.mode.repeat_all = MODE_UNDEF;
994 res.mode.repeat_one = MODE_UNDEF;
996 log_init(1, LOG_DAEMON);
997 log_setverbose(verbose);
999 if (getcwd(cwd, sizeof(cwd)) == NULL)
1000 fatal("getcwd");
1002 if ((ctl_sock = ctl_connect()) == -1)
1003 fatal("can't connect");
1005 ibuf = xmalloc(sizeof(*ibuf));
1006 imsg_init(ibuf, ctl_sock);
1008 optreset = 1;
1009 optind = 1;
1011 /* we'll drop rpath too later in ctlaction */
1012 if (pledge("stdio rpath", NULL) == -1)
1013 fatal("pledge");
1015 exit(parse(&res, argc, argv));