Blob


1 /*
2 * Copyright (c) 2022 Omar Polo <op@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include "config.h"
19 #include <sys/socket.h>
20 #include <sys/stat.h>
21 #include <sys/wait.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <limits.h>
26 #include <signal.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <stdint.h>
30 #include <string.h>
31 #include <syslog.h>
32 #include <unistd.h>
34 #include "amused.h"
35 #include "control.h"
36 #include "log.h"
37 #include "playlist.h"
38 #include "xmalloc.h"
40 char *csock = NULL;
41 int debug;
42 int verbose;
43 struct imsgev *iev_player;
45 const char *argv0;
46 pid_t player_pid;
47 struct event ev_sigint;
48 struct event ev_sigterm;
50 enum amused_process {
51 PROC_MAIN,
52 PROC_PLAYER,
53 };
55 static __dead void
56 main_shutdown(void)
57 {
58 pid_t pid;
59 int status;
61 /* close pipes. */
62 msgbuf_clear(&iev_player->ibuf.w);
63 close(iev_player->ibuf.fd);
64 free(iev_player);
66 log_debug("waiting for children to terminate");
67 do {
68 pid = wait(&status);
69 if (pid == -1) {
70 if (errno != EINTR && errno != ECHILD)
71 fatal("wait");
72 } else if (WIFSIGNALED(status))
73 log_warnx("player terminated; signal %d",
74 WTERMSIG(status));
75 } while (pid != -1 || (pid == -1 && errno == EINTR));
77 log_info("terminating");
78 exit(0);
79 }
81 static void
82 main_sig_handler(int sig, short event, void *arg)
83 {
84 /*
85 * Normal signal handler rules don't apply because libevent
86 * decouples for us.
87 */
89 switch (sig) {
90 case SIGTERM:
91 case SIGINT:
92 main_shutdown();
93 break;
94 default:
95 fatalx("unexpected signal %d", sig);
96 }
97 }
99 static void
100 main_dispatch_player(int sig, short event, void *d)
102 char *errstr;
103 struct imsgev *iev = d;
104 struct imsgbuf *ibuf = &iev->ibuf;
105 struct imsg imsg;
106 size_t datalen;
107 ssize_t n;
108 int shut = 0;
110 if (event & EV_READ) {
111 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
112 fatal("imsg_read error");
113 if (n == 0) /* Connection closed */
114 shut = 1;
116 if (event & EV_WRITE) {
117 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
118 fatal("msgbuf_write");
119 if (n == 0) /* Connection closed */
120 shut = 1;
123 for (;;) {
124 if ((n = imsg_get(ibuf, &imsg)) == -1)
125 fatal("imsg_get");
126 if (n == 0) /* No more messages. */
127 break;
129 datalen = IMSG_DATA_SIZE(imsg);
130 switch (imsg.hdr.type) {
131 case IMSG_POS:
132 if (datalen != sizeof(current_position))
133 fatalx("IMSG_POS: got wrong size (%zu vs %zu)",
134 datalen, sizeof(current_position));
135 memcpy(&current_position, imsg.data,
136 sizeof(current_position));
137 if (current_position < 0)
138 current_position = -1;
139 break;
140 case IMSG_LEN:
141 if (datalen != sizeof(current_duration))
142 fatalx("IMSG_LEN: got wrong size (%zu vs %zu)",
143 datalen, sizeof(current_duration));
144 memcpy(&current_duration, imsg.data,
145 sizeof(current_duration));
146 if (current_duration < 0)
147 current_duration = -1;
148 break;
149 case IMSG_ERR:
150 if (datalen == 0)
151 errstr = "unknown error";
152 else {
153 errstr = imsg.data;
154 errstr[datalen-1] = '\0';
156 log_warnx("%s; skipping %s", errstr, current_song);
157 playlist_dropcurrent();
158 /* fallthrough */
159 case IMSG_EOF:
160 if (repeat_one && current_song != NULL) {
161 if (main_play_song(current_song))
162 break;
163 playlist_dropcurrent();
165 main_playlist_advance();
166 if (play_state == STATE_PLAYING)
167 control_notify(NULL, IMSG_CTL_NEXT);
168 else
169 control_notify(NULL, IMSG_CTL_STOP);
170 break;
171 default:
172 log_debug("%s: error handling imsg %d", __func__,
173 imsg.hdr.type);
174 break;
176 imsg_free(&imsg);
179 if (!shut)
180 imsg_event_add(iev);
181 else {
182 /* This pipe is dead. Remove its event handler. */
183 event_del(&iev->ev);
184 event_loopexit(NULL);
188 static pid_t
189 start_child(enum amused_process proc, int fd)
191 const char *argv[7];
192 int argc = 0;
193 pid_t pid;
195 if (fd == -1 && debug)
196 goto exec;
198 switch (pid = fork()) {
199 case -1:
200 fatal("cannot fork");
201 case 0:
202 break;
203 default:
204 close(fd);
205 return pid;
208 if (fd != 3) {
209 if (fd != -1 && dup2(fd, 3) == -1)
210 fatal("cannot setup imsg fd");
211 } else if (fcntl(F_SETFD, 0) == -1)
212 fatal("cannot setup imsg fd");
214 exec:
215 argv[argc++] = argv0;
217 switch (proc) {
218 case PROC_MAIN:
219 argv[argc++] = "-s";
220 argv[argc++] = csock;
221 argv[argc++] = "-Tm";
222 break;
223 case PROC_PLAYER:
224 argv[argc++] = "-Tp";
225 break;
228 if (debug)
229 argv[argc++] = "-d";
230 if (verbose)
231 argv[argc++] = "-v";
232 argv[argc++] = NULL;
234 /* obnoxious casts */
235 execvp(argv0, (char *const *)argv);
236 fatal("execvp %s", argv0);
239 /* daemon main routine */
240 static __dead void
241 amused_main(void)
243 int pipe_main2player[2];
244 int control_fd;
246 log_init(debug, LOG_DAEMON);
247 log_setverbose(verbose);
248 log_procinit("main");
250 if (!debug)
251 daemon(1, 0);
253 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
254 PF_UNSPEC, pipe_main2player) == -1)
255 fatal("socketpair");
257 player_pid = start_child(PROC_PLAYER, pipe_main2player[1]);
259 event_init();
261 signal_set(&ev_sigint, SIGINT, main_sig_handler, NULL);
262 signal_set(&ev_sigterm, SIGTERM, main_sig_handler, NULL);
264 signal_add(&ev_sigint, NULL);
265 signal_add(&ev_sigterm, NULL);
267 signal(SIGHUP, SIG_IGN);
268 signal(SIGCHLD, SIG_IGN);
269 signal(SIGPIPE, SIG_IGN);
271 iev_player = xmalloc(sizeof(*iev_player));
272 imsg_init(&iev_player->ibuf, pipe_main2player[0]);
273 iev_player->handler = main_dispatch_player;
274 iev_player->events = EV_READ;
275 event_set(&iev_player->ev, iev_player->ibuf.fd, iev_player->events,
276 iev_player->handler, iev_player);
277 event_add(&iev_player->ev, NULL);
279 if ((control_fd = control_init(csock)) == -1)
280 fatal("control socket setup failed %s", csock);
281 control_listen(control_fd);
283 if (pledge("stdio rpath unix sendfd", NULL) == -1)
284 fatal("pledge");
286 log_info("startup");
287 event_dispatch();
288 main_shutdown();
291 int
292 main(int argc, char **argv)
294 int ch, proc = -1;
296 log_init(1, LOG_DAEMON); /* Log to stderr until daemonized */
297 log_setverbose(1);
299 argv0 = argv[0];
300 if (argv0 == NULL)
301 argv0 = "amused";
303 while ((ch = getopt(argc, argv, "ds:T:v")) != -1) {
304 switch (ch) {
305 case 'd':
306 debug = 1;
307 break;
308 case 's':
309 free(csock);
310 csock = xstrdup(optarg);
311 break;
312 case 'T':
313 switch (*optarg) {
314 case 'm':
315 proc = PROC_MAIN;
316 break;
317 case 'p':
318 proc = PROC_PLAYER;
319 break;
320 default:
321 usage();
323 break;
324 case 'v':
325 verbose++;
326 break;
327 default:
328 usage();
331 argv += optind;
332 argc -= optind;
334 if (proc == PROC_MAIN)
335 amused_main();
336 if (proc == PROC_PLAYER)
337 exit(player(debug, verbose));
339 if (csock == NULL)
340 xasprintf(&csock, "/tmp/amused-%d", getuid());
342 if (argc > 0)
343 debug = 0;
345 ctl(argc, argv);
348 void
349 spawn_daemon(void)
351 start_child(PROC_MAIN, -1);
354 void
355 imsg_event_add(struct imsgev *iev)
357 iev->events = EV_READ;
358 if (iev->ibuf.w.queued)
359 iev->events |= EV_WRITE;
361 event_del(&iev->ev);
362 event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev);
363 event_add(&iev->ev, NULL);
366 int
367 imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
368 pid_t pid, int fd, const void *data, uint16_t datalen)
370 int ret;
372 if ((ret = imsg_compose(&iev->ibuf, type, peerid, pid, fd, data,
373 datalen)) != -1)
374 imsg_event_add(iev);
376 return ret;
379 int
380 main_send_player(uint16_t type, int fd, const void *data, size_t len)
382 return imsg_compose_event(iev_player, type, 0, 0, fd, data, len);
385 int
386 main_play_song(const char *path)
388 struct stat sb;
389 int fd;
391 if ((fd = open(path, O_RDONLY)) == -1) {
392 log_warn("open %s", path);
393 return 0;
396 if (fstat(fd, &sb) == -1) {
397 log_warn("failed to stat %s", path);
398 close(fd);
399 return 0;
402 if (!S_ISREG(sb.st_mode)) {
403 log_info("skipping non-regular file: %s", path);
404 close(fd);
405 return 0;
408 play_state = STATE_PLAYING;
409 main_send_player(IMSG_PLAY, fd, NULL, 0);
410 return 1;
413 void
414 main_playlist_jump(struct imsgev *iev, struct imsg *imsg)
416 size_t datalen;
417 char arg[PATH_MAX];
418 const char *song;
420 datalen = IMSG_DATA_SIZE(*imsg);
421 if (datalen != sizeof(arg)) {
422 main_senderr(iev, "wrong size");
423 return;
426 memcpy(arg, imsg->data, sizeof(arg));
427 if (arg[sizeof(arg)-1] != '\0') {
428 main_senderr(iev, "data corrupted");
429 return;
432 song = playlist_jump(arg);
433 if (song == NULL) {
434 main_senderr(iev, "not found");
435 return;
438 main_send_player(IMSG_STOP, -1, NULL, 0);
439 if (!main_play_song(song)) {
440 main_senderr(iev, "can't play");
441 playlist_dropcurrent();
442 main_playlist_advance();
443 return;
446 main_send_status(iev);
449 void
450 main_playlist_resume(void)
452 const char *song;
454 if ((song = current_song) == NULL)
455 song = playlist_advance();
457 for (; song != NULL; song = playlist_advance()) {
458 if (main_play_song(song))
459 return;
461 playlist_dropcurrent();
465 void
466 main_playlist_advance(void)
468 const char *song;
470 for (;;) {
471 song = playlist_advance();
472 if (song == NULL)
473 return;
475 if (main_play_song(song))
476 break;
478 playlist_dropcurrent();
482 void
483 main_playlist_previous(void)
485 const char *song;
487 for (;;) {
488 song = playlist_previous();
489 if (song == NULL)
490 return;
492 if (main_play_song(song))
493 break;
495 playlist_dropcurrent();
499 void
500 main_restart_track(void)
502 if (current_song == NULL)
503 return;
505 if (main_play_song(current_song))
506 return;
508 playlist_dropcurrent();
509 main_playlist_advance();
512 void
513 main_senderr(struct imsgev *iev, const char *msg)
515 imsg_compose_event(iev, IMSG_CTL_ERR, 0, 0, -1,
516 msg, strlen(msg)+1);
519 void
520 main_enqueue(int tx, struct playlist *px, struct imsgev *iev,
521 struct imsg *imsg)
523 size_t datalen;
524 char path[PATH_MAX];
525 const char *err = NULL;
527 datalen = IMSG_DATA_SIZE(*imsg);
528 if (datalen != sizeof(path)) {
529 err = "data size mismatch";
530 goto err;
533 memcpy(path, imsg->data, sizeof(path));
534 if (path[datalen-1] != '\0') {
535 err = "malformed data";
536 goto err;
539 if (tx)
540 playlist_push(px, path);
541 else
542 playlist_enqueue(path);
543 imsg_compose_event(iev, IMSG_CTL_ADD, 0, 0, -1, path, sizeof(path));
544 return;
545 err:
546 main_senderr(iev, err);
549 void
550 main_send_playlist(struct imsgev *iev)
552 struct player_status s;
553 size_t i;
555 for (i = 0; i < playlist.len; ++i) {
556 memset(&s, 0, sizeof(s));
557 strlcpy(s.path, playlist.songs[i], sizeof(s.path));
558 s.status = play_off == i ? STATE_PLAYING : STATE_STOPPED;
559 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, &s,
560 sizeof(s));
563 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
566 void
567 main_send_status(struct imsgev *iev)
569 struct player_status s;
571 memset(&s, 0, sizeof(s));
573 if (current_song != NULL)
574 strlcpy(s.path, current_song, sizeof(s.path));
575 s.status = play_state;
576 s.position = current_position;
577 s.duration = current_duration;
578 s.rp.repeat_all = repeat_all;
579 s.rp.repeat_one = repeat_one;
581 imsg_compose_event(iev, IMSG_CTL_STATUS, 0, 0, -1, &s, sizeof(s));