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 <sys/types.h>
18 #include <sys/queue.h>
19 #include <sys/socket.h>
20 #include <sys/stat.h>
21 #include <sys/uio.h>
22 #include <sys/wait.h>
24 #include <event.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <sndio.h>
29 #include <signal.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stdint.h>
33 #include <string.h>
34 #include <syslog.h>
35 #include <unistd.h>
36 #include <imsg.h>
38 #include "amused.h"
39 #include "control.h"
40 #include "log.h"
41 #include "playlist.h"
42 #include "xmalloc.h"
44 char *csock = NULL;
45 int debug;
46 int verbose;
47 struct imsgev *iev_player;
49 const char *argv0;
50 pid_t player_pid;
51 struct event ev_sigint;
52 struct event ev_sigterm;
54 enum amused_process {
55 PROC_MAIN,
56 PROC_PLAYER,
57 };
59 __dead void
60 main_shutdown(void)
61 {
62 pid_t pid;
63 int status;
65 /* close pipes. */
66 msgbuf_clear(&iev_player->ibuf.w);
67 close(iev_player->ibuf.fd);
68 free(iev_player);
70 log_debug("waiting for children to terminate");
71 do {
72 pid = wait(&status);
73 if (pid == -1) {
74 if (errno != EINTR && errno != ECHILD)
75 fatal("wait");
76 } else if (WIFSIGNALED(status))
77 log_warnx("player terminated; signal %d",
78 WTERMSIG(status));
79 } while (pid != -1 || (pid == -1 && errno == EINTR));
81 log_info("terminating");
82 exit(0);
83 }
85 static void
86 main_sig_handler(int sig, short event, void *arg)
87 {
88 /*
89 * Normal signal handler rules don't apply because libevent
90 * decouples for us.
91 */
93 switch (sig) {
94 case SIGTERM:
95 case SIGINT:
96 main_shutdown();
97 break;
98 default:
99 fatalx("unexpected signal %d", sig);
103 static void
104 main_dispatch_player(int sig, short event, void *d)
106 struct imsgev *iev = d;
107 struct imsgbuf *ibuf = &iev->ibuf;
108 struct imsg imsg;
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 switch (imsg.hdr.type) {
132 case IMSG_ERR:
133 playlist_dropcurrent();
134 /* fallthrough */
135 case IMSG_EOF:
136 if (repeat_one && current_song != NULL) {
137 if (main_play_song(current_song))
138 break;
139 playlist_dropcurrent();
141 main_playlist_advance();
142 if (play_state == STATE_PLAYING)
143 control_notify(NULL, IMSG_CTL_NEXT);
144 else
145 control_notify(NULL, IMSG_CTL_STOP);
146 break;
147 default:
148 log_debug("%s: error handling imsg %d", __func__,
149 imsg.hdr.type);
150 break;
152 imsg_free(&imsg);
155 if (!shut)
156 imsg_event_add(iev);
157 else {
158 /* This pipe is dead. Remove its event handler. */
159 event_del(&iev->ev);
160 event_loopexit(NULL);
164 static pid_t
165 start_child(enum amused_process proc, int fd)
167 const char *argv[7];
168 int argc = 0;
169 pid_t pid;
171 if (fd == -1 && debug)
172 goto exec;
174 switch (pid = fork()) {
175 case -1:
176 fatal("cannot fork");
177 case 0:
178 break;
179 default:
180 close(fd);
181 return pid;
184 if (fd != 3) {
185 if (fd != -1 && dup2(fd, 3) == -1)
186 fatal("cannot setup imsg fd");
187 } else if (fcntl(F_SETFD, 0) == -1)
188 fatal("cannot setup imsg fd");
190 exec:
191 argv[argc++] = argv0;
193 switch (proc) {
194 case PROC_MAIN:
195 argv[argc++] = "-s";
196 argv[argc++] = csock;
197 argv[argc++] = "-Tm";
198 break;
199 case PROC_PLAYER:
200 argv[argc++] = "-Tp";
201 break;
204 if (debug)
205 argv[argc++] = "-d";
206 if (verbose)
207 argv[argc++] = "-v";
208 argv[argc++] = NULL;
210 /* obnoxious casts */
211 execvp(argv0, (char *const *)argv);
212 fatal("execvp %s", argv0);
215 /* daemon main routine */
216 static __dead int
217 amused_main(void)
219 int pipe_main2player[2];
220 int control_fd;
222 log_init(debug, LOG_DAEMON);
223 log_setverbose(verbose);
224 log_procinit("main");
226 if (!debug)
227 daemon(1, 0);
229 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
230 PF_UNSPEC, pipe_main2player) == -1)
231 fatal("socketpair");
233 player_pid = start_child(PROC_PLAYER, pipe_main2player[1]);
235 event_init();
237 signal_set(&ev_sigint, SIGINT, main_sig_handler, NULL);
238 signal_set(&ev_sigterm, SIGTERM, main_sig_handler, NULL);
240 signal_add(&ev_sigint, NULL);
241 signal_add(&ev_sigterm, NULL);
243 signal(SIGHUP, SIG_IGN);
244 signal(SIGCHLD, SIG_IGN);
245 signal(SIGPIPE, SIG_IGN);
247 iev_player = xmalloc(sizeof(*iev_player));
248 imsg_init(&iev_player->ibuf, pipe_main2player[0]);
249 iev_player->handler = main_dispatch_player;
250 iev_player->events = EV_READ;
251 event_set(&iev_player->ev, iev_player->ibuf.fd, iev_player->events,
252 iev_player->handler, iev_player);
253 event_add(&iev_player->ev, NULL);
255 if ((control_fd = control_init(csock)) == -1)
256 fatal("control socket setup failed %s", csock);
257 control_listen(control_fd);
259 if (pledge("stdio rpath unix sendfd", NULL) == -1)
260 fatal("pledge");
262 log_info("startup");
263 event_dispatch();
264 main_shutdown();
267 int
268 main(int argc, char **argv)
270 int ch, proc = -1;
272 log_init(1, LOG_DAEMON); /* Log to stderr until daemonized */
273 log_setverbose(1);
275 argv0 = argv[0];
276 if (argv0 == NULL)
277 argv0 = "amused";
279 while ((ch = getopt(argc, argv, "ds:T:v")) != -1) {
280 switch (ch) {
281 case 'd':
282 debug = 1;
283 break;
284 case 's':
285 free(csock);
286 csock = xstrdup(optarg);
287 break;
288 case 'T':
289 switch (*optarg) {
290 case 'm':
291 proc = PROC_MAIN;
292 break;
293 case 'p':
294 proc = PROC_PLAYER;
295 break;
296 default:
297 usage();
299 break;
300 case 'v':
301 verbose++;
302 break;
303 default:
304 usage();
307 argv += optind;
308 argc -= optind;
310 if (proc == PROC_MAIN)
311 amused_main();
312 if (proc == PROC_PLAYER)
313 exit(player(debug, verbose));
315 if (csock == NULL)
316 xasprintf(&csock, "/tmp/amused-%d", getuid());
318 if (argc > 0)
319 debug = 0;
321 ctl(argc, argv);
324 void
325 spawn_daemon(void)
327 start_child(PROC_MAIN, -1);
330 void
331 imsg_event_add(struct imsgev *iev)
333 iev->events = EV_READ;
334 if (iev->ibuf.w.queued)
335 iev->events |= EV_WRITE;
337 event_del(&iev->ev);
338 event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev);
339 event_add(&iev->ev, NULL);
342 int
343 imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
344 pid_t pid, int fd, const void *data, uint16_t datalen)
346 int ret;
348 if ((ret = imsg_compose(&iev->ibuf, type, peerid, pid, fd, data,
349 datalen)) != -1)
350 imsg_event_add(iev);
352 return ret;
355 int
356 main_send_player(uint16_t type, int fd, const void *data, uint16_t datalen)
358 return imsg_compose_event(iev_player, type, 0, 0, fd, data, datalen);
361 int
362 main_play_song(const char *song)
364 struct stat sb;
365 char path[PATH_MAX] = { 0 };
366 int fd;
368 strlcpy(path, song, sizeof(path));
369 if ((fd = open(path, O_RDONLY)) == -1) {
370 log_warn("open %s", path);
371 return 0;
374 if (fstat(fd, &sb) == -1) {
375 log_warn("failed to stat %s", path);
376 close(fd);
377 return 0;
380 if (S_ISDIR(sb.st_mode)) {
381 log_info("skipping a directory: %s", path);
382 close(fd);
383 return 0;
386 play_state = STATE_PLAYING;
387 imsg_compose_event(iev_player, IMSG_PLAY, 0, 0, fd,
388 path, sizeof(path));
389 return 1;
392 void
393 main_playlist_jump(struct imsgev *iev, struct imsg *imsg)
395 size_t datalen;
396 char arg[PATH_MAX];
397 const char *song;
399 datalen = IMSG_DATA_SIZE(*imsg);
400 if (datalen != sizeof(arg)) {
401 main_senderr(iev, "wrong size");
402 return;
405 memcpy(arg, imsg->data, sizeof(arg));
406 if (arg[sizeof(arg)-1] != '\0') {
407 main_senderr(iev, "data corrupted");
408 return;
411 song = playlist_jump(arg);
412 if (song == NULL) {
413 main_senderr(iev, "not found");
414 return;
417 main_send_player(IMSG_STOP, -1, NULL, 0);
418 if (!main_play_song(song)) {
419 main_senderr(iev, "can't play");
420 playlist_dropcurrent();
421 main_playlist_advance();
422 return;
425 main_send_status(iev);
428 void
429 main_playlist_resume(void)
431 const char *song;
433 if ((song = current_song) == NULL)
434 song = playlist_advance();
436 for (; song != NULL; song = playlist_advance()) {
437 if (main_play_song(song))
438 return;
440 playlist_dropcurrent();
444 void
445 main_playlist_advance(void)
447 const char *song;
449 for (;;) {
450 song = playlist_advance();
451 if (song == NULL)
452 return;
454 if (main_play_song(song))
455 break;
457 playlist_dropcurrent();
461 void
462 main_playlist_previous(void)
464 const char *song;
466 for (;;) {
467 song = playlist_previous();
468 if (song == NULL)
469 return;
471 if (main_play_song(song))
472 break;
474 playlist_dropcurrent();
478 void
479 main_restart_track(void)
481 const char *song;
483 song = current_song;
484 if (song == NULL)
485 return;
487 if (main_play_song(song))
488 return;
490 playlist_dropcurrent();
491 main_playlist_advance();
494 void
495 main_senderr(struct imsgev *iev, const char *msg)
497 imsg_compose_event(iev, IMSG_CTL_ERR, 0, 0, -1,
498 msg, strlen(msg)+1);
501 void
502 main_enqueue(int tx, struct playlist *px, struct imsgev *iev,
503 struct imsg *imsg)
505 size_t datalen;
506 char path[PATH_MAX] = { 0 };
507 const char *err = NULL;
509 datalen = IMSG_DATA_SIZE(*imsg);
510 if (datalen != sizeof(path)) {
511 err = "data size mismatch";
512 goto err;
515 memcpy(path, imsg->data, sizeof(path));
516 if (path[datalen-1] != '\0') {
517 err = "malformed data";
518 goto err;
521 if (tx)
522 playlist_push(px, path);
523 else
524 playlist_enqueue(path);
525 imsg_compose_event(iev, IMSG_CTL_ADD, 0, 0, -1, path, sizeof(path));
526 return;
527 err:
528 main_senderr(iev, err);
531 void
532 main_send_playlist(struct imsgev *iev)
534 struct player_status s;
535 size_t i;
537 for (i = 0; i < playlist.len; ++i) {
538 memset(&s, 0, sizeof(s));
539 strlcpy(s.path, playlist.songs[i], sizeof(s.path));
540 s.status = play_off == i ? STATE_PLAYING : STATE_STOPPED;
541 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, &s,
542 sizeof(s));
545 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
548 void
549 main_send_status(struct imsgev *iev)
551 struct player_status s;
553 memset(&s, 0, sizeof(s));
555 if (current_song != NULL)
556 strlcpy(s.path, current_song, sizeof(s.path));
557 s.status = play_state;
558 s.rp.repeat_all = repeat_all;
559 s.rp.repeat_one = repeat_one;
561 imsg_compose_event(iev, IMSG_CTL_STATUS, 0, 0, -1, &s, sizeof(s));