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 <signal.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <stdint.h>
32 #include <string.h>
33 #include <syslog.h>
34 #include <unistd.h>
35 #include <imsg.h>
37 #include "amused.h"
38 #include "control.h"
39 #include "log.h"
40 #include "playlist.h"
41 #include "xmalloc.h"
43 char *csock = NULL;
44 int debug;
45 int verbose;
46 struct imsgev *iev_player;
48 const char *argv0;
49 pid_t player_pid;
50 struct event ev_sigint;
51 struct event ev_sigterm;
53 enum amused_process {
54 PROC_MAIN,
55 PROC_PLAYER,
56 };
58 __dead void
59 main_shutdown(void)
60 {
61 pid_t pid;
62 int status;
64 /* close pipes. */
65 msgbuf_clear(&iev_player->ibuf.w);
66 close(iev_player->ibuf.fd);
67 free(iev_player);
69 log_debug("waiting for children to terminate");
70 do {
71 pid = wait(&status);
72 if (pid == -1) {
73 if (errno != EINTR && errno != ECHILD)
74 fatal("wait");
75 } else if (WIFSIGNALED(status))
76 log_warnx("player terminated; signal %d",
77 WTERMSIG(status));
78 } while (pid != -1 || (pid == -1 && errno == EINTR));
80 log_info("terminating");
81 exit(0);
82 }
84 static void
85 main_sig_handler(int sig, short event, void *arg)
86 {
87 /*
88 * Normal signal handler rules don't apply because libevent
89 * decouples for us.
90 */
92 switch (sig) {
93 case SIGTERM:
94 case SIGINT:
95 main_shutdown();
96 break;
97 default:
98 fatalx("unexpected signal %d", sig);
99 }
102 static void
103 main_dispatch_player(int sig, short event, void *d)
105 struct imsgev *iev = d;
106 struct imsgbuf *ibuf = &iev->ibuf;
107 struct imsg imsg;
108 ssize_t n;
109 int shut = 0;
111 if (event & EV_READ) {
112 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
113 fatal("imsg_read error");
114 if (n == 0) /* Connection closed */
115 shut = 1;
117 if (event & EV_WRITE) {
118 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
119 fatal("msgbuf_write");
120 if (n == 0) /* Connection closed */
121 shut = 1;
124 for (;;) {
125 if ((n = imsg_get(ibuf, &imsg)) == -1)
126 fatal("imsg_get");
127 if (n == 0) /* No more messages. */
128 break;
130 switch (imsg.hdr.type) {
131 case IMSG_ERR:
132 playlist_dropcurrent();
133 /* fallthrough */
134 case IMSG_EOF:
135 if (repeat_one && current_song != NULL) {
136 if (main_play_song(current_song))
137 break;
138 playlist_dropcurrent();
140 main_playlist_advance();
141 if (play_state == STATE_PLAYING)
142 control_notify(NULL, IMSG_CTL_NEXT);
143 else
144 control_notify(NULL, IMSG_CTL_STOP);
145 break;
146 default:
147 log_debug("%s: error handling imsg %d", __func__,
148 imsg.hdr.type);
149 break;
151 imsg_free(&imsg);
154 if (!shut)
155 imsg_event_add(iev);
156 else {
157 /* This pipe is dead. Remove its event handler. */
158 event_del(&iev->ev);
159 event_loopexit(NULL);
163 static pid_t
164 start_child(enum amused_process proc, int fd)
166 const char *argv[7];
167 int argc = 0;
168 pid_t pid;
170 if (fd == -1 && debug)
171 goto exec;
173 switch (pid = fork()) {
174 case -1:
175 fatal("cannot fork");
176 case 0:
177 break;
178 default:
179 close(fd);
180 return pid;
183 if (fd != 3) {
184 if (fd != -1 && dup2(fd, 3) == -1)
185 fatal("cannot setup imsg fd");
186 } else if (fcntl(F_SETFD, 0) == -1)
187 fatal("cannot setup imsg fd");
189 exec:
190 argv[argc++] = argv0;
192 switch (proc) {
193 case PROC_MAIN:
194 argv[argc++] = "-s";
195 argv[argc++] = csock;
196 argv[argc++] = "-Tm";
197 break;
198 case PROC_PLAYER:
199 argv[argc++] = "-Tp";
200 break;
203 if (debug)
204 argv[argc++] = "-d";
205 if (verbose)
206 argv[argc++] = "-v";
207 argv[argc++] = NULL;
209 /* obnoxious casts */
210 execvp(argv0, (char *const *)argv);
211 fatal("execvp %s", argv0);
214 /* daemon main routine */
215 static __dead int
216 amused_main(void)
218 int pipe_main2player[2];
219 int control_fd;
221 log_init(debug, LOG_DAEMON);
222 log_setverbose(verbose);
223 log_procinit("main");
225 if (!debug)
226 daemon(1, 0);
228 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
229 PF_UNSPEC, pipe_main2player) == -1)
230 fatal("socketpair");
232 player_pid = start_child(PROC_PLAYER, pipe_main2player[1]);
234 event_init();
236 signal_set(&ev_sigint, SIGINT, main_sig_handler, NULL);
237 signal_set(&ev_sigterm, SIGTERM, main_sig_handler, NULL);
239 signal_add(&ev_sigint, NULL);
240 signal_add(&ev_sigterm, NULL);
242 signal(SIGHUP, SIG_IGN);
243 signal(SIGCHLD, SIG_IGN);
244 signal(SIGPIPE, SIG_IGN);
246 iev_player = xmalloc(sizeof(*iev_player));
247 imsg_init(&iev_player->ibuf, pipe_main2player[0]);
248 iev_player->handler = main_dispatch_player;
249 iev_player->events = EV_READ;
250 event_set(&iev_player->ev, iev_player->ibuf.fd, iev_player->events,
251 iev_player->handler, iev_player);
252 event_add(&iev_player->ev, NULL);
254 if ((control_fd = control_init(csock)) == -1)
255 fatal("control socket setup failed %s", csock);
256 control_listen(control_fd);
258 if (pledge("stdio rpath unix sendfd", NULL) == -1)
259 fatal("pledge");
261 log_info("startup");
262 event_dispatch();
263 main_shutdown();
266 int
267 main(int argc, char **argv)
269 int ch, proc = -1;
271 log_init(1, LOG_DAEMON); /* Log to stderr until daemonized */
272 log_setverbose(1);
274 argv0 = argv[0];
275 if (argv0 == NULL)
276 argv0 = "amused";
278 while ((ch = getopt(argc, argv, "ds:T:v")) != -1) {
279 switch (ch) {
280 case 'd':
281 debug = 1;
282 break;
283 case 's':
284 free(csock);
285 csock = xstrdup(optarg);
286 break;
287 case 'T':
288 switch (*optarg) {
289 case 'm':
290 proc = PROC_MAIN;
291 break;
292 case 'p':
293 proc = PROC_PLAYER;
294 break;
295 default:
296 usage();
298 break;
299 case 'v':
300 verbose++;
301 break;
302 default:
303 usage();
306 argv += optind;
307 argc -= optind;
309 if (proc == PROC_MAIN)
310 amused_main();
311 if (proc == PROC_PLAYER)
312 exit(player(debug, verbose));
314 if (csock == NULL)
315 xasprintf(&csock, "/tmp/amused-%d", getuid());
317 if (argc > 0)
318 debug = 0;
320 ctl(argc, argv);
323 void
324 spawn_daemon(void)
326 start_child(PROC_MAIN, -1);
329 void
330 imsg_event_add(struct imsgev *iev)
332 iev->events = EV_READ;
333 if (iev->ibuf.w.queued)
334 iev->events |= EV_WRITE;
336 event_del(&iev->ev);
337 event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev);
338 event_add(&iev->ev, NULL);
341 int
342 imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
343 pid_t pid, int fd, const void *data, uint16_t datalen)
345 int ret;
347 if ((ret = imsg_compose(&iev->ibuf, type, peerid, pid, fd, data,
348 datalen)) != -1)
349 imsg_event_add(iev);
351 return ret;
354 int
355 main_send_player(uint16_t type, int fd, const void *data, uint16_t datalen)
357 return imsg_compose_event(iev_player, type, 0, 0, fd, data, datalen);
360 int
361 main_play_song(const char *song)
363 struct stat sb;
364 char path[PATH_MAX] = { 0 };
365 int fd;
367 strlcpy(path, song, sizeof(path));
368 if ((fd = open(path, O_RDONLY)) == -1) {
369 log_warn("open %s", path);
370 return 0;
373 if (fstat(fd, &sb) == -1) {
374 log_warn("failed to stat %s", path);
375 close(fd);
376 return 0;
379 if (S_ISDIR(sb.st_mode)) {
380 log_info("skipping a directory: %s", path);
381 close(fd);
382 return 0;
385 play_state = STATE_PLAYING;
386 imsg_compose_event(iev_player, IMSG_PLAY, 0, 0, fd,
387 path, sizeof(path));
388 return 1;
391 void
392 main_playlist_jump(struct imsgev *iev, struct imsg *imsg)
394 size_t datalen;
395 char arg[PATH_MAX];
396 const char *song;
398 datalen = IMSG_DATA_SIZE(*imsg);
399 if (datalen != sizeof(arg)) {
400 main_senderr(iev, "wrong size");
401 return;
404 memcpy(arg, imsg->data, sizeof(arg));
405 if (arg[sizeof(arg)-1] != '\0') {
406 main_senderr(iev, "data corrupted");
407 return;
410 song = playlist_jump(arg);
411 if (song == NULL) {
412 main_senderr(iev, "not found");
413 return;
416 main_send_player(IMSG_STOP, -1, NULL, 0);
417 if (!main_play_song(song)) {
418 main_senderr(iev, "can't play");
419 playlist_dropcurrent();
420 main_playlist_advance();
421 return;
424 main_send_status(iev);
427 void
428 main_playlist_resume(void)
430 const char *song;
432 if ((song = current_song) == NULL)
433 song = playlist_advance();
435 for (; song != NULL; song = playlist_advance()) {
436 if (main_play_song(song))
437 return;
439 playlist_dropcurrent();
443 void
444 main_playlist_advance(void)
446 const char *song;
448 for (;;) {
449 song = playlist_advance();
450 if (song == NULL)
451 return;
453 if (main_play_song(song))
454 break;
456 playlist_dropcurrent();
460 void
461 main_playlist_previous(void)
463 const char *song;
465 for (;;) {
466 song = playlist_previous();
467 if (song == NULL)
468 return;
470 if (main_play_song(song))
471 break;
473 playlist_dropcurrent();
477 void
478 main_restart_track(void)
480 const char *song;
482 song = current_song;
483 if (song == NULL)
484 return;
486 if (main_play_song(song))
487 return;
489 playlist_dropcurrent();
490 main_playlist_advance();
493 void
494 main_senderr(struct imsgev *iev, const char *msg)
496 imsg_compose_event(iev, IMSG_CTL_ERR, 0, 0, -1,
497 msg, strlen(msg)+1);
500 void
501 main_enqueue(int tx, struct playlist *px, struct imsgev *iev,
502 struct imsg *imsg)
504 size_t datalen;
505 char path[PATH_MAX] = { 0 };
506 const char *err = NULL;
508 datalen = IMSG_DATA_SIZE(*imsg);
509 if (datalen != sizeof(path)) {
510 err = "data size mismatch";
511 goto err;
514 memcpy(path, imsg->data, sizeof(path));
515 if (path[datalen-1] != '\0') {
516 err = "malformed data";
517 goto err;
520 if (tx)
521 playlist_push(px, path);
522 else
523 playlist_enqueue(path);
524 imsg_compose_event(iev, IMSG_CTL_ADD, 0, 0, -1, path, sizeof(path));
525 return;
526 err:
527 main_senderr(iev, err);
530 void
531 main_send_playlist(struct imsgev *iev)
533 struct player_status s;
534 size_t i;
536 for (i = 0; i < playlist.len; ++i) {
537 memset(&s, 0, sizeof(s));
538 strlcpy(s.path, playlist.songs[i], sizeof(s.path));
539 s.status = play_off == i ? STATE_PLAYING : STATE_STOPPED;
540 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, &s,
541 sizeof(s));
544 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
547 void
548 main_send_status(struct imsgev *iev)
550 struct player_status s;
552 memset(&s, 0, sizeof(s));
554 if (current_song != NULL)
555 strlcpy(s.path, current_song, sizeof(s.path));
556 s.status = play_state;
557 s.rp.repeat_all = repeat_all;
558 s.rp.repeat_one = repeat_one;
560 imsg_compose_event(iev, IMSG_CTL_STATUS, 0, 0, -1, &s, sizeof(s));