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 <sys/types.h>
18 #include <sys/queue.h>
19 #include <sys/socket.h>
20 #include <sys/stat.h>
21 #include <sys/uio.h>
22 #include <sys/wait.h>
24 #include <event.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <signal.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <stdint.h>
32 #include <string.h>
33 #include <syslog.h>
34 #include <unistd.h>
35 #include <imsg.h>
37 #include "amused.h"
38 #include "control.h"
39 #include "log.h"
40 #include "playlist.h"
41 #include "xmalloc.h"
43 char *csock = NULL;
44 int debug;
45 int verbose;
46 struct imsgev *iev_player;
48 const char *argv0;
49 pid_t player_pid;
50 struct event ev_sigint;
51 struct event ev_sigterm;
53 enum amused_process {
54 PROC_MAIN,
55 PROC_PLAYER,
56 };
58 __dead void
59 main_shutdown(void)
60 {
61 pid_t pid;
62 int status;
64 /* close pipes. */
65 msgbuf_clear(&iev_player->ibuf.w);
66 close(iev_player->ibuf.fd);
67 free(iev_player);
69 log_debug("waiting for children to terminate");
70 do {
71 pid = wait(&status);
72 if (pid == -1) {
73 if (errno != EINTR && errno != ECHILD)
74 fatal("wait");
75 } else if (WIFSIGNALED(status))
76 log_warnx("player terminated; signal %d",
77 WTERMSIG(status));
78 } while (pid != -1 || (pid == -1 && errno == EINTR));
80 log_info("terminating");
81 exit(0);
82 }
84 static void
85 main_sig_handler(int sig, short event, void *arg)
86 {
87 /*
88 * Normal signal handler rules don't apply because libevent
89 * decouples for us.
90 */
92 switch (sig) {
93 case SIGTERM:
94 case SIGINT:
95 main_shutdown();
96 break;
97 default:
98 fatalx("unexpected signal %d", sig);
99 }
102 static void
103 main_dispatch_player(int sig, short event, void *d)
105 struct imsgev *iev = d;
106 struct imsgbuf *ibuf = &iev->ibuf;
107 struct imsg imsg;
108 ssize_t n;
109 int shut = 0;
111 if (event & EV_READ) {
112 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
113 fatal("imsg_read error");
114 if (n == 0) /* Connection closed */
115 shut = 1;
117 if (event & EV_WRITE) {
118 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
119 fatal("msgbuf_write");
120 if (n == 0) /* Connection closed */
121 shut = 1;
124 for (;;) {
125 if ((n = imsg_get(ibuf, &imsg)) == -1)
126 fatal("imsg_get");
127 if (n == 0) /* No more messages. */
128 break;
130 switch (imsg.hdr.type) {
131 case IMSG_ERR:
132 log_warnx("failed to play, skipping %s", current_song);
133 playlist_dropcurrent();
134 /* fallthrough */
135 case IMSG_EOF:
136 if (repeat_one && current_song != NULL) {
137 if (main_play_song(current_song))
138 break;
139 playlist_dropcurrent();
141 main_playlist_advance();
142 if (play_state == STATE_PLAYING)
143 control_notify(NULL, IMSG_CTL_NEXT);
144 else
145 control_notify(NULL, IMSG_CTL_STOP);
146 break;
147 default:
148 log_debug("%s: error handling imsg %d", __func__,
149 imsg.hdr.type);
150 break;
152 imsg_free(&imsg);
155 if (!shut)
156 imsg_event_add(iev);
157 else {
158 /* This pipe is dead. Remove its event handler. */
159 event_del(&iev->ev);
160 event_loopexit(NULL);
164 static pid_t
165 start_child(enum amused_process proc, int fd)
167 const char *argv[7];
168 int argc = 0;
169 pid_t pid;
171 if (fd == -1 && debug)
172 goto exec;
174 switch (pid = fork()) {
175 case -1:
176 fatal("cannot fork");
177 case 0:
178 break;
179 default:
180 close(fd);
181 return pid;
184 if (fd != 3) {
185 if (fd != -1 && dup2(fd, 3) == -1)
186 fatal("cannot setup imsg fd");
187 } else if (fcntl(F_SETFD, 0) == -1)
188 fatal("cannot setup imsg fd");
190 exec:
191 argv[argc++] = argv0;
193 switch (proc) {
194 case PROC_MAIN:
195 argv[argc++] = "-s";
196 argv[argc++] = csock;
197 argv[argc++] = "-Tm";
198 break;
199 case PROC_PLAYER:
200 argv[argc++] = "-Tp";
201 break;
204 if (debug)
205 argv[argc++] = "-d";
206 if (verbose)
207 argv[argc++] = "-v";
208 argv[argc++] = NULL;
210 /* obnoxious casts */
211 execvp(argv0, (char *const *)argv);
212 fatal("execvp %s", argv0);
215 /* daemon main routine */
216 static __dead void
217 amused_main(void)
219 int pipe_main2player[2];
220 int control_fd;
222 log_init(debug, LOG_DAEMON);
223 log_setverbose(verbose);
224 log_procinit("main");
226 if (!debug)
227 daemon(1, 0);
229 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
230 PF_UNSPEC, pipe_main2player) == -1)
231 fatal("socketpair");
233 player_pid = start_child(PROC_PLAYER, pipe_main2player[1]);
235 event_init();
237 signal_set(&ev_sigint, SIGINT, main_sig_handler, NULL);
238 signal_set(&ev_sigterm, SIGTERM, main_sig_handler, NULL);
240 signal_add(&ev_sigint, NULL);
241 signal_add(&ev_sigterm, NULL);
243 signal(SIGHUP, SIG_IGN);
244 signal(SIGCHLD, SIG_IGN);
245 signal(SIGPIPE, SIG_IGN);
247 iev_player = xmalloc(sizeof(*iev_player));
248 imsg_init(&iev_player->ibuf, pipe_main2player[0]);
249 iev_player->handler = main_dispatch_player;
250 iev_player->events = EV_READ;
251 event_set(&iev_player->ev, iev_player->ibuf.fd, iev_player->events,
252 iev_player->handler, iev_player);
253 event_add(&iev_player->ev, NULL);
255 if ((control_fd = control_init(csock)) == -1)
256 fatal("control socket setup failed %s", csock);
257 control_listen(control_fd);
259 if (pledge("stdio rpath unix sendfd", NULL) == -1)
260 fatal("pledge");
262 log_info("startup");
263 event_dispatch();
264 main_shutdown();
267 int
268 main(int argc, char **argv)
270 int ch, proc = -1;
272 log_init(1, LOG_DAEMON); /* Log to stderr until daemonized */
273 log_setverbose(1);
275 argv0 = argv[0];
276 if (argv0 == NULL)
277 argv0 = "amused";
279 while ((ch = getopt(argc, argv, "ds:T:v")) != -1) {
280 switch (ch) {
281 case 'd':
282 debug = 1;
283 break;
284 case 's':
285 free(csock);
286 csock = xstrdup(optarg);
287 break;
288 case 'T':
289 switch (*optarg) {
290 case 'm':
291 proc = PROC_MAIN;
292 break;
293 case 'p':
294 proc = PROC_PLAYER;
295 break;
296 default:
297 usage();
299 break;
300 case 'v':
301 verbose++;
302 break;
303 default:
304 usage();
307 argv += optind;
308 argc -= optind;
310 if (proc == PROC_MAIN)
311 amused_main();
312 if (proc == PROC_PLAYER)
313 exit(player(debug, verbose));
315 if (csock == NULL)
316 xasprintf(&csock, "/tmp/amused-%d", getuid());
318 if (argc > 0)
319 debug = 0;
321 ctl(argc, argv);
324 void
325 spawn_daemon(void)
327 start_child(PROC_MAIN, -1);
330 void
331 imsg_event_add(struct imsgev *iev)
333 iev->events = EV_READ;
334 if (iev->ibuf.w.queued)
335 iev->events |= EV_WRITE;
337 event_del(&iev->ev);
338 event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev);
339 event_add(&iev->ev, NULL);
342 int
343 imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
344 pid_t pid, int fd, const void *data, uint16_t datalen)
346 int ret;
348 if ((ret = imsg_compose(&iev->ibuf, type, peerid, pid, fd, data,
349 datalen)) != -1)
350 imsg_event_add(iev);
352 return ret;
355 int
356 main_send_player(uint16_t type, int fd)
358 return imsg_compose_event(iev_player, type, 0, 0, fd, NULL, 0);
361 int
362 main_play_song(const char *path)
364 struct stat sb;
365 int fd;
367 if ((fd = open(path, O_RDONLY)) == -1) {
368 log_warn("open %s", path);
369 return 0;
372 if (fstat(fd, &sb) == -1) {
373 log_warn("failed to stat %s", path);
374 close(fd);
375 return 0;
378 if (S_ISDIR(sb.st_mode)) {
379 log_info("skipping a directory: %s", path);
380 close(fd);
381 return 0;
384 play_state = STATE_PLAYING;
385 main_send_player(IMSG_PLAY, fd);
386 return 1;
389 void
390 main_playlist_jump(struct imsgev *iev, struct imsg *imsg)
392 size_t datalen;
393 char arg[PATH_MAX];
394 const char *song;
396 datalen = IMSG_DATA_SIZE(*imsg);
397 if (datalen != sizeof(arg)) {
398 main_senderr(iev, "wrong size");
399 return;
402 memcpy(arg, imsg->data, sizeof(arg));
403 if (arg[sizeof(arg)-1] != '\0') {
404 main_senderr(iev, "data corrupted");
405 return;
408 song = playlist_jump(arg);
409 if (song == NULL) {
410 main_senderr(iev, "not found");
411 return;
414 main_send_player(IMSG_STOP, -1);
415 if (!main_play_song(song)) {
416 main_senderr(iev, "can't play");
417 playlist_dropcurrent();
418 main_playlist_advance();
419 return;
422 main_send_status(iev);
425 void
426 main_playlist_resume(void)
428 const char *song;
430 if ((song = current_song) == NULL)
431 song = playlist_advance();
433 for (; song != NULL; song = playlist_advance()) {
434 if (main_play_song(song))
435 return;
437 playlist_dropcurrent();
441 void
442 main_playlist_advance(void)
444 const char *song;
446 for (;;) {
447 song = playlist_advance();
448 if (song == NULL)
449 return;
451 if (main_play_song(song))
452 break;
454 playlist_dropcurrent();
458 void
459 main_playlist_previous(void)
461 const char *song;
463 for (;;) {
464 song = playlist_previous();
465 if (song == NULL)
466 return;
468 if (main_play_song(song))
469 break;
471 playlist_dropcurrent();
475 void
476 main_restart_track(void)
478 const char *song;
480 song = current_song;
481 if (song == NULL)
482 return;
484 if (main_play_song(song))
485 return;
487 playlist_dropcurrent();
488 main_playlist_advance();
491 void
492 main_senderr(struct imsgev *iev, const char *msg)
494 imsg_compose_event(iev, IMSG_CTL_ERR, 0, 0, -1,
495 msg, strlen(msg)+1);
498 void
499 main_enqueue(int tx, struct playlist *px, struct imsgev *iev,
500 struct imsg *imsg)
502 size_t datalen;
503 char path[PATH_MAX] = { 0 };
504 const char *err = NULL;
506 datalen = IMSG_DATA_SIZE(*imsg);
507 if (datalen != sizeof(path)) {
508 err = "data size mismatch";
509 goto err;
512 memcpy(path, imsg->data, sizeof(path));
513 if (path[datalen-1] != '\0') {
514 err = "malformed data";
515 goto err;
518 if (tx)
519 playlist_push(px, path);
520 else
521 playlist_enqueue(path);
522 imsg_compose_event(iev, IMSG_CTL_ADD, 0, 0, -1, path, sizeof(path));
523 return;
524 err:
525 main_senderr(iev, err);
528 void
529 main_send_playlist(struct imsgev *iev)
531 struct player_status s;
532 size_t i;
534 for (i = 0; i < playlist.len; ++i) {
535 memset(&s, 0, sizeof(s));
536 strlcpy(s.path, playlist.songs[i], sizeof(s.path));
537 s.status = play_off == i ? STATE_PLAYING : STATE_STOPPED;
538 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, &s,
539 sizeof(s));
542 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
545 void
546 main_send_status(struct imsgev *iev)
548 struct player_status s;
550 memset(&s, 0, sizeof(s));
552 if (current_song != NULL)
553 strlcpy(s.path, current_song, sizeof(s.path));
554 s.status = play_state;
555 s.rp.repeat_all = repeat_all;
556 s.rp.repeat_one = repeat_one;
558 imsg_compose_event(iev, IMSG_CTL_STATUS, 0, 0, -1, &s, sizeof(s));