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 size_t datalen;
107 ssize_t n;
108 int shut = 0;
110 if (event & POLLIN) {
111 if ((n = imsg_read(imsgbuf)) == -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(&imsgbuf->w)) == -1 && errno != EAGAIN)
118 fatal("msgbuf_write");
119 if (n == 0) /* Connection closed */
120 shut = 1;
123 for (;;) {
124 if ((n = imsg_get(imsgbuf, &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->imsgbuf, pipe_main2player[0]);
282 iev_player->handler = main_dispatch_player;
283 iev_player->events = POLLIN;
284 ev_add(iev_player->imsgbuf.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 const char *tmpdir;
350 if ((tmpdir = getenv("TMPDIR")) == NULL)
351 tmpdir = "/tmp";
353 xasprintf(&csock, "%s/amused-%d", tmpdir, getuid());
356 if (argc > 0)
357 debug = 0;
359 ctl(argc, argv);
362 void
363 spawn_daemon(void)
365 start_child(PROC_MAIN, -1);
368 void
369 imsg_event_add(struct imsgev *iev)
371 iev->events = POLLIN;
372 if (iev->imsgbuf.w.queued)
373 iev->events |= POLLOUT;
375 ev_add(iev->imsgbuf.fd, iev->events, iev->handler, iev);
378 int
379 imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
380 pid_t pid, int fd, const void *data, uint16_t datalen)
382 int ret;
384 if ((ret = imsg_compose(&iev->imsgbuf, type, peerid, pid, fd, data,
385 datalen)) != -1)
386 imsg_event_add(iev);
388 return ret;
391 int
392 main_send_player(uint16_t type, int fd, const void *data, size_t len)
394 return imsg_compose_event(iev_player, type, 0, 0, fd, data, len);
397 int
398 main_play_song(const char *path)
400 struct stat sb;
401 int fd;
403 if ((fd = open(path, O_RDONLY)) == -1) {
404 log_warn("open %s", path);
405 return 0;
408 if (fstat(fd, &sb) == -1) {
409 log_warn("failed to stat %s", path);
410 close(fd);
411 return 0;
414 if (!S_ISREG(sb.st_mode)) {
415 log_info("skipping non-regular file: %s", path);
416 close(fd);
417 return 0;
420 play_state = STATE_PLAYING;
421 main_send_player(IMSG_PLAY, fd, NULL, 0);
422 return 1;
425 void
426 main_playlist_jump(struct imsgev *iev, struct imsg *imsg)
428 size_t datalen;
429 char arg[PATH_MAX];
430 const char *song;
432 datalen = IMSG_DATA_SIZE(*imsg);
433 if (datalen != sizeof(arg)) {
434 main_senderr(iev, "wrong size");
435 return;
438 memcpy(arg, imsg->data, sizeof(arg));
439 if (arg[sizeof(arg)-1] != '\0') {
440 main_senderr(iev, "data corrupted");
441 return;
444 song = playlist_jump(arg);
445 if (song == NULL) {
446 main_senderr(iev, "not found");
447 return;
450 control_notify(IMSG_CTL_JUMP);
452 main_send_player(IMSG_STOP, -1, NULL, 0);
453 if (!main_play_song(song)) {
454 main_senderr(iev, "can't play");
455 playlist_dropcurrent();
456 main_playlist_advance();
457 return;
460 main_send_status(iev);
463 void
464 main_playlist_resume(void)
466 const char *song;
468 if ((song = current_song) == NULL)
469 song = playlist_advance();
471 for (; song != NULL; song = playlist_advance()) {
472 if (main_play_song(song))
473 return;
475 playlist_dropcurrent();
479 void
480 main_playlist_advance(void)
482 const char *song;
484 for (;;) {
485 song = playlist_advance();
486 if (song == NULL)
487 return;
489 if (main_play_song(song))
490 break;
492 playlist_dropcurrent();
496 void
497 main_playlist_previous(void)
499 const char *song;
501 for (;;) {
502 song = playlist_previous();
503 if (song == NULL)
504 return;
506 if (main_play_song(song))
507 break;
509 playlist_dropcurrent();
513 void
514 main_senderr(struct imsgev *iev, const char *msg)
516 imsg_compose_event(iev, IMSG_CTL_ERR, 0, 0, -1,
517 msg, strlen(msg)+1);
520 void
521 main_enqueue(int tx, struct playlist *px, struct imsgev *iev,
522 struct imsg *imsg)
524 size_t datalen;
525 char path[PATH_MAX];
526 const char *err = NULL;
528 datalen = IMSG_DATA_SIZE(*imsg);
529 if (datalen != sizeof(path)) {
530 err = "data size mismatch";
531 goto err;
534 memcpy(path, imsg->data, sizeof(path));
535 if (path[datalen-1] != '\0') {
536 err = "malformed data";
537 goto err;
540 if (tx)
541 playlist_push(px, path);
542 else
543 playlist_enqueue(path);
544 imsg_compose_event(iev, IMSG_CTL_ADD, 0, 0, -1, path, sizeof(path));
545 return;
546 err:
547 main_senderr(iev, err);
550 void
551 main_send_playlist(struct imsgev *iev)
553 struct player_status s;
554 size_t i;
556 for (i = 0; i < playlist.len; ++i) {
557 memset(&s, 0, sizeof(s));
558 strlcpy(s.path, playlist.songs[i], sizeof(s.path));
559 s.status = play_off == i ? STATE_PLAYING : STATE_STOPPED;
560 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, &s,
561 sizeof(s));
564 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
567 void
568 main_send_status(struct imsgev *iev)
570 struct player_status s;
572 memset(&s, 0, sizeof(s));
574 if (current_song != NULL)
575 strlcpy(s.path, current_song, sizeof(s.path));
576 s.status = play_state;
577 s.position = current_position;
578 s.duration = current_duration;
579 s.mode.repeat_all = repeat_all;
580 s.mode.repeat_one = repeat_one;
581 s.mode.consume = consume;
583 imsg_compose_event(iev, IMSG_CTL_STATUS, 0, 0, -1, &s, sizeof(s));
586 void
587 main_seek(struct player_seek *s)
589 switch (play_state) {
590 case STATE_STOPPED:
591 main_playlist_resume();
592 break;
593 case STATE_PLAYING:
594 break;
595 case STATE_PAUSED:
596 play_state = STATE_PLAYING;
597 break;
600 main_send_player(IMSG_CTL_SEEK, -1, s, sizeof(*s));