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->imsgbuf.w);
63 close(iev_player->imsgbuf.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 *imsgbuf = &iev->imsgbuf;
105 struct imsg imsg;
106 struct ibuf ibuf;
107 size_t datalen;
108 ssize_t n;
109 int shut = 0;
111 if (event & POLLIN) {
112 if ((n = imsg_read(imsgbuf)) == -1 && errno != EAGAIN)
113 fatal("imsg_read error");
114 if (n == 0) /* Connection closed */
115 shut = 1;
117 if (event & POLLOUT) {
118 if ((n = msgbuf_write(&imsgbuf->w)) == -1 && errno != EAGAIN)
119 fatal("msgbuf_write");
120 if (n == 0) /* Connection closed */
121 shut = 1;
124 for (;;) {
125 if ((n = imsg_get(imsgbuf, &imsg)) == -1)
126 fatal("imsg_get");
127 if (n == 0) /* No more messages. */
128 break;
130 switch (imsg_get_type(&imsg)) {
131 case IMSG_POS:
132 if (imsg_get_data(&imsg, &current_position,
133 sizeof(current_position)) == -1)
134 fatalx("IMSG_POS: got wrong size");
135 if (current_position < 0)
136 current_position = -1;
137 control_notify(IMSG_CTL_SEEK);
138 break;
139 case IMSG_LEN:
140 if (imsg_get_data(&imsg, &current_duration,
141 sizeof(current_duration)) == -1)
142 fatalx("IMSG_LEN: got wrong size");
143 if (current_duration < 0)
144 current_duration = -1;
145 break;
146 case IMSG_ERR:
147 if (imsg_get_ibuf(&imsg, &ibuf) == -1 ||
148 (datalen = ibuf_size(&ibuf)) == 0)
149 errstr = "unknown error";
150 else {
151 errstr = ibuf_data(&ibuf);
152 errstr[datalen-1] = '\0';
154 log_warnx("%s; skipping %s", errstr, current_song);
155 playlist_dropcurrent();
156 main_playlist_advance();
157 if (play_state == STATE_PLAYING)
158 control_notify(IMSG_CTL_NEXT);
159 else
160 control_notify(IMSG_CTL_STOP);
161 break;
162 case IMSG_EOF:
163 if (repeat_one && main_play_song(current_song))
164 break;
165 else if (repeat_one || consume)
166 playlist_dropcurrent();
167 main_playlist_advance();
168 if (play_state == STATE_PLAYING)
169 control_notify(IMSG_CTL_NEXT);
170 else
171 control_notify(IMSG_CTL_STOP);
172 break;
173 default:
174 log_debug("%s: error handling imsg %d", __func__,
175 imsg_get_type(&imsg));
176 break;
178 imsg_free(&imsg);
181 if (shut)
182 ev_break();
183 else
184 imsg_event_add(iev);
187 static pid_t
188 start_child(enum amused_process proc, int fd)
190 const char *argv[7];
191 int argc = 0;
192 pid_t pid;
194 if (fd == -1 && debug)
195 goto exec;
197 switch (pid = fork()) {
198 case -1:
199 fatal("cannot fork");
200 case 0:
201 break;
202 default:
203 close(fd);
204 return pid;
207 if (fd != 3) {
208 if (fd != -1 && dup2(fd, 3) == -1)
209 fatal("cannot setup imsg fd");
210 } else if (fcntl(F_SETFD, 0) == -1)
211 fatal("cannot setup imsg fd");
213 exec:
214 argv[argc++] = argv0;
216 switch (proc) {
217 case PROC_MAIN:
218 argv[argc++] = "-s";
219 argv[argc++] = csock;
220 argv[argc++] = "-Tm";
221 break;
222 case PROC_PLAYER:
223 argv[argc++] = "-Tp";
224 break;
227 if (debug)
228 argv[argc++] = "-d";
229 if (verbose)
230 argv[argc++] = "-v";
231 argv[argc++] = NULL;
233 /* obnoxious casts */
234 execvp(argv0, (char *const *)argv);
235 fatal("execvp %s", argv0);
238 /* daemon main routine */
239 static __dead void
240 amused_main(void)
242 int pipe_main2player[2];
243 int control_fd, flags;
245 log_init(debug, LOG_DAEMON);
246 log_setverbose(verbose);
247 log_procinit("main");
249 if (!debug)
250 daemon(1, 0);
252 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, pipe_main2player) == -1)
253 fatal("socketpair");
255 if ((flags = fcntl(pipe_main2player[0], F_GETFL)) == -1 ||
256 fcntl(pipe_main2player[0], F_SETFL, flags | O_NONBLOCK) == -1 ||
257 (flags = fcntl(pipe_main2player[1], F_GETFL)) == -1 ||
258 fcntl(pipe_main2player[1], F_SETFL, flags | O_NONBLOCK) == -1)
259 fatal("fcntl(O_NONBLOCK)");
261 if (fcntl(pipe_main2player[0], F_SETFD, FD_CLOEXEC) == -1 ||
262 fcntl(pipe_main2player[1], F_SETFD, FD_CLOEXEC) == -1)
263 fatal("fcntl(CLOEXEC)");
265 player_pid = start_child(PROC_PLAYER, pipe_main2player[1]);
267 if (ev_init() == -1)
268 fatal("ev_init");
270 signal(SIGHUP, SIG_IGN);
271 signal(SIGCHLD, SIG_IGN);
272 signal(SIGPIPE, SIG_IGN);
274 ev_signal(SIGINT, main_sig_handler, NULL);
275 ev_signal(SIGTERM, main_sig_handler, NULL);
277 iev_player = xmalloc(sizeof(*iev_player));
278 imsg_init(&iev_player->imsgbuf, pipe_main2player[0]);
279 iev_player->handler = main_dispatch_player;
280 iev_player->events = POLLIN;
281 ev_add(iev_player->imsgbuf.fd, iev_player->events,
282 iev_player->handler, iev_player);
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 ev_loop();
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 const char *tmpdir;
347 if ((tmpdir = getenv("TMPDIR")) == NULL)
348 tmpdir = "/tmp";
350 xasprintf(&csock, "%s/amused-%d", tmpdir, getuid());
353 if (argc > 0)
354 debug = 0;
356 ctl(argc, argv);
359 void
360 spawn_daemon(void)
362 start_child(PROC_MAIN, -1);
365 void
366 imsg_event_add(struct imsgev *iev)
368 iev->events = POLLIN;
369 if (iev->imsgbuf.w.queued)
370 iev->events |= POLLOUT;
372 ev_add(iev->imsgbuf.fd, iev->events, iev->handler, iev);
375 int
376 imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
377 pid_t pid, int fd, const void *data, uint16_t datalen)
379 int ret;
381 if ((ret = imsg_compose(&iev->imsgbuf, type, peerid, pid, fd, data,
382 datalen)) != -1)
383 imsg_event_add(iev);
385 return ret;
388 int
389 main_send_player(uint16_t type, int fd, const void *data, size_t len)
391 return imsg_compose_event(iev_player, type, 0, 0, fd, data, len);
394 int
395 main_play_song(const char *path)
397 struct stat sb;
398 int fd;
400 if ((fd = open(path, O_RDONLY)) == -1) {
401 log_warn("open %s", path);
402 return 0;
405 if (fstat(fd, &sb) == -1) {
406 log_warn("failed to stat %s", path);
407 close(fd);
408 return 0;
411 if (!S_ISREG(sb.st_mode)) {
412 log_info("skipping non-regular file: %s", path);
413 close(fd);
414 return 0;
417 play_state = STATE_PLAYING;
418 main_send_player(IMSG_PLAY, fd, NULL, 0);
419 return 1;
422 void
423 main_playlist_jump(struct imsgev *iev, struct imsg *imsg)
425 char arg[PATH_MAX];
426 const char *song;
428 if (imsg_get_data(imsg, arg, sizeof(arg)) == -1) {
429 main_senderr(iev, "wrong size");
430 return;
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 char path[PATH_MAX];
519 const char *err = NULL;
521 if (imsg_get_data(imsg, path, sizeof(path)) == -1) {
522 err = "data size mismatch";
523 goto err;
526 if (path[sizeof(path)-1] != '\0') {
527 err = "malformed data";
528 goto err;
531 if (tx)
532 playlist_push(px, path);
533 else
534 playlist_enqueue(path);
535 imsg_compose_event(iev, IMSG_CTL_ADD, 0, 0, -1, path, sizeof(path));
536 return;
537 err:
538 main_senderr(iev, err);
541 void
542 main_send_playlist(struct imsgev *iev)
544 struct player_status s;
545 size_t i;
547 for (i = 0; i < playlist.len; ++i) {
548 memset(&s, 0, sizeof(s));
549 strlcpy(s.path, playlist.songs[i], sizeof(s.path));
550 s.status = play_off == i ? STATE_PLAYING : STATE_STOPPED;
551 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, &s,
552 sizeof(s));
555 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
558 void
559 main_send_status(struct imsgev *iev)
561 struct player_status s;
563 memset(&s, 0, sizeof(s));
565 if (current_song != NULL)
566 strlcpy(s.path, current_song, sizeof(s.path));
567 s.status = play_state;
568 s.position = current_position;
569 s.duration = current_duration;
570 s.mode.repeat_all = repeat_all;
571 s.mode.repeat_one = repeat_one;
572 s.mode.consume = consume;
574 imsg_compose_event(iev, IMSG_CTL_STATUS, 0, 0, -1, &s, sizeof(s));
577 void
578 main_seek(struct player_seek *s)
580 switch (play_state) {
581 case STATE_STOPPED:
582 main_playlist_resume();
583 break;
584 case STATE_PLAYING:
585 break;
586 case STATE_PAUSED:
587 play_state = STATE_PLAYING;
588 break;
591 main_send_player(IMSG_CTL_SEEK, -1, s, sizeof(*s));