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 if (i == 0) {
208 *ret = 1;
209 return 1;
212 imsg_compose(ibuf, IMSG_CTL_COMMIT, 0, 0, -1,
213 &curr, sizeof(curr));
214 imsg_flush(ibuf);
215 return 0;
218 static const char *
219 imsg_strerror(struct imsg *imsg)
221 size_t datalen;
222 const char *msg;
224 datalen = IMSG_DATA_SIZE(*imsg);
225 msg = imsg->data;
226 if (datalen == 0 || msg[datalen-1] != '\0')
227 fatalx("malformed error message");
229 return msg;
232 static const char *
233 event_name(int type)
235 switch (type) {
236 case IMSG_CTL_PLAY:
237 return "play";
238 case IMSG_CTL_PAUSE:
239 return "pause";
240 case IMSG_CTL_STOP:
241 return "stop";
242 case IMSG_CTL_NEXT:
243 return "next";
244 case IMSG_CTL_PREV:
245 return "prev";
246 case IMSG_CTL_JUMP:
247 return "jump";
248 case IMSG_CTL_ADD:
249 return "add";
250 case IMSG_CTL_COMMIT:
251 return "load";
252 case IMSG_CTL_MODE:
253 return "mode";
254 case IMSG_CTL_SEEK:
255 return "seek";
256 default:
257 return "unknown";
261 static void
262 print_time(const char *label, int64_t seconds, const char *suffx)
264 int hours, minutes;
266 if (seconds < 0)
267 seconds = 0;
269 hours = seconds / 3600;
270 seconds -= hours * 3600;
272 minutes = seconds / 60;
273 seconds -= minutes * 60;
275 printf("%s", label);
276 if (hours != 0)
277 printf("%02d:", hours);
278 printf("%02d:%02lld%s", minutes, (long long)seconds, suffx);
281 static void
282 print_status(struct player_status *ps, const char *spec)
284 const char *status;
285 double percent;
286 char *dup, *tmp, *tok;
288 if (ps->status == STATE_STOPPED)
289 status = "stopped";
290 else if (ps->status == STATE_PLAYING)
291 status = "playing";
292 else if (ps->status == STATE_PAUSED)
293 status = "paused";
294 else
295 status = "unknown";
297 percent = 100.0 * (double)ps->position / (double)ps->duration;
299 tmp = dup = xstrdup(spec);
300 while ((tok = strsep(&tmp, ",")) != NULL) {
301 if (*tok == '\0')
302 continue;
304 if (!strcmp(tok, "path")) {
305 puts(ps->path);
306 } else if (!strcmp(tok, "mode:oneline")) {
307 printf("repeat one:%s ",
308 ps->mode.repeat_one ? "on" : "off");
309 printf("all:%s ", ps->mode.repeat_all ? "on" : "off");
310 printf("consume:%s\n", ps->mode.consume ? "on" : "off");
311 } else if (!strcmp(tok, "repeat")) {
312 printf("repeat one %s\n",
313 ps->mode.repeat_one ? "on" : "off");
314 printf("repeat all %s\n",
315 ps->mode.repeat_all ? "on" : "off");
316 printf("consume %s\n",
317 ps->mode.consume ? "on" : "off");
318 } else if (!strcmp(tok, "status")) {
319 printf("%s %s\n", status, ps->path);
320 } else if (!strcmp(tok, "time:oneline")) {
321 print_time("time ", ps->position, " / ");
322 print_time("", ps->duration, "\n");
323 } else if (!strcmp(tok, "time:percentage")) {
324 printf("position %.2f%%\n", percent);
325 } else if (!strcmp(tok, "time:raw")) {
326 printf("position %lld\n", (long long)ps->position);
327 printf("duration %lld\n", (long long)ps->duration);
328 } else if (!strcmp(tok, "time")) {
329 print_time("position ", ps->position, "\n");
330 print_time("duration ", ps->duration, "\n");
334 free(dup);
337 static int
338 ctlaction(struct parse_result *res)
340 char path[PATH_MAX];
341 struct imsg imsg;
342 struct player_status ps;
343 size_t datalen;
344 ssize_t n;
345 int i, type, ret = 0, done = 1;
347 if (pledge("stdio", NULL) == -1)
348 fatal("pledge");
350 switch (res->action) {
351 case PLAY:
352 imsg_compose(ibuf, IMSG_CTL_PLAY, 0, 0, -1, NULL, 0);
353 if (verbose) {
354 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
355 NULL, 0);
356 done = 0;
358 break;
359 case PAUSE:
360 imsg_compose(ibuf, IMSG_CTL_PAUSE, 0, 0, -1, NULL, 0);
361 break;
362 case TOGGLE:
363 imsg_compose(ibuf, IMSG_CTL_TOGGLE_PLAY, 0, 0, -1, NULL, 0);
364 if (verbose) {
365 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
366 NULL, 0);
367 done = 0;
369 break;
370 case STOP:
371 imsg_compose(ibuf, IMSG_CTL_STOP, 0, 0, -1, NULL, 0);
372 break;
373 case ADD:
374 done = 0;
375 for (i = 0; res->files[i] != NULL; ++i) {
376 memset(path, 0, sizeof(path));
377 if (canonpath(res->files[i], path, sizeof(path))
378 == -1) {
379 log_warn("canonpath %s", res->files[i]);
380 continue;
383 imsg_compose(ibuf, IMSG_CTL_ADD, 0, 0, -1,
384 path, sizeof(path));
386 ret = i == 0;
387 break;
388 case FLUSH:
389 imsg_compose(ibuf, IMSG_CTL_FLUSH, 0, 0, -1, NULL, 0);
390 break;
391 case SHOW:
392 done = 0;
393 imsg_compose(ibuf, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
394 break;
395 case STATUS:
396 done = 0;
397 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1, NULL, 0);
398 break;
399 case NEXT:
400 imsg_compose(ibuf, IMSG_CTL_NEXT, 0, 0, -1, NULL, 0);
401 if (verbose) {
402 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
403 NULL, 0);
404 done = 0;
406 break;
407 case PREV:
408 imsg_compose(ibuf, IMSG_CTL_PREV, 0, 0, -1, NULL, 0);
409 if (verbose) {
410 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
411 NULL, 0);
412 done = 0;
414 break;
415 case LOAD:
416 done = 0;
417 imsg_compose(ibuf, IMSG_CTL_BEGIN, 0, 0, -1, NULL, 0);
418 break;
419 case JUMP:
420 done = 0;
421 memset(path, 0, sizeof(path));
422 strlcpy(path, res->files[0], sizeof(path));
423 imsg_compose(ibuf, IMSG_CTL_JUMP, 0, 0, -1,
424 path, sizeof(path));
425 break;
426 case MODE:
427 imsg_compose(ibuf, IMSG_CTL_MODE, 0, 0, -1,
428 &res->mode, sizeof(res->mode));
429 break;
430 case MONITOR:
431 done = 0;
432 imsg_compose(ibuf, IMSG_CTL_MONITOR, 0, 0, -1,
433 NULL, 0);
434 break;
435 case RESTART:
436 memset(&res->seek, 0, sizeof(res->seek));
437 /* fallthrough */
438 case SEEK:
439 imsg_compose(ibuf, IMSG_CTL_SEEK, 0, 0, -1, &res->seek,
440 sizeof(res->seek));
441 break;
442 case NONE:
443 /* action not expected */
444 fatalx("invalid action %u", res->action);
445 break;
448 if (ret != 0)
449 goto end;
451 imsg_flush(ibuf);
453 i = 0;
454 while (!done) {
455 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
456 fatalx("imsg_read error");
457 if (n == 0)
458 fatalx("pipe closed");
460 while (!done) {
461 if ((n = imsg_get(ibuf, &imsg)) == -1)
462 fatalx("imsg_get error");
463 if (n == 0)
464 break;
466 if (imsg.hdr.type == IMSG_CTL_ERR) {
467 log_warnx("%s: %s", res->ctl->name,
468 imsg_strerror(&imsg));
469 ret = 1;
470 done = 1;
471 break;
474 datalen = IMSG_DATA_SIZE(imsg);
476 switch (res->action) {
477 case ADD:
478 if (res->files[i] == NULL)
479 fatalx("received more replies than "
480 "files enqueued.");
482 if (imsg.hdr.type == IMSG_CTL_ADD)
483 log_debug("enqueued %s", res->files[i]);
484 else
485 fatalx("invalid message %d",
486 imsg.hdr.type);
487 i++;
488 done = res->files[i] == NULL;
489 break;
490 case SHOW:
491 if (datalen == 0) {
492 done = 1;
493 break;
495 if (datalen != sizeof(ps))
496 fatalx("data size mismatch");
497 memcpy(&ps, imsg.data, sizeof(ps));
498 if (ps.path[sizeof(ps.path) - 1] != '\0')
499 fatalx("received corrupted data");
500 if (res->pretty) {
501 char c = ' ';
502 if (ps.status == STATE_PLAYING)
503 c = '>';
504 printf("%c ", c);
506 puts(ps.path);
507 break;
508 case PLAY:
509 case TOGGLE:
510 case STATUS:
511 case NEXT:
512 case PREV:
513 case JUMP:
514 if (imsg.hdr.type != IMSG_CTL_STATUS)
515 fatalx("invalid message %d",
516 imsg.hdr.type);
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");
524 print_status(&ps, res->status_format);
525 done = 1;
526 break;
527 case LOAD:
528 if (imsg.hdr.type == IMSG_CTL_ADD)
529 break;
530 if (imsg.hdr.type == IMSG_CTL_COMMIT) {
531 done = 1;
532 break;
535 if (imsg.hdr.type != IMSG_CTL_BEGIN)
536 fatalx("invalid message %d",
537 imsg.hdr.type);
539 load_files(res, &ret);
540 break;
541 case MONITOR:
542 if (imsg.hdr.type != IMSG_CTL_MONITOR)
543 fatalx("invalid message %d",
544 imsg.hdr.type);
546 if (datalen != sizeof(type))
547 fatalx("data size mismatch");
549 memcpy(&type, imsg.data, sizeof(type));
550 if (type < 0 || type > IMSG__LAST)
551 fatalx("received corrupted data");
553 if (!res->monitor[type])
554 break;
556 puts(event_name(type));
557 fflush(stdout);
558 break;
559 default:
560 done = 1;
561 break;
564 imsg_free(&imsg);
568 end:
569 return ret;
572 static int
573 ctl_noarg(struct parse_result *res, int argc, char **argv)
575 int ch;
577 while ((ch = getopt(argc, argv, "")) != -1)
578 ctl_usage(res->ctl);
579 argc -= optind;
580 argv += optind;
582 if (argc > 0)
583 ctl_usage(res->ctl);
585 return ctlaction(res);
588 static int
589 ctl_add(struct parse_result *res, int argc, char **argv)
591 int ch;
593 while ((ch = getopt(argc, argv, "")) != -1)
594 ctl_usage(res->ctl);
595 argc -= optind;
596 argv += optind;
598 if (argc == 0)
599 ctl_usage(res->ctl);
600 res->files = argv;
602 return ctlaction(res);
605 static int
606 ctl_show(struct parse_result *res, int argc, char **argv)
608 int ch;
610 while ((ch = getopt(argc, argv, "p")) != -1) {
611 switch (ch) {
612 case 'p':
613 res->pretty = 1;
614 break;
615 default:
616 ctl_usage(res->ctl);
620 return ctlaction(res);
623 static int
624 ctl_load(struct parse_result *res, int argc, char **argv)
626 int ch;
628 while ((ch = getopt(argc, argv, "")) != -1)
629 ctl_usage(res->ctl);
630 argc -= optind;
631 argv += optind;
633 if (argc > 1)
634 ctl_usage(res->ctl);
636 res->fp = stdin;
637 if (argc == 1) {
638 if ((res->fp = fopen(argv[0], "r")) == NULL)
639 fatal("can't open %s", argv[0]);
642 return ctlaction(res);
645 static int
646 ctl_jump(struct parse_result *res, int argc, char **argv)
648 int ch;
650 while ((ch = getopt(argc, argv, "")) != -1)
651 ctl_usage(res->ctl);
652 argc -= optind;
653 argv += optind;
655 if (argc != 1)
656 ctl_usage(res->ctl);
658 res->files = argv;
659 return ctlaction(res);
662 static int
663 parse_mode(struct parse_result *res, const char *v)
665 if (v == NULL)
666 return MODE_TOGGLE;
667 if (!strcmp(v, "on"))
668 return MODE_ON;
669 if (!strcmp(v, "off"))
670 return MODE_OFF;
671 ctl_usage(res->ctl);
674 static int
675 ctl_repeat(struct parse_result *res, int argc, char **argv)
677 int ch;
679 while ((ch = getopt(argc, argv, "")) != -1)
680 ctl_usage(res->ctl);
681 argc -= optind;
682 argv += optind;
684 if (argc != 1 && argc != 2)
685 ctl_usage(res->ctl);
687 if (!strcmp(argv[0], "one"))
688 res->mode.repeat_one = parse_mode(res, argv[1]);
689 else if (!strcmp(argv[0], "all"))
690 res->mode.repeat_all = parse_mode(res, argv[1]);
691 else
692 ctl_usage(res->ctl);
694 return ctlaction(res);
697 static int
698 ctl_consume(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)
708 ctl_usage(res->ctl);
710 res->mode.consume = parse_mode(res, argv[0]);
711 return ctlaction(res);
714 static int
715 ctl_monitor(struct parse_result *res, int argc, char **argv)
717 int ch, n = 0;
718 const char *events;
719 char *dup, *tmp, *tok;
721 while ((ch = getopt(argc, argv, "")) != -1)
722 ctl_usage(res->ctl);
723 argc -= optind;
724 argv += optind;
726 if (argc > 1)
727 ctl_usage(res->ctl);
729 events = "play,pause,stop,next,prev,jump,mode,add,load,seek";
730 if (argc == 1)
731 events = *argv;
733 tmp = dup = xstrdup(events);
734 while ((tok = strsep(&tmp, ",")) != NULL) {
735 if (*tok == '\0')
736 continue;
738 n++;
739 if (!strcmp(tok, "play"))
740 res->monitor[IMSG_CTL_PLAY] = 1;
741 else if (!strcmp(tok, "pause"))
742 res->monitor[IMSG_CTL_PAUSE] = 1;
743 else if (!strcmp(tok, "stop"))
744 res->monitor[IMSG_CTL_STOP] = 1;
745 else if (!strcmp(tok, "next"))
746 res->monitor[IMSG_CTL_NEXT] = 1;
747 else if (!strcmp(tok, "prev"))
748 res->monitor[IMSG_CTL_PREV] = 1;
749 else if (!strcmp(tok, "jump"))
750 res->monitor[IMSG_CTL_JUMP] = 1;
751 else if (!strcmp(tok, "mode"))
752 res->monitor[IMSG_CTL_MODE] = 1;
753 else if (!strcmp(tok, "add"))
754 res->monitor[IMSG_CTL_ADD] = 1;
755 else if (!strcmp(tok, "load"))
756 res->monitor[IMSG_CTL_COMMIT] = 1;
757 else if (!strcmp(tok, "seek"))
758 res->monitor[IMSG_CTL_SEEK] = 1;
759 else {
760 log_warnx("unknown event \"%s\"", tok);
761 n--;
765 free(dup);
766 if (n == 0)
767 ctl_usage(res->ctl);
768 return ctlaction(res);
771 static int
772 ctl_seek(struct parse_result *res, int argc, char **argv)
774 const char *n;
775 char *ep;
776 int hours = 0, minutes = 0, seconds = 0;
777 int sign = 1;
779 if (argc > 0) {
780 /* skip the command name */
781 argc--;
782 argv++;
785 if (argc > 0 && !strcmp(*argv, "--")) {
786 argc--;
787 argv++;
790 if (argc != 1)
791 ctl_usage(res->ctl);
793 n = *argv;
794 if (*n == '-' || *n == '+')
795 res->seek.relative = 1;
796 if (*n == '-') {
797 n++;
798 sign = -1;
801 seconds = strtol(n, &ep, 10);
802 if (n[0] == '\0' ||
803 (*ep != '\0' && *ep != ':' && *ep != '%') ||
804 (*ep == '%' && ep[1] != '\0'))
805 fatalx("invalid offset: %s", argv[0]);
806 if (*ep == '\0' || *ep == '%') {
807 res->seek.percent = *ep == '%';
808 goto done;
811 n = ++ep;
812 minutes = seconds;
813 seconds = strtol(n, &ep, 10);
814 if (n[0] == '\0' || (*ep != '\0' && *ep != ':'))
815 fatalx("invalid offset: %s", argv[0]);
816 if (*ep == '\0')
817 goto done;
819 n = ++ep;
820 hours = minutes;
821 minutes = seconds;
822 seconds = strtol(n, &ep, 10);
823 if (n[0] == '\0' || *ep != '\0')
824 fatalx("invalid offset: %s", argv[0]);
826 done:
827 res->seek.offset = sign * (hours * 3600 + minutes * 60 + seconds);
828 return ctlaction(res);
831 static int
832 ctl_status(struct parse_result *res, int argc, char **argv)
834 int ch;
836 while ((ch = getopt(argc, argv, "f:")) != -1) {
837 switch (ch) {
838 case 'f':
839 res->status_format = optarg;
840 break;
841 default:
842 ctl_usage(res->ctl);
845 argc -= optind;
846 argv += optind;
848 if (argc > 0)
849 ctl_usage(res->ctl);
851 return ctlaction(res);
854 static int
855 ctl_get_lock(const char *lockfile)
857 int lockfd;
859 if ((lockfd = open(lockfile, O_WRONLY|O_CREAT, 0600)) == -1) {
860 log_debug("open failed: %s", strerror(errno));
861 return -1;
864 if (flock(lockfd, LOCK_EX|LOCK_NB) == -1) {
865 log_debug("flock failed: %s", strerror(errno));
866 if (errno != EAGAIN)
867 return -1;
868 while (flock(lockfd, LOCK_EX) == -1 && errno == EINTR)
869 /* nop */;
870 close(lockfd);
871 return -2;
873 log_debug("flock succeeded");
875 return lockfd;
878 static int
879 ctl_connect(void)
881 struct timespec ts = { 0, 50000000 }; /* 0.05 seconds */
882 struct sockaddr_un sa;
883 size_t size;
884 int fd, lockfd = -1, locked = 0, spawned = 0;
885 int attempt = 0;
886 char *lockfile = NULL;
888 memset(&sa, 0, sizeof(sa));
889 sa.sun_family = AF_UNIX;
890 size = strlcpy(sa.sun_path, csock, sizeof(sa.sun_path));
891 if (size >= sizeof(sa.sun_path)) {
892 errno = ENAMETOOLONG;
893 return -1;
896 retry:
897 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
898 return -1;
900 if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
901 log_debug("connection failed: %s", strerror(errno));
902 if (errno != ECONNREFUSED && errno != ENOENT)
903 goto failed;
904 if (attempt++ == 100)
905 goto failed;
906 close(fd);
908 if (!locked) {
909 xasprintf(&lockfile, "%s.lock", csock);
910 if ((lockfd = ctl_get_lock(lockfile)) < 0) {
911 log_debug("didn't get the lock (%d)", lockfd);
913 free(lockfile);
914 lockfile = NULL;
916 if (lockfd == -1)
917 goto retry;
920 /*
921 * Always retry at least once, even if we got
922 * the lock, because another client could have
923 * taken the lock, started the server and released
924 * the lock between our connect() and flock()
925 */
926 locked = 1;
927 goto retry;
930 if (!spawned) {
931 log_debug("spawning the daemon");
932 spawn_daemon();
933 spawned = 1;
936 nanosleep(&ts, NULL);
937 goto retry;
940 if (locked && lockfd >= 0) {
941 unlink(lockfile);
942 free(lockfile);
943 close(lockfd);
945 return fd;
947 failed:
948 if (locked) {
949 free(lockfile);
950 close(lockfd);
952 close(fd);
953 return -1;
956 __dead void
957 ctl(int argc, char **argv)
959 struct parse_result res;
960 const char *fmt;
961 int ctl_sock;
963 memset(&res, 0, sizeof(res));
964 if ((fmt = getenv("AMUSED_STATUS_FORMAT")) == NULL)
965 fmt = "status,time,repeat";
966 res.status_format = fmt;
968 res.mode.consume = MODE_UNDEF;
969 res.mode.repeat_all = MODE_UNDEF;
970 res.mode.repeat_one = MODE_UNDEF;
972 log_init(1, LOG_DAEMON);
973 log_setverbose(verbose);
975 if (getcwd(cwd, sizeof(cwd)) == NULL)
976 fatal("getcwd");
978 if ((ctl_sock = ctl_connect()) == -1)
979 fatal("can't connect");
981 if (ctl_sock == -1)
982 fatalx("failed to connect to the daemon");
984 ibuf = xmalloc(sizeof(*ibuf));
985 imsg_init(ibuf, ctl_sock);
987 optreset = 1;
988 optind = 1;
990 /* we'll drop rpath too later in ctlaction */
991 if (pledge("stdio rpath", NULL) == -1)
992 fatal("pledge");
994 exit(parse(&res, argc, argv));