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 static int notify_seek;
52 enum amused_process {
53 PROC_MAIN,
54 PROC_PLAYER,
55 };
57 static __dead void
58 main_shutdown(void)
59 {
60 pid_t pid;
61 int status;
63 /* close pipes. */
64 msgbuf_clear(&iev_player->ibuf.w);
65 close(iev_player->ibuf.fd);
66 free(iev_player);
68 log_debug("waiting for children to terminate");
69 do {
70 pid = wait(&status);
71 if (pid == -1) {
72 if (errno != EINTR && errno != ECHILD)
73 fatal("wait");
74 } else if (WIFSIGNALED(status))
75 log_warnx("player terminated; signal %d",
76 WTERMSIG(status));
77 } while (pid != -1 || (pid == -1 && errno == EINTR));
79 log_info("terminating");
80 exit(0);
81 }
83 static void
84 main_sig_handler(int sig, short event, void *arg)
85 {
86 /*
87 * Normal signal handler rules don't apply because libevent
88 * decouples for us.
89 */
91 switch (sig) {
92 case SIGTERM:
93 case SIGINT:
94 main_shutdown();
95 break;
96 default:
97 fatalx("unexpected signal %d", sig);
98 }
99 }
101 static void
102 main_dispatch_player(int sig, short event, void *d)
104 char *errstr;
105 struct imsgev *iev = d;
106 struct imsgbuf *ibuf = &iev->ibuf;
107 struct imsg imsg;
108 size_t datalen;
109 ssize_t n;
110 int shut = 0;
112 if (event & EV_READ) {
113 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
114 fatal("imsg_read error");
115 if (n == 0) /* Connection closed */
116 shut = 1;
118 if (event & EV_WRITE) {
119 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
120 fatal("msgbuf_write");
121 if (n == 0) /* Connection closed */
122 shut = 1;
125 for (;;) {
126 if ((n = imsg_get(ibuf, &imsg)) == -1)
127 fatal("imsg_get");
128 if (n == 0) /* No more messages. */
129 break;
131 datalen = IMSG_DATA_SIZE(imsg);
132 switch (imsg.hdr.type) {
133 case IMSG_POS:
134 if (datalen != sizeof(current_position))
135 fatalx("IMSG_POS: got wrong size (%zu vs %zu)",
136 datalen, sizeof(current_position));
137 memcpy(&current_position, imsg.data,
138 sizeof(current_position));
139 if (current_position < 0)
140 current_position = -1;
141 if (notify_seek) {
142 notify_seek = 0;
143 control_notify(IMSG_CTL_SEEK);
145 break;
146 case IMSG_LEN:
147 if (datalen != sizeof(current_duration))
148 fatalx("IMSG_LEN: got wrong size (%zu vs %zu)",
149 datalen, sizeof(current_duration));
150 memcpy(&current_duration, imsg.data,
151 sizeof(current_duration));
152 if (current_duration < 0)
153 current_duration = -1;
154 break;
155 case IMSG_ERR:
156 if (datalen == 0)
157 errstr = "unknown error";
158 else {
159 errstr = imsg.data;
160 errstr[datalen-1] = '\0';
162 log_warnx("%s; skipping %s", errstr, current_song);
163 playlist_dropcurrent();
164 /* fallthrough */
165 case IMSG_EOF:
166 if (repeat_one && current_song != NULL) {
167 if (main_play_song(current_song))
168 break;
169 playlist_dropcurrent();
171 main_playlist_advance();
172 if (play_state == STATE_PLAYING)
173 control_notify(IMSG_CTL_NEXT);
174 else
175 control_notify(IMSG_CTL_STOP);
176 break;
177 default:
178 log_debug("%s: error handling imsg %d", __func__,
179 imsg.hdr.type);
180 break;
182 imsg_free(&imsg);
185 if (!shut)
186 imsg_event_add(iev);
187 else {
188 /* This pipe is dead. Remove its event handler. */
189 event_del(&iev->ev);
190 event_loopexit(NULL);
194 static pid_t
195 start_child(enum amused_process proc, int fd)
197 const char *argv[7];
198 int argc = 0;
199 pid_t pid;
201 if (fd == -1 && debug)
202 goto exec;
204 switch (pid = fork()) {
205 case -1:
206 fatal("cannot fork");
207 case 0:
208 break;
209 default:
210 close(fd);
211 return pid;
214 if (fd != 3) {
215 if (fd != -1 && dup2(fd, 3) == -1)
216 fatal("cannot setup imsg fd");
217 } else if (fcntl(F_SETFD, 0) == -1)
218 fatal("cannot setup imsg fd");
220 exec:
221 argv[argc++] = argv0;
223 switch (proc) {
224 case PROC_MAIN:
225 argv[argc++] = "-s";
226 argv[argc++] = csock;
227 argv[argc++] = "-Tm";
228 break;
229 case PROC_PLAYER:
230 argv[argc++] = "-Tp";
231 break;
234 if (debug)
235 argv[argc++] = "-d";
236 if (verbose)
237 argv[argc++] = "-v";
238 argv[argc++] = NULL;
240 /* obnoxious casts */
241 execvp(argv0, (char *const *)argv);
242 fatal("execvp %s", argv0);
245 /* daemon main routine */
246 static __dead void
247 amused_main(void)
249 int pipe_main2player[2];
250 int control_fd;
252 log_init(debug, LOG_DAEMON);
253 log_setverbose(verbose);
254 log_procinit("main");
256 if (!debug)
257 daemon(1, 0);
259 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
260 PF_UNSPEC, pipe_main2player) == -1)
261 fatal("socketpair");
263 player_pid = start_child(PROC_PLAYER, pipe_main2player[1]);
265 event_init();
267 signal_set(&ev_sigint, SIGINT, main_sig_handler, NULL);
268 signal_set(&ev_sigterm, SIGTERM, main_sig_handler, NULL);
270 signal_add(&ev_sigint, NULL);
271 signal_add(&ev_sigterm, NULL);
273 signal(SIGHUP, SIG_IGN);
274 signal(SIGCHLD, SIG_IGN);
275 signal(SIGPIPE, SIG_IGN);
277 iev_player = xmalloc(sizeof(*iev_player));
278 imsg_init(&iev_player->ibuf, pipe_main2player[0]);
279 iev_player->handler = main_dispatch_player;
280 iev_player->events = EV_READ;
281 event_set(&iev_player->ev, iev_player->ibuf.fd, iev_player->events,
282 iev_player->handler, iev_player);
283 event_add(&iev_player->ev, NULL);
285 if ((control_fd = control_init(csock)) == -1)
286 fatal("control socket setup failed %s", csock);
287 control_listen(control_fd);
289 if (pledge("stdio rpath unix sendfd", NULL) == -1)
290 fatal("pledge");
292 log_info("startup");
293 event_dispatch();
294 main_shutdown();
297 int
298 main(int argc, char **argv)
300 int ch, proc = -1;
302 log_init(1, LOG_DAEMON); /* Log to stderr until daemonized */
303 log_setverbose(1);
305 argv0 = argv[0];
306 if (argv0 == NULL)
307 argv0 = "amused";
309 while ((ch = getopt(argc, argv, "ds:T:v")) != -1) {
310 switch (ch) {
311 case 'd':
312 debug = 1;
313 break;
314 case 's':
315 free(csock);
316 csock = xstrdup(optarg);
317 break;
318 case 'T':
319 switch (*optarg) {
320 case 'm':
321 proc = PROC_MAIN;
322 break;
323 case 'p':
324 proc = PROC_PLAYER;
325 break;
326 default:
327 usage();
329 break;
330 case 'v':
331 verbose++;
332 break;
333 default:
334 usage();
337 argv += optind;
338 argc -= optind;
340 if (proc == PROC_MAIN)
341 amused_main();
342 if (proc == PROC_PLAYER)
343 exit(player(debug, verbose));
345 if (csock == NULL)
346 xasprintf(&csock, "/tmp/amused-%d", getuid());
348 if (argc > 0)
349 debug = 0;
351 ctl(argc, argv);
354 void
355 spawn_daemon(void)
357 start_child(PROC_MAIN, -1);
360 void
361 imsg_event_add(struct imsgev *iev)
363 iev->events = EV_READ;
364 if (iev->ibuf.w.queued)
365 iev->events |= EV_WRITE;
367 event_del(&iev->ev);
368 event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev);
369 event_add(&iev->ev, NULL);
372 int
373 imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
374 pid_t pid, int fd, const void *data, uint16_t datalen)
376 int ret;
378 if ((ret = imsg_compose(&iev->ibuf, type, peerid, pid, fd, data,
379 datalen)) != -1)
380 imsg_event_add(iev);
382 return ret;
385 int
386 main_send_player(uint16_t type, int fd, const void *data, size_t len)
388 return imsg_compose_event(iev_player, type, 0, 0, fd, data, len);
391 int
392 main_play_song(const char *path)
394 struct stat sb;
395 int fd;
397 if ((fd = open(path, O_RDONLY)) == -1) {
398 log_warn("open %s", path);
399 return 0;
402 if (fstat(fd, &sb) == -1) {
403 log_warn("failed to stat %s", path);
404 close(fd);
405 return 0;
408 if (!S_ISREG(sb.st_mode)) {
409 log_info("skipping non-regular file: %s", path);
410 close(fd);
411 return 0;
414 play_state = STATE_PLAYING;
415 main_send_player(IMSG_PLAY, fd, NULL, 0);
416 return 1;
419 void
420 main_playlist_jump(struct imsgev *iev, struct imsg *imsg)
422 size_t datalen;
423 char arg[PATH_MAX];
424 const char *song;
426 datalen = IMSG_DATA_SIZE(*imsg);
427 if (datalen != sizeof(arg)) {
428 main_senderr(iev, "wrong size");
429 return;
432 memcpy(arg, imsg->data, sizeof(arg));
433 if (arg[sizeof(arg)-1] != '\0') {
434 main_senderr(iev, "data corrupted");
435 return;
438 song = playlist_jump(arg);
439 if (song == NULL) {
440 main_senderr(iev, "not found");
441 return;
444 control_notify(IMSG_CTL_JUMP);
446 main_send_player(IMSG_STOP, -1, NULL, 0);
447 if (!main_play_song(song)) {
448 main_senderr(iev, "can't play");
449 playlist_dropcurrent();
450 main_playlist_advance();
451 return;
454 main_send_status(iev);
457 void
458 main_playlist_resume(void)
460 const char *song;
462 if ((song = current_song) == NULL)
463 song = playlist_advance();
465 for (; song != NULL; song = playlist_advance()) {
466 if (main_play_song(song))
467 return;
469 playlist_dropcurrent();
473 void
474 main_playlist_advance(void)
476 const char *song;
478 for (;;) {
479 song = playlist_advance();
480 if (song == NULL)
481 return;
483 if (main_play_song(song))
484 break;
486 playlist_dropcurrent();
490 void
491 main_playlist_previous(void)
493 const char *song;
495 for (;;) {
496 song = playlist_previous();
497 if (song == NULL)
498 return;
500 if (main_play_song(song))
501 break;
503 playlist_dropcurrent();
507 void
508 main_senderr(struct imsgev *iev, const char *msg)
510 imsg_compose_event(iev, IMSG_CTL_ERR, 0, 0, -1,
511 msg, strlen(msg)+1);
514 void
515 main_enqueue(int tx, struct playlist *px, struct imsgev *iev,
516 struct imsg *imsg)
518 size_t datalen;
519 char path[PATH_MAX];
520 const char *err = NULL;
522 datalen = IMSG_DATA_SIZE(*imsg);
523 if (datalen != sizeof(path)) {
524 err = "data size mismatch";
525 goto err;
528 memcpy(path, imsg->data, sizeof(path));
529 if (path[datalen-1] != '\0') {
530 err = "malformed data";
531 goto err;
534 if (tx)
535 playlist_push(px, path);
536 else
537 playlist_enqueue(path);
538 imsg_compose_event(iev, IMSG_CTL_ADD, 0, 0, -1, path, sizeof(path));
539 return;
540 err:
541 main_senderr(iev, err);
544 void
545 main_send_playlist(struct imsgev *iev)
547 struct player_status s;
548 size_t i;
550 for (i = 0; i < playlist.len; ++i) {
551 memset(&s, 0, sizeof(s));
552 strlcpy(s.path, playlist.songs[i], sizeof(s.path));
553 s.status = play_off == i ? STATE_PLAYING : STATE_STOPPED;
554 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, &s,
555 sizeof(s));
558 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
561 void
562 main_send_status(struct imsgev *iev)
564 struct player_status s;
566 memset(&s, 0, sizeof(s));
568 if (current_song != NULL)
569 strlcpy(s.path, current_song, sizeof(s.path));
570 s.status = play_state;
571 s.position = current_position;
572 s.duration = current_duration;
573 s.rp.repeat_all = repeat_all;
574 s.rp.repeat_one = repeat_one;
576 imsg_compose_event(iev, IMSG_CTL_STATUS, 0, 0, -1, &s, sizeof(s));
579 void
580 main_seek(struct player_seek *s)
582 switch (play_state) {
583 case STATE_STOPPED:
584 main_playlist_resume();
585 break;
586 case STATE_PLAYING:
587 break;
588 case STATE_PAUSED:
589 play_state = STATE_PLAYING;
590 break;
593 notify_seek = 1;
594 main_send_player(IMSG_CTL_SEEK, -1, s, sizeof(*s));