Blob


1 /*
2 * Copyright (c) 2022 Omar Polo <op@openbsd.org>
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];
95 if (input[0] != '/') {
96 if (snprintf(path, sizeof(path), "%s/%s", cwd, input)
97 >= sizeof(path)) {
98 errno = ENAMETOOLONG;
99 return -1;
101 input = path;
104 p = input;
105 q = buf;
106 while (*p && (q - buf < bufsize)) {
107 if (p[0] == '/' && (p[1] == '/' || p[1] == '\0')) {
108 p += 1;
110 } else if (p[0] == '/' && p[1] == '.' &&
111 (p[2] == '/' || p[2] == '\0')) {
112 p += 2;
114 } else if (p[0] == '/' && p[1] == '.' && p[2] == '.' &&
115 (p[3] == '/' || p[3] == '\0')) {
116 p += 3;
117 if (q != buf) /* "/../" at start of buf */
118 while (*--q != '/')
119 continue;
121 } else {
122 *q++ = *p++;
125 if ((*p == '\0') && (q - buf < bufsize)) {
126 *q = 0;
127 return 0;
128 } else {
129 errno = ENAMETOOLONG;
130 return -1;
134 static int
135 parse(struct parse_result *res, int argc, char **argv)
137 struct ctl_command *ctl = NULL;
138 const char *argv0;
139 int i, status;
141 if ((argv0 = argv[0]) == NULL)
142 argv0 = "status";
144 for (i = 0; ctl_commands[i].name != NULL; ++i) {
145 if (strncmp(ctl_commands[i].name, argv0, strlen(argv0))
146 == 0) {
147 if (ctl != NULL) {
148 fprintf(stderr,
149 "ambiguous argument: %s\n", argv0);
150 usage();
152 ctl = &ctl_commands[i];
156 if (ctl == NULL) {
157 fprintf(stderr, "unknown argument: %s\n", argv[0]);
158 usage();
161 res->action = ctl->action;
162 res->ctl = ctl;
164 status = ctl->main(res, argc, argv);
165 close(ibuf->fd);
166 free(ibuf);
167 return status;
170 static int
171 load_files(struct parse_result *res, int *ret)
173 const char *file;
174 char *line = NULL;
175 char path[PATH_MAX];
176 size_t linesize = 0, i = 0;
177 ssize_t linelen, curr = -1;
179 while ((linelen = getline(&line, &linesize, res->fp)) != -1) {
180 if (linelen == 0)
181 continue;
182 line[linelen-1] = '\0';
183 file = line;
184 if (!strncmp(file, "> ", 2)) {
185 file += 2;
186 curr = i;
187 } else if (!strncmp(file, " ", 2))
188 file += 2;
190 memset(path, 0, sizeof(path));
191 if (canonpath(file, path, sizeof(path)) == -1) {
192 log_warn("canonpath %s", file);
193 continue;
196 i++;
197 imsg_compose(ibuf, IMSG_CTL_ADD, 0, 0, -1,
198 path, sizeof(path));
201 free(line);
202 if (ferror(res->fp))
203 fatal("getline");
204 fclose(res->fp);
205 res->fp = NULL;
207 imsg_compose(ibuf, IMSG_CTL_COMMIT, 0, 0, -1,
208 &curr, sizeof(curr));
209 imsg_flush(ibuf);
210 return 0;
213 static const char *
214 imsg_strerror(struct imsg *imsg)
216 size_t datalen;
217 const char *msg;
219 datalen = IMSG_DATA_SIZE(*imsg);
220 msg = imsg->data;
221 if (datalen == 0 || msg[datalen-1] != '\0')
222 fatalx("malformed error message");
224 return msg;
227 static const char *
228 event_name(int type)
230 switch (type) {
231 case IMSG_CTL_PLAY:
232 return "play";
233 case IMSG_CTL_PAUSE:
234 return "pause";
235 case IMSG_CTL_STOP:
236 return "stop";
237 case IMSG_CTL_NEXT:
238 return "next";
239 case IMSG_CTL_PREV:
240 return "prev";
241 case IMSG_CTL_JUMP:
242 return "jump";
243 case IMSG_CTL_ADD:
244 return "add";
245 case IMSG_CTL_COMMIT:
246 return "load";
247 case IMSG_CTL_MODE:
248 return "mode";
249 case IMSG_CTL_SEEK:
250 return "seek";
251 default:
252 return "unknown";
256 static void
257 print_time(const char *label, int64_t seconds, const char *suffx)
259 int hours, minutes;
261 if (seconds < 0)
262 seconds = 0;
264 hours = seconds / 3600;
265 seconds -= hours * 3600;
267 minutes = seconds / 60;
268 seconds -= minutes * 60;
270 printf("%s", label);
271 if (hours != 0)
272 printf("%02d:", hours);
273 printf("%02d:%02lld%s", minutes, (long long)seconds, suffx);
276 static void
277 print_status(struct player_status *ps, const char *spec)
279 const char *status;
280 double percent;
281 char *dup, *tmp, *tok;
283 if (ps->status == STATE_STOPPED)
284 status = "stopped";
285 else if (ps->status == STATE_PLAYING)
286 status = "playing";
287 else if (ps->status == STATE_PAUSED)
288 status = "paused";
289 else
290 status = "unknown";
292 percent = 100.0 * (double)ps->position / (double)ps->duration;
294 tmp = dup = xstrdup(spec);
295 while ((tok = strsep(&tmp, ",")) != NULL) {
296 if (*tok == '\0')
297 continue;
299 if (!strcmp(tok, "path")) {
300 puts(ps->path);
301 } else if (!strcmp(tok, "mode:oneline")) {
302 printf("repeat one:%s ",
303 ps->mode.repeat_one ? "on" : "off");
304 printf("all:%s ", ps->mode.repeat_all ? "on" : "off");
305 printf("consume:%s\n", ps->mode.consume ? "on" : "off");
306 } else if (!strcmp(tok, "mode")) {
307 printf("repeat all %s\n",
308 ps->mode.repeat_all ? "on" : "off");
309 printf("repeat one %s\n",
310 ps->mode.repeat_one ? "on" : "off");
311 printf("consume %s\n",
312 ps->mode.consume ? "on" : "off");
313 } else if (!strcmp(tok, "status")) {
314 printf("%s %s\n", status, ps->path);
315 } else if (!strcmp(tok, "time:oneline")) {
316 print_time("time ", ps->position, " / ");
317 print_time("", ps->duration, "\n");
318 } else if (!strcmp(tok, "time:percentage")) {
319 printf("position %.2f%%\n", percent);
320 } else if (!strcmp(tok, "time:raw")) {
321 printf("position %lld\n", (long long)ps->position);
322 printf("duration %lld\n", (long long)ps->duration);
323 } else if (!strcmp(tok, "time")) {
324 print_time("position ", ps->position, "\n");
325 print_time("duration ", ps->duration, "\n");
329 free(dup);
332 static void
333 print_monitor_event(struct player_event *ev)
335 switch (ev->event) {
336 case IMSG_CTL_MODE:
337 printf("%s repeat one:%s all:%s consume:%s\n",
338 event_name(ev->event),
339 ev->mode.repeat_one ? "on" : "off",
340 ev->mode.repeat_all ? "on" : "off",
341 ev->mode.consume ? "on" : "off");
342 break;
343 case IMSG_CTL_SEEK:
344 printf("%s %lld %lld\n", event_name(ev->event),
345 (long long)ev->position, (long long)ev->duration);
346 break;
347 default:
348 puts(event_name(ev->event));
349 break;
352 fflush(stdout);
355 static int
356 ctlaction(struct parse_result *res)
358 char path[PATH_MAX];
359 struct imsg imsg;
360 struct player_status ps;
361 struct player_event ev;
362 size_t datalen;
363 ssize_t n;
364 int i, ret = 0, done = 1;
366 if (pledge("stdio", NULL) == -1)
367 fatal("pledge");
369 switch (res->action) {
370 case PLAY:
371 imsg_compose(ibuf, IMSG_CTL_PLAY, 0, 0, -1, NULL, 0);
372 if (verbose) {
373 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
374 NULL, 0);
375 done = 0;
377 break;
378 case PAUSE:
379 imsg_compose(ibuf, IMSG_CTL_PAUSE, 0, 0, -1, NULL, 0);
380 break;
381 case TOGGLE:
382 imsg_compose(ibuf, IMSG_CTL_TOGGLE_PLAY, 0, 0, -1, NULL, 0);
383 if (verbose) {
384 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
385 NULL, 0);
386 done = 0;
388 break;
389 case STOP:
390 imsg_compose(ibuf, IMSG_CTL_STOP, 0, 0, -1, NULL, 0);
391 break;
392 case ADD:
393 done = 0;
394 for (i = 0; res->files[i] != NULL; ++i) {
395 memset(path, 0, sizeof(path));
396 if (canonpath(res->files[i], path, sizeof(path))
397 == -1) {
398 log_warn("canonpath %s", res->files[i]);
399 continue;
402 imsg_compose(ibuf, IMSG_CTL_ADD, 0, 0, -1,
403 path, sizeof(path));
405 ret = i == 0;
406 break;
407 case FLUSH:
408 imsg_compose(ibuf, IMSG_CTL_FLUSH, 0, 0, -1, NULL, 0);
409 break;
410 case SHOW:
411 done = 0;
412 imsg_compose(ibuf, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
413 break;
414 case STATUS:
415 done = 0;
416 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1, NULL, 0);
417 break;
418 case NEXT:
419 imsg_compose(ibuf, IMSG_CTL_NEXT, 0, 0, -1, NULL, 0);
420 if (verbose) {
421 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
422 NULL, 0);
423 done = 0;
425 break;
426 case PREV:
427 imsg_compose(ibuf, IMSG_CTL_PREV, 0, 0, -1, NULL, 0);
428 if (verbose) {
429 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
430 NULL, 0);
431 done = 0;
433 break;
434 case LOAD:
435 done = 0;
436 imsg_compose(ibuf, IMSG_CTL_BEGIN, 0, 0, -1, NULL, 0);
437 break;
438 case JUMP:
439 done = 0;
440 memset(path, 0, sizeof(path));
441 strlcpy(path, res->files[0], sizeof(path));
442 imsg_compose(ibuf, IMSG_CTL_JUMP, 0, 0, -1,
443 path, sizeof(path));
444 break;
445 case MODE:
446 done = 0;
447 imsg_compose(ibuf, IMSG_CTL_MODE, 0, 0, -1,
448 &res->mode, sizeof(res->mode));
449 res->status_format = "mode:oneline";
450 if (verbose)
451 res->status_format = "mode";
452 break;
453 case MONITOR:
454 done = 0;
455 imsg_compose(ibuf, IMSG_CTL_MONITOR, 0, 0, -1,
456 NULL, 0);
457 break;
458 case RESTART:
459 memset(&res->seek, 0, sizeof(res->seek));
460 /* fallthrough */
461 case SEEK:
462 imsg_compose(ibuf, IMSG_CTL_SEEK, 0, 0, -1, &res->seek,
463 sizeof(res->seek));
464 break;
465 case NONE:
466 /* action not expected */
467 fatalx("invalid action %u", res->action);
468 break;
471 if (ret != 0)
472 goto end;
474 imsg_flush(ibuf);
476 i = 0;
477 while (!done) {
478 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
479 fatalx("imsg_read error");
480 if (n == 0)
481 fatalx("pipe closed");
483 while (!done) {
484 if ((n = imsg_get(ibuf, &imsg)) == -1)
485 fatalx("imsg_get error");
486 if (n == 0)
487 break;
489 if (imsg.hdr.type == IMSG_CTL_ERR) {
490 log_warnx("%s: %s", res->ctl->name,
491 imsg_strerror(&imsg));
492 ret = 1;
493 done = 1;
494 break;
497 datalen = IMSG_DATA_SIZE(imsg);
499 switch (res->action) {
500 case ADD:
501 if (res->files[i] == NULL)
502 fatalx("received more replies than "
503 "files enqueued.");
505 if (imsg.hdr.type == IMSG_CTL_ADD)
506 log_debug("enqueued %s", res->files[i]);
507 else
508 fatalx("invalid message %d",
509 imsg.hdr.type);
510 i++;
511 done = res->files[i] == NULL;
512 break;
513 case SHOW:
514 if (datalen == 0) {
515 done = 1;
516 break;
518 if (datalen != sizeof(ps))
519 fatalx("data size mismatch");
520 memcpy(&ps, imsg.data, sizeof(ps));
521 if (ps.path[sizeof(ps.path) - 1] != '\0')
522 fatalx("received corrupted data");
523 if (res->pretty) {
524 char c = ' ';
525 if (ps.status == STATE_PLAYING)
526 c = '>';
527 printf("%c ", c);
529 puts(ps.path);
530 break;
531 case PLAY:
532 case TOGGLE:
533 case STATUS:
534 case NEXT:
535 case PREV:
536 case JUMP:
537 case MODE:
538 if (imsg.hdr.type != IMSG_CTL_STATUS)
539 fatalx("invalid message %d",
540 imsg.hdr.type);
542 if (datalen != sizeof(ps))
543 fatalx("data size mismatch");
544 memcpy(&ps, imsg.data, sizeof(ps));
545 if (ps.path[sizeof(ps.path) - 1] != '\0')
546 fatalx("received corrupted data");
548 print_status(&ps, res->status_format);
549 done = 1;
550 break;
551 case LOAD:
552 if (imsg.hdr.type == IMSG_CTL_ADD)
553 break;
554 if (imsg.hdr.type == IMSG_CTL_COMMIT) {
555 done = 1;
556 break;
559 if (imsg.hdr.type != IMSG_CTL_BEGIN)
560 fatalx("invalid message %d",
561 imsg.hdr.type);
563 load_files(res, &ret);
564 break;
565 case MONITOR:
566 if (imsg.hdr.type != IMSG_CTL_MONITOR)
567 fatalx("invalid message %d",
568 imsg.hdr.type);
570 if (datalen != sizeof(ev))
571 fatalx("data size mismatch");
573 memcpy(&ev, imsg.data, sizeof(ev));
574 if (ev.event < 0 || ev.event > IMSG__LAST)
575 fatalx("received corrupted data");
577 if (!res->monitor[ev.event])
578 break;
580 print_monitor_event(&ev);
581 break;
582 default:
583 done = 1;
584 break;
587 imsg_free(&imsg);
591 end:
592 return ret;
595 static int
596 ctl_noarg(struct parse_result *res, int argc, char **argv)
598 int ch;
600 while ((ch = getopt(argc, argv, "")) != -1)
601 ctl_usage(res->ctl);
602 argc -= optind;
603 argv += optind;
605 if (argc > 0)
606 ctl_usage(res->ctl);
608 return ctlaction(res);
611 static int
612 ctl_add(struct parse_result *res, int argc, char **argv)
614 int ch;
616 while ((ch = getopt(argc, argv, "")) != -1)
617 ctl_usage(res->ctl);
618 argc -= optind;
619 argv += optind;
621 if (argc == 0)
622 ctl_usage(res->ctl);
623 res->files = argv;
625 return ctlaction(res);
628 static int
629 ctl_show(struct parse_result *res, int argc, char **argv)
631 int ch;
633 while ((ch = getopt(argc, argv, "p")) != -1) {
634 switch (ch) {
635 case 'p':
636 res->pretty = 1;
637 break;
638 default:
639 ctl_usage(res->ctl);
643 return ctlaction(res);
646 static int
647 ctl_load(struct parse_result *res, int argc, char **argv)
649 int ch;
651 while ((ch = getopt(argc, argv, "")) != -1)
652 ctl_usage(res->ctl);
653 argc -= optind;
654 argv += optind;
656 if (argc > 1)
657 ctl_usage(res->ctl);
659 res->fp = stdin;
660 if (argc == 1) {
661 if ((res->fp = fopen(argv[0], "r")) == NULL)
662 fatal("can't open %s", argv[0]);
665 return ctlaction(res);
668 static int
669 ctl_jump(struct parse_result *res, int argc, char **argv)
671 int ch;
673 while ((ch = getopt(argc, argv, "")) != -1)
674 ctl_usage(res->ctl);
675 argc -= optind;
676 argv += optind;
678 if (argc != 1)
679 ctl_usage(res->ctl);
681 res->files = argv;
682 return ctlaction(res);
685 static int
686 parse_mode(struct parse_result *res, const char *v)
688 if (v == NULL)
689 return MODE_TOGGLE;
690 if (!strcmp(v, "on"))
691 return MODE_ON;
692 if (!strcmp(v, "off"))
693 return MODE_OFF;
694 ctl_usage(res->ctl);
697 static int
698 ctl_repeat(struct parse_result *res, int argc, char **argv)
700 int ch;
702 while ((ch = getopt(argc, argv, "")) != -1)
703 ctl_usage(res->ctl);
704 argc -= optind;
705 argv += optind;
707 if (argc != 1 && argc != 2)
708 ctl_usage(res->ctl);
710 if (!strcmp(argv[0], "one"))
711 res->mode.repeat_one = parse_mode(res, argv[1]);
712 else if (!strcmp(argv[0], "all"))
713 res->mode.repeat_all = parse_mode(res, argv[1]);
714 else
715 ctl_usage(res->ctl);
717 return ctlaction(res);
720 static int
721 ctl_consume(struct parse_result *res, int argc, char **argv)
723 int ch;
725 while ((ch = getopt(argc, argv, "")) != -1)
726 ctl_usage(res->ctl);
727 argc -= optind;
728 argv += optind;
730 if (argc > 1)
731 ctl_usage(res->ctl);
733 res->mode.consume = parse_mode(res, argv[0]);
734 return ctlaction(res);
737 static int
738 ctl_monitor(struct parse_result *res, int argc, char **argv)
740 int ch, n = 0;
741 const char *events;
742 char *dup, *tmp, *tok;
744 while ((ch = getopt(argc, argv, "")) != -1)
745 ctl_usage(res->ctl);
746 argc -= optind;
747 argv += optind;
749 if (argc > 1)
750 ctl_usage(res->ctl);
752 events = "play,pause,stop,next,prev,jump,mode,add,load,seek";
753 if (argc == 1)
754 events = *argv;
756 tmp = dup = xstrdup(events);
757 while ((tok = strsep(&tmp, ",")) != NULL) {
758 if (*tok == '\0')
759 continue;
761 n++;
762 if (!strcmp(tok, "play"))
763 res->monitor[IMSG_CTL_PLAY] = 1;
764 else if (!strcmp(tok, "pause"))
765 res->monitor[IMSG_CTL_PAUSE] = 1;
766 else if (!strcmp(tok, "stop"))
767 res->monitor[IMSG_CTL_STOP] = 1;
768 else if (!strcmp(tok, "next"))
769 res->monitor[IMSG_CTL_NEXT] = 1;
770 else if (!strcmp(tok, "prev"))
771 res->monitor[IMSG_CTL_PREV] = 1;
772 else if (!strcmp(tok, "jump"))
773 res->monitor[IMSG_CTL_JUMP] = 1;
774 else if (!strcmp(tok, "mode"))
775 res->monitor[IMSG_CTL_MODE] = 1;
776 else if (!strcmp(tok, "add"))
777 res->monitor[IMSG_CTL_ADD] = 1;
778 else if (!strcmp(tok, "load"))
779 res->monitor[IMSG_CTL_COMMIT] = 1;
780 else if (!strcmp(tok, "seek"))
781 res->monitor[IMSG_CTL_SEEK] = 1;
782 else {
783 log_warnx("unknown event \"%s\"", tok);
784 n--;
788 free(dup);
789 if (n == 0)
790 ctl_usage(res->ctl);
791 return ctlaction(res);
794 static int
795 ctl_seek(struct parse_result *res, int argc, char **argv)
797 const char *n;
798 char *ep;
799 int hours = 0, minutes = 0, seconds = 0;
800 int sign = 1;
802 if (argc > 0) {
803 /* skip the command name */
804 argc--;
805 argv++;
808 if (argc > 0 && !strcmp(*argv, "--")) {
809 argc--;
810 argv++;
813 if (argc != 1)
814 ctl_usage(res->ctl);
816 n = *argv;
817 if (*n == '-' || *n == '+')
818 res->seek.relative = 1;
819 if (*n == '-') {
820 n++;
821 sign = -1;
824 seconds = strtol(n, &ep, 10);
825 if (n[0] == '\0' ||
826 (*ep != '\0' && *ep != ':' && *ep != '%') ||
827 (*ep == '%' && ep[1] != '\0'))
828 fatalx("invalid offset: %s", argv[0]);
829 if (*ep == '\0' || *ep == '%') {
830 res->seek.percent = *ep == '%';
831 goto done;
834 n = ++ep;
835 minutes = seconds;
836 seconds = strtol(n, &ep, 10);
837 if (n[0] == '\0' || (*ep != '\0' && *ep != ':'))
838 fatalx("invalid offset: %s", argv[0]);
839 if (*ep == '\0')
840 goto done;
842 n = ++ep;
843 hours = minutes;
844 minutes = seconds;
845 seconds = strtol(n, &ep, 10);
846 if (n[0] == '\0' || *ep != '\0')
847 fatalx("invalid offset: %s", argv[0]);
849 done:
850 res->seek.offset = sign * (hours * 3600 + minutes * 60 + seconds);
851 return ctlaction(res);
854 static int
855 ctl_status(struct parse_result *res, int argc, char **argv)
857 int ch;
859 while ((ch = getopt(argc, argv, "f:")) != -1) {
860 switch (ch) {
861 case 'f':
862 res->status_format = optarg;
863 break;
864 default:
865 ctl_usage(res->ctl);
868 argc -= optind;
869 argv += optind;
871 if (argc > 0)
872 ctl_usage(res->ctl);
874 return ctlaction(res);
877 static int
878 ctl_get_lock(const char *lockfile)
880 int lockfd;
882 if ((lockfd = open(lockfile, O_WRONLY|O_CREAT, 0600)) == -1) {
883 log_debug("open failed: %s", strerror(errno));
884 return -1;
887 if (flock(lockfd, LOCK_EX|LOCK_NB) == -1) {
888 log_debug("flock failed: %s", strerror(errno));
889 if (errno != EAGAIN)
890 return -1;
891 while (flock(lockfd, LOCK_EX) == -1 && errno == EINTR)
892 /* nop */;
893 close(lockfd);
894 return -2;
896 log_debug("flock succeeded");
898 return lockfd;
901 static int
902 ctl_connect(void)
904 struct timespec ts = { 0, 50000000 }; /* 0.05 seconds */
905 struct sockaddr_un sa;
906 size_t size;
907 int fd, lockfd = -1, locked = 0, spawned = 0;
908 int attempt = 0;
909 char *lockfile = NULL;
911 memset(&sa, 0, sizeof(sa));
912 sa.sun_family = AF_UNIX;
913 size = strlcpy(sa.sun_path, csock, sizeof(sa.sun_path));
914 if (size >= sizeof(sa.sun_path)) {
915 errno = ENAMETOOLONG;
916 return -1;
919 retry:
920 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
921 return -1;
923 if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
924 log_debug("connection failed: %s", strerror(errno));
925 if (errno != ECONNREFUSED && errno != ENOENT)
926 goto failed;
927 if (attempt++ == 100)
928 goto failed;
929 close(fd);
931 if (!locked) {
932 xasprintf(&lockfile, "%s.lock", csock);
933 if ((lockfd = ctl_get_lock(lockfile)) < 0) {
934 log_debug("didn't get the lock (%d)", lockfd);
936 free(lockfile);
937 lockfile = NULL;
939 if (lockfd == -1)
940 goto retry;
943 /*
944 * Always retry at least once, even if we got
945 * the lock, because another client could have
946 * taken the lock, started the server and released
947 * the lock between our connect() and flock()
948 */
949 locked = 1;
950 goto retry;
953 if (!spawned) {
954 log_debug("spawning the daemon");
955 spawn_daemon();
956 spawned = 1;
959 nanosleep(&ts, NULL);
960 goto retry;
963 if (locked && lockfd >= 0) {
964 unlink(lockfile);
965 free(lockfile);
966 close(lockfd);
968 return fd;
970 failed:
971 if (locked) {
972 free(lockfile);
973 close(lockfd);
975 close(fd);
976 return -1;
979 __dead void
980 ctl(int argc, char **argv)
982 struct parse_result res;
983 const char *fmt;
984 int ctl_sock;
986 memset(&res, 0, sizeof(res));
987 if ((fmt = getenv("AMUSED_STATUS_FORMAT")) == NULL)
988 fmt = "status,time:oneline,mode:oneline";
989 res.status_format = fmt;
991 res.mode.consume = MODE_UNDEF;
992 res.mode.repeat_all = MODE_UNDEF;
993 res.mode.repeat_one = MODE_UNDEF;
995 log_init(1, LOG_DAEMON);
996 log_setverbose(verbose);
998 if (getcwd(cwd, sizeof(cwd)) == NULL)
999 fatal("getcwd");
1001 if ((ctl_sock = ctl_connect()) == -1)
1002 fatal("can't connect");
1004 if (ctl_sock == -1)
1005 fatalx("failed to connect to the daemon");
1007 ibuf = xmalloc(sizeof(*ibuf));
1008 imsg_init(ibuf, 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));