Blob


1 /*
2 * Copyright (c) 2022 Omar Polo <op@omarpolo.com>
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 <poll.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <stdint.h>
31 #include <string.h>
32 #include <syslog.h>
33 #include <unistd.h>
35 #include "amused.h"
36 #include "control.h"
37 #include "ev.h"
38 #include "log.h"
39 #include "playlist.h"
40 #include "xmalloc.h"
42 char *csock = NULL;
43 int debug;
44 int verbose;
45 struct imsgev *iev_player;
47 const char *argv0;
48 pid_t player_pid;
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, int event, void *arg)
83 {
84 /*
85 * Normal signal handler rules don't apply because ev.c
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, int 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 & POLLIN) {
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 & POLLOUT) {
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 ev_break();
186 else
187 imsg_event_add(iev);
190 static pid_t
191 start_child(enum amused_process proc, int fd)
193 const char *argv[7];
194 int argc = 0;
195 pid_t pid;
197 if (fd == -1 && debug)
198 goto exec;
200 switch (pid = fork()) {
201 case -1:
202 fatal("cannot fork");
203 case 0:
204 break;
205 default:
206 close(fd);
207 return pid;
210 if (fd != 3) {
211 if (fd != -1 && dup2(fd, 3) == -1)
212 fatal("cannot setup imsg fd");
213 } else if (fcntl(F_SETFD, 0) == -1)
214 fatal("cannot setup imsg fd");
216 exec:
217 argv[argc++] = argv0;
219 switch (proc) {
220 case PROC_MAIN:
221 argv[argc++] = "-s";
222 argv[argc++] = csock;
223 argv[argc++] = "-Tm";
224 break;
225 case PROC_PLAYER:
226 argv[argc++] = "-Tp";
227 break;
230 if (debug)
231 argv[argc++] = "-d";
232 if (verbose)
233 argv[argc++] = "-v";
234 argv[argc++] = NULL;
236 /* obnoxious casts */
237 execvp(argv0, (char *const *)argv);
238 fatal("execvp %s", argv0);
241 /* daemon main routine */
242 static __dead void
243 amused_main(void)
245 int pipe_main2player[2];
246 int control_fd, flags;
248 log_init(debug, LOG_DAEMON);
249 log_setverbose(verbose);
250 log_procinit("main");
252 if (!debug)
253 daemon(1, 0);
255 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe_main2player) == -1)
256 fatal("socketpair");
258 if ((flags = fcntl(pipe_main2player[0], F_GETFL)) == -1 ||
259 fcntl(pipe_main2player[0], F_SETFL, flags | O_NONBLOCK) == -1 ||
260 (flags = fcntl(pipe_main2player[1], F_GETFL)) == -1 ||
261 fcntl(pipe_main2player[1], F_SETFL, flags | O_NONBLOCK) == -1)
262 fatal("fcntl(O_NONBLOCK)");
264 if (fcntl(pipe_main2player[0], F_SETFD, FD_CLOEXEC) == -1 ||
265 fcntl(pipe_main2player[1], F_SETFD, FD_CLOEXEC) == -1)
266 fatal("fcntl(CLOEXEC)");
268 player_pid = start_child(PROC_PLAYER, pipe_main2player[1]);
270 if (ev_init() == -1)
271 fatal("ev_init");
273 signal(SIGHUP, SIG_IGN);
274 signal(SIGCHLD, SIG_IGN);
275 signal(SIGPIPE, SIG_IGN);
277 ev_signal(SIGINT, main_sig_handler, NULL);
278 ev_signal(SIGTERM, main_sig_handler, NULL);
280 iev_player = xmalloc(sizeof(*iev_player));
281 imsg_init(&iev_player->ibuf, pipe_main2player[0]);
282 iev_player->handler = main_dispatch_player;
283 iev_player->events = POLLIN;
284 ev_add(iev_player->ibuf.fd, iev_player->events,
285 iev_player->handler, iev_player);
287 if ((control_fd = control_init(csock)) == -1)
288 fatal("control socket setup failed %s", csock);
289 control_listen(control_fd);
291 if (pledge("stdio rpath unix sendfd", NULL) == -1)
292 fatal("pledge");
294 log_info("startup");
295 ev_loop();
296 main_shutdown();
299 int
300 main(int argc, char **argv)
302 int ch, proc = -1;
304 log_init(1, LOG_DAEMON); /* Log to stderr until daemonized */
305 log_setverbose(1);
307 argv0 = argv[0];
308 if (argv0 == NULL)
309 argv0 = "amused";
311 while ((ch = getopt(argc, argv, "ds:T:v")) != -1) {
312 switch (ch) {
313 case 'd':
314 debug = 1;
315 break;
316 case 's':
317 free(csock);
318 csock = xstrdup(optarg);
319 break;
320 case 'T':
321 switch (*optarg) {
322 case 'm':
323 proc = PROC_MAIN;
324 break;
325 case 'p':
326 proc = PROC_PLAYER;
327 break;
328 default:
329 usage();
331 break;
332 case 'v':
333 verbose++;
334 break;
335 default:
336 usage();
339 argv += optind;
340 argc -= optind;
342 if (proc == PROC_MAIN)
343 amused_main();
344 if (proc == PROC_PLAYER)
345 exit(player(debug, verbose));
347 if (csock == NULL)
348 xasprintf(&csock, "/tmp/amused-%d", getuid());
350 if (argc > 0)
351 debug = 0;
353 ctl(argc, argv);
356 void
357 spawn_daemon(void)
359 start_child(PROC_MAIN, -1);
362 void
363 imsg_event_add(struct imsgev *iev)
365 iev->events = POLLIN;
366 if (iev->ibuf.w.queued)
367 iev->events |= POLLOUT;
369 ev_add(iev->ibuf.fd, iev->events, iev->handler, iev);
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.mode.repeat_all = repeat_all;
574 s.mode.repeat_one = repeat_one;
575 s.mode.consume = consume;
577 imsg_compose_event(iev, IMSG_CTL_STATUS, 0, 0, -1, &s, sizeof(s));
580 void
581 main_seek(struct player_seek *s)
583 switch (play_state) {
584 case STATE_STOPPED:
585 main_playlist_resume();
586 break;
587 case STATE_PLAYING:
588 break;
589 case STATE_PAUSED:
590 play_state = STATE_PLAYING;
591 break;
594 main_send_player(IMSG_CTL_SEEK, -1, s, sizeof(*s));