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 one %s\n",
308 ps->mode.repeat_one ? "on" : "off");
309 printf("repeat all %s\n",
310 ps->mode.repeat_all ? "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 int
333 ctlaction(struct parse_result *res)
335 char path[PATH_MAX];
336 struct imsg imsg;
337 struct player_status ps;
338 size_t datalen;
339 ssize_t n;
340 int i, type, ret = 0, done = 1;
342 if (pledge("stdio", NULL) == -1)
343 fatal("pledge");
345 switch (res->action) {
346 case PLAY:
347 imsg_compose(ibuf, IMSG_CTL_PLAY, 0, 0, -1, NULL, 0);
348 if (verbose) {
349 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
350 NULL, 0);
351 done = 0;
353 break;
354 case PAUSE:
355 imsg_compose(ibuf, IMSG_CTL_PAUSE, 0, 0, -1, NULL, 0);
356 break;
357 case TOGGLE:
358 imsg_compose(ibuf, IMSG_CTL_TOGGLE_PLAY, 0, 0, -1, NULL, 0);
359 if (verbose) {
360 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
361 NULL, 0);
362 done = 0;
364 break;
365 case STOP:
366 imsg_compose(ibuf, IMSG_CTL_STOP, 0, 0, -1, NULL, 0);
367 break;
368 case ADD:
369 done = 0;
370 for (i = 0; res->files[i] != NULL; ++i) {
371 memset(path, 0, sizeof(path));
372 if (canonpath(res->files[i], path, sizeof(path))
373 == -1) {
374 log_warn("canonpath %s", res->files[i]);
375 continue;
378 imsg_compose(ibuf, IMSG_CTL_ADD, 0, 0, -1,
379 path, sizeof(path));
381 ret = i == 0;
382 break;
383 case FLUSH:
384 imsg_compose(ibuf, IMSG_CTL_FLUSH, 0, 0, -1, NULL, 0);
385 break;
386 case SHOW:
387 done = 0;
388 imsg_compose(ibuf, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
389 break;
390 case STATUS:
391 done = 0;
392 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1, NULL, 0);
393 break;
394 case NEXT:
395 imsg_compose(ibuf, IMSG_CTL_NEXT, 0, 0, -1, NULL, 0);
396 if (verbose) {
397 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
398 NULL, 0);
399 done = 0;
401 break;
402 case PREV:
403 imsg_compose(ibuf, IMSG_CTL_PREV, 0, 0, -1, NULL, 0);
404 if (verbose) {
405 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
406 NULL, 0);
407 done = 0;
409 break;
410 case LOAD:
411 done = 0;
412 imsg_compose(ibuf, IMSG_CTL_BEGIN, 0, 0, -1, NULL, 0);
413 break;
414 case JUMP:
415 done = 0;
416 memset(path, 0, sizeof(path));
417 strlcpy(path, res->files[0], sizeof(path));
418 imsg_compose(ibuf, IMSG_CTL_JUMP, 0, 0, -1,
419 path, sizeof(path));
420 break;
421 case MODE:
422 imsg_compose(ibuf, IMSG_CTL_MODE, 0, 0, -1,
423 &res->mode, sizeof(res->mode));
424 break;
425 case MONITOR:
426 done = 0;
427 imsg_compose(ibuf, IMSG_CTL_MONITOR, 0, 0, -1,
428 NULL, 0);
429 break;
430 case RESTART:
431 memset(&res->seek, 0, sizeof(res->seek));
432 /* fallthrough */
433 case SEEK:
434 imsg_compose(ibuf, IMSG_CTL_SEEK, 0, 0, -1, &res->seek,
435 sizeof(res->seek));
436 break;
437 case NONE:
438 /* action not expected */
439 fatalx("invalid action %u", res->action);
440 break;
443 if (ret != 0)
444 goto end;
446 imsg_flush(ibuf);
448 i = 0;
449 while (!done) {
450 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
451 fatalx("imsg_read error");
452 if (n == 0)
453 fatalx("pipe closed");
455 while (!done) {
456 if ((n = imsg_get(ibuf, &imsg)) == -1)
457 fatalx("imsg_get error");
458 if (n == 0)
459 break;
461 if (imsg.hdr.type == IMSG_CTL_ERR) {
462 log_warnx("%s: %s", res->ctl->name,
463 imsg_strerror(&imsg));
464 ret = 1;
465 done = 1;
466 break;
469 datalen = IMSG_DATA_SIZE(imsg);
471 switch (res->action) {
472 case ADD:
473 if (res->files[i] == NULL)
474 fatalx("received more replies than "
475 "files enqueued.");
477 if (imsg.hdr.type == IMSG_CTL_ADD)
478 log_debug("enqueued %s", res->files[i]);
479 else
480 fatalx("invalid message %d",
481 imsg.hdr.type);
482 i++;
483 done = res->files[i] == NULL;
484 break;
485 case SHOW:
486 if (datalen == 0) {
487 done = 1;
488 break;
490 if (datalen != sizeof(ps))
491 fatalx("data size mismatch");
492 memcpy(&ps, imsg.data, sizeof(ps));
493 if (ps.path[sizeof(ps.path) - 1] != '\0')
494 fatalx("received corrupted data");
495 if (res->pretty) {
496 char c = ' ';
497 if (ps.status == STATE_PLAYING)
498 c = '>';
499 printf("%c ", c);
501 puts(ps.path);
502 break;
503 case PLAY:
504 case TOGGLE:
505 case STATUS:
506 case NEXT:
507 case PREV:
508 case JUMP:
509 if (imsg.hdr.type != IMSG_CTL_STATUS)
510 fatalx("invalid message %d",
511 imsg.hdr.type);
513 if (datalen != sizeof(ps))
514 fatalx("data size mismatch");
515 memcpy(&ps, imsg.data, sizeof(ps));
516 if (ps.path[sizeof(ps.path) - 1] != '\0')
517 fatalx("received corrupted data");
519 print_status(&ps, res->status_format);
520 done = 1;
521 break;
522 case LOAD:
523 if (imsg.hdr.type == IMSG_CTL_ADD)
524 break;
525 if (imsg.hdr.type == IMSG_CTL_COMMIT) {
526 done = 1;
527 break;
530 if (imsg.hdr.type != IMSG_CTL_BEGIN)
531 fatalx("invalid message %d",
532 imsg.hdr.type);
534 load_files(res, &ret);
535 break;
536 case MONITOR:
537 if (imsg.hdr.type != IMSG_CTL_MONITOR)
538 fatalx("invalid message %d",
539 imsg.hdr.type);
541 if (datalen != sizeof(type))
542 fatalx("data size mismatch");
544 memcpy(&type, imsg.data, sizeof(type));
545 if (type < 0 || type > IMSG__LAST)
546 fatalx("received corrupted data");
548 if (!res->monitor[type])
549 break;
551 puts(event_name(type));
552 fflush(stdout);
553 break;
554 default:
555 done = 1;
556 break;
559 imsg_free(&imsg);
563 end:
564 return ret;
567 static int
568 ctl_noarg(struct parse_result *res, int argc, char **argv)
570 int ch;
572 while ((ch = getopt(argc, argv, "")) != -1)
573 ctl_usage(res->ctl);
574 argc -= optind;
575 argv += optind;
577 if (argc > 0)
578 ctl_usage(res->ctl);
580 return ctlaction(res);
583 static int
584 ctl_add(struct parse_result *res, int argc, char **argv)
586 int ch;
588 while ((ch = getopt(argc, argv, "")) != -1)
589 ctl_usage(res->ctl);
590 argc -= optind;
591 argv += optind;
593 if (argc == 0)
594 ctl_usage(res->ctl);
595 res->files = argv;
597 return ctlaction(res);
600 static int
601 ctl_show(struct parse_result *res, int argc, char **argv)
603 int ch;
605 while ((ch = getopt(argc, argv, "p")) != -1) {
606 switch (ch) {
607 case 'p':
608 res->pretty = 1;
609 break;
610 default:
611 ctl_usage(res->ctl);
615 return ctlaction(res);
618 static int
619 ctl_load(struct parse_result *res, int argc, char **argv)
621 int ch;
623 while ((ch = getopt(argc, argv, "")) != -1)
624 ctl_usage(res->ctl);
625 argc -= optind;
626 argv += optind;
628 if (argc > 1)
629 ctl_usage(res->ctl);
631 res->fp = stdin;
632 if (argc == 1) {
633 if ((res->fp = fopen(argv[0], "r")) == NULL)
634 fatal("can't open %s", argv[0]);
637 return ctlaction(res);
640 static int
641 ctl_jump(struct parse_result *res, int argc, char **argv)
643 int ch;
645 while ((ch = getopt(argc, argv, "")) != -1)
646 ctl_usage(res->ctl);
647 argc -= optind;
648 argv += optind;
650 if (argc != 1)
651 ctl_usage(res->ctl);
653 res->files = argv;
654 return ctlaction(res);
657 static int
658 parse_mode(struct parse_result *res, const char *v)
660 if (v == NULL)
661 return MODE_TOGGLE;
662 if (!strcmp(v, "on"))
663 return MODE_ON;
664 if (!strcmp(v, "off"))
665 return MODE_OFF;
666 ctl_usage(res->ctl);
669 static int
670 ctl_repeat(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 && argc != 2)
680 ctl_usage(res->ctl);
682 if (!strcmp(argv[0], "one"))
683 res->mode.repeat_one = parse_mode(res, argv[1]);
684 else if (!strcmp(argv[0], "all"))
685 res->mode.repeat_all = parse_mode(res, argv[1]);
686 else
687 ctl_usage(res->ctl);
689 return ctlaction(res);
692 static int
693 ctl_consume(struct parse_result *res, int argc, char **argv)
695 int ch;
697 while ((ch = getopt(argc, argv, "")) != -1)
698 ctl_usage(res->ctl);
699 argc -= optind;
700 argv += optind;
702 if (argc > 1)
703 ctl_usage(res->ctl);
705 res->mode.consume = parse_mode(res, argv[0]);
706 return ctlaction(res);
709 static int
710 ctl_monitor(struct parse_result *res, int argc, char **argv)
712 int ch, n = 0;
713 const char *events;
714 char *dup, *tmp, *tok;
716 while ((ch = getopt(argc, argv, "")) != -1)
717 ctl_usage(res->ctl);
718 argc -= optind;
719 argv += optind;
721 if (argc > 1)
722 ctl_usage(res->ctl);
724 events = "play,pause,stop,next,prev,jump,mode,add,load,seek";
725 if (argc == 1)
726 events = *argv;
728 tmp = dup = xstrdup(events);
729 while ((tok = strsep(&tmp, ",")) != NULL) {
730 if (*tok == '\0')
731 continue;
733 n++;
734 if (!strcmp(tok, "play"))
735 res->monitor[IMSG_CTL_PLAY] = 1;
736 else if (!strcmp(tok, "pause"))
737 res->monitor[IMSG_CTL_PAUSE] = 1;
738 else if (!strcmp(tok, "stop"))
739 res->monitor[IMSG_CTL_STOP] = 1;
740 else if (!strcmp(tok, "next"))
741 res->monitor[IMSG_CTL_NEXT] = 1;
742 else if (!strcmp(tok, "prev"))
743 res->monitor[IMSG_CTL_PREV] = 1;
744 else if (!strcmp(tok, "jump"))
745 res->monitor[IMSG_CTL_JUMP] = 1;
746 else if (!strcmp(tok, "mode"))
747 res->monitor[IMSG_CTL_MODE] = 1;
748 else if (!strcmp(tok, "add"))
749 res->monitor[IMSG_CTL_ADD] = 1;
750 else if (!strcmp(tok, "load"))
751 res->monitor[IMSG_CTL_COMMIT] = 1;
752 else if (!strcmp(tok, "seek"))
753 res->monitor[IMSG_CTL_SEEK] = 1;
754 else {
755 log_warnx("unknown event \"%s\"", tok);
756 n--;
760 free(dup);
761 if (n == 0)
762 ctl_usage(res->ctl);
763 return ctlaction(res);
766 static int
767 ctl_seek(struct parse_result *res, int argc, char **argv)
769 const char *n;
770 char *ep;
771 int hours = 0, minutes = 0, seconds = 0;
772 int sign = 1;
774 if (argc > 0) {
775 /* skip the command name */
776 argc--;
777 argv++;
780 if (argc > 0 && !strcmp(*argv, "--")) {
781 argc--;
782 argv++;
785 if (argc != 1)
786 ctl_usage(res->ctl);
788 n = *argv;
789 if (*n == '-' || *n == '+')
790 res->seek.relative = 1;
791 if (*n == '-') {
792 n++;
793 sign = -1;
796 seconds = strtol(n, &ep, 10);
797 if (n[0] == '\0' ||
798 (*ep != '\0' && *ep != ':' && *ep != '%') ||
799 (*ep == '%' && ep[1] != '\0'))
800 fatalx("invalid offset: %s", argv[0]);
801 if (*ep == '\0' || *ep == '%') {
802 res->seek.percent = *ep == '%';
803 goto done;
806 n = ++ep;
807 minutes = seconds;
808 seconds = strtol(n, &ep, 10);
809 if (n[0] == '\0' || (*ep != '\0' && *ep != ':'))
810 fatalx("invalid offset: %s", argv[0]);
811 if (*ep == '\0')
812 goto done;
814 n = ++ep;
815 hours = minutes;
816 minutes = seconds;
817 seconds = strtol(n, &ep, 10);
818 if (n[0] == '\0' || *ep != '\0')
819 fatalx("invalid offset: %s", argv[0]);
821 done:
822 res->seek.offset = sign * (hours * 3600 + minutes * 60 + seconds);
823 return ctlaction(res);
826 static int
827 ctl_status(struct parse_result *res, int argc, char **argv)
829 int ch;
831 while ((ch = getopt(argc, argv, "f:")) != -1) {
832 switch (ch) {
833 case 'f':
834 res->status_format = optarg;
835 break;
836 default:
837 ctl_usage(res->ctl);
840 argc -= optind;
841 argv += optind;
843 if (argc > 0)
844 ctl_usage(res->ctl);
846 return ctlaction(res);
849 static int
850 ctl_get_lock(const char *lockfile)
852 int lockfd;
854 if ((lockfd = open(lockfile, O_WRONLY|O_CREAT, 0600)) == -1) {
855 log_debug("open failed: %s", strerror(errno));
856 return -1;
859 if (flock(lockfd, LOCK_EX|LOCK_NB) == -1) {
860 log_debug("flock failed: %s", strerror(errno));
861 if (errno != EAGAIN)
862 return -1;
863 while (flock(lockfd, LOCK_EX) == -1 && errno == EINTR)
864 /* nop */;
865 close(lockfd);
866 return -2;
868 log_debug("flock succeeded");
870 return lockfd;
873 static int
874 ctl_connect(void)
876 struct timespec ts = { 0, 50000000 }; /* 0.05 seconds */
877 struct sockaddr_un sa;
878 size_t size;
879 int fd, lockfd = -1, locked = 0, spawned = 0;
880 int attempt = 0;
881 char *lockfile = NULL;
883 memset(&sa, 0, sizeof(sa));
884 sa.sun_family = AF_UNIX;
885 size = strlcpy(sa.sun_path, csock, sizeof(sa.sun_path));
886 if (size >= sizeof(sa.sun_path)) {
887 errno = ENAMETOOLONG;
888 return -1;
891 retry:
892 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
893 return -1;
895 if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
896 log_debug("connection failed: %s", strerror(errno));
897 if (errno != ECONNREFUSED && errno != ENOENT)
898 goto failed;
899 if (attempt++ == 100)
900 goto failed;
901 close(fd);
903 if (!locked) {
904 xasprintf(&lockfile, "%s.lock", csock);
905 if ((lockfd = ctl_get_lock(lockfile)) < 0) {
906 log_debug("didn't get the lock (%d)", lockfd);
908 free(lockfile);
909 lockfile = NULL;
911 if (lockfd == -1)
912 goto retry;
915 /*
916 * Always retry at least once, even if we got
917 * the lock, because another client could have
918 * taken the lock, started the server and released
919 * the lock between our connect() and flock()
920 */
921 locked = 1;
922 goto retry;
925 if (!spawned) {
926 log_debug("spawning the daemon");
927 spawn_daemon();
928 spawned = 1;
931 nanosleep(&ts, NULL);
932 goto retry;
935 if (locked && lockfd >= 0) {
936 unlink(lockfile);
937 free(lockfile);
938 close(lockfd);
940 return fd;
942 failed:
943 if (locked) {
944 free(lockfile);
945 close(lockfd);
947 close(fd);
948 return -1;
951 __dead void
952 ctl(int argc, char **argv)
954 struct parse_result res;
955 const char *fmt;
956 int ctl_sock;
958 memset(&res, 0, sizeof(res));
959 if ((fmt = getenv("AMUSED_STATUS_FORMAT")) == NULL)
960 fmt = "status,time,repeat";
961 res.status_format = fmt;
963 res.mode.consume = MODE_UNDEF;
964 res.mode.repeat_all = MODE_UNDEF;
965 res.mode.repeat_one = MODE_UNDEF;
967 log_init(1, LOG_DAEMON);
968 log_setverbose(verbose);
970 if (getcwd(cwd, sizeof(cwd)) == NULL)
971 fatal("getcwd");
973 if ((ctl_sock = ctl_connect()) == -1)
974 fatal("can't connect");
976 if (ctl_sock == -1)
977 fatalx("failed to connect to the daemon");
979 ibuf = xmalloc(sizeof(*ibuf));
980 imsg_init(ibuf, ctl_sock);
982 optreset = 1;
983 optind = 1;
985 /* we'll drop rpath too later in ctlaction */
986 if (pledge("stdio rpath", NULL) == -1)
987 fatal("pledge");
989 exit(parse(&res, argc, argv));