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 <sndio.h>
29 #include <signal.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stdint.h>
33 #include <string.h>
34 #include <syslog.h>
35 #include <unistd.h>
36 #include <imsg.h>
38 #include "amused.h"
39 #include "control.h"
40 #include "log.h"
41 #include "playlist.h"
42 #include "xmalloc.h"
44 struct sio_hdl *hdl;
45 char *csock = NULL;
46 int debug;
47 int verbose;
48 struct imsgev *iev_player;
50 const char *argv0;
51 pid_t player_pid;
52 struct event ev_sigint;
53 struct event ev_sigterm;
55 enum amused_process {
56 PROC_MAIN,
57 PROC_PLAYER,
58 };
60 __dead void
61 main_shutdown(void)
62 {
63 pid_t pid;
64 int status;
66 /* close pipes. */
67 msgbuf_clear(&iev_player->ibuf.w);
68 close(iev_player->ibuf.fd);
69 free(iev_player);
71 log_debug("waiting for children to terminate");
72 do {
73 pid = wait(&status);
74 if (pid == -1) {
75 if (errno != EINTR && errno != ECHILD)
76 fatal("wait");
77 } else if (WIFSIGNALED(status))
78 log_warnx("player terminated; signal %d",
79 WTERMSIG(status));
80 } while (pid != -1 || (pid == -1 && errno == EINTR));
82 log_info("terminating");
83 exit(0);
84 }
86 static void
87 main_sig_handler(int sig, short event, void *arg)
88 {
89 /*
90 * Normal signal handler rules don't apply because libevent
91 * decouples for us.
92 */
94 switch (sig) {
95 case SIGTERM:
96 case SIGINT:
97 main_shutdown();
98 break;
99 default:
100 fatalx("unexpected signal %d", sig);
104 static void
105 main_dispatch_player(int sig, short event, void *d)
107 struct imsgev *iev = d;
108 struct imsgbuf *ibuf = &iev->ibuf;
109 struct imsg imsg;
110 ssize_t n;
111 int shut = 0;
113 if (event & EV_READ) {
114 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
115 fatal("imsg_read error");
116 if (n == 0) /* Connection closed */
117 shut = 1;
119 if (event & EV_WRITE) {
120 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
121 fatal("msgbuf_write");
122 if (n == 0) /* Connection closed */
123 shut = 1;
126 for (;;) {
127 if ((n = imsg_get(ibuf, &imsg)) == -1)
128 fatal("imsg_get");
129 if (n == 0) /* No more messages. */
130 break;
132 switch (imsg.hdr.type) {
133 case IMSG_ERR:
134 playlist_dropcurrent();
135 /* fallthrough */
136 case IMSG_EOF:
137 if (repeat_one && current_song != NULL) {
138 if (main_play_song(current_song))
139 break;
140 playlist_dropcurrent();
142 main_playlist_advance();
143 if (play_state == STATE_PLAYING)
144 control_notify(NULL, IMSG_CTL_NEXT);
145 else
146 control_notify(NULL, IMSG_CTL_STOP);
147 break;
148 default:
149 log_debug("%s: error handling imsg %d", __func__,
150 imsg.hdr.type);
151 break;
153 imsg_free(&imsg);
156 if (!shut)
157 imsg_event_add(iev);
158 else {
159 /* This pipe is dead. Remove its event handler. */
160 event_del(&iev->ev);
161 event_loopexit(NULL);
165 static pid_t
166 start_child(enum amused_process proc, int fd)
168 const char *argv[7];
169 int argc = 0;
170 pid_t pid;
172 if (fd == -1 && debug)
173 goto exec;
175 switch (pid = fork()) {
176 case -1:
177 fatal("cannot fork");
178 case 0:
179 break;
180 default:
181 close(fd);
182 return pid;
185 if (fd != 3) {
186 if (fd != -1 && dup2(fd, 3) == -1)
187 fatal("cannot setup imsg fd");
188 } else if (fcntl(F_SETFD, 0) == -1)
189 fatal("cannot setup imsg fd");
191 exec:
192 argv[argc++] = argv0;
194 switch (proc) {
195 case PROC_MAIN:
196 argv[argc++] = "-s";
197 argv[argc++] = csock;
198 argv[argc++] = "-Tm";
199 break;
200 case PROC_PLAYER:
201 argv[argc++] = "-Tp";
202 break;
205 if (debug)
206 argv[argc++] = "-d";
207 if (verbose)
208 argv[argc++] = "-v";
209 argv[argc++] = NULL;
211 /* obnoxious casts */
212 execvp(argv0, (char *const *)argv);
213 fatal("execvp %s", argv0);
216 /* daemon main routine */
217 static __dead int
218 amused_main(void)
220 int pipe_main2player[2];
221 int control_fd;
223 log_init(debug, LOG_DAEMON);
224 log_setverbose(verbose);
225 log_procinit("main");
227 if (!debug)
228 daemon(1, 0);
230 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
231 PF_UNSPEC, pipe_main2player) == -1)
232 fatal("socketpair");
234 player_pid = start_child(PROC_PLAYER, pipe_main2player[1]);
236 event_init();
238 signal_set(&ev_sigint, SIGINT, main_sig_handler, NULL);
239 signal_set(&ev_sigterm, SIGTERM, main_sig_handler, NULL);
241 signal_add(&ev_sigint, NULL);
242 signal_add(&ev_sigterm, NULL);
244 signal(SIGHUP, SIG_IGN);
245 signal(SIGCHLD, SIG_IGN);
246 signal(SIGPIPE, SIG_IGN);
248 iev_player = xmalloc(sizeof(*iev_player));
249 imsg_init(&iev_player->ibuf, pipe_main2player[0]);
250 iev_player->handler = main_dispatch_player;
251 iev_player->events = EV_READ;
252 event_set(&iev_player->ev, iev_player->ibuf.fd, iev_player->events,
253 iev_player->handler, iev_player);
254 event_add(&iev_player->ev, NULL);
256 if ((control_fd = control_init(csock)) == -1)
257 fatal("control socket setup failed %s", csock);
258 control_listen(control_fd);
260 if (pledge("stdio rpath unix sendfd", NULL) == -1)
261 fatal("pledge");
263 log_info("startup");
264 event_dispatch();
265 main_shutdown();
268 int
269 main(int argc, char **argv)
271 int ch, proc = -1;
273 log_init(1, LOG_DAEMON); /* Log to stderr until daemonized */
274 log_setverbose(1);
276 argv0 = argv[0];
277 if (argv0 == NULL)
278 argv0 = "amused";
280 while ((ch = getopt(argc, argv, "ds:T:v")) != -1) {
281 switch (ch) {
282 case 'd':
283 debug = 1;
284 break;
285 case 's':
286 free(csock);
287 csock = xstrdup(optarg);
288 break;
289 case 'T':
290 switch (*optarg) {
291 case 'm':
292 proc = PROC_MAIN;
293 break;
294 case 'p':
295 proc = PROC_PLAYER;
296 break;
297 default:
298 usage();
300 break;
301 case 'v':
302 verbose++;
303 break;
304 default:
305 usage();
308 argv += optind;
309 argc -= optind;
311 if (proc == PROC_MAIN)
312 amused_main();
313 if (proc == PROC_PLAYER)
314 exit(player(debug, verbose));
316 if (csock == NULL)
317 xasprintf(&csock, "/tmp/amused-%d", getuid());
319 if (argc > 0)
320 debug = 0;
322 ctl(argc, argv);
325 void
326 spawn_daemon(void)
328 start_child(PROC_MAIN, -1);
331 void
332 imsg_event_add(struct imsgev *iev)
334 iev->events = EV_READ;
335 if (iev->ibuf.w.queued)
336 iev->events |= EV_WRITE;
338 event_del(&iev->ev);
339 event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev);
340 event_add(&iev->ev, NULL);
343 int
344 imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
345 pid_t pid, int fd, const void *data, uint16_t datalen)
347 int ret;
349 if ((ret = imsg_compose(&iev->ibuf, type, peerid, pid, fd, data,
350 datalen)) != -1)
351 imsg_event_add(iev);
353 return ret;
356 int
357 main_send_player(uint16_t type, int fd, const void *data, uint16_t datalen)
359 return imsg_compose_event(iev_player, type, 0, 0, fd, data, datalen);
362 int
363 main_play_song(const char *song)
365 struct stat sb;
366 char path[PATH_MAX] = { 0 };
367 int fd;
369 strlcpy(path, song, sizeof(path));
370 if ((fd = open(path, O_RDONLY)) == -1) {
371 log_warn("open %s", path);
372 return 0;
375 if (fstat(fd, &sb) == -1) {
376 log_warn("failed to stat %s", path);
377 close(fd);
378 return 0;
381 if (S_ISDIR(sb.st_mode)) {
382 log_info("skipping a directory: %s", path);
383 close(fd);
384 return 0;
387 play_state = STATE_PLAYING;
388 imsg_compose_event(iev_player, IMSG_PLAY, 0, 0, fd,
389 path, sizeof(path));
390 return 1;
393 void
394 main_playlist_jump(struct imsgev *iev, struct imsg *imsg)
396 size_t datalen;
397 char arg[PATH_MAX];
398 const char *song;
400 datalen = IMSG_DATA_SIZE(*imsg);
401 if (datalen != sizeof(arg)) {
402 main_senderr(iev, "wrong size");
403 return;
406 memcpy(arg, imsg->data, sizeof(arg));
407 if (arg[sizeof(arg)-1] != '\0') {
408 main_senderr(iev, "data corrupted");
409 return;
412 song = playlist_jump(arg);
413 if (song == NULL) {
414 main_senderr(iev, "not found");
415 return;
418 main_send_player(IMSG_STOP, -1, NULL, 0);
419 if (!main_play_song(song)) {
420 main_senderr(iev, "can't play");
421 playlist_dropcurrent();
422 main_playlist_advance();
423 return;
426 main_send_status(iev);
429 void
430 main_playlist_resume(void)
432 const char *song;
434 if ((song = current_song) == NULL)
435 song = playlist_advance();
437 for (; song != NULL; song = playlist_advance()) {
438 if (main_play_song(song))
439 return;
441 playlist_dropcurrent();
445 void
446 main_playlist_advance(void)
448 const char *song;
450 for (;;) {
451 song = playlist_advance();
452 if (song == NULL)
453 return;
455 if (main_play_song(song))
456 break;
458 playlist_dropcurrent();
462 void
463 main_playlist_previous(void)
465 const char *song;
467 for (;;) {
468 song = playlist_previous();
469 if (song == NULL)
470 return;
472 if (main_play_song(song))
473 break;
475 playlist_dropcurrent();
479 void
480 main_restart_track(void)
482 const char *song;
484 song = current_song;
485 if (song == NULL)
486 return;
488 if (main_play_song(song))
489 return;
491 playlist_dropcurrent();
492 main_playlist_advance();
495 void
496 main_senderr(struct imsgev *iev, const char *msg)
498 imsg_compose_event(iev, IMSG_CTL_ERR, 0, 0, -1,
499 msg, strlen(msg)+1);
502 void
503 main_enqueue(int tx, struct playlist *px, struct imsgev *iev,
504 struct imsg *imsg)
506 size_t datalen;
507 char path[PATH_MAX] = { 0 };
508 const char *err = NULL;
510 datalen = IMSG_DATA_SIZE(*imsg);
511 if (datalen != sizeof(path)) {
512 err = "data size mismatch";
513 goto err;
516 memcpy(path, imsg->data, sizeof(path));
517 if (path[datalen-1] != '\0') {
518 err = "malformed data";
519 goto err;
522 if (tx)
523 playlist_push(px, path);
524 else
525 playlist_enqueue(path);
526 imsg_compose_event(iev, IMSG_CTL_ADD, 0, 0, -1, path, sizeof(path));
527 return;
528 err:
529 main_senderr(iev, err);
532 void
533 main_send_playlist(struct imsgev *iev)
535 struct player_status s;
536 size_t i;
538 for (i = 0; i < playlist.len; ++i) {
539 memset(&s, 0, sizeof(s));
540 strlcpy(s.path, playlist.songs[i], sizeof(s.path));
541 s.status = play_off == i ? STATE_PLAYING : STATE_STOPPED;
542 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, &s,
543 sizeof(s));
546 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
549 void
550 main_send_status(struct imsgev *iev)
552 struct player_status s;
554 memset(&s, 0, sizeof(s));
556 if (current_song != NULL)
557 strlcpy(s.path, current_song, sizeof(s.path));
558 s.status = play_state;
559 s.rp.repeat_all = repeat_all;
560 s.rp.repeat_one = repeat_one;
562 imsg_compose_event(iev, IMSG_CTL_STATUS, 0, 0, -1, &s, sizeof(s));