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 event_name(int type)
247 switch (type) {
248 case IMSG_CTL_PLAY:
249 return "play";
250 case IMSG_CTL_PAUSE:
251 return "pause";
252 case IMSG_CTL_STOP:
253 return "stop";
254 case IMSG_CTL_NEXT:
255 return "next";
256 case IMSG_CTL_PREV:
257 return "prev";
258 case IMSG_CTL_JUMP:
259 return "jump";
260 case IMSG_CTL_ADD:
261 return "add";
262 case IMSG_CTL_COMMIT:
263 return "load";
264 case IMSG_CTL_SEEK:
265 return "seek";
266 default:
267 return "unknown";
271 static void
272 print_time(const char *label, int64_t seconds, const char *suffx)
274 int hours, minutes;
276 if (seconds < 0)
277 seconds = 0;
279 hours = seconds / 3600;
280 seconds -= hours * 3600;
282 minutes = seconds / 60;
283 seconds -= minutes * 60;
285 printf("%s", label);
286 if (hours != 0)
287 printf("%02d:", hours);
288 printf("%02d:%02lld%s", minutes, (long long)seconds, suffx);
291 static void
292 print_status(struct player_status *ps, const char *spec)
294 const char *status;
295 double percent;
296 char *dup, *tmp, *tok;
298 if (ps->status == STATE_STOPPED)
299 status = "stopped";
300 else if (ps->status == STATE_PLAYING)
301 status = "playing";
302 else if (ps->status == STATE_PAUSED)
303 status = "paused";
304 else
305 status = "unknown";
307 percent = 100.0 * (double)ps->position / (double)ps->duration;
309 tmp = dup = xstrdup(spec);
310 while ((tok = strsep(&tmp, ",")) != NULL) {
311 if (*tok == '\0')
312 continue;
314 if (!strcmp(tok, "path")) {
315 puts(ps->path);
316 } else if (!strcmp(tok, "repeat:oneline")) {
317 printf("repeat one:%s ",
318 ps->rp.repeat_one ? "on" : "off");
319 printf("all:%s\n", ps->rp.repeat_all ? "on" : "off");
320 } else if (!strcmp(tok, "repeat")) {
321 printf("repeat one %s\n",
322 ps->rp.repeat_one ? "on" : "off");
323 printf("repeat all %s\n",
324 ps->rp.repeat_all ? "on" : "off");
325 } else if (!strcmp(tok, "status")) {
326 printf("%s %s\n", status, ps->path);
327 } else if (!strcmp(tok, "time:oneline")) {
328 print_time("time ", ps->position, " / ");
329 print_time("", ps->duration, "\n");
330 } else if (!strcmp(tok, "time:percentage")) {
331 printf("position %.2f%%\n", percent);
332 } else if (!strcmp(tok, "time:raw")) {
333 printf("position %lld\n", (long long)ps->position);
334 printf("duration %lld\n", (long long)ps->duration);
335 } else if (!strcmp(tok, "time")) {
336 print_time("position ", ps->position, "\n");
337 print_time("duration ", ps->duration, "\n");
341 free(dup);
344 static int
345 ctlaction(struct parse_result *res)
347 char path[PATH_MAX];
348 struct imsg imsg;
349 struct player_status ps;
350 size_t datalen;
351 ssize_t n;
352 int i, type, ret = 0, done = 1;
354 switch (res->action) {
355 case PLAY:
356 imsg_compose(ibuf, IMSG_CTL_PLAY, 0, 0, -1, NULL, 0);
357 if (verbose) {
358 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
359 NULL, 0);
360 done = 0;
362 break;
363 case PAUSE:
364 imsg_compose(ibuf, IMSG_CTL_PAUSE, 0, 0, -1, NULL, 0);
365 break;
366 case TOGGLE:
367 imsg_compose(ibuf, IMSG_CTL_TOGGLE_PLAY, 0, 0, -1, NULL, 0);
368 if (verbose) {
369 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
370 NULL, 0);
371 done = 0;
373 break;
374 case STOP:
375 imsg_compose(ibuf, IMSG_CTL_STOP, 0, 0, -1, NULL, 0);
376 break;
377 case ADD:
378 done = 0;
379 for (i = 0; res->files[i] != NULL; ++i) {
380 memset(path, 0, sizeof(path));
381 if (canonpath(res->files[i], path, sizeof(path))
382 == -1) {
383 log_warn("canonpath %s", res->files[i]);
384 continue;
387 imsg_compose(ibuf, IMSG_CTL_ADD, 0, 0, -1,
388 path, sizeof(path));
390 ret = i == 0;
391 break;
392 case FLUSH:
393 imsg_compose(ibuf, IMSG_CTL_FLUSH, 0, 0, -1, NULL, 0);
394 break;
395 case SHOW:
396 done = 0;
397 imsg_compose(ibuf, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
398 break;
399 case STATUS:
400 done = 0;
401 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1, NULL, 0);
402 break;
403 case NEXT:
404 imsg_compose(ibuf, IMSG_CTL_NEXT, 0, 0, -1, NULL, 0);
405 if (verbose) {
406 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
407 NULL, 0);
408 done = 0;
410 break;
411 case PREV:
412 imsg_compose(ibuf, IMSG_CTL_PREV, 0, 0, -1, NULL, 0);
413 if (verbose) {
414 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
415 NULL, 0);
416 done = 0;
418 break;
419 case LOAD:
420 done = 0;
421 imsg_compose(ibuf, IMSG_CTL_BEGIN, 0, 0, -1, NULL, 0);
422 break;
423 case JUMP:
424 done = 0;
425 memset(path, 0, sizeof(path));
426 strlcpy(path, res->file, sizeof(path));
427 imsg_compose(ibuf, IMSG_CTL_JUMP, 0, 0, -1,
428 path, sizeof(path));
429 break;
430 case REPEAT:
431 imsg_compose(ibuf, IMSG_CTL_REPEAT, 0, 0, -1,
432 &res->rep, sizeof(res->rep));
433 break;
434 case MONITOR:
435 done = 0;
436 imsg_compose(ibuf, IMSG_CTL_MONITOR, 0, 0, -1,
437 NULL, 0);
438 break;
439 case RESTART:
440 memset(&res->seek, 0, sizeof(res->seek));
441 /* fallthrough */
442 case SEEK:
443 imsg_compose(ibuf, IMSG_CTL_SEEK, 0, 0, -1, &res->seek,
444 sizeof(res->seek));
445 break;
446 case NONE:
447 /* action not expected */
448 fatalx("invalid action %u", res->action);
449 break;
452 if (ret != 0)
453 goto end;
455 imsg_flush(ibuf);
457 i = 0;
458 while (!done) {
459 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
460 fatalx("imsg_read error");
461 if (n == 0)
462 fatalx("pipe closed");
464 while (!done) {
465 if ((n = imsg_get(ibuf, &imsg)) == -1)
466 fatalx("imsg_get error");
467 if (n == 0)
468 break;
470 if (imsg.hdr.type == IMSG_CTL_ERR) {
471 log_warnx("%s: %s", res->ctl->name,
472 imsg_strerror(&imsg));
473 ret = 1;
474 done = 1;
475 break;
478 datalen = IMSG_DATA_SIZE(imsg);
480 switch (res->action) {
481 case ADD:
482 if (res->files[i] == NULL)
483 fatalx("received more replies than "
484 "files enqueued.");
486 if (imsg.hdr.type == IMSG_CTL_ADD)
487 log_debug("enqueued %s", res->files[i]);
488 else
489 fatalx("invalid message %d",
490 imsg.hdr.type);
491 i++;
492 done = res->files[i] == NULL;
493 break;
494 case SHOW:
495 if (datalen == 0) {
496 done = 1;
497 break;
499 if (datalen != sizeof(ps))
500 fatalx("data size mismatch");
501 memcpy(&ps, imsg.data, sizeof(ps));
502 if (ps.path[sizeof(ps.path) - 1] != '\0')
503 fatalx("received corrupted data");
504 if (res->pretty) {
505 char c = ' ';
506 if (ps.status == STATE_PLAYING)
507 c = '>';
508 printf("%c ", c);
510 puts(ps.path);
511 break;
512 case PLAY:
513 case TOGGLE:
514 case RESTART:
515 case STATUS:
516 case NEXT:
517 case PREV:
518 case JUMP:
519 if (imsg.hdr.type != IMSG_CTL_STATUS)
520 fatalx("invalid message %d",
521 imsg.hdr.type);
523 if (datalen != sizeof(ps))
524 fatalx("data size mismatch");
525 memcpy(&ps, imsg.data, sizeof(ps));
526 if (ps.path[sizeof(ps.path) - 1] != '\0')
527 fatalx("received corrupted data");
529 print_status(&ps, res->status_format);
530 done = 1;
531 break;
532 case LOAD:
533 if (imsg.hdr.type == IMSG_CTL_ADD)
534 break;
535 if (imsg.hdr.type == IMSG_CTL_COMMIT) {
536 done = 1;
537 break;
540 if (imsg.hdr.type != IMSG_CTL_BEGIN)
541 fatalx("invalid message %d",
542 imsg.hdr.type);
544 load_files(res, &ret);
545 break;
546 case MONITOR:
547 if (imsg.hdr.type != IMSG_CTL_MONITOR)
548 fatalx("invalid message %d",
549 imsg.hdr.type);
551 if (datalen != sizeof(type))
552 fatalx("data size mismatch");
554 memcpy(&type, imsg.data, sizeof(type));
555 if (type < 0 || type > IMSG__LAST)
556 fatalx("received corrupted data");
558 if (!res->monitor[type])
559 break;
561 puts(event_name(type));
562 fflush(stdout);
563 break;
564 default:
565 done = 1;
566 break;
569 imsg_free(&imsg);
573 end:
574 return ret;
577 static int
578 ctl_noarg(struct parse_result *res, int argc, char **argv)
580 int ch;
582 while ((ch = getopt(argc, argv, "")) != -1)
583 ctl_usage(res->ctl);
584 argc -= optind;
585 argv += optind;
587 if (argc > 0)
588 ctl_usage(res->ctl);
590 return ctlaction(res);
593 static int
594 ctl_add(struct parse_result *res, int argc, char **argv)
596 int ch;
598 while ((ch = getopt(argc, argv, "")) != -1)
599 ctl_usage(res->ctl);
600 argc -= optind;
601 argv += optind;
603 if (argc == 0)
604 ctl_usage(res->ctl);
605 res->files = argv;
607 return ctlaction(res);
610 static int
611 ctl_show(struct parse_result *res, int argc, char **argv)
613 int ch;
615 while ((ch = getopt(argc, argv, "p")) != -1) {
616 switch (ch) {
617 case 'p':
618 res->pretty = 1;
619 break;
620 default:
621 ctl_usage(res->ctl);
625 return ctlaction(res);
628 static int
629 ctl_load(struct parse_result *res, int argc, char **argv)
631 int ch;
633 while ((ch = getopt(argc, argv, "")) != -1)
634 ctl_usage(res->ctl);
635 argc -= optind;
636 argv += optind;
638 if (argc == 0)
639 res->file = NULL;
640 else if (argc == 1)
641 res->file = argv[0];
642 else
643 ctl_usage(res->ctl);
645 if (pledge("stdio rpath", NULL) == -1)
646 fatal("pledge");
648 return ctlaction(res);
651 static int
652 ctl_jump(struct parse_result *res, int argc, char **argv)
654 int ch;
656 while ((ch = getopt(argc, argv, "")) != -1)
657 ctl_usage(res->ctl);
658 argc -= optind;
659 argv += optind;
661 if (argc != 1)
662 ctl_usage(res->ctl);
664 res->file = argv[0];
665 return ctlaction(res);
668 static int
669 ctl_repeat(struct parse_result *res, int argc, char **argv)
671 int ch, b;
673 while ((ch = getopt(argc, argv, "")) != -1)
674 ctl_usage(res->ctl);
675 argc -= optind;
676 argv += optind;
678 if (argc != 2)
679 ctl_usage(res->ctl);
681 if (!strcmp(argv[1], "on"))
682 b = 1;
683 else if (!strcmp(argv[1], "off"))
684 b = 0;
685 else
686 ctl_usage(res->ctl);
688 res->rep.repeat_one = -1;
689 res->rep.repeat_all = -1;
690 if (!strcmp(argv[0], "one"))
691 res->rep.repeat_one = b;
692 else if (!strcmp(argv[0], "all"))
693 res->rep.repeat_all = b;
694 else
695 ctl_usage(res->ctl);
697 return ctlaction(res);
700 static int
701 ctl_monitor(struct parse_result *res, int argc, char **argv)
703 int ch, n = 0;
704 const char *events;
705 char *dup, *tmp, *tok;
707 while ((ch = getopt(argc, argv, "")) != -1)
708 ctl_usage(res->ctl);
709 argc -= optind;
710 argv += optind;
712 if (argc > 1)
713 ctl_usage(res->ctl);
715 events = "play,pause,stop,next,prev,jump,repeat,add,load,seek";
716 if (argc == 1)
717 events = *argv;
719 tmp = dup = xstrdup(events);
720 while ((tok = strsep(&tmp, ",")) != NULL) {
721 if (*tok == '\0')
722 continue;
724 n++;
725 if (!strcmp(tok, "play"))
726 res->monitor[IMSG_CTL_PLAY] = 1;
727 else if (!strcmp(tok, "pause"))
728 res->monitor[IMSG_CTL_PAUSE] = 1;
729 else if (!strcmp(tok, "stop"))
730 res->monitor[IMSG_CTL_STOP] = 1;
731 else if (!strcmp(tok, "next"))
732 res->monitor[IMSG_CTL_NEXT] = 1;
733 else if (!strcmp(tok, "prev"))
734 res->monitor[IMSG_CTL_PREV] = 1;
735 else if (!strcmp(tok, "jump"))
736 res->monitor[IMSG_CTL_JUMP] = 1;
737 else if (!strcmp(tok, "repeat"))
738 res->monitor[IMSG_CTL_REPEAT] = 1;
739 else if (!strcmp(tok, "add"))
740 res->monitor[IMSG_CTL_ADD] = 1;
741 else if (!strcmp(tok, "load"))
742 res->monitor[IMSG_CTL_COMMIT] = 1;
743 else if (!strcmp(tok, "seek"))
744 res->monitor[IMSG_CTL_SEEK] = 1;
745 else {
746 log_warnx("unknown event \"%s\"", tok);
747 n--;
751 free(dup);
752 if (n == 0)
753 ctl_usage(res->ctl);
754 return ctlaction(res);
757 static int
758 ctl_seek(struct parse_result *res, int argc, char **argv)
760 const char *n;
761 char *ep;
762 int hours = 0, minutes = 0, seconds = 0;
763 int sign = 1;
765 if (argc > 0) {
766 /* skip the command name */
767 argc--;
768 argv++;
771 if (argc > 0 && !strcmp(*argv, "--")) {
772 argc--;
773 argv++;
776 if (argc != 1)
777 ctl_usage(res->ctl);
779 n = *argv;
780 if (*n == '-' || *n == '+')
781 res->seek.relative = 1;
782 if (*n == '-') {
783 n++;
784 sign = -1;
787 seconds = strtol(n, &ep, 10);
788 if (n[0] == '\0' ||
789 (*ep != '\0' && *ep != ':' && *ep != '%') ||
790 (*ep == '%' && ep[1] != '\0'))
791 fatalx("invalid offset: %s", argv[0]);
792 if (*ep == '\0' || *ep == '%') {
793 res->seek.percent = *ep == '%';
794 goto done;
797 n = ++ep;
798 minutes = seconds;
799 seconds = strtol(n, &ep, 10);
800 if (n[0] == '\0' || (*ep != '\0' && *ep != ':'))
801 fatalx("invalid offset: %s", argv[0]);
802 if (*ep == '\0')
803 goto done;
805 n = ++ep;
806 hours = minutes;
807 minutes = seconds;
808 seconds = strtol(n, &ep, 10);
809 if (n[0] == '\0' || *ep != '\0')
810 fatalx("invalid offset: %s", argv[0]);
812 done:
813 res->seek.offset = sign * (hours * 3600 + minutes * 60 + seconds);
814 return ctlaction(res);
817 static int
818 ctl_status(struct parse_result *res, int argc, char **argv)
820 int ch;
822 while ((ch = getopt(argc, argv, "f:")) != -1) {
823 switch (ch) {
824 case 'f':
825 res->status_format = optarg;
826 break;
827 default:
828 ctl_usage(res->ctl);
831 argc -= optind;
832 argv += optind;
834 if (argc > 0)
835 ctl_usage(res->ctl);
837 return ctlaction(res);
840 static int
841 ctl_get_lock(const char *lockfile)
843 int lockfd;
845 if ((lockfd = open(lockfile, O_WRONLY|O_CREAT, 0600)) == -1) {
846 log_debug("open failed: %s", strerror(errno));
847 return -1;
850 if (flock(lockfd, LOCK_EX|LOCK_NB) == -1) {
851 log_debug("flock failed: %s", strerror(errno));
852 if (errno != EAGAIN)
853 return -1;
854 while (flock(lockfd, LOCK_EX) == -1 && errno == EINTR)
855 /* nop */;
856 close(lockfd);
857 return -2;
859 log_debug("flock succeeded");
861 return lockfd;
864 static int
865 ctl_connect(void)
867 struct timespec ts = { 0, 50000000 }; /* 0.05 seconds */
868 struct sockaddr_un sa;
869 size_t size;
870 int fd, lockfd = -1, locked = 0, spawned = 0;
871 int attempt = 0;
872 char *lockfile = NULL;
874 memset(&sa, 0, sizeof(sa));
875 sa.sun_family = AF_UNIX;
876 size = strlcpy(sa.sun_path, csock, sizeof(sa.sun_path));
877 if (size >= sizeof(sa.sun_path)) {
878 errno = ENAMETOOLONG;
879 return -1;
882 retry:
883 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
884 return -1;
886 if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
887 log_debug("connection failed: %s", strerror(errno));
888 if (errno != ECONNREFUSED && errno != ENOENT)
889 goto failed;
890 if (attempt++ == 100)
891 goto failed;
892 close(fd);
894 if (!locked) {
895 xasprintf(&lockfile, "%s.lock", csock);
896 if ((lockfd = ctl_get_lock(lockfile)) < 0) {
897 log_debug("didn't get the lock (%d)", lockfd);
899 free(lockfile);
900 lockfile = NULL;
902 if (lockfd == -1)
903 goto retry;
906 /*
907 * Always retry at least once, even if we got
908 * the lock, because another client could have
909 * taken the lock, started the server and released
910 * the lock between our connect() and flock()
911 */
912 locked = 1;
913 goto retry;
916 if (!spawned) {
917 log_debug("spawning the daemon");
918 spawn_daemon();
919 spawned = 1;
922 nanosleep(&ts, NULL);
923 goto retry;
926 if (locked && lockfd >= 0) {
927 unlink(lockfile);
928 free(lockfile);
929 close(lockfd);
931 return fd;
933 failed:
934 if (locked) {
935 free(lockfile);
936 close(lockfd);
938 close(fd);
939 return -1;
942 __dead void
943 ctl(int argc, char **argv)
945 struct parse_result res;
946 const char *fmt;
947 int ctl_sock;
949 memset(&res, 0, sizeof(res));
950 if ((fmt = getenv("AMUSED_STATUS_FORMAT")) == NULL)
951 fmt = "status,time,repeat";
952 res.status_format = fmt;
954 log_init(1, LOG_DAEMON);
955 log_setverbose(verbose);
957 if (getcwd(cwd, sizeof(cwd)) == NULL)
958 fatal("getcwd");
960 if ((ctl_sock = ctl_connect()) == -1)
961 fatal("can't connect");
963 if (ctl_sock == -1)
964 fatalx("failed to connect to the daemon");
966 ibuf = xmalloc(sizeof(*ibuf));
967 imsg_init(ibuf, ctl_sock);
969 optreset = 1;
970 optind = 1;
972 exit(parse(&res, argc, argv));