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;
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 | SOCK_CLOEXEC | SOCK_NONBLOCK,
256 PF_UNSPEC, pipe_main2player) == -1)
257 fatal("socketpair");
259 player_pid = start_child(PROC_PLAYER, pipe_main2player[1]);
261 if (ev_init() == -1)
262 fatal("ev_init");
264 signal(SIGHUP, SIG_IGN);
265 signal(SIGCHLD, SIG_IGN);
266 signal(SIGPIPE, SIG_IGN);
268 ev_signal(SIGINT, main_sig_handler, NULL);
269 ev_signal(SIGTERM, main_sig_handler, NULL);
271 iev_player = xmalloc(sizeof(*iev_player));
272 imsg_init(&iev_player->ibuf, pipe_main2player[0]);
273 iev_player->handler = main_dispatch_player;
274 iev_player->events = POLLIN;
275 ev_add(iev_player->ibuf.fd, iev_player->events,
276 iev_player->handler, iev_player);
278 if ((control_fd = control_init(csock)) == -1)
279 fatal("control socket setup failed %s", csock);
280 control_listen(control_fd);
282 if (pledge("stdio rpath unix sendfd", NULL) == -1)
283 fatal("pledge");
285 log_info("startup");
286 ev_loop();
287 main_shutdown();
290 int
291 main(int argc, char **argv)
293 int ch, proc = -1;
295 log_init(1, LOG_DAEMON); /* Log to stderr until daemonized */
296 log_setverbose(1);
298 argv0 = argv[0];
299 if (argv0 == NULL)
300 argv0 = "amused";
302 while ((ch = getopt(argc, argv, "ds:T:v")) != -1) {
303 switch (ch) {
304 case 'd':
305 debug = 1;
306 break;
307 case 's':
308 free(csock);
309 csock = xstrdup(optarg);
310 break;
311 case 'T':
312 switch (*optarg) {
313 case 'm':
314 proc = PROC_MAIN;
315 break;
316 case 'p':
317 proc = PROC_PLAYER;
318 break;
319 default:
320 usage();
322 break;
323 case 'v':
324 verbose++;
325 break;
326 default:
327 usage();
330 argv += optind;
331 argc -= optind;
333 if (proc == PROC_MAIN)
334 amused_main();
335 if (proc == PROC_PLAYER)
336 exit(player(debug, verbose));
338 if (csock == NULL)
339 xasprintf(&csock, "/tmp/amused-%d", getuid());
341 if (argc > 0)
342 debug = 0;
344 ctl(argc, argv);
347 void
348 spawn_daemon(void)
350 start_child(PROC_MAIN, -1);
353 void
354 imsg_event_add(struct imsgev *iev)
356 iev->events = POLLIN;
357 if (iev->ibuf.w.queued)
358 iev->events |= POLLOUT;
360 ev_add(iev->ibuf.fd, iev->events, iev->handler, iev);
363 int
364 imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
365 pid_t pid, int fd, const void *data, uint16_t datalen)
367 int ret;
369 if ((ret = imsg_compose(&iev->ibuf, type, peerid, pid, fd, data,
370 datalen)) != -1)
371 imsg_event_add(iev);
373 return ret;
376 int
377 main_send_player(uint16_t type, int fd, const void *data, size_t len)
379 return imsg_compose_event(iev_player, type, 0, 0, fd, data, len);
382 int
383 main_play_song(const char *path)
385 struct stat sb;
386 int fd;
388 if ((fd = open(path, O_RDONLY)) == -1) {
389 log_warn("open %s", path);
390 return 0;
393 if (fstat(fd, &sb) == -1) {
394 log_warn("failed to stat %s", path);
395 close(fd);
396 return 0;
399 if (!S_ISREG(sb.st_mode)) {
400 log_info("skipping non-regular file: %s", path);
401 close(fd);
402 return 0;
405 play_state = STATE_PLAYING;
406 main_send_player(IMSG_PLAY, fd, NULL, 0);
407 return 1;
410 void
411 main_playlist_jump(struct imsgev *iev, struct imsg *imsg)
413 size_t datalen;
414 char arg[PATH_MAX];
415 const char *song;
417 datalen = IMSG_DATA_SIZE(*imsg);
418 if (datalen != sizeof(arg)) {
419 main_senderr(iev, "wrong size");
420 return;
423 memcpy(arg, imsg->data, sizeof(arg));
424 if (arg[sizeof(arg)-1] != '\0') {
425 main_senderr(iev, "data corrupted");
426 return;
429 song = playlist_jump(arg);
430 if (song == NULL) {
431 main_senderr(iev, "not found");
432 return;
435 control_notify(IMSG_CTL_JUMP);
437 main_send_player(IMSG_STOP, -1, NULL, 0);
438 if (!main_play_song(song)) {
439 main_senderr(iev, "can't play");
440 playlist_dropcurrent();
441 main_playlist_advance();
442 return;
445 main_send_status(iev);
448 void
449 main_playlist_resume(void)
451 const char *song;
453 if ((song = current_song) == NULL)
454 song = playlist_advance();
456 for (; song != NULL; song = playlist_advance()) {
457 if (main_play_song(song))
458 return;
460 playlist_dropcurrent();
464 void
465 main_playlist_advance(void)
467 const char *song;
469 for (;;) {
470 song = playlist_advance();
471 if (song == NULL)
472 return;
474 if (main_play_song(song))
475 break;
477 playlist_dropcurrent();
481 void
482 main_playlist_previous(void)
484 const char *song;
486 for (;;) {
487 song = playlist_previous();
488 if (song == NULL)
489 return;
491 if (main_play_song(song))
492 break;
494 playlist_dropcurrent();
498 void
499 main_senderr(struct imsgev *iev, const char *msg)
501 imsg_compose_event(iev, IMSG_CTL_ERR, 0, 0, -1,
502 msg, strlen(msg)+1);
505 void
506 main_enqueue(int tx, struct playlist *px, struct imsgev *iev,
507 struct imsg *imsg)
509 size_t datalen;
510 char path[PATH_MAX];
511 const char *err = NULL;
513 datalen = IMSG_DATA_SIZE(*imsg);
514 if (datalen != sizeof(path)) {
515 err = "data size mismatch";
516 goto err;
519 memcpy(path, imsg->data, sizeof(path));
520 if (path[datalen-1] != '\0') {
521 err = "malformed data";
522 goto err;
525 if (tx)
526 playlist_push(px, path);
527 else
528 playlist_enqueue(path);
529 imsg_compose_event(iev, IMSG_CTL_ADD, 0, 0, -1, path, sizeof(path));
530 return;
531 err:
532 main_senderr(iev, err);
535 void
536 main_send_playlist(struct imsgev *iev)
538 struct player_status s;
539 size_t i;
541 for (i = 0; i < playlist.len; ++i) {
542 memset(&s, 0, sizeof(s));
543 strlcpy(s.path, playlist.songs[i], sizeof(s.path));
544 s.status = play_off == i ? STATE_PLAYING : STATE_STOPPED;
545 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, &s,
546 sizeof(s));
549 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
552 void
553 main_send_status(struct imsgev *iev)
555 struct player_status s;
557 memset(&s, 0, sizeof(s));
559 if (current_song != NULL)
560 strlcpy(s.path, current_song, sizeof(s.path));
561 s.status = play_state;
562 s.position = current_position;
563 s.duration = current_duration;
564 s.mode.repeat_all = repeat_all;
565 s.mode.repeat_one = repeat_one;
566 s.mode.consume = consume;
568 imsg_compose_event(iev, IMSG_CTL_STATUS, 0, 0, -1, &s, sizeof(s));
571 void
572 main_seek(struct player_seek *s)
574 switch (play_state) {
575 case STATE_STOPPED:
576 main_playlist_resume();
577 break;
578 case STATE_PLAYING:
579 break;
580 case STATE_PAUSED:
581 play_state = STATE_PLAYING;
582 break;
585 main_send_player(IMSG_CTL_SEEK, -1, s, sizeof(*s));