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 static int notify_seek;
52 enum amused_process {
53 PROC_MAIN,
54 PROC_PLAYER,
55 };
57 static __dead void
58 main_shutdown(void)
59 {
60 pid_t pid;
61 int status;
63 /* close pipes. */
64 msgbuf_clear(&iev_player->ibuf.w);
65 close(iev_player->ibuf.fd);
66 free(iev_player);
68 log_debug("waiting for children to terminate");
69 do {
70 pid = wait(&status);
71 if (pid == -1) {
72 if (errno != EINTR && errno != ECHILD)
73 fatal("wait");
74 } else if (WIFSIGNALED(status))
75 log_warnx("player terminated; signal %d",
76 WTERMSIG(status));
77 } while (pid != -1 || (pid == -1 && errno == EINTR));
79 log_info("terminating");
80 exit(0);
81 }
83 static void
84 main_sig_handler(int sig, short event, void *arg)
85 {
86 /*
87 * Normal signal handler rules don't apply because libevent
88 * decouples for us.
89 */
91 switch (sig) {
92 case SIGTERM:
93 case SIGINT:
94 main_shutdown();
95 break;
96 default:
97 fatalx("unexpected signal %d", sig);
98 }
99 }
101 static void
102 main_dispatch_player(int sig, short event, void *d)
104 char *errstr;
105 struct imsgev *iev = d;
106 struct imsgbuf *ibuf = &iev->ibuf;
107 struct imsg imsg;
108 size_t datalen;
109 ssize_t n;
110 int shut = 0;
112 if (event & EV_READ) {
113 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
114 fatal("imsg_read error");
115 if (n == 0) /* Connection closed */
116 shut = 1;
118 if (event & EV_WRITE) {
119 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
120 fatal("msgbuf_write");
121 if (n == 0) /* Connection closed */
122 shut = 1;
125 for (;;) {
126 if ((n = imsg_get(ibuf, &imsg)) == -1)
127 fatal("imsg_get");
128 if (n == 0) /* No more messages. */
129 break;
131 datalen = IMSG_DATA_SIZE(imsg);
132 switch (imsg.hdr.type) {
133 case IMSG_POS:
134 if (datalen != sizeof(current_position))
135 fatalx("IMSG_POS: got wrong size (%zu vs %zu)",
136 datalen, sizeof(current_position));
137 memcpy(&current_position, imsg.data,
138 sizeof(current_position));
139 if (current_position < 0)
140 current_position = -1;
141 if (notify_seek) {
142 notify_seek = 0;
143 control_notify(IMSG_CTL_SEEK);
145 break;
146 case IMSG_LEN:
147 if (datalen != sizeof(current_duration))
148 fatalx("IMSG_LEN: got wrong size (%zu vs %zu)",
149 datalen, sizeof(current_duration));
150 memcpy(&current_duration, imsg.data,
151 sizeof(current_duration));
152 if (current_duration < 0)
153 current_duration = -1;
154 break;
155 case IMSG_ERR:
156 if (datalen == 0)
157 errstr = "unknown error";
158 else {
159 errstr = imsg.data;
160 errstr[datalen-1] = '\0';
162 log_warnx("%s; skipping %s", errstr, current_song);
163 playlist_dropcurrent();
164 main_playlist_advance();
165 if (play_state == STATE_PLAYING)
166 control_notify(IMSG_CTL_NEXT);
167 else
168 control_notify(IMSG_CTL_STOP);
169 break;
170 case IMSG_EOF:
171 if (repeat_one && main_play_song(current_song))
172 break;
173 else if (repeat_one || consume)
174 playlist_dropcurrent();
175 main_playlist_advance();
176 if (play_state == STATE_PLAYING)
177 control_notify(IMSG_CTL_NEXT);
178 else
179 control_notify(IMSG_CTL_STOP);
180 break;
181 default:
182 log_debug("%s: error handling imsg %d", __func__,
183 imsg.hdr.type);
184 break;
186 imsg_free(&imsg);
189 if (!shut)
190 imsg_event_add(iev);
191 else {
192 /* This pipe is dead. Remove its event handler. */
193 event_del(&iev->ev);
194 event_loopexit(NULL);
198 static pid_t
199 start_child(enum amused_process proc, int fd)
201 const char *argv[7];
202 int argc = 0;
203 pid_t pid;
205 if (fd == -1 && debug)
206 goto exec;
208 switch (pid = fork()) {
209 case -1:
210 fatal("cannot fork");
211 case 0:
212 break;
213 default:
214 close(fd);
215 return pid;
218 if (fd != 3) {
219 if (fd != -1 && dup2(fd, 3) == -1)
220 fatal("cannot setup imsg fd");
221 } else if (fcntl(F_SETFD, 0) == -1)
222 fatal("cannot setup imsg fd");
224 exec:
225 argv[argc++] = argv0;
227 switch (proc) {
228 case PROC_MAIN:
229 argv[argc++] = "-s";
230 argv[argc++] = csock;
231 argv[argc++] = "-Tm";
232 break;
233 case PROC_PLAYER:
234 argv[argc++] = "-Tp";
235 break;
238 if (debug)
239 argv[argc++] = "-d";
240 if (verbose)
241 argv[argc++] = "-v";
242 argv[argc++] = NULL;
244 /* obnoxious casts */
245 execvp(argv0, (char *const *)argv);
246 fatal("execvp %s", argv0);
249 /* daemon main routine */
250 static __dead void
251 amused_main(void)
253 int pipe_main2player[2];
254 int control_fd;
256 log_init(debug, LOG_DAEMON);
257 log_setverbose(verbose);
258 log_procinit("main");
260 if (!debug)
261 daemon(1, 0);
263 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
264 PF_UNSPEC, pipe_main2player) == -1)
265 fatal("socketpair");
267 player_pid = start_child(PROC_PLAYER, pipe_main2player[1]);
269 event_init();
271 signal_set(&ev_sigint, SIGINT, main_sig_handler, NULL);
272 signal_set(&ev_sigterm, SIGTERM, main_sig_handler, NULL);
274 signal_add(&ev_sigint, NULL);
275 signal_add(&ev_sigterm, NULL);
277 signal(SIGHUP, SIG_IGN);
278 signal(SIGCHLD, SIG_IGN);
279 signal(SIGPIPE, SIG_IGN);
281 iev_player = xmalloc(sizeof(*iev_player));
282 imsg_init(&iev_player->ibuf, pipe_main2player[0]);
283 iev_player->handler = main_dispatch_player;
284 iev_player->events = EV_READ;
285 event_set(&iev_player->ev, iev_player->ibuf.fd, iev_player->events,
286 iev_player->handler, iev_player);
287 event_add(&iev_player->ev, NULL);
289 if ((control_fd = control_init(csock)) == -1)
290 fatal("control socket setup failed %s", csock);
291 control_listen(control_fd);
293 if (pledge("stdio rpath unix sendfd", NULL) == -1)
294 fatal("pledge");
296 log_info("startup");
297 event_dispatch();
298 main_shutdown();
301 int
302 main(int argc, char **argv)
304 int ch, proc = -1;
306 log_init(1, LOG_DAEMON); /* Log to stderr until daemonized */
307 log_setverbose(1);
309 argv0 = argv[0];
310 if (argv0 == NULL)
311 argv0 = "amused";
313 while ((ch = getopt(argc, argv, "ds:T:v")) != -1) {
314 switch (ch) {
315 case 'd':
316 debug = 1;
317 break;
318 case 's':
319 free(csock);
320 csock = xstrdup(optarg);
321 break;
322 case 'T':
323 switch (*optarg) {
324 case 'm':
325 proc = PROC_MAIN;
326 break;
327 case 'p':
328 proc = PROC_PLAYER;
329 break;
330 default:
331 usage();
333 break;
334 case 'v':
335 verbose++;
336 break;
337 default:
338 usage();
341 argv += optind;
342 argc -= optind;
344 if (proc == PROC_MAIN)
345 amused_main();
346 if (proc == PROC_PLAYER)
347 exit(player(debug, verbose));
349 if (csock == NULL)
350 xasprintf(&csock, "/tmp/amused-%d", getuid());
352 if (argc > 0)
353 debug = 0;
355 ctl(argc, argv);
358 void
359 spawn_daemon(void)
361 start_child(PROC_MAIN, -1);
364 void
365 imsg_event_add(struct imsgev *iev)
367 iev->events = EV_READ;
368 if (iev->ibuf.w.queued)
369 iev->events |= EV_WRITE;
371 event_del(&iev->ev);
372 event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev);
373 event_add(&iev->ev, NULL);
376 int
377 imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
378 pid_t pid, int fd, const void *data, uint16_t datalen)
380 int ret;
382 if ((ret = imsg_compose(&iev->ibuf, type, peerid, pid, fd, data,
383 datalen)) != -1)
384 imsg_event_add(iev);
386 return ret;
389 int
390 main_send_player(uint16_t type, int fd, const void *data, size_t len)
392 return imsg_compose_event(iev_player, type, 0, 0, fd, data, len);
395 int
396 main_play_song(const char *path)
398 struct stat sb;
399 int fd;
401 if ((fd = open(path, O_RDONLY)) == -1) {
402 log_warn("open %s", path);
403 return 0;
406 if (fstat(fd, &sb) == -1) {
407 log_warn("failed to stat %s", path);
408 close(fd);
409 return 0;
412 if (!S_ISREG(sb.st_mode)) {
413 log_info("skipping non-regular file: %s", path);
414 close(fd);
415 return 0;
418 play_state = STATE_PLAYING;
419 main_send_player(IMSG_PLAY, fd, NULL, 0);
420 return 1;
423 void
424 main_playlist_jump(struct imsgev *iev, struct imsg *imsg)
426 size_t datalen;
427 char arg[PATH_MAX];
428 const char *song;
430 datalen = IMSG_DATA_SIZE(*imsg);
431 if (datalen != sizeof(arg)) {
432 main_senderr(iev, "wrong size");
433 return;
436 memcpy(arg, imsg->data, sizeof(arg));
437 if (arg[sizeof(arg)-1] != '\0') {
438 main_senderr(iev, "data corrupted");
439 return;
442 song = playlist_jump(arg);
443 if (song == NULL) {
444 main_senderr(iev, "not found");
445 return;
448 control_notify(IMSG_CTL_JUMP);
450 main_send_player(IMSG_STOP, -1, NULL, 0);
451 if (!main_play_song(song)) {
452 main_senderr(iev, "can't play");
453 playlist_dropcurrent();
454 main_playlist_advance();
455 return;
458 main_send_status(iev);
461 void
462 main_playlist_resume(void)
464 const char *song;
466 if ((song = current_song) == NULL)
467 song = playlist_advance();
469 for (; song != NULL; song = playlist_advance()) {
470 if (main_play_song(song))
471 return;
473 playlist_dropcurrent();
477 void
478 main_playlist_advance(void)
480 const char *song;
482 for (;;) {
483 song = playlist_advance();
484 if (song == NULL)
485 return;
487 if (main_play_song(song))
488 break;
490 playlist_dropcurrent();
494 void
495 main_playlist_previous(void)
497 const char *song;
499 for (;;) {
500 song = playlist_previous();
501 if (song == NULL)
502 return;
504 if (main_play_song(song))
505 break;
507 playlist_dropcurrent();
511 void
512 main_senderr(struct imsgev *iev, const char *msg)
514 imsg_compose_event(iev, IMSG_CTL_ERR, 0, 0, -1,
515 msg, strlen(msg)+1);
518 void
519 main_enqueue(int tx, struct playlist *px, struct imsgev *iev,
520 struct imsg *imsg)
522 size_t datalen;
523 char path[PATH_MAX];
524 const char *err = NULL;
526 datalen = IMSG_DATA_SIZE(*imsg);
527 if (datalen != sizeof(path)) {
528 err = "data size mismatch";
529 goto err;
532 memcpy(path, imsg->data, sizeof(path));
533 if (path[datalen-1] != '\0') {
534 err = "malformed data";
535 goto err;
538 if (tx)
539 playlist_push(px, path);
540 else
541 playlist_enqueue(path);
542 imsg_compose_event(iev, IMSG_CTL_ADD, 0, 0, -1, path, sizeof(path));
543 return;
544 err:
545 main_senderr(iev, err);
548 void
549 main_send_playlist(struct imsgev *iev)
551 struct player_status s;
552 size_t i;
554 for (i = 0; i < playlist.len; ++i) {
555 memset(&s, 0, sizeof(s));
556 strlcpy(s.path, playlist.songs[i], sizeof(s.path));
557 s.status = play_off == i ? STATE_PLAYING : STATE_STOPPED;
558 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, &s,
559 sizeof(s));
562 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
565 void
566 main_send_status(struct imsgev *iev)
568 struct player_status s;
570 memset(&s, 0, sizeof(s));
572 if (current_song != NULL)
573 strlcpy(s.path, current_song, sizeof(s.path));
574 s.status = play_state;
575 s.position = current_position;
576 s.duration = current_duration;
577 s.mode.repeat_all = repeat_all;
578 s.mode.repeat_one = repeat_one;
579 s.mode.consume = consume;
581 imsg_compose_event(iev, IMSG_CTL_STATUS, 0, 0, -1, &s, sizeof(s));
584 void
585 main_seek(struct player_seek *s)
587 switch (play_state) {
588 case STATE_STOPPED:
589 main_playlist_resume();
590 break;
591 case STATE_PLAYING:
592 break;
593 case STATE_PAUSED:
594 play_state = STATE_PLAYING;
595 break;
598 notify_seek = 1;
599 main_send_player(IMSG_CTL_SEEK, -1, s, sizeof(*s));