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_monitor(struct parse_result *, int, char **);
48 static int ctl_seek(struct parse_result *, int, char **);
49 static int ctl_status(struct parse_result *, int, char **);
51 struct ctl_command ctl_commands[] = {
52 { "add", ADD, ctl_add, "files...", 0 },
53 { "flush", FLUSH, ctl_noarg, "", 0 },
54 { "jump", JUMP, ctl_jump, "pattern", 0 },
55 { "load", LOAD, ctl_load, "[file]", 1 },
56 { "monitor", MONITOR, ctl_monitor, "[events]", 0 },
57 { "next", NEXT, ctl_noarg, "", 0 },
58 { "pause", PAUSE, ctl_noarg, "", 0 },
59 { "play", PLAY, ctl_noarg, "", 0 },
60 { "prev", PREV, ctl_noarg, "", 0 },
61 { "repeat", REPEAT, ctl_repeat, "one|all on|off", 0 },
62 { "restart", RESTART, ctl_noarg, "", 0 },
63 { "seek", SEEK, ctl_seek, "[+-]time[%]", 0 },
64 { "show", SHOW, ctl_show, "[-p]", 0 },
65 { "status", STATUS, ctl_status, "[-f fmt]", 0 },
66 { "stop", STOP, ctl_noarg, "", 0 },
67 { "toggle", TOGGLE, ctl_noarg, "", 0 },
68 { NULL, 0, NULL, NULL, 0 },
69 };
71 __dead void
72 usage(void)
73 {
74 fprintf(stderr, "usage: %s [-dv] [-s socket]\n", getprogname());
75 exit(1);
76 }
78 static __dead void
79 ctl_usage(struct ctl_command *ctl)
80 {
81 fprintf(stderr, "usage: %s [-v] [-s socket] %s %s\n", getprogname(),
82 ctl->name, ctl->usage);
83 exit(1);
84 }
86 /* based on canonpath from kern_pledge.c */
87 static int
88 canonpath(const char *input, char *buf, size_t bufsize)
89 {
90 const char *p;
91 char *q, path[PATH_MAX];
93 if (input[0] != '/') {
94 if (snprintf(path, sizeof(path), "%s/%s", cwd, input)
95 >= sizeof(path)) {
96 errno = ENAMETOOLONG;
97 return -1;
98 }
99 input = path;
102 p = input;
103 q = buf;
104 while (*p && (q - buf < bufsize)) {
105 if (p[0] == '/' && (p[1] == '/' || p[1] == '\0')) {
106 p += 1;
108 } else if (p[0] == '/' && p[1] == '.' &&
109 (p[2] == '/' || p[2] == '\0')) {
110 p += 2;
112 } else if (p[0] == '/' && p[1] == '.' && p[2] == '.' &&
113 (p[3] == '/' || p[3] == '\0')) {
114 p += 3;
115 if (q != buf) /* "/../" at start of buf */
116 while (*--q != '/')
117 continue;
119 } else {
120 *q++ = *p++;
123 if ((*p == '\0') && (q - buf < bufsize)) {
124 *q = 0;
125 return 0;
126 } else {
127 errno = ENAMETOOLONG;
128 return -1;
132 static int
133 parse(struct parse_result *res, int argc, char **argv)
135 struct ctl_command *ctl = NULL;
136 const char *argv0;
137 int i, status;
139 if ((argv0 = argv[0]) == NULL)
140 argv0 = "status";
142 for (i = 0; ctl_commands[i].name != NULL; ++i) {
143 if (strncmp(ctl_commands[i].name, argv0, strlen(argv0))
144 == 0) {
145 if (ctl != NULL) {
146 fprintf(stderr,
147 "ambiguous argument: %s\n", argv0);
148 usage();
150 ctl = &ctl_commands[i];
154 if (ctl == NULL) {
155 fprintf(stderr, "unknown argument: %s\n", argv[0]);
156 usage();
159 res->action = ctl->action;
160 res->ctl = ctl;
162 if (!ctl->has_pledge) {
163 /* pledge(2) default if command doesn't have its own */
164 if (pledge("stdio", NULL) == -1)
165 fatal("pledge");
168 status = ctl->main(res, argc, argv);
169 close(ibuf->fd);
170 free(ibuf);
171 return status;
174 static int
175 load_files(struct parse_result *res, int *ret)
177 FILE *f;
178 const char *file;
179 char *line = NULL;
180 char path[PATH_MAX];
181 size_t linesize = 0, i = 0;
182 ssize_t linelen, curr = -1;
184 if (res->file == NULL)
185 f = stdin;
186 else if ((f = fopen(res->file, "r")) == NULL) {
187 log_warn("can't open %s", res->file);
188 *ret = 1;
189 return 1;
192 while ((linelen = getline(&line, &linesize, f)) != -1) {
193 if (linelen == 0)
194 continue;
195 line[linelen-1] = '\0';
196 file = line;
197 if (!strncmp(file, "> ", 2)) {
198 file += 2;
199 curr = i;
200 } else if (!strncmp(file, " ", 2))
201 file += 2;
203 memset(path, 0, sizeof(path));
204 if (canonpath(file, path, sizeof(path)) == -1) {
205 log_warn("canonpath %s", file);
206 continue;
209 i++;
210 imsg_compose(ibuf, IMSG_CTL_ADD, 0, 0, -1,
211 path, sizeof(path));
214 free(line);
215 if (ferror(f))
216 fatal("getline");
217 fclose(f);
219 if (i == 0) {
220 *ret = 1;
221 return 1;
224 imsg_compose(ibuf, IMSG_CTL_COMMIT, 0, 0, -1,
225 &curr, sizeof(curr));
226 imsg_flush(ibuf);
227 return 0;
230 static const char *
231 imsg_strerror(struct imsg *imsg)
233 size_t datalen;
234 const char *msg;
236 datalen = IMSG_DATA_SIZE(*imsg);
237 msg = imsg->data;
238 if (datalen == 0 || msg[datalen-1] != '\0')
239 fatalx("malformed error message");
241 return msg;
244 static const char *
245 imsg_name(int type)
247 switch (type) {
248 case IMSG_CTL_PLAY:
249 return "play";
250 case IMSG_CTL_TOGGLE_PLAY:
251 return "toggle";
252 case IMSG_CTL_PAUSE:
253 return "pause";
254 case IMSG_CTL_STOP:
255 return "stop";
256 case IMSG_CTL_FLUSH:
257 return "flush";
258 case IMSG_CTL_NEXT:
259 return "next";
260 case IMSG_CTL_PREV:
261 return "prev";
262 case IMSG_CTL_JUMP:
263 return "jump";
264 case IMSG_CTL_REPEAT:
265 return "repeat";
266 case IMSG_CTL_ADD:
267 return "add";
268 case IMSG_CTL_COMMIT:
269 return "load";
270 default:
271 return "unknown";
275 static void
276 print_time(const char *label, int64_t seconds, const char *suffx)
278 int hours, minutes;
280 if (seconds < 0)
281 seconds = 0;
283 hours = seconds / 3600;
284 seconds -= hours * 3600;
286 minutes = seconds / 60;
287 seconds -= minutes * 60;
289 printf("%s", label);
290 if (hours != 0)
291 printf("%02d:", hours);
292 printf("%02d:%02lld%s", minutes, (long long)seconds, suffx);
295 static void
296 print_status(struct player_status *ps, const char *spec)
298 const char *status;
299 double percent;
300 char *dup, *tmp, *tok;
302 if (ps->status == STATE_STOPPED)
303 status = "stopped";
304 else if (ps->status == STATE_PLAYING)
305 status = "playing";
306 else if (ps->status == STATE_PAUSED)
307 status = "paused";
308 else
309 status = "unknown";
311 percent = 100.0 * (double)ps->position / (double)ps->duration;
313 tmp = dup = xstrdup(spec);
314 while ((tok = strsep(&tmp, ",")) != NULL) {
315 if (*tok == '\0')
316 continue;
318 if (!strcmp(tok, "path")) {
319 puts(ps->path);
320 } else if (!strcmp(tok, "repeat:oneline")) {
321 printf("repeat one:%s ",
322 ps->rp.repeat_one ? "on" : "off");
323 printf("all:%s\n", ps->rp.repeat_all ? "on" : "off");
324 } else if (!strcmp(tok, "repeat")) {
325 printf("repeat one %s\n",
326 ps->rp.repeat_one ? "on" : "off");
327 printf("repeat all %s\n",
328 ps->rp.repeat_all ? "on" : "off");
329 } else if (!strcmp(tok, "status")) {
330 printf("%s %s\n", status, ps->path);
331 } else if (!strcmp(tok, "time:oneline")) {
332 print_time("time ", ps->position, " / ");
333 print_time("", ps->duration, "\n");
334 } else if (!strcmp(tok, "time:percentage")) {
335 printf("position %.2f%%\n", percent);
336 } else if (!strcmp(tok, "time:raw")) {
337 printf("position %lld\n", (long long)ps->position);
338 printf("duration %lld\n", (long long)ps->duration);
339 } else if (!strcmp(tok, "time")) {
340 print_time("position ", ps->position, "\n");
341 print_time("duration ", ps->duration, "\n");
345 free(dup);
348 static int
349 ctlaction(struct parse_result *res)
351 char path[PATH_MAX];
352 struct imsg imsg;
353 struct player_status ps;
354 size_t datalen;
355 ssize_t n;
356 int i, type, ret = 0, done = 1;
358 switch (res->action) {
359 case PLAY:
360 imsg_compose(ibuf, IMSG_CTL_PLAY, 0, 0, -1, NULL, 0);
361 if (verbose) {
362 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
363 NULL, 0);
364 done = 0;
366 break;
367 case PAUSE:
368 imsg_compose(ibuf, IMSG_CTL_PAUSE, 0, 0, -1, NULL, 0);
369 break;
370 case TOGGLE:
371 imsg_compose(ibuf, IMSG_CTL_TOGGLE_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 STOP:
379 imsg_compose(ibuf, IMSG_CTL_STOP, 0, 0, -1, NULL, 0);
380 break;
381 case ADD:
382 done = 0;
383 for (i = 0; res->files[i] != NULL; ++i) {
384 memset(path, 0, sizeof(path));
385 if (canonpath(res->files[i], path, sizeof(path))
386 == -1) {
387 log_warn("canonpath %s", res->files[i]);
388 continue;
391 imsg_compose(ibuf, IMSG_CTL_ADD, 0, 0, -1,
392 path, sizeof(path));
394 ret = i == 0;
395 break;
396 case FLUSH:
397 imsg_compose(ibuf, IMSG_CTL_FLUSH, 0, 0, -1, NULL, 0);
398 break;
399 case SHOW:
400 done = 0;
401 imsg_compose(ibuf, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
402 break;
403 case STATUS:
404 done = 0;
405 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1, NULL, 0);
406 break;
407 case NEXT:
408 imsg_compose(ibuf, IMSG_CTL_NEXT, 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 PREV:
416 imsg_compose(ibuf, IMSG_CTL_PREV, 0, 0, -1, NULL, 0);
417 if (verbose) {
418 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
419 NULL, 0);
420 done = 0;
422 break;
423 case LOAD:
424 done = 0;
425 imsg_compose(ibuf, IMSG_CTL_BEGIN, 0, 0, -1, NULL, 0);
426 break;
427 case JUMP:
428 done = 0;
429 memset(path, 0, sizeof(path));
430 strlcpy(path, res->file, sizeof(path));
431 imsg_compose(ibuf, IMSG_CTL_JUMP, 0, 0, -1,
432 path, sizeof(path));
433 break;
434 case REPEAT:
435 imsg_compose(ibuf, IMSG_CTL_REPEAT, 0, 0, -1,
436 &res->rep, sizeof(res->rep));
437 break;
438 case MONITOR:
439 done = 0;
440 imsg_compose(ibuf, IMSG_CTL_MONITOR, 0, 0, -1,
441 NULL, 0);
442 break;
443 case RESTART:
444 memset(&res->seek, 0, sizeof(res->seek));
445 /* fallthrough */
446 case SEEK:
447 imsg_compose(ibuf, IMSG_CTL_SEEK, 0, 0, -1, &res->seek,
448 sizeof(res->seek));
449 break;
450 case NONE:
451 /* action not expected */
452 fatalx("invalid action %u", res->action);
453 break;
456 if (ret != 0)
457 goto end;
459 imsg_flush(ibuf);
461 i = 0;
462 while (!done) {
463 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
464 fatalx("imsg_read error");
465 if (n == 0)
466 fatalx("pipe closed");
468 while (!done) {
469 if ((n = imsg_get(ibuf, &imsg)) == -1)
470 fatalx("imsg_get error");
471 if (n == 0)
472 break;
474 if (imsg.hdr.type == IMSG_CTL_ERR) {
475 log_warnx("%s: %s", res->ctl->name,
476 imsg_strerror(&imsg));
477 ret = 1;
478 done = 1;
479 break;
482 datalen = IMSG_DATA_SIZE(imsg);
484 switch (res->action) {
485 case ADD:
486 if (res->files[i] == NULL)
487 fatalx("received more replies than "
488 "files enqueued.");
490 if (imsg.hdr.type == IMSG_CTL_ADD)
491 log_debug("enqueued %s", res->files[i]);
492 else
493 fatalx("invalid message %d",
494 imsg.hdr.type);
495 i++;
496 done = res->files[i] == NULL;
497 break;
498 case SHOW:
499 if (datalen == 0) {
500 done = 1;
501 break;
503 if (datalen != sizeof(ps))
504 fatalx("data size mismatch");
505 memcpy(&ps, imsg.data, sizeof(ps));
506 if (ps.path[sizeof(ps.path) - 1] != '\0')
507 fatalx("received corrupted data");
508 if (res->pretty) {
509 char c = ' ';
510 if (ps.status == STATE_PLAYING)
511 c = '>';
512 printf("%c ", c);
514 puts(ps.path);
515 break;
516 case PLAY:
517 case TOGGLE:
518 case RESTART:
519 case STATUS:
520 case NEXT:
521 case PREV:
522 case JUMP:
523 if (imsg.hdr.type != IMSG_CTL_STATUS)
524 fatalx("invalid message %d",
525 imsg.hdr.type);
527 if (datalen != sizeof(ps))
528 fatalx("data size mismatch");
529 memcpy(&ps, imsg.data, sizeof(ps));
530 if (ps.path[sizeof(ps.path) - 1] != '\0')
531 fatalx("received corrupted data");
533 print_status(&ps, res->status_format);
534 done = 1;
535 break;
536 case LOAD:
537 if (imsg.hdr.type == IMSG_CTL_ADD)
538 break;
539 if (imsg.hdr.type == IMSG_CTL_COMMIT) {
540 done = 1;
541 break;
544 if (imsg.hdr.type != IMSG_CTL_BEGIN)
545 fatalx("invalid message %d",
546 imsg.hdr.type);
548 load_files(res, &ret);
549 break;
550 case MONITOR:
551 if (imsg.hdr.type != IMSG_CTL_MONITOR)
552 fatalx("invalid message %d",
553 imsg.hdr.type);
555 if (datalen != sizeof(type))
556 fatalx("data size mismatch");
558 memcpy(&type, imsg.data, sizeof(type));
559 if (type < 0 || type > IMSG__LAST)
560 fatalx("received corrupted data");
562 if (!res->monitor[type])
563 break;
565 puts(imsg_name(type));
566 fflush(stdout);
567 break;
568 default:
569 done = 1;
570 break;
573 imsg_free(&imsg);
577 end:
578 return ret;
581 static int
582 ctl_noarg(struct parse_result *res, int argc, char **argv)
584 int ch;
586 while ((ch = getopt(argc, argv, "")) != -1)
587 ctl_usage(res->ctl);
588 argc -= optind;
589 argv += optind;
591 if (argc > 0)
592 ctl_usage(res->ctl);
594 return ctlaction(res);
597 static int
598 ctl_add(struct parse_result *res, int argc, char **argv)
600 int ch;
602 while ((ch = getopt(argc, argv, "")) != -1)
603 ctl_usage(res->ctl);
604 argc -= optind;
605 argv += optind;
607 if (argc == 0)
608 ctl_usage(res->ctl);
609 res->files = argv;
611 return ctlaction(res);
614 static int
615 ctl_show(struct parse_result *res, int argc, char **argv)
617 int ch;
619 while ((ch = getopt(argc, argv, "p")) != -1) {
620 switch (ch) {
621 case 'p':
622 res->pretty = 1;
623 break;
624 default:
625 ctl_usage(res->ctl);
629 return ctlaction(res);
632 static int
633 ctl_load(struct parse_result *res, int argc, char **argv)
635 int ch;
637 while ((ch = getopt(argc, argv, "")) != -1)
638 ctl_usage(res->ctl);
639 argc -= optind;
640 argv += optind;
642 if (argc == 0)
643 res->file = NULL;
644 else if (argc == 1)
645 res->file = argv[0];
646 else
647 ctl_usage(res->ctl);
649 if (pledge("stdio rpath", NULL) == -1)
650 fatal("pledge");
652 return ctlaction(res);
655 static int
656 ctl_jump(struct parse_result *res, int argc, char **argv)
658 int ch;
660 while ((ch = getopt(argc, argv, "")) != -1)
661 ctl_usage(res->ctl);
662 argc -= optind;
663 argv += optind;
665 if (argc != 1)
666 ctl_usage(res->ctl);
668 res->file = argv[0];
669 return ctlaction(res);
672 static int
673 ctl_repeat(struct parse_result *res, int argc, char **argv)
675 int ch, b;
677 while ((ch = getopt(argc, argv, "")) != -1)
678 ctl_usage(res->ctl);
679 argc -= optind;
680 argv += optind;
682 if (argc != 2)
683 ctl_usage(res->ctl);
685 if (!strcmp(argv[1], "on"))
686 b = 1;
687 else if (!strcmp(argv[1], "off"))
688 b = 0;
689 else
690 ctl_usage(res->ctl);
692 res->rep.repeat_one = -1;
693 res->rep.repeat_all = -1;
694 if (!strcmp(argv[0], "one"))
695 res->rep.repeat_one = b;
696 else if (!strcmp(argv[0], "all"))
697 res->rep.repeat_all = b;
698 else
699 ctl_usage(res->ctl);
701 return ctlaction(res);
704 static int
705 ctl_monitor(struct parse_result *res, int argc, char **argv)
707 int ch;
708 const char *events;
709 char *dup, *tmp, *tok;
711 while ((ch = getopt(argc, argv, "")) != -1)
712 ctl_usage(res->ctl);
713 argc -= optind;
714 argv += optind;
716 if (argc > 1)
717 ctl_usage(res->ctl);
719 if (argc == 1)
720 events = *argv;
721 else
722 events = "play,toggle,pause,stop,restart,flush,next,prev,"
723 "jump,repeat,add,load";
725 tmp = dup = xstrdup(events);
726 while ((tok = strsep(&tmp, ",")) != NULL) {
727 if (*tok == '\0')
728 continue;
730 if (!strcmp(tok, "play"))
731 res->monitor[IMSG_CTL_PLAY] = 1;
732 else if (!strcmp(tok, "toggle"))
733 res->monitor[IMSG_CTL_TOGGLE_PLAY] = 1;
734 else if (!strcmp(tok, "pause"))
735 res->monitor[IMSG_CTL_PAUSE] = 1;
736 else if (!strcmp(tok, "stop"))
737 res->monitor[IMSG_CTL_STOP] = 1;
738 else if (!strcmp(tok, "restart")) /* compat */
739 res->monitor[IMSG_CTL_SEEK] = 1;
740 else if (!strcmp(tok, "flush"))
741 res->monitor[IMSG_CTL_FLUSH] = 1;
742 else if (!strcmp(tok, "next"))
743 res->monitor[IMSG_CTL_NEXT] = 1;
744 else if (!strcmp(tok, "prev"))
745 res->monitor[IMSG_CTL_PREV] = 1;
746 else if (!strcmp(tok, "jump"))
747 res->monitor[IMSG_CTL_JUMP] = 1;
748 else if (!strcmp(tok, "repeat"))
749 res->monitor[IMSG_CTL_REPEAT] = 1;
750 else if (!strcmp(tok, "add"))
751 res->monitor[IMSG_CTL_ADD] = 1;
752 else if (!strcmp(tok, "load"))
753 res->monitor[IMSG_CTL_COMMIT] = 1;
754 else if (!strcmp(tok, "seek"))
755 res->monitor[IMSG_CTL_SEEK] = 1;
756 else
757 fatalx("unknown event \"%s\"", tok);
760 free(dup);
761 return ctlaction(res);
764 static int
765 ctl_seek(struct parse_result *res, int argc, char **argv)
767 const char *n;
768 char *ep;
769 int hours = 0, minutes = 0, seconds = 0;
770 int sign = 1;
772 if (argc > 0) {
773 /* skip the command name */
774 argc--;
775 argv++;
778 if (argc > 0 && !strcmp(*argv, "--")) {
779 argc--;
780 argv++;
783 if (argc != 1)
784 ctl_usage(res->ctl);
786 n = *argv;
787 if (*n == '-' || *n == '+')
788 res->seek.relative = 1;
789 if (*n == '-') {
790 n++;
791 sign = -1;
794 seconds = strtol(n, &ep, 10);
795 if (n[0] == '\0' ||
796 (*ep != '\0' && *ep != ':' && *ep != '%') ||
797 (*ep == '%' && ep[1] != '\0'))
798 fatalx("invalid offset: %s", argv[0]);
799 if (*ep == '\0' || *ep == '%') {
800 res->seek.percent = *ep == '%';
801 goto done;
804 n = ++ep;
805 minutes = seconds;
806 seconds = strtol(n, &ep, 10);
807 if (n[0] == '\0' || (*ep != '\0' && *ep != ':'))
808 fatalx("invalid offset: %s", argv[0]);
809 if (*ep == '\0')
810 goto done;
812 n = ++ep;
813 hours = minutes;
814 minutes = seconds;
815 seconds = strtol(n, &ep, 10);
816 if (n[0] == '\0' || *ep != '\0')
817 fatalx("invalid offset: %s", argv[0]);
819 done:
820 res->seek.offset = sign * (hours * 3600 + minutes * 60 + seconds);
821 return ctlaction(res);
824 static int
825 ctl_status(struct parse_result *res, int argc, char **argv)
827 int ch;
829 while ((ch = getopt(argc, argv, "f:")) != -1) {
830 switch (ch) {
831 case 'f':
832 res->status_format = optarg;
833 break;
834 default:
835 ctl_usage(res->ctl);
838 argc -= optind;
839 argv += optind;
841 if (argc > 0)
842 ctl_usage(res->ctl);
844 return ctlaction(res);
847 static int
848 ctl_get_lock(const char *lockfile)
850 int lockfd;
852 if ((lockfd = open(lockfile, O_WRONLY|O_CREAT, 0600)) == -1) {
853 log_debug("open failed: %s", strerror(errno));
854 return -1;
857 if (flock(lockfd, LOCK_EX|LOCK_NB) == -1) {
858 log_debug("flock failed: %s", strerror(errno));
859 if (errno != EAGAIN)
860 return -1;
861 while (flock(lockfd, LOCK_EX) == -1 && errno == EINTR)
862 /* nop */;
863 close(lockfd);
864 return -2;
866 log_debug("flock succeeded");
868 return lockfd;
871 static int
872 ctl_connect(void)
874 struct timespec ts = { 0, 50000000 }; /* 0.05 seconds */
875 struct sockaddr_un sa;
876 size_t size;
877 int fd, lockfd = -1, locked = 0, spawned = 0;
878 int attempt = 0;
879 char *lockfile = NULL;
881 memset(&sa, 0, sizeof(sa));
882 sa.sun_family = AF_UNIX;
883 size = strlcpy(sa.sun_path, csock, sizeof(sa.sun_path));
884 if (size >= sizeof(sa.sun_path)) {
885 errno = ENAMETOOLONG;
886 return -1;
889 retry:
890 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
891 return -1;
893 if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
894 log_debug("connection failed: %s", strerror(errno));
895 if (errno != ECONNREFUSED && errno != ENOENT)
896 goto failed;
897 if (attempt++ == 100)
898 goto failed;
899 close(fd);
901 if (!locked) {
902 xasprintf(&lockfile, "%s.lock", csock);
903 if ((lockfd = ctl_get_lock(lockfile)) < 0) {
904 log_debug("didn't get the lock (%d)", lockfd);
906 free(lockfile);
907 lockfile = NULL;
909 if (lockfd == -1)
910 goto retry;
913 /*
914 * Always retry at least once, even if we got
915 * the lock, because another client could have
916 * taken the lock, started the server and released
917 * the lock between our connect() and flock()
918 */
919 locked = 1;
920 goto retry;
923 if (!spawned) {
924 log_debug("spawning the daemon");
925 spawn_daemon();
926 spawned = 1;
929 nanosleep(&ts, NULL);
930 goto retry;
933 if (locked && lockfd >= 0) {
934 unlink(lockfile);
935 free(lockfile);
936 close(lockfd);
938 return fd;
940 failed:
941 if (locked) {
942 free(lockfile);
943 close(lockfd);
945 close(fd);
946 return -1;
949 __dead void
950 ctl(int argc, char **argv)
952 struct parse_result res;
953 const char *fmt;
954 int ctl_sock;
956 memset(&res, 0, sizeof(res));
957 if ((fmt = getenv("AMUSED_STATUS_FORMAT")) == NULL)
958 fmt = "status,time,repeat";
959 res.status_format = fmt;
961 log_init(1, LOG_DAEMON);
962 log_setverbose(verbose);
964 if (getcwd(cwd, sizeof(cwd)) == NULL)
965 fatal("getcwd");
967 if ((ctl_sock = ctl_connect()) == -1)
968 fatal("can't connect");
970 if (ctl_sock == -1)
971 fatalx("failed to connect to the daemon");
973 ibuf = xmalloc(sizeof(*ibuf));
974 imsg_init(ibuf, ctl_sock);
976 optreset = 1;
977 optind = 1;
979 exit(parse(&res, argc, argv));