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 struct sio_hdl *hdl;
45 char *csock = NULL;
46 int debug;
47 int verbose;
48 struct imsgev *iev_player;
50 const char *argv0;
51 pid_t player_pid;
52 struct event ev_sigint;
53 struct event ev_sigterm;
55 enum amused_process {
56 PROC_MAIN,
57 PROC_PLAYER,
58 };
60 __dead void
61 main_shutdown(void)
62 {
63 pid_t pid;
64 int status;
66 /* close pipes. */
67 msgbuf_clear(&iev_player->ibuf.w);
68 close(iev_player->ibuf.fd);
69 free(iev_player);
71 log_debug("waiting for children to terminate");
72 do {
73 pid = wait(&status);
74 if (pid == -1) {
75 if (errno != EINTR && errno != ECHILD)
76 fatal("wait");
77 } else if (WIFSIGNALED(status))
78 log_warnx("player terminated; signal %d",
79 WTERMSIG(status));
80 } while (pid != -1 || (pid == -1 && errno == EINTR));
82 log_info("terminating");
83 exit(0);
84 }
86 static void
87 main_sig_handler(int sig, short event, void *arg)
88 {
89 /*
90 * Normal signal handler rules don't apply because libevent
91 * decouples for us.
92 */
94 switch (sig) {
95 case SIGTERM:
96 case SIGINT:
97 main_shutdown();
98 break;
99 default:
100 fatalx("unexpected signal %d", sig);
104 static void
105 main_dispatch_player(int sig, short event, void *d)
107 struct imsgev *iev = d;
108 struct imsgbuf *ibuf = &iev->ibuf;
109 struct imsg imsg;
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 switch (imsg.hdr.type) {
133 case IMSG_ERR:
134 playlist_dropcurrent();
135 /* fallthrough */
136 case IMSG_EOF:
137 if (repeat_one && current_song != NULL) {
138 if (main_play_song(current_song))
139 break;
140 playlist_dropcurrent();
142 main_playlist_advance();
143 if (play_state == STATE_PLAYING)
144 control_notify(NULL, IMSG_CTL_NEXT);
145 else
146 control_notify(NULL, IMSG_CTL_STOP);
147 break;
148 default:
149 log_debug("%s: error handling imsg %d", __func__,
150 imsg.hdr.type);
151 break;
153 imsg_free(&imsg);
156 if (!shut)
157 imsg_event_add(iev);
158 else {
159 /* This pipe is dead. Remove its event handler. */
160 event_del(&iev->ev);
161 event_loopexit(NULL);
165 static pid_t
166 start_child(enum amused_process proc, int fd)
168 const char *argv[6];
169 int argc = 0;
170 pid_t pid;
172 switch (pid = fork()) {
173 case -1:
174 fatal("cannot fork");
175 case 0:
176 break;
177 default:
178 close(fd);
179 return pid;
182 if (fd != 3) {
183 if (fd != -1 && dup2(fd, 3) == -1)
184 fatal("cannot setup imsg fd");
185 } else if (fcntl(F_SETFD, 0) == -1)
186 fatal("cannot setup imsg fd");
188 argv[argc++] = argv0;
190 switch (proc) {
191 case PROC_MAIN:
192 argv[argc++] = "-s";
193 argv[argc++] = csock;
194 break;
195 case PROC_PLAYER:
196 argv[argc++] = "-Tp";
197 break;
200 if (debug)
201 argv[argc++] = "-d";
202 if (verbose)
203 argv[argc++] = "-v";
204 argv[argc++] = NULL;
206 /* obnoxious casts */
207 execvp(argv0, (char *const *)argv);
208 fatal("execvp %s", argv0);
211 /* daemon main routine */
212 static __dead int
213 amused_main(void)
215 int pipe_main2player[2];
216 int control_fd;
218 log_init(debug, LOG_DAEMON);
219 log_setverbose(verbose);
220 log_procinit("main");
222 if (!debug)
223 daemon(1, 0);
225 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
226 PF_UNSPEC, pipe_main2player) == -1)
227 fatal("socketpair");
229 player_pid = start_child(PROC_PLAYER, pipe_main2player[1]);
231 event_init();
233 signal_set(&ev_sigint, SIGINT, main_sig_handler, NULL);
234 signal_set(&ev_sigterm, SIGTERM, main_sig_handler, NULL);
236 signal_add(&ev_sigint, NULL);
237 signal_add(&ev_sigterm, NULL);
239 signal(SIGHUP, SIG_IGN);
240 signal(SIGCHLD, SIG_IGN);
241 signal(SIGPIPE, SIG_IGN);
243 iev_player = xmalloc(sizeof(*iev_player));
244 imsg_init(&iev_player->ibuf, pipe_main2player[0]);
245 iev_player->handler = main_dispatch_player;
246 iev_player->events = EV_READ;
247 event_set(&iev_player->ev, iev_player->ibuf.fd, iev_player->events,
248 iev_player->handler, iev_player);
249 event_add(&iev_player->ev, NULL);
251 if ((control_fd = control_init(csock)) == -1)
252 fatal("control socket setup failed %s", csock);
253 control_listen(control_fd);
255 if (pledge("stdio rpath unix sendfd", NULL) == -1)
256 fatal("pledge");
258 log_info("startup");
259 event_dispatch();
260 main_shutdown();
263 int
264 main(int argc, char **argv)
266 int ch, proc = PROC_MAIN;
268 log_init(1, LOG_DAEMON); /* Log to stderr until daemonized */
269 log_setverbose(1);
271 argv0 = argv[0];
272 if (argv0 == NULL)
273 argv0 = "amused";
275 while ((ch = getopt(argc, argv, "ds:T:v")) != -1) {
276 switch (ch) {
277 case 'd':
278 debug = 1;
279 break;
280 case 's':
281 free(csock);
282 csock = xstrdup(optarg);
283 break;
284 case 'T':
285 switch (*optarg) {
286 case 'p':
287 proc = PROC_PLAYER;
288 break;
289 default:
290 usage();
292 break;
293 case 'v':
294 verbose++;
295 break;
296 default:
297 usage();
300 argv += optind;
301 argc -= optind;
303 if (proc == PROC_PLAYER)
304 exit(player(debug, verbose));
306 if (csock == NULL)
307 xasprintf(&csock, "/tmp/amused-%d", getuid());
309 if (argc == 0)
310 amused_main();
311 else
312 ctl(argc, argv);
313 return 0;
316 void
317 spawn_daemon(void)
319 debug = 0;
320 start_child(PROC_MAIN, -1);
323 void
324 imsg_event_add(struct imsgev *iev)
326 iev->events = EV_READ;
327 if (iev->ibuf.w.queued)
328 iev->events |= EV_WRITE;
330 event_del(&iev->ev);
331 event_set(&iev->ev, iev->ibuf.fd, iev->events, iev->handler, iev);
332 event_add(&iev->ev, NULL);
335 int
336 imsg_compose_event(struct imsgev *iev, uint16_t type, uint32_t peerid,
337 pid_t pid, int fd, const void *data, uint16_t datalen)
339 int ret;
341 if ((ret = imsg_compose(&iev->ibuf, type, peerid, pid, fd, data,
342 datalen)) != -1)
343 imsg_event_add(iev);
345 return ret;
348 int
349 main_send_player(uint16_t type, int fd, const void *data, uint16_t datalen)
351 return imsg_compose_event(iev_player, type, 0, 0, fd, data, datalen);
354 int
355 main_play_song(const char *song)
357 struct stat sb;
358 char path[PATH_MAX] = { 0 };
359 int fd;
361 strlcpy(path, song, sizeof(path));
362 if ((fd = open(path, O_RDONLY)) == -1) {
363 log_warn("open %s", path);
364 return 0;
367 if (fstat(fd, &sb) == -1) {
368 log_warn("failed to stat %s", path);
369 close(fd);
370 return 0;
373 if (S_ISDIR(sb.st_mode)) {
374 log_info("skipping a directory: %s", path);
375 close(fd);
376 return 0;
379 play_state = STATE_PLAYING;
380 imsg_compose_event(iev_player, IMSG_PLAY, 0, 0, fd,
381 path, sizeof(path));
382 return 1;
385 void
386 main_playlist_jump(struct imsgev *iev, struct imsg *imsg)
388 size_t datalen;
389 char arg[PATH_MAX];
390 const char *song;
392 datalen = IMSG_DATA_SIZE(*imsg);
393 if (datalen != sizeof(arg)) {
394 main_senderr(iev, "wrong size");
395 return;
398 memcpy(arg, imsg->data, sizeof(arg));
399 if (arg[sizeof(arg)-1] != '\0') {
400 main_senderr(iev, "data corrupted");
401 return;
404 song = playlist_jump(arg);
405 if (song == NULL) {
406 main_senderr(iev, "not found");
407 return;
410 main_send_player(IMSG_STOP, -1, NULL, 0);
411 if (!main_play_song(song)) {
412 main_senderr(iev, "can't play");
413 playlist_dropcurrent();
414 main_playlist_advance();
415 return;
418 main_send_status(iev);
421 void
422 main_playlist_resume(void)
424 const char *song;
426 if ((song = current_song) == NULL)
427 song = playlist_advance();
429 for (; song != NULL; song = playlist_advance()) {
430 if (main_play_song(song))
431 return;
433 playlist_dropcurrent();
437 void
438 main_playlist_advance(void)
440 const char *song;
442 for (;;) {
443 song = playlist_advance();
444 if (song == NULL)
445 return;
447 if (main_play_song(song))
448 break;
450 playlist_dropcurrent();
454 void
455 main_playlist_previous(void)
457 const char *song;
459 for (;;) {
460 song = playlist_previous();
461 if (song == NULL)
462 return;
464 if (main_play_song(song))
465 break;
467 playlist_dropcurrent();
471 void
472 main_restart_track(void)
474 const char *song;
476 song = current_song;
477 if (song == NULL)
478 return;
480 if (main_play_song(song))
481 return;
483 playlist_dropcurrent();
484 main_playlist_advance();
487 void
488 main_senderr(struct imsgev *iev, const char *msg)
490 imsg_compose_event(iev, IMSG_CTL_ERR, 0, 0, -1,
491 msg, strlen(msg)+1);
494 void
495 main_enqueue(int tx, struct playlist *px, struct imsgev *iev,
496 struct imsg *imsg)
498 size_t datalen;
499 char path[PATH_MAX] = { 0 };
500 const char *err = NULL;
502 datalen = IMSG_DATA_SIZE(*imsg);
503 if (datalen != sizeof(path)) {
504 err = "data size mismatch";
505 goto err;
508 memcpy(path, imsg->data, sizeof(path));
509 if (path[datalen-1] != '\0') {
510 err = "malformed data";
511 goto err;
514 if (tx)
515 playlist_push(px, path);
516 else
517 playlist_enqueue(path);
518 imsg_compose_event(iev, IMSG_CTL_ADD, 0, 0, -1, path, sizeof(path));
519 return;
520 err:
521 main_senderr(iev, err);
524 void
525 main_send_playlist(struct imsgev *iev)
527 struct player_status s;
528 size_t i;
530 for (i = 0; i < playlist.len; ++i) {
531 memset(&s, 0, sizeof(s));
532 strlcpy(s.path, playlist.songs[i], sizeof(s.path));
533 s.status = play_off == i ? STATE_PLAYING : STATE_STOPPED;
534 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, &s,
535 sizeof(s));
538 imsg_compose_event(iev, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
541 void
542 main_send_status(struct imsgev *iev)
544 struct player_status s;
546 memset(&s, 0, sizeof(s));
548 if (current_song != NULL)
549 strlcpy(s.path, current_song, sizeof(s.path));
550 s.status = play_state;
551 s.rp.repeat_all = repeat_all;
552 s.rp.repeat_one = repeat_one;
554 imsg_compose_event(iev, IMSG_CTL_STATUS, 0, 0, -1, &s, sizeof(s));