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..."},
53 { "flush", FLUSH, ctl_noarg, ""},
54 { "jump", JUMP, ctl_jump, "pattern"},
55 { "load", LOAD, ctl_load, "[file]"},
56 { "monitor", MONITOR, ctl_monitor, "[events]"},
57 { "next", NEXT, ctl_noarg, ""},
58 { "pause", PAUSE, ctl_noarg, ""},
59 { "play", PLAY, ctl_noarg, ""},
60 { "prev", PREV, ctl_noarg, ""},
61 { "repeat", REPEAT, ctl_repeat, "one|all on|off"},
62 { "restart", RESTART, ctl_noarg, ""},
63 { "seek", SEEK, ctl_seek, "[+-]time[%]"},
64 { "show", SHOW, ctl_show, "[-p]"},
65 { "status", STATUS, ctl_status, "[-f fmt]"},
66 { "stop", STOP, ctl_noarg, ""},
67 { "toggle", TOGGLE, ctl_noarg, ""},
68 { NULL, 0, NULL, NULL},
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 status = ctl->main(res, argc, argv);
163 close(ibuf->fd);
164 free(ibuf);
165 return status;
168 static int
169 load_files(struct parse_result *res, int *ret)
171 const char *file;
172 char *line = NULL;
173 char path[PATH_MAX];
174 size_t linesize = 0, i = 0;
175 ssize_t linelen, curr = -1;
177 while ((linelen = getline(&line, &linesize, res->fp)) != -1) {
178 if (linelen == 0)
179 continue;
180 line[linelen-1] = '\0';
181 file = line;
182 if (!strncmp(file, "> ", 2)) {
183 file += 2;
184 curr = i;
185 } else if (!strncmp(file, " ", 2))
186 file += 2;
188 memset(path, 0, sizeof(path));
189 if (canonpath(file, path, sizeof(path)) == -1) {
190 log_warn("canonpath %s", file);
191 continue;
194 i++;
195 imsg_compose(ibuf, IMSG_CTL_ADD, 0, 0, -1,
196 path, sizeof(path));
199 free(line);
200 if (ferror(res->fp))
201 fatal("getline");
202 fclose(res->fp);
203 res->fp = NULL;
205 if (i == 0) {
206 *ret = 1;
207 return 1;
210 imsg_compose(ibuf, IMSG_CTL_COMMIT, 0, 0, -1,
211 &curr, sizeof(curr));
212 imsg_flush(ibuf);
213 return 0;
216 static const char *
217 imsg_strerror(struct imsg *imsg)
219 size_t datalen;
220 const char *msg;
222 datalen = IMSG_DATA_SIZE(*imsg);
223 msg = imsg->data;
224 if (datalen == 0 || msg[datalen-1] != '\0')
225 fatalx("malformed error message");
227 return msg;
230 static const char *
231 event_name(int type)
233 switch (type) {
234 case IMSG_CTL_PLAY:
235 return "play";
236 case IMSG_CTL_PAUSE:
237 return "pause";
238 case IMSG_CTL_STOP:
239 return "stop";
240 case IMSG_CTL_NEXT:
241 return "next";
242 case IMSG_CTL_PREV:
243 return "prev";
244 case IMSG_CTL_JUMP:
245 return "jump";
246 case IMSG_CTL_ADD:
247 return "add";
248 case IMSG_CTL_COMMIT:
249 return "load";
250 case IMSG_CTL_SEEK:
251 return "seek";
252 default:
253 return "unknown";
257 static void
258 print_time(const char *label, int64_t seconds, const char *suffx)
260 int hours, minutes;
262 if (seconds < 0)
263 seconds = 0;
265 hours = seconds / 3600;
266 seconds -= hours * 3600;
268 minutes = seconds / 60;
269 seconds -= minutes * 60;
271 printf("%s", label);
272 if (hours != 0)
273 printf("%02d:", hours);
274 printf("%02d:%02lld%s", minutes, (long long)seconds, suffx);
277 static void
278 print_status(struct player_status *ps, const char *spec)
280 const char *status;
281 double percent;
282 char *dup, *tmp, *tok;
284 if (ps->status == STATE_STOPPED)
285 status = "stopped";
286 else if (ps->status == STATE_PLAYING)
287 status = "playing";
288 else if (ps->status == STATE_PAUSED)
289 status = "paused";
290 else
291 status = "unknown";
293 percent = 100.0 * (double)ps->position / (double)ps->duration;
295 tmp = dup = xstrdup(spec);
296 while ((tok = strsep(&tmp, ",")) != NULL) {
297 if (*tok == '\0')
298 continue;
300 if (!strcmp(tok, "path")) {
301 puts(ps->path);
302 } else if (!strcmp(tok, "repeat:oneline")) {
303 printf("repeat one:%s ",
304 ps->rp.repeat_one ? "on" : "off");
305 printf("all:%s\n", ps->rp.repeat_all ? "on" : "off");
306 } else if (!strcmp(tok, "repeat")) {
307 printf("repeat one %s\n",
308 ps->rp.repeat_one ? "on" : "off");
309 printf("repeat all %s\n",
310 ps->rp.repeat_all ? "on" : "off");
311 } else if (!strcmp(tok, "status")) {
312 printf("%s %s\n", status, ps->path);
313 } else if (!strcmp(tok, "time:oneline")) {
314 print_time("time ", ps->position, " / ");
315 print_time("", ps->duration, "\n");
316 } else if (!strcmp(tok, "time:percentage")) {
317 printf("position %.2f%%\n", percent);
318 } else if (!strcmp(tok, "time:raw")) {
319 printf("position %lld\n", (long long)ps->position);
320 printf("duration %lld\n", (long long)ps->duration);
321 } else if (!strcmp(tok, "time")) {
322 print_time("position ", ps->position, "\n");
323 print_time("duration ", ps->duration, "\n");
327 free(dup);
330 static int
331 ctlaction(struct parse_result *res)
333 char path[PATH_MAX];
334 struct imsg imsg;
335 struct player_status ps;
336 size_t datalen;
337 ssize_t n;
338 int i, type, ret = 0, done = 1;
340 if (pledge("stdio", NULL) == -1)
341 fatal("pledge");
343 switch (res->action) {
344 case PLAY:
345 imsg_compose(ibuf, IMSG_CTL_PLAY, 0, 0, -1, NULL, 0);
346 if (verbose) {
347 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
348 NULL, 0);
349 done = 0;
351 break;
352 case PAUSE:
353 imsg_compose(ibuf, IMSG_CTL_PAUSE, 0, 0, -1, NULL, 0);
354 break;
355 case TOGGLE:
356 imsg_compose(ibuf, IMSG_CTL_TOGGLE_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 STOP:
364 imsg_compose(ibuf, IMSG_CTL_STOP, 0, 0, -1, NULL, 0);
365 break;
366 case ADD:
367 done = 0;
368 for (i = 0; res->files[i] != NULL; ++i) {
369 memset(path, 0, sizeof(path));
370 if (canonpath(res->files[i], path, sizeof(path))
371 == -1) {
372 log_warn("canonpath %s", res->files[i]);
373 continue;
376 imsg_compose(ibuf, IMSG_CTL_ADD, 0, 0, -1,
377 path, sizeof(path));
379 ret = i == 0;
380 break;
381 case FLUSH:
382 imsg_compose(ibuf, IMSG_CTL_FLUSH, 0, 0, -1, NULL, 0);
383 break;
384 case SHOW:
385 done = 0;
386 imsg_compose(ibuf, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
387 break;
388 case STATUS:
389 done = 0;
390 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1, NULL, 0);
391 break;
392 case NEXT:
393 imsg_compose(ibuf, IMSG_CTL_NEXT, 0, 0, -1, NULL, 0);
394 if (verbose) {
395 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
396 NULL, 0);
397 done = 0;
399 break;
400 case PREV:
401 imsg_compose(ibuf, IMSG_CTL_PREV, 0, 0, -1, NULL, 0);
402 if (verbose) {
403 imsg_compose(ibuf, IMSG_CTL_STATUS, 0, 0, -1,
404 NULL, 0);
405 done = 0;
407 break;
408 case LOAD:
409 done = 0;
410 imsg_compose(ibuf, IMSG_CTL_BEGIN, 0, 0, -1, NULL, 0);
411 break;
412 case JUMP:
413 done = 0;
414 memset(path, 0, sizeof(path));
415 strlcpy(path, res->files[0], sizeof(path));
416 imsg_compose(ibuf, IMSG_CTL_JUMP, 0, 0, -1,
417 path, sizeof(path));
418 break;
419 case REPEAT:
420 imsg_compose(ibuf, IMSG_CTL_REPEAT, 0, 0, -1,
421 &res->rep, sizeof(res->rep));
422 break;
423 case MONITOR:
424 done = 0;
425 imsg_compose(ibuf, IMSG_CTL_MONITOR, 0, 0, -1,
426 NULL, 0);
427 break;
428 case RESTART:
429 memset(&res->seek, 0, sizeof(res->seek));
430 /* fallthrough */
431 case SEEK:
432 imsg_compose(ibuf, IMSG_CTL_SEEK, 0, 0, -1, &res->seek,
433 sizeof(res->seek));
434 break;
435 case NONE:
436 /* action not expected */
437 fatalx("invalid action %u", res->action);
438 break;
441 if (ret != 0)
442 goto end;
444 imsg_flush(ibuf);
446 i = 0;
447 while (!done) {
448 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
449 fatalx("imsg_read error");
450 if (n == 0)
451 fatalx("pipe closed");
453 while (!done) {
454 if ((n = imsg_get(ibuf, &imsg)) == -1)
455 fatalx("imsg_get error");
456 if (n == 0)
457 break;
459 if (imsg.hdr.type == IMSG_CTL_ERR) {
460 log_warnx("%s: %s", res->ctl->name,
461 imsg_strerror(&imsg));
462 ret = 1;
463 done = 1;
464 break;
467 datalen = IMSG_DATA_SIZE(imsg);
469 switch (res->action) {
470 case ADD:
471 if (res->files[i] == NULL)
472 fatalx("received more replies than "
473 "files enqueued.");
475 if (imsg.hdr.type == IMSG_CTL_ADD)
476 log_debug("enqueued %s", res->files[i]);
477 else
478 fatalx("invalid message %d",
479 imsg.hdr.type);
480 i++;
481 done = res->files[i] == NULL;
482 break;
483 case SHOW:
484 if (datalen == 0) {
485 done = 1;
486 break;
488 if (datalen != sizeof(ps))
489 fatalx("data size mismatch");
490 memcpy(&ps, imsg.data, sizeof(ps));
491 if (ps.path[sizeof(ps.path) - 1] != '\0')
492 fatalx("received corrupted data");
493 if (res->pretty) {
494 char c = ' ';
495 if (ps.status == STATE_PLAYING)
496 c = '>';
497 printf("%c ", c);
499 puts(ps.path);
500 break;
501 case PLAY:
502 case TOGGLE:
503 case RESTART:
504 case STATUS:
505 case NEXT:
506 case PREV:
507 case JUMP:
508 if (imsg.hdr.type != IMSG_CTL_STATUS)
509 fatalx("invalid message %d",
510 imsg.hdr.type);
512 if (datalen != sizeof(ps))
513 fatalx("data size mismatch");
514 memcpy(&ps, imsg.data, sizeof(ps));
515 if (ps.path[sizeof(ps.path) - 1] != '\0')
516 fatalx("received corrupted data");
518 print_status(&ps, res->status_format);
519 done = 1;
520 break;
521 case LOAD:
522 if (imsg.hdr.type == IMSG_CTL_ADD)
523 break;
524 if (imsg.hdr.type == IMSG_CTL_COMMIT) {
525 done = 1;
526 break;
529 if (imsg.hdr.type != IMSG_CTL_BEGIN)
530 fatalx("invalid message %d",
531 imsg.hdr.type);
533 load_files(res, &ret);
534 break;
535 case MONITOR:
536 if (imsg.hdr.type != IMSG_CTL_MONITOR)
537 fatalx("invalid message %d",
538 imsg.hdr.type);
540 if (datalen != sizeof(type))
541 fatalx("data size mismatch");
543 memcpy(&type, imsg.data, sizeof(type));
544 if (type < 0 || type > IMSG__LAST)
545 fatalx("received corrupted data");
547 if (!res->monitor[type])
548 break;
550 puts(event_name(type));
551 fflush(stdout);
552 break;
553 default:
554 done = 1;
555 break;
558 imsg_free(&imsg);
562 end:
563 return ret;
566 static int
567 ctl_noarg(struct parse_result *res, int argc, char **argv)
569 int ch;
571 while ((ch = getopt(argc, argv, "")) != -1)
572 ctl_usage(res->ctl);
573 argc -= optind;
574 argv += optind;
576 if (argc > 0)
577 ctl_usage(res->ctl);
579 return ctlaction(res);
582 static int
583 ctl_add(struct parse_result *res, int argc, char **argv)
585 int ch;
587 while ((ch = getopt(argc, argv, "")) != -1)
588 ctl_usage(res->ctl);
589 argc -= optind;
590 argv += optind;
592 if (argc == 0)
593 ctl_usage(res->ctl);
594 res->files = argv;
596 return ctlaction(res);
599 static int
600 ctl_show(struct parse_result *res, int argc, char **argv)
602 int ch;
604 while ((ch = getopt(argc, argv, "p")) != -1) {
605 switch (ch) {
606 case 'p':
607 res->pretty = 1;
608 break;
609 default:
610 ctl_usage(res->ctl);
614 return ctlaction(res);
617 static int
618 ctl_load(struct parse_result *res, int argc, char **argv)
620 int ch;
622 while ((ch = getopt(argc, argv, "")) != -1)
623 ctl_usage(res->ctl);
624 argc -= optind;
625 argv += optind;
627 if (argc > 1)
628 ctl_usage(res->ctl);
630 res->fp = stdin;
631 if (argc == 1) {
632 if ((res->fp = fopen(argv[0], "r")) == NULL)
633 fatal("can't open %s", argv[0]);
636 return ctlaction(res);
639 static int
640 ctl_jump(struct parse_result *res, int argc, char **argv)
642 int ch;
644 while ((ch = getopt(argc, argv, "")) != -1)
645 ctl_usage(res->ctl);
646 argc -= optind;
647 argv += optind;
649 if (argc != 1)
650 ctl_usage(res->ctl);
652 res->files = argv;
653 return ctlaction(res);
656 static int
657 ctl_repeat(struct parse_result *res, int argc, char **argv)
659 int ch, b;
661 while ((ch = getopt(argc, argv, "")) != -1)
662 ctl_usage(res->ctl);
663 argc -= optind;
664 argv += optind;
666 if (argc != 2)
667 ctl_usage(res->ctl);
669 if (!strcmp(argv[1], "on"))
670 b = 1;
671 else if (!strcmp(argv[1], "off"))
672 b = 0;
673 else
674 ctl_usage(res->ctl);
676 res->rep.repeat_one = -1;
677 res->rep.repeat_all = -1;
678 if (!strcmp(argv[0], "one"))
679 res->rep.repeat_one = b;
680 else if (!strcmp(argv[0], "all"))
681 res->rep.repeat_all = b;
682 else
683 ctl_usage(res->ctl);
685 return ctlaction(res);
688 static int
689 ctl_monitor(struct parse_result *res, int argc, char **argv)
691 int ch, n = 0;
692 const char *events;
693 char *dup, *tmp, *tok;
695 while ((ch = getopt(argc, argv, "")) != -1)
696 ctl_usage(res->ctl);
697 argc -= optind;
698 argv += optind;
700 if (argc > 1)
701 ctl_usage(res->ctl);
703 events = "play,pause,stop,next,prev,jump,repeat,add,load,seek";
704 if (argc == 1)
705 events = *argv;
707 tmp = dup = xstrdup(events);
708 while ((tok = strsep(&tmp, ",")) != NULL) {
709 if (*tok == '\0')
710 continue;
712 n++;
713 if (!strcmp(tok, "play"))
714 res->monitor[IMSG_CTL_PLAY] = 1;
715 else if (!strcmp(tok, "pause"))
716 res->monitor[IMSG_CTL_PAUSE] = 1;
717 else if (!strcmp(tok, "stop"))
718 res->monitor[IMSG_CTL_STOP] = 1;
719 else if (!strcmp(tok, "next"))
720 res->monitor[IMSG_CTL_NEXT] = 1;
721 else if (!strcmp(tok, "prev"))
722 res->monitor[IMSG_CTL_PREV] = 1;
723 else if (!strcmp(tok, "jump"))
724 res->monitor[IMSG_CTL_JUMP] = 1;
725 else if (!strcmp(tok, "repeat"))
726 res->monitor[IMSG_CTL_REPEAT] = 1;
727 else if (!strcmp(tok, "add"))
728 res->monitor[IMSG_CTL_ADD] = 1;
729 else if (!strcmp(tok, "load"))
730 res->monitor[IMSG_CTL_COMMIT] = 1;
731 else if (!strcmp(tok, "seek"))
732 res->monitor[IMSG_CTL_SEEK] = 1;
733 else {
734 log_warnx("unknown event \"%s\"", tok);
735 n--;
739 free(dup);
740 if (n == 0)
741 ctl_usage(res->ctl);
742 return ctlaction(res);
745 static int
746 ctl_seek(struct parse_result *res, int argc, char **argv)
748 const char *n;
749 char *ep;
750 int hours = 0, minutes = 0, seconds = 0;
751 int sign = 1;
753 if (argc > 0) {
754 /* skip the command name */
755 argc--;
756 argv++;
759 if (argc > 0 && !strcmp(*argv, "--")) {
760 argc--;
761 argv++;
764 if (argc != 1)
765 ctl_usage(res->ctl);
767 n = *argv;
768 if (*n == '-' || *n == '+')
769 res->seek.relative = 1;
770 if (*n == '-') {
771 n++;
772 sign = -1;
775 seconds = strtol(n, &ep, 10);
776 if (n[0] == '\0' ||
777 (*ep != '\0' && *ep != ':' && *ep != '%') ||
778 (*ep == '%' && ep[1] != '\0'))
779 fatalx("invalid offset: %s", argv[0]);
780 if (*ep == '\0' || *ep == '%') {
781 res->seek.percent = *ep == '%';
782 goto done;
785 n = ++ep;
786 minutes = seconds;
787 seconds = strtol(n, &ep, 10);
788 if (n[0] == '\0' || (*ep != '\0' && *ep != ':'))
789 fatalx("invalid offset: %s", argv[0]);
790 if (*ep == '\0')
791 goto done;
793 n = ++ep;
794 hours = minutes;
795 minutes = seconds;
796 seconds = strtol(n, &ep, 10);
797 if (n[0] == '\0' || *ep != '\0')
798 fatalx("invalid offset: %s", argv[0]);
800 done:
801 res->seek.offset = sign * (hours * 3600 + minutes * 60 + seconds);
802 return ctlaction(res);
805 static int
806 ctl_status(struct parse_result *res, int argc, char **argv)
808 int ch;
810 while ((ch = getopt(argc, argv, "f:")) != -1) {
811 switch (ch) {
812 case 'f':
813 res->status_format = optarg;
814 break;
815 default:
816 ctl_usage(res->ctl);
819 argc -= optind;
820 argv += optind;
822 if (argc > 0)
823 ctl_usage(res->ctl);
825 return ctlaction(res);
828 static int
829 ctl_get_lock(const char *lockfile)
831 int lockfd;
833 if ((lockfd = open(lockfile, O_WRONLY|O_CREAT, 0600)) == -1) {
834 log_debug("open failed: %s", strerror(errno));
835 return -1;
838 if (flock(lockfd, LOCK_EX|LOCK_NB) == -1) {
839 log_debug("flock failed: %s", strerror(errno));
840 if (errno != EAGAIN)
841 return -1;
842 while (flock(lockfd, LOCK_EX) == -1 && errno == EINTR)
843 /* nop */;
844 close(lockfd);
845 return -2;
847 log_debug("flock succeeded");
849 return lockfd;
852 static int
853 ctl_connect(void)
855 struct timespec ts = { 0, 50000000 }; /* 0.05 seconds */
856 struct sockaddr_un sa;
857 size_t size;
858 int fd, lockfd = -1, locked = 0, spawned = 0;
859 int attempt = 0;
860 char *lockfile = NULL;
862 memset(&sa, 0, sizeof(sa));
863 sa.sun_family = AF_UNIX;
864 size = strlcpy(sa.sun_path, csock, sizeof(sa.sun_path));
865 if (size >= sizeof(sa.sun_path)) {
866 errno = ENAMETOOLONG;
867 return -1;
870 retry:
871 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
872 return -1;
874 if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
875 log_debug("connection failed: %s", strerror(errno));
876 if (errno != ECONNREFUSED && errno != ENOENT)
877 goto failed;
878 if (attempt++ == 100)
879 goto failed;
880 close(fd);
882 if (!locked) {
883 xasprintf(&lockfile, "%s.lock", csock);
884 if ((lockfd = ctl_get_lock(lockfile)) < 0) {
885 log_debug("didn't get the lock (%d)", lockfd);
887 free(lockfile);
888 lockfile = NULL;
890 if (lockfd == -1)
891 goto retry;
894 /*
895 * Always retry at least once, even if we got
896 * the lock, because another client could have
897 * taken the lock, started the server and released
898 * the lock between our connect() and flock()
899 */
900 locked = 1;
901 goto retry;
904 if (!spawned) {
905 log_debug("spawning the daemon");
906 spawn_daemon();
907 spawned = 1;
910 nanosleep(&ts, NULL);
911 goto retry;
914 if (locked && lockfd >= 0) {
915 unlink(lockfile);
916 free(lockfile);
917 close(lockfd);
919 return fd;
921 failed:
922 if (locked) {
923 free(lockfile);
924 close(lockfd);
926 close(fd);
927 return -1;
930 __dead void
931 ctl(int argc, char **argv)
933 struct parse_result res;
934 const char *fmt;
935 int ctl_sock;
937 memset(&res, 0, sizeof(res));
938 if ((fmt = getenv("AMUSED_STATUS_FORMAT")) == NULL)
939 fmt = "status,time,repeat";
940 res.status_format = fmt;
942 log_init(1, LOG_DAEMON);
943 log_setverbose(verbose);
945 if (getcwd(cwd, sizeof(cwd)) == NULL)
946 fatal("getcwd");
948 if ((ctl_sock = ctl_connect()) == -1)
949 fatal("can't connect");
951 if (ctl_sock == -1)
952 fatalx("failed to connect to the daemon");
954 ibuf = xmalloc(sizeof(*ibuf));
955 imsg_init(ibuf, ctl_sock);
957 optreset = 1;
958 optind = 1;
960 /* we'll drop rpath too later in ctlaction */
961 if (pledge("stdio rpath", NULL) == -1)
962 fatal("pledge");
964 exit(parse(&res, argc, argv));