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 control_notify(IMSG_CTL_SEEK);
140 break;
141 case IMSG_LEN:
142 if (datalen != sizeof(current_duration))
143 fatalx("IMSG_LEN: got wrong size (%zu vs %zu)",
144 datalen, sizeof(current_duration));
145 memcpy(&current_duration, imsg.data,
146 sizeof(current_duration));
147 if (current_duration < 0)
148 current_duration = -1;
149 break;
150 case IMSG_ERR:
151 if (datalen == 0)
152 errstr = "unknown error";
153 else {
154 errstr = imsg.data;
155 errstr[datalen-1] = '\0';
157 log_warnx("%s; skipping %s", errstr, current_song);
158 playlist_dropcurrent();
159 main_playlist_advance();
160 if (play_state == STATE_PLAYING)
161 control_notify(IMSG_CTL_NEXT);
162 else
163 control_notify(IMSG_CTL_STOP);
164 break;
165 case IMSG_EOF:
166 if (repeat_one && main_play_song(current_song))
167 break;
168 else if (repeat_one || consume)
169 playlist_dropcurrent();
170 main_playlist_advance();
171 if (play_state == STATE_PLAYING)
172 control_notify(IMSG_CTL_NEXT);
173 else
174 control_notify(IMSG_CTL_STOP);
175 break;
176 default:
177 log_debug("%s: error handling imsg %d", __func__,
178 imsg.hdr.type);
179 break;
181 imsg_free(&imsg);
184 if (!shut)
185 imsg_event_add(iev);
186 else {
187 /* This pipe is dead. Remove its event handler. */
188 event_del(&iev->ev);
189 event_loopexit(NULL);
193 static pid_t
194 start_child(enum amused_process proc, int fd)
196 const char *argv[7];
197 int argc = 0;
198 pid_t pid;
200 if (fd == -1 && debug)
201 goto exec;
203 switch (pid = fork()) {
204 case -1:
205 fatal("cannot fork");
206 case 0:
207 break;
208 default:
209 close(fd);
210 return pid;
213 if (fd != 3) {
214 if (fd != -1 && dup2(fd, 3) == -1)
215 fatal("cannot setup imsg fd");
216 } else if (fcntl(F_SETFD, 0) == -1)
217 fatal("cannot setup imsg fd");
219 exec:
220 argv[argc++] = argv0;
222 switch (proc) {
223 case PROC_MAIN:
224 argv[argc++] = "-s";
225 argv[argc++] = csock;
226 argv[argc++] = "-Tm";
227 break;
228 case PROC_PLAYER:
229 argv[argc++] = "-Tp";
230 break;
233 if (debug)
234 argv[argc++] = "-d";
235 if (verbose)
236 argv[argc++] = "-v";
237 argv[argc++] = NULL;
239 /* obnoxious casts */
240 execvp(argv0, (char *const *)argv);
241 fatal("execvp %s", argv0);
244 /* daemon main routine */
245 static __dead void
246 amused_main(void)
248 int pipe_main2player[2];
249 int control_fd;
251 log_init(debug, LOG_DAEMON);
252 log_setverbose(verbose);
253 log_procinit("main");
255 if (!debug)
256 daemon(1, 0);
258 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
259 PF_UNSPEC, pipe_main2player) == -1)
260 fatal("socketpair");
262 player_pid = start_child(PROC_PLAYER, pipe_main2player[1]);
264 event_init();
266 signal_set(&ev_sigint, SIGINT, main_sig_handler, NULL);
267 signal_set(&ev_sigterm, SIGTERM, main_sig_handler, NULL);
269 signal_add(&ev_sigint, NULL);
270 signal_add(&ev_sigterm, NULL);
272 signal(SIGHUP, SIG_IGN);
273 signal(SIGCHLD, SIG_IGN);
274 signal(SIGPIPE, SIG_IGN);
276 iev_player = xmalloc(sizeof(*iev_player));
277 imsg_init(&iev_player->ibuf, pipe_main2player[0]);
278 iev_player->handler = main_dispatch_player;
279 iev_player->events = EV_READ;
280 event_set(&iev_player->ev, iev_player->ibuf.fd, iev_player->events,
281 iev_player->handler, iev_player);
282 event_add(&iev_player->ev, NULL);
284 if ((control_fd = control_init(csock)) == -1)
285 fatal("control socket setup failed %s", csock);
286 control_listen(control_fd);
288 if (pledge("stdio rpath unix sendfd", NULL) == -1)
289 fatal("pledge");
291 log_info("startup");
292 event_dispatch();
293 main_shutdown();
296 int
297 main(int argc, char **argv)
299 int ch, proc = -1;
301 log_init(1, LOG_DAEMON); /* Log to stderr until daemonized */
302 log_setverbose(1);
304 argv0 = argv[0];
305 if (argv0 == NULL)
306 argv0 = "amused";
308 while ((ch = getopt(argc, argv, "ds:T:v")) != -1) {
309 switch (ch) {
310 case 'd':
311 debug = 1;
312 break;
313 case 's':
314 free(csock);
315 csock = xstrdup(optarg);
316 break;
317 case 'T':
318 switch (*optarg) {
319 case 'm':
320 proc = PROC_MAIN;
321 break;
322 case 'p':
323 proc = PROC_PLAYER;
324 break;
325 default:
326 usage();
328 break;
329 case 'v':
330 verbose++;
331 break;
332 default:
333 usage();
336 argv += optind;
337 argc -= optind;
339 if (proc == PROC_MAIN)
340 amused_main();
341 if (proc == PROC_PLAYER)
342 exit(player(debug, verbose));
344 if (csock == NULL)
345 xasprintf(&csock, "/tmp/amused-%d", getuid());
347 if (argc > 0)
348 debug = 0;
350 ctl(argc, argv);
353 void
354 spawn_daemon(void)
356 start_child(PROC_MAIN, -1);
359 void
360 imsg_event_add(struct imsgev *iev)
362 iev->events = EV_READ;
363 if (iev->ibuf.w.queued)
364 iev->events |= EV_WRITE;
366 event_del(&iev->ev);
367 event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev);
368 event_add(&iev->ev, NULL);
371 int
372 imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
373 pid_t pid, int fd, const void *data, uint16_t datalen)
375 int ret;
377 if ((ret = imsg_compose(&iev->ibuf, type, peerid, pid, fd, data,
378 datalen)) != -1)
379 imsg_event_add(iev);
381 return ret;
384 int
385 main_send_player(uint16_t type, int fd, const void *data, size_t len)
387 return imsg_compose_event(iev_player, type, 0, 0, fd, data, len);
390 int
391 main_play_song(const char *path)
393 struct stat sb;
394 int fd;
396 if ((fd = open(path, O_RDONLY)) == -1) {
397 log_warn("open %s", path);
398 return 0;
401 if (fstat(fd, &sb) == -1) {
402 log_warn("failed to stat %s", path);
403 close(fd);
404 return 0;
407 if (!S_ISREG(sb.st_mode)) {
408 log_info("skipping non-regular file: %s", path);
409 close(fd);
410 return 0;
413 play_state = STATE_PLAYING;
414 main_send_player(IMSG_PLAY, fd, NULL, 0);
415 return 1;
418 void
419 main_playlist_jump(struct imsgev *iev, struct imsg *imsg)
421 size_t datalen;
422 char arg[PATH_MAX];
423 const char *song;
425 datalen = IMSG_DATA_SIZE(*imsg);
426 if (datalen != sizeof(arg)) {
427 main_senderr(iev, "wrong size");
428 return;
431 memcpy(arg, imsg->data, sizeof(arg));
432 if (arg[sizeof(arg)-1] != '\0') {
433 main_senderr(iev, "data corrupted");
434 return;
437 song = playlist_jump(arg);
438 if (song == NULL) {
439 main_senderr(iev, "not found");
440 return;
443 control_notify(IMSG_CTL_JUMP);
445 main_send_player(IMSG_STOP, -1, NULL, 0);
446 if (!main_play_song(song)) {
447 main_senderr(iev, "can't play");
448 playlist_dropcurrent();
449 main_playlist_advance();
450 return;
453 main_send_status(iev);
456 void
457 main_playlist_resume(void)
459 const char *song;
461 if ((song = current_song) == NULL)
462 song = playlist_advance();
464 for (; song != NULL; song = playlist_advance()) {
465 if (main_play_song(song))
466 return;
468 playlist_dropcurrent();
472 void
473 main_playlist_advance(void)
475 const char *song;
477 for (;;) {
478 song = playlist_advance();
479 if (song == NULL)
480 return;
482 if (main_play_song(song))
483 break;
485 playlist_dropcurrent();
489 void
490 main_playlist_previous(void)
492 const char *song;
494 for (;;) {
495 song = playlist_previous();
496 if (song == NULL)
497 return;
499 if (main_play_song(song))
500 break;
502 playlist_dropcurrent();
506 void
507 main_senderr(struct imsgev *iev, const char *msg)
509 imsg_compose_event(iev, IMSG_CTL_ERR, 0, 0, -1,
510 msg, strlen(msg)+1);
513 void
514 main_enqueue(int tx, struct playlist *px, struct imsgev *iev,
515 struct imsg *imsg)
517 size_t datalen;
518 char path[PATH_MAX];
519 const char *err = NULL;
521 datalen = IMSG_DATA_SIZE(*imsg);
522 if (datalen != sizeof(path)) {
523 err = "data size mismatch";
524 goto err;
527 memcpy(path, imsg->data, sizeof(path));
528 if (path[datalen-1] != '\0') {
529 err = "malformed data";
530 goto err;
533 if (tx)
534 playlist_push(px, path);
535 else
536 playlist_enqueue(path);
537 imsg_compose_event(iev, IMSG_CTL_ADD, 0, 0, -1, path, sizeof(path));
538 return;
539 err:
540 main_senderr(iev, err);
543 void
544 main_send_playlist(struct imsgev *iev)
546 struct player_status s;
547 size_t i;
549 for (i = 0; i < playlist.len; ++i) {
550 memset(&s, 0, sizeof(s));
551 strlcpy(s.path, playlist.songs[i], sizeof(s.path));
552 s.status = play_off == i ? STATE_PLAYING : STATE_STOPPED;
553 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, &s,
554 sizeof(s));
557 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
560 void
561 main_send_status(struct imsgev *iev)
563 struct player_status s;
565 memset(&s, 0, sizeof(s));
567 if (current_song != NULL)
568 strlcpy(s.path, current_song, sizeof(s.path));
569 s.status = play_state;
570 s.position = current_position;
571 s.duration = current_duration;
572 s.mode.repeat_all = repeat_all;
573 s.mode.repeat_one = repeat_one;
574 s.mode.consume = consume;
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 main_send_player(IMSG_CTL_SEEK, -1, s, sizeof(*s));