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(int argc, char **argv)
135 struct ctl_command *ctl = NULL;
136 struct parse_result res;
137 const char *argv0;
138 int i, status;
140 memset(&res, 0, sizeof(res));
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 if (!ctl->has_pledge) {
166 /* pledge(2) default if command doesn't have its own */
167 if (pledge("stdio", NULL) == -1)
168 fatal("pledge");
171 status = ctl->main(&res, argc, argv);
172 close(ibuf->fd);
173 free(ibuf);
174 return status;
177 static int
178 load_files(struct parse_result *res, int *ret)
180 FILE *f;
181 const char *file;
182 char *line = NULL;
183 char path[PATH_MAX];
184 size_t linesize = 0, i = 0;
185 ssize_t linelen, curr = -1;
187 if (res->file == NULL)
188 f = stdin;
189 else if ((f = fopen(res->file, "r")) == NULL) {
190 log_warn("can't open %s", res->file);
191 *ret = 1;
192 return 1;
195 while ((linelen = getline(&line, &linesize, f)) != -1) {
196 if (linelen == 0)
197 continue;
198 line[linelen-1] = '\0';
199 file = line;
200 if (!strncmp(file, "> ", 2)) {
201 file += 2;
202 curr = i;
203 } else if (!strncmp(file, " ", 2))
204 file += 2;
206 memset(path, 0, sizeof(path));
207 if (canonpath(file, path, sizeof(path)) == -1) {
208 log_warn("canonpath %s", file);
209 continue;
212 i++;
213 imsg_compose(ibuf, IMSG_CTL_ADD, 0, 0, -1,
214 path, sizeof(path));
217 free(line);
218 if (ferror(f))
219 fatal("getline");
220 fclose(f);
222 if (i == 0) {
223 *ret = 1;
224 return 1;
227 imsg_compose(ibuf, IMSG_CTL_COMMIT, 0, 0, -1,
228 &curr, sizeof(curr));
229 imsg_flush(ibuf);
230 return 0;
233 static const char *
234 imsg_strerror(struct imsg *imsg)
236 size_t datalen;
237 const char *msg;
239 datalen = IMSG_DATA_SIZE(*imsg);
240 msg = imsg->data;
241 if (datalen == 0 || msg[datalen-1] != '\0')
242 fatalx("malformed error message");
244 return msg;
247 static const char *
248 imsg_name(int type)
250 switch (type) {
251 case IMSG_CTL_PLAY:
252 return "play";
253 case IMSG_CTL_TOGGLE_PLAY:
254 return "toggle";
255 case IMSG_CTL_PAUSE:
256 return "pause";
257 case IMSG_CTL_STOP:
258 return "stop";
259 case IMSG_CTL_FLUSH:
260 return "flush";
261 case IMSG_CTL_NEXT:
262 return "next";
263 case IMSG_CTL_PREV:
264 return "prev";
265 case IMSG_CTL_JUMP:
266 return "jump";
267 case IMSG_CTL_REPEAT:
268 return "repeat";
269 case IMSG_CTL_ADD:
270 return "add";
271 case IMSG_CTL_COMMIT:
272 return "load";
273 default:
274 return "unknown";
278 static void
279 print_time(const char *label, int64_t seconds, const char *suffx)
281 int hours, minutes;
283 if (seconds < 0)
284 seconds = 0;
286 hours = seconds / 3600;
287 seconds -= hours * 3600;
289 minutes = seconds / 60;
290 seconds -= minutes * 60;
292 printf("%s", label);
293 if (hours != 0)
294 printf("%02d:", hours);
295 printf("%02d:%02lld%s", minutes, (long long)seconds, suffx);
298 static void
299 print_status(struct player_status *ps, const char *spec)
301 const char *status;
302 double percent;
303 char *dup, *tmp, *tok;
305 if (ps->status == STATE_STOPPED)
306 status = "stopped";
307 else if (ps->status == STATE_PLAYING)
308 status = "playing";
309 else if (ps->status == STATE_PAUSED)
310 status = "paused";
311 else
312 status = "unknown";
314 percent = 100.0 * (double)ps->position / (double)ps->duration;
316 tmp = dup = xstrdup(spec);
317 while ((tok = strsep(&tmp, ",")) != NULL) {
318 if (*tok == '\0')
319 continue;
321 if (!strcmp(tok, "path")) {
322 puts(ps->path);
323 } else if (!strcmp(tok, "repeat:oneline")) {
324 printf("repeat one:%s ",
325 ps->rp.repeat_one ? "on" : "off");
326 printf("all:%s\n", ps->rp.repeat_all ? "on" : "off");
327 } else if (!strcmp(tok, "repeat")) {
328 printf("repeat one %s\n",
329 ps->rp.repeat_one ? "on" : "off");
330 printf("repeat all %s\n",
331 ps->rp.repeat_all ? "on" : "off");
332 } else if (!strcmp(tok, "status")) {
333 printf("%s %s\n", status, ps->path);
334 } else if (!strcmp(tok, "time:oneline")) {
335 print_time("time ", ps->position, " / ");
336 print_time("", ps->duration, "\n");
337 } else if (!strcmp(tok, "time:percentage")) {
338 printf("position %.2f%%\n", percent);
339 } else if (!strcmp(tok, "time:raw")) {
340 printf("position %lld\n", (long long)ps->position);
341 printf("duration %lld\n", (long long)ps->duration);
342 } else if (!strcmp(tok, "time")) {
343 print_time("position ", ps->position, "\n");
344 print_time("duration ", ps->duration, "\n");
348 free(dup);
351 static int
352 ctlaction(struct parse_result *res)
354 char path[PATH_MAX];
355 struct imsg imsg;
356 struct player_status ps;
357 size_t datalen;
358 ssize_t n;
359 int i, type, ret = 0, done = 1;
361 switch (res->action) {
362 case PLAY:
363 imsg_compose(ibuf, IMSG_CTL_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 PAUSE:
371 imsg_compose(ibuf, IMSG_CTL_PAUSE, 0, 0, -1, NULL, 0);
372 break;
373 case TOGGLE:
374 imsg_compose(ibuf, IMSG_CTL_TOGGLE_PLAY, 0, 0, -1, NULL, 0);
375 if (verbose) {
376 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
377 NULL, 0);
378 done = 0;
380 break;
381 case STOP:
382 imsg_compose(ibuf, IMSG_CTL_STOP, 0, 0, -1, NULL, 0);
383 break;
384 case ADD:
385 done = 0;
386 for (i = 0; res->files[i] != NULL; ++i) {
387 memset(path, 0, sizeof(path));
388 if (canonpath(res->files[i], path, sizeof(path))
389 == -1) {
390 log_warn("canonpath %s", res->files[i]);
391 continue;
394 imsg_compose(ibuf, IMSG_CTL_ADD, 0, 0, -1,
395 path, sizeof(path));
397 ret = i == 0;
398 break;
399 case FLUSH:
400 imsg_compose(ibuf, IMSG_CTL_FLUSH, 0, 0, -1, NULL, 0);
401 break;
402 case SHOW:
403 done = 0;
404 imsg_compose(ibuf, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
405 break;
406 case STATUS:
407 done = 0;
408 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1, NULL, 0);
409 break;
410 case NEXT:
411 imsg_compose(ibuf, IMSG_CTL_NEXT, 0, 0, -1, NULL, 0);
412 if (verbose) {
413 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
414 NULL, 0);
415 done = 0;
417 break;
418 case PREV:
419 imsg_compose(ibuf, IMSG_CTL_PREV, 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 LOAD:
427 done = 0;
428 imsg_compose(ibuf, IMSG_CTL_BEGIN, 0, 0, -1, NULL, 0);
429 break;
430 case JUMP:
431 done = 0;
432 memset(path, 0, sizeof(path));
433 strlcpy(path, res->file, sizeof(path));
434 imsg_compose(ibuf, IMSG_CTL_JUMP, 0, 0, -1,
435 path, sizeof(path));
436 break;
437 case REPEAT:
438 imsg_compose(ibuf, IMSG_CTL_REPEAT, 0, 0, -1,
439 &res->rep, sizeof(res->rep));
440 break;
441 case MONITOR:
442 done = 0;
443 imsg_compose(ibuf, IMSG_CTL_MONITOR, 0, 0, -1,
444 NULL, 0);
445 break;
446 case RESTART:
447 memset(&res->seek, 0, sizeof(res->seek));
448 /* fallthrough */
449 case SEEK:
450 imsg_compose(ibuf, IMSG_CTL_SEEK, 0, 0, -1, &res->seek,
451 sizeof(res->seek));
452 break;
453 case NONE:
454 /* action not expected */
455 fatalx("invalid action %u", res->action);
456 break;
459 if (ret != 0)
460 goto end;
462 imsg_flush(ibuf);
464 i = 0;
465 while (!done) {
466 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
467 fatalx("imsg_read error");
468 if (n == 0)
469 fatalx("pipe closed");
471 while (!done) {
472 if ((n = imsg_get(ibuf, &imsg)) == -1)
473 fatalx("imsg_get error");
474 if (n == 0)
475 break;
477 if (imsg.hdr.type == IMSG_CTL_ERR) {
478 log_warnx("%s: %s", res->ctl->name,
479 imsg_strerror(&imsg));
480 ret = 1;
481 done = 1;
482 break;
485 datalen = IMSG_DATA_SIZE(imsg);
487 switch (res->action) {
488 case ADD:
489 if (res->files[i] == NULL)
490 fatalx("received more replies than "
491 "files enqueued.");
493 if (imsg.hdr.type == IMSG_CTL_ADD)
494 log_debug("enqueued %s", res->files[i]);
495 else
496 fatalx("invalid message %d",
497 imsg.hdr.type);
498 i++;
499 done = res->files[i] == NULL;
500 break;
501 case SHOW:
502 if (datalen == 0) {
503 done = 1;
504 break;
506 if (datalen != sizeof(ps))
507 fatalx("data size mismatch");
508 memcpy(&ps, imsg.data, sizeof(ps));
509 if (ps.path[sizeof(ps.path) - 1] != '\0')
510 fatalx("received corrupted data");
511 if (res->pretty) {
512 char c = ' ';
513 if (ps.status == STATE_PLAYING)
514 c = '>';
515 printf("%c ", c);
517 puts(ps.path);
518 break;
519 case PLAY:
520 case TOGGLE:
521 case RESTART:
522 case STATUS:
523 case NEXT:
524 case PREV:
525 case JUMP:
526 if (imsg.hdr.type != IMSG_CTL_STATUS)
527 fatalx("invalid message %d",
528 imsg.hdr.type);
530 if (datalen != sizeof(ps))
531 fatalx("data size mismatch");
532 memcpy(&ps, imsg.data, sizeof(ps));
533 if (ps.path[sizeof(ps.path) - 1] != '\0')
534 fatalx("received corrupted data");
536 print_status(&ps, res->status_format);
537 done = 1;
538 break;
539 case LOAD:
540 if (imsg.hdr.type == IMSG_CTL_ADD)
541 break;
542 if (imsg.hdr.type == IMSG_CTL_COMMIT) {
543 done = 1;
544 break;
547 if (imsg.hdr.type != IMSG_CTL_BEGIN)
548 fatalx("invalid message %d",
549 imsg.hdr.type);
551 load_files(res, &ret);
552 break;
553 case MONITOR:
554 if (imsg.hdr.type != IMSG_CTL_MONITOR)
555 fatalx("invalid message %d",
556 imsg.hdr.type);
558 if (datalen != sizeof(type))
559 fatalx("data size mismatch");
561 memcpy(&type, imsg.data, sizeof(type));
562 if (type < 0 || type > IMSG__LAST)
563 fatalx("received corrupted data");
565 if (!res->monitor[type])
566 break;
568 puts(imsg_name(type));
569 fflush(stdout);
570 break;
571 default:
572 done = 1;
573 break;
576 imsg_free(&imsg);
580 end:
581 return ret;
584 static int
585 ctl_noarg(struct parse_result *res, int argc, char **argv)
587 int ch;
589 while ((ch = getopt(argc, argv, "")) != -1)
590 ctl_usage(res->ctl);
591 argc -= optind;
592 argv += optind;
594 if (argc > 0)
595 ctl_usage(res->ctl);
597 return ctlaction(res);
600 static int
601 ctl_add(struct parse_result *res, int argc, char **argv)
603 int ch;
605 while ((ch = getopt(argc, argv, "")) != -1)
606 ctl_usage(res->ctl);
607 argc -= optind;
608 argv += optind;
610 if (argc == 0)
611 ctl_usage(res->ctl);
612 res->files = argv;
614 return ctlaction(res);
617 static int
618 ctl_show(struct parse_result *res, int argc, char **argv)
620 int ch;
622 while ((ch = getopt(argc, argv, "p")) != -1) {
623 switch (ch) {
624 case 'p':
625 res->pretty = 1;
626 break;
627 default:
628 ctl_usage(res->ctl);
632 return ctlaction(res);
635 static int
636 ctl_load(struct parse_result *res, int argc, char **argv)
638 int ch;
640 while ((ch = getopt(argc, argv, "")) != -1)
641 ctl_usage(res->ctl);
642 argc -= optind;
643 argv += optind;
645 if (argc == 0)
646 res->file = NULL;
647 else if (argc == 1)
648 res->file = argv[0];
649 else
650 ctl_usage(res->ctl);
652 if (pledge("stdio rpath", NULL) == -1)
653 fatal("pledge");
655 return ctlaction(res);
658 static int
659 ctl_jump(struct parse_result *res, int argc, char **argv)
661 int ch;
663 while ((ch = getopt(argc, argv, "")) != -1)
664 ctl_usage(res->ctl);
665 argc -= optind;
666 argv += optind;
668 if (argc != 1)
669 ctl_usage(res->ctl);
671 res->file = argv[0];
672 return ctlaction(res);
675 static int
676 ctl_repeat(struct parse_result *res, int argc, char **argv)
678 int ch, b;
680 while ((ch = getopt(argc, argv, "")) != -1)
681 ctl_usage(res->ctl);
682 argc -= optind;
683 argv += optind;
685 if (argc != 2)
686 ctl_usage(res->ctl);
688 if (!strcmp(argv[1], "on"))
689 b = 1;
690 else if (!strcmp(argv[1], "off"))
691 b = 0;
692 else
693 ctl_usage(res->ctl);
695 res->rep.repeat_one = -1;
696 res->rep.repeat_all = -1;
697 if (!strcmp(argv[0], "one"))
698 res->rep.repeat_one = b;
699 else if (!strcmp(argv[0], "all"))
700 res->rep.repeat_all = b;
701 else
702 ctl_usage(res->ctl);
704 return ctlaction(res);
707 static int
708 ctl_monitor(struct parse_result *res, int argc, char **argv)
710 int ch;
711 const char *events;
712 char *dup, *tmp, *tok;
714 while ((ch = getopt(argc, argv, "")) != -1)
715 ctl_usage(res->ctl);
716 argc -= optind;
717 argv += optind;
719 if (argc > 1)
720 ctl_usage(res->ctl);
722 if (argc == 1)
723 events = *argv;
724 else
725 events = "play,toggle,pause,stop,restart,flush,next,prev,"
726 "jump,repeat,add,load";
728 tmp = dup = xstrdup(events);
729 while ((tok = strsep(&tmp, ",")) != NULL) {
730 if (*tok == '\0')
731 continue;
733 if (!strcmp(tok, "play"))
734 res->monitor[IMSG_CTL_PLAY] = 1;
735 else if (!strcmp(tok, "toggle"))
736 res->monitor[IMSG_CTL_TOGGLE_PLAY] = 1;
737 else if (!strcmp(tok, "pause"))
738 res->monitor[IMSG_CTL_PAUSE] = 1;
739 else if (!strcmp(tok, "stop"))
740 res->monitor[IMSG_CTL_STOP] = 1;
741 else if (!strcmp(tok, "restart")) /* compat */
742 res->monitor[IMSG_CTL_SEEK] = 1;
743 else if (!strcmp(tok, "flush"))
744 res->monitor[IMSG_CTL_FLUSH] = 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, "repeat"))
752 res->monitor[IMSG_CTL_REPEAT] = 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 fatalx("unknown event \"%s\"", tok);
763 free(dup);
764 return ctlaction(res);
767 static int
768 ctl_seek(struct parse_result *res, int argc, char **argv)
770 const char *n;
771 char *ep;
772 int hours = 0, minutes = 0, seconds = 0;
773 int sign = 1;
775 if (argc > 0) {
776 /* skip the command name */
777 argc--;
778 argv++;
781 if (argc > 0 && !strcmp(*argv, "--")) {
782 argc--;
783 argv++;
786 if (argc != 1)
787 ctl_usage(res->ctl);
789 n = *argv;
790 if (*n == '-' || *n == '+')
791 res->seek.relative = 1;
792 if (*n == '-') {
793 n++;
794 sign = -1;
797 seconds = strtol(n, &ep, 10);
798 if (n[0] == '\0' ||
799 (*ep != '\0' && *ep != ':' && *ep != '%') ||
800 (*ep == '%' && ep[1] != '\0'))
801 fatalx("invalid offset: %s", argv[0]);
802 if (*ep == '\0' || *ep == '%') {
803 res->seek.percent = *ep == '%';
804 goto done;
807 n = ++ep;
808 minutes = seconds;
809 seconds = strtol(n, &ep, 10);
810 if (n[0] == '\0' || (*ep != '\0' && *ep != ':'))
811 fatalx("invalid offset: %s", argv[0]);
812 if (*ep == '\0')
813 goto done;
815 n = ++ep;
816 hours = minutes;
817 minutes = seconds;
818 seconds = strtol(n, &ep, 10);
819 if (n[0] == '\0' || *ep != '\0')
820 fatalx("invalid offset: %s", argv[0]);
822 done:
823 res->seek.offset = sign * (hours * 3600 + minutes * 60 + seconds);
824 return ctlaction(res);
827 static int
828 ctl_status(struct parse_result *res, int argc, char **argv)
830 const char *fmt = NULL;
831 int ch;
833 while ((ch = getopt(argc, argv, "f:")) != -1) {
834 switch (ch) {
835 case 'f':
836 fmt = optarg;
837 break;
838 default:
839 ctl_usage(res->ctl);
842 argc -= optind;
843 argv += optind;
845 if (argc > 0)
846 ctl_usage(res->ctl);
848 if (fmt == NULL && (fmt = getenv("AMUSED_STATUS_FORMAT")) == NULL)
849 fmt = "status,time,repeat";
850 res->status_format = fmt;
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 int ctl_sock;
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(argc, argv));