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 char *errstr;
106 struct imsgev *iev = d;
107 struct imsgbuf *ibuf = &iev->ibuf;
108 struct imsg imsg;
109 size_t datalen;
110 ssize_t n;
111 int shut = 0;
113 if (event & EV_READ) {
114 if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
115 fatal("imsg_read error");
116 if (n == 0) /* Connection closed */
117 shut = 1;
119 if (event & EV_WRITE) {
120 if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
121 fatal("msgbuf_write");
122 if (n == 0) /* Connection closed */
123 shut = 1;
126 for (;;) {
127 if ((n = imsg_get(ibuf, &imsg)) == -1)
128 fatal("imsg_get");
129 if (n == 0) /* No more messages. */
130 break;
132 datalen = IMSG_DATA_SIZE(imsg);
133 switch (imsg.hdr.type) {
134 case IMSG_POS:
135 if (datalen != sizeof(current_position))
136 fatalx("IMSG_POS: got wrong size (%zu vs %zu)",
137 datalen, sizeof(current_position));
138 memcpy(&current_position, imsg.data,
139 sizeof(current_position));
140 if (current_position < 0)
141 current_position = -1;
142 break;
143 case IMSG_LEN:
144 if (datalen != sizeof(current_duration))
145 fatalx("IMSG_LEN: got wrong size (%zu vs %zu)",
146 datalen, sizeof(current_duration));
147 memcpy(&current_duration, imsg.data,
148 sizeof(current_duration));
149 if (current_duration < 0)
150 current_duration = -1;
151 break;
152 case IMSG_ERR:
153 if (datalen == 0)
154 errstr = "unknown error";
155 else {
156 errstr = imsg.data;
157 errstr[datalen-1] = '\0';
159 log_warnx("%s; skipping %s", errstr, current_song);
160 playlist_dropcurrent();
161 /* fallthrough */
162 case IMSG_EOF:
163 if (repeat_one && current_song != NULL) {
164 if (main_play_song(current_song))
165 break;
166 playlist_dropcurrent();
168 main_playlist_advance();
169 if (play_state == STATE_PLAYING)
170 control_notify(NULL, IMSG_CTL_NEXT);
171 else
172 control_notify(NULL, IMSG_CTL_STOP);
173 break;
174 default:
175 log_debug("%s: error handling imsg %d", __func__,
176 imsg.hdr.type);
177 break;
179 imsg_free(&imsg);
182 if (!shut)
183 imsg_event_add(iev);
184 else {
185 /* This pipe is dead. Remove its event handler. */
186 event_del(&iev->ev);
187 event_loopexit(NULL);
191 static pid_t
192 start_child(enum amused_process proc, int fd)
194 const char *argv[7];
195 int argc = 0;
196 pid_t pid;
198 if (fd == -1 && debug)
199 goto exec;
201 switch (pid = fork()) {
202 case -1:
203 fatal("cannot fork");
204 case 0:
205 break;
206 default:
207 close(fd);
208 return pid;
211 if (fd != 3) {
212 if (fd != -1 && dup2(fd, 3) == -1)
213 fatal("cannot setup imsg fd");
214 } else if (fcntl(F_SETFD, 0) == -1)
215 fatal("cannot setup imsg fd");
217 exec:
218 argv[argc++] = argv0;
220 switch (proc) {
221 case PROC_MAIN:
222 argv[argc++] = "-s";
223 argv[argc++] = csock;
224 argv[argc++] = "-Tm";
225 break;
226 case PROC_PLAYER:
227 argv[argc++] = "-Tp";
228 break;
231 if (debug)
232 argv[argc++] = "-d";
233 if (verbose)
234 argv[argc++] = "-v";
235 argv[argc++] = NULL;
237 /* obnoxious casts */
238 execvp(argv0, (char *const *)argv);
239 fatal("execvp %s", argv0);
242 /* daemon main routine */
243 static __dead void
244 amused_main(void)
246 int pipe_main2player[2];
247 int control_fd;
249 log_init(debug, LOG_DAEMON);
250 log_setverbose(verbose);
251 log_procinit("main");
253 if (!debug)
254 daemon(1, 0);
256 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
257 PF_UNSPEC, pipe_main2player) == -1)
258 fatal("socketpair");
260 player_pid = start_child(PROC_PLAYER, pipe_main2player[1]);
262 event_init();
264 signal_set(&ev_sigint, SIGINT, main_sig_handler, NULL);
265 signal_set(&ev_sigterm, SIGTERM, main_sig_handler, NULL);
267 signal_add(&ev_sigint, NULL);
268 signal_add(&ev_sigterm, NULL);
270 signal(SIGHUP, SIG_IGN);
271 signal(SIGCHLD, SIG_IGN);
272 signal(SIGPIPE, SIG_IGN);
274 iev_player = xmalloc(sizeof(*iev_player));
275 imsg_init(&iev_player->ibuf, pipe_main2player[0]);
276 iev_player->handler = main_dispatch_player;
277 iev_player->events = EV_READ;
278 event_set(&iev_player->ev, iev_player->ibuf.fd, iev_player->events,
279 iev_player->handler, iev_player);
280 event_add(&iev_player->ev, NULL);
282 if ((control_fd = control_init(csock)) == -1)
283 fatal("control socket setup failed %s", csock);
284 control_listen(control_fd);
286 if (pledge("stdio rpath unix sendfd", NULL) == -1)
287 fatal("pledge");
289 log_info("startup");
290 event_dispatch();
291 main_shutdown();
294 int
295 main(int argc, char **argv)
297 int ch, proc = -1;
299 log_init(1, LOG_DAEMON); /* Log to stderr until daemonized */
300 log_setverbose(1);
302 argv0 = argv[0];
303 if (argv0 == NULL)
304 argv0 = "amused";
306 while ((ch = getopt(argc, argv, "ds:T:v")) != -1) {
307 switch (ch) {
308 case 'd':
309 debug = 1;
310 break;
311 case 's':
312 free(csock);
313 csock = xstrdup(optarg);
314 break;
315 case 'T':
316 switch (*optarg) {
317 case 'm':
318 proc = PROC_MAIN;
319 break;
320 case 'p':
321 proc = PROC_PLAYER;
322 break;
323 default:
324 usage();
326 break;
327 case 'v':
328 verbose++;
329 break;
330 default:
331 usage();
334 argv += optind;
335 argc -= optind;
337 if (proc == PROC_MAIN)
338 amused_main();
339 if (proc == PROC_PLAYER)
340 exit(player(debug, verbose));
342 if (csock == NULL)
343 xasprintf(&csock, "/tmp/amused-%d", getuid());
345 if (argc > 0)
346 debug = 0;
348 ctl(argc, argv);
351 void
352 spawn_daemon(void)
354 start_child(PROC_MAIN, -1);
357 void
358 imsg_event_add(struct imsgev *iev)
360 iev->events = EV_READ;
361 if (iev->ibuf.w.queued)
362 iev->events |= EV_WRITE;
364 event_del(&iev->ev);
365 event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev);
366 event_add(&iev->ev, NULL);
369 int
370 imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
371 pid_t pid, int fd, const void *data, uint16_t datalen)
373 int ret;
375 if ((ret = imsg_compose(&iev->ibuf, type, peerid, pid, fd, data,
376 datalen)) != -1)
377 imsg_event_add(iev);
379 return ret;
382 int
383 main_send_player(uint16_t type, int fd)
385 return imsg_compose_event(iev_player, type, 0, 0, fd, NULL, 0);
388 int
389 main_play_song(const char *path)
391 struct stat sb;
392 int fd;
394 if ((fd = open(path, O_RDONLY)) == -1) {
395 log_warn("open %s", path);
396 return 0;
399 if (fstat(fd, &sb) == -1) {
400 log_warn("failed to stat %s", path);
401 close(fd);
402 return 0;
405 if (!S_ISREG(sb.st_mode)) {
406 log_info("skipping non-regular file: %s", path);
407 close(fd);
408 return 0;
411 play_state = STATE_PLAYING;
412 main_send_player(IMSG_PLAY, fd);
413 return 1;
416 void
417 main_playlist_jump(struct imsgev *iev, struct imsg *imsg)
419 size_t datalen;
420 char arg[PATH_MAX];
421 const char *song;
423 datalen = IMSG_DATA_SIZE(*imsg);
424 if (datalen != sizeof(arg)) {
425 main_senderr(iev, "wrong size");
426 return;
429 memcpy(arg, imsg->data, sizeof(arg));
430 if (arg[sizeof(arg)-1] != '\0') {
431 main_senderr(iev, "data corrupted");
432 return;
435 song = playlist_jump(arg);
436 if (song == NULL) {
437 main_senderr(iev, "not found");
438 return;
441 main_send_player(IMSG_STOP, -1);
442 if (!main_play_song(song)) {
443 main_senderr(iev, "can't play");
444 playlist_dropcurrent();
445 main_playlist_advance();
446 return;
449 main_send_status(iev);
452 void
453 main_playlist_resume(void)
455 const char *song;
457 if ((song = current_song) == NULL)
458 song = playlist_advance();
460 for (; song != NULL; song = playlist_advance()) {
461 if (main_play_song(song))
462 return;
464 playlist_dropcurrent();
468 void
469 main_playlist_advance(void)
471 const char *song;
473 for (;;) {
474 song = playlist_advance();
475 if (song == NULL)
476 return;
478 if (main_play_song(song))
479 break;
481 playlist_dropcurrent();
485 void
486 main_playlist_previous(void)
488 const char *song;
490 for (;;) {
491 song = playlist_previous();
492 if (song == NULL)
493 return;
495 if (main_play_song(song))
496 break;
498 playlist_dropcurrent();
502 void
503 main_restart_track(void)
505 if (current_song == NULL)
506 return;
508 if (main_play_song(current_song))
509 return;
511 playlist_dropcurrent();
512 main_playlist_advance();
515 void
516 main_senderr(struct imsgev *iev, const char *msg)
518 imsg_compose_event(iev, IMSG_CTL_ERR, 0, 0, -1,
519 msg, strlen(msg)+1);
522 void
523 main_enqueue(int tx, struct playlist *px, struct imsgev *iev,
524 struct imsg *imsg)
526 size_t datalen;
527 char path[PATH_MAX];
528 const char *err = NULL;
530 datalen = IMSG_DATA_SIZE(*imsg);
531 if (datalen != sizeof(path)) {
532 err = "data size mismatch";
533 goto err;
536 memcpy(path, imsg->data, sizeof(path));
537 if (path[datalen-1] != '\0') {
538 err = "malformed data";
539 goto err;
542 if (tx)
543 playlist_push(px, path);
544 else
545 playlist_enqueue(path);
546 imsg_compose_event(iev, IMSG_CTL_ADD, 0, 0, -1, path, sizeof(path));
547 return;
548 err:
549 main_senderr(iev, err);
552 void
553 main_send_playlist(struct imsgev *iev)
555 struct player_status s;
556 size_t i;
558 for (i = 0; i < playlist.len; ++i) {
559 memset(&s, 0, sizeof(s));
560 strlcpy(s.path, playlist.songs[i], sizeof(s.path));
561 s.status = play_off == i ? STATE_PLAYING : STATE_STOPPED;
562 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, &s,
563 sizeof(s));
566 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
569 void
570 main_send_status(struct imsgev *iev)
572 struct player_status s;
574 memset(&s, 0, sizeof(s));
576 if (current_song != NULL)
577 strlcpy(s.path, current_song, sizeof(s.path));
578 s.status = play_state;
579 s.position = current_position;
580 s.duration = current_duration;
581 s.rp.repeat_all = repeat_all;
582 s.rp.repeat_one = repeat_one;
584 imsg_compose_event(iev, IMSG_CTL_STATUS, 0, 0, -1, &s, sizeof(s));