2 * Copyright (c) 2023 Omar Polo <op@omarpolo.com>
3 * Copyright (c) 2014 Reyk Floeter <reyk@openbsd.org>
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 #include <sys/socket.h>
21 #include <sys/types.h>
47 #define nitems(x) (sizeof(x)/sizeof(x[0]))
50 #define FORM_URLENCODED "application/x-www-form-urlencoded"
52 #define ICON_REPEAT_ALL "🔁"
53 #define ICON_REPEAT_ONE "🔂"
57 #define ICON_PAUSE "⏸"
58 #define ICON_TOGGLE "⏯"
61 static struct imsgbuf ibuf;
62 static struct playlist playlist_tmp;
63 static struct player_status player_status;
64 static uint64_t position, duration;
65 static const char *prefix = "";
66 static size_t prefixlen;
68 const char *head = "<!doctype html>"
71 "<meta name='viewport' content='width=device-width, initial-scale=1'/>"
72 "<title>Amused Web</title>"
73 "<link rel='stylesheet' href='/style.css?v=0'>"
78 const char *css = "*{box-sizing:border-box}"
86 " flex-direction: column;"
88 "button{cursor:pointer}"
97 ".playlist-wrapper{min-height:80vh}"
104 " font-family: monospace;"
109 " background: transparent;"
110 " transition: background-color .25s ease-in-out;"
112 ".playlist button::before{"
115 " display: inline-block;"
117 ".playlist button:hover{"
118 " background-color: #dfdddd;"
120 ".playlist #current button{"
121 " font-weight: bold;"
123 ".playlist #current button::before{"
125 " font-weight: bold;"
133 " background-color: white;"
134 " background: #3d3d3d;"
136 " border-radius: 10px 10px 0 0;"
138 " text-align: center;"
148 " font-size: 0.9rem;"
152 " padding: 5px 20px;"
160 " if (e) {e.preventDefault()}"
161 " let cur = document.querySelector('#current');"
162 " if (cur) {cur.scrollIntoView(); window.scrollBy(0, -100);}"
165 "document.querySelector('.controls a').addEventListener('click',cur)";
167 const char *foot = "<script src='/app.js?v=0'></script></body></html>";
170 dial(const char *sock)
172 struct sockaddr_un sa;
176 memset(&sa, 0, sizeof(sa));
177 sa.sun_family = AF_UNIX;
178 len = strlcpy(sa.sun_path, sock, sizeof(sa.sun_path));
179 if (len >= sizeof(sa.sun_path))
180 err(1, "path too long: %s", sock);
182 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
184 if (connect(s, (struct sockaddr *)&sa, sizeof(sa)) == -1)
185 err(1, "failed to connect to %s", sock);
191 * Adapted from usr.sbin/httpd/httpd.c' url_decode.
194 url_decode(char *url)
204 /* Encoding character is followed by two hex chars */
205 if (!isxdigit((unsigned char)p[1]) ||
206 !isxdigit((unsigned char)p[2]) ||
207 (p[1] == '0' && p[2] == '0'))
214 * We don't have to validate "hex" because it is
215 * guaranteed to include two hex chars followed
218 x = strtoul(hex, NULL, 16);
238 imsg_dispatch(int fd, int ev, void *d)
241 static int off_found;
243 struct player_status ps;
244 struct player_event event;
249 if (ev & (POLLIN|POLLHUP)) {
250 if ((n = imsg_read(&ibuf)) == -1 && errno != EAGAIN)
253 fatalx("pipe closed");
256 if ((n = msgbuf_write(&ibuf.w)) == -1 && errno != EAGAIN)
257 fatal("msgbuf_write");
259 fatalx("pipe closed");
263 if ((n = imsg_get(&ibuf, &imsg)) == -1)
268 datalen = IMSG_DATA_SIZE(imsg);
270 switch (imsg.hdr.type) {
273 if (datalen == 0 || msg[datalen - 1] != '\0')
274 fatalx("malformed error message");
275 log_warnx("error: %s", msg);
279 playlist_free(&playlist_tmp);
280 imsg_compose(&ibuf, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
283 case IMSG_CTL_MONITOR:
284 if (datalen != sizeof(event))
285 fatalx("corrupted IMSG_CTL_MONITOR");
286 memcpy(&event, imsg.data, sizeof(event));
287 switch (event.event) {
292 imsg_compose(&ibuf, IMSG_CTL_STATUS, 0, 0, -1,
299 case IMSG_CTL_COMMIT:
300 imsg_compose(&ibuf, IMSG_CTL_SHOW, 0, 0, -1,
302 imsg_compose(&ibuf, IMSG_CTL_STATUS, 0, 0, -1,
307 position = event.position;
308 duration = event.duration;
312 log_debug("ignoring event %d", event.event);
319 playlist_swap(&playlist_tmp, off);
320 memset(&playlist_tmp, 0, sizeof(playlist_tmp));
325 if (datalen != sizeof(ps))
326 fatalx("corrupted IMSG_CTL_SHOW");
327 memcpy(&ps, imsg.data, sizeof(ps));
328 if (ps.path[sizeof(ps.path) - 1] != '\0')
329 fatalx("corrupted IMSG_CTL_SHOW");
330 playlist_push(&playlist_tmp, ps.path);
331 if (ps.status == STATE_PLAYING)
337 case IMSG_CTL_STATUS:
338 if (datalen != sizeof(player_status))
339 fatalx("corrupted IMSG_CTL_STATUS");
340 memcpy(&player_status, imsg.data, datalen);
341 if (player_status.path[sizeof(player_status.path) - 1]
343 fatalx("corrupted IMSG_CTL_STATUS");
351 ev_add(fd, ev, imsg_dispatch, NULL);
355 route_notfound(struct client *clt)
357 if (http_reply(clt, 404, "Not Found", "text/plain") == -1 ||
358 http_writes(clt, "Page not found\n") == -1)
363 render_playlist(struct client *clt)
366 const char *path, *p;
369 http_writes(clt, "<section class='playlist-wrapper'>");
370 http_writes(clt, "<form action=jump method=post"
371 " enctype='"FORM_URLENCODED"'>");
372 http_writes(clt, "<ul class=playlist>");
374 for (i = 0; i < playlist.len; ++i) {
375 current = play_off == i;
377 p = path = playlist.songs[i];
378 if (!strncmp(p, prefix, prefixlen))
381 http_fmt(clt, "<li%s>", current ? " id=current" : "");
382 http_writes(clt, "<button type=submit name=jump value=\"");
383 http_htmlescape(clt, path);
384 http_writes(clt, "\">");
385 http_htmlescape(clt, p);
386 http_writes(clt, "</button></li>");
389 http_writes(clt, "</ul>");
390 http_writes(clt, "</form>");
391 http_writes(clt, "</section>");
395 render_controls(struct client *clt)
397 const char *oc, *ac, *p;
400 ac = player_status.mode.repeat_all ? " class='mode-active'" : "";
401 oc = player_status.mode.repeat_one ? " class='mode-active'" : "";
402 playing = player_status.status == STATE_PLAYING;
404 if ((p = strrchr(player_status.path, '/')) != NULL)
407 p = player_status.path;
409 if (http_writes(clt, "<section class=controls>") == -1 ||
410 http_writes(clt, "<p><a href='#current'>") == -1 ||
411 http_htmlescape(clt, p) == -1 ||
412 http_writes(clt, "</a></p>") == -1 ||
413 http_writes(clt, "<form action=ctrls method=post"
414 " enctype='"FORM_URLENCODED"'>") == -1 ||
415 http_writes(clt, "<button type=submit name=ctl value=prev>"
416 ICON_PREV"</button>") == -1 ||
417 http_fmt(clt, "<button type=submit name=ctl value=%s>"
418 "%s</button>", playing ? "pause" : "play",
419 playing ? ICON_PAUSE : ICON_PLAY) == -1 ||
420 http_writes(clt, "<button type=submit name=ctl value=next>"
421 ICON_NEXT"</button>") == -1 ||
422 http_writes(clt, "</form>") == -1 ||
423 http_writes(clt, "<form action=mode method=post"
424 " enctype='"FORM_URLENCODED"'>") == -1 ||
425 http_fmt(clt, "<button%s type=submit name=mode value=all>"
426 ICON_REPEAT_ALL"</button>", ac) == -1 ||
427 http_fmt(clt, "<button%s type=submit name=mode value=one>"
428 ICON_REPEAT_ONE"</button>", oc) == -1 ||
429 http_writes(clt, "</form>") == -1 ||
430 http_writes(clt, "</section>") == -1)
435 route_home(struct client *clt)
437 if (http_reply(clt, 200, "OK", "text/html;charset=UTF-8") == -1)
440 if (http_write(clt, head, strlen(head)) == -1)
443 if (http_writes(clt, "<main>") == -1)
446 if (http_writes(clt, "<section class=searchbox>"
447 "<input type=search name=filter aria-label='Filter playlist'"
448 " placeholder='Filter playlist' id=search />"
452 render_controls(clt);
453 render_playlist(clt);
455 if (http_writes(clt, "</main>") == -1)
458 http_write(clt, foot, strlen(foot));
462 route_jump(struct client *clt)
469 while ((field = strsep(&form, "&")) != NULL) {
470 if (url_decode(field) == -1)
473 if (strncmp(field, "jump=", 5) != 0)
478 memset(&path, 0, sizeof(path));
479 if (strlcpy(path, field, sizeof(path)) >= sizeof(path))
482 log_warnx("path is %s", path);
483 imsg_compose(&ibuf, IMSG_CTL_JUMP, 0, 0, -1,
485 ev_add(ibuf.w.fd, POLLIN|POLLOUT, imsg_dispatch, NULL);
492 http_reply(clt, 302, "See Other", "/");
496 http_reply(clt, 400, "Bad Request", "text/plain");
497 http_writes(clt, "Bad Request.\n");
501 route_controls(struct client *clt)
507 while ((field = strsep(&form, "&")) != NULL) {
508 if (url_decode(field) == -1)
511 if (strncmp(field, "ctl=", 4) != 0)
516 if (!strcmp(field, "play"))
518 else if (!strcmp(field, "pause"))
519 cmd = IMSG_CTL_PAUSE;
520 else if (!strcmp(field, "next"))
522 else if (!strcmp(field, "prev"))
527 imsg_compose(&ibuf, cmd, 0, 0, -1, NULL, 0);
535 http_reply(clt, 302, "See Other", "/");
539 http_reply(clt, 400, "Bad Request", "text/plain");
540 http_writes(clt, "Bad Request.\n");
544 route_mode(struct client *clt)
548 struct player_mode pm;
550 pm.repeat_one = pm.repeat_all = pm.consume = MODE_UNDEF;
553 while ((field = strsep(&form, "&")) != NULL) {
554 if (url_decode(field) == -1)
557 if (strncmp(field, "mode=", 5) != 0)
562 if (!strcmp(field, "all"))
563 pm.repeat_all = MODE_TOGGLE;
564 else if (!strcmp(field, "one"))
565 pm.repeat_one = MODE_TOGGLE;
569 imsg_compose(&ibuf, IMSG_CTL_MODE, 0, 0, -1, &pm, sizeof(pm));
570 ev_add(ibuf.w.fd, POLLIN|POLLOUT, imsg_dispatch, NULL);
577 http_reply(clt, 302, "See Other", "/");
581 http_reply(clt, 400, "Bad Request", "text/plain");
582 http_writes(clt, "Bad Request.\n");
586 route_assets(struct client *clt)
588 if (!strcmp(clt->req.path, "/style.css")) {
589 http_reply(clt, 200, "OK", "text/css");
590 http_write(clt, css, strlen(css));
594 if (!strcmp(clt->req.path, "/app.js")) {
595 http_reply(clt, 200, "OK", "application/javascript");
596 http_write(clt, js, strlen(js));
604 route_dispatch(struct client *clt)
606 static const struct route {
611 { METHOD_GET, "/", &route_home },
612 { METHOD_POST, "/jump", &route_jump },
613 { METHOD_POST, "/ctrls", &route_controls },
614 { METHOD_POST, "/mode", &route_mode },
616 { METHOD_GET, "/style.css", &route_assets },
617 { METHOD_GET, "/app.js", &route_assets },
619 { METHOD_GET, "*", &route_notfound },
620 { METHOD_POST, "*", &route_notfound },
622 struct request *req = &clt->req;
625 if ((req->method != METHOD_GET && req->method != METHOD_POST) ||
626 (req->ctype != NULL && strcmp(req->ctype, FORM_URLENCODED) != 0) ||
628 http_reply(clt, 400, "Bad Request", NULL);
632 for (i = 0; i < nitems(routes); ++i) {
633 if (req->method != routes[i].method ||
634 fnmatch(routes[i].path, req->path, 0) != 0)
636 clt->done = 1; /* assume with one round is done */
637 clt->route = routes[i].route;
646 client_ev(int fd, int ev, void *d)
648 struct client *clt = d;
650 if (ev & (POLLIN|POLLHUP)) {
651 if (bufio_read(&clt->bio) == -1 && errno != EAGAIN) {
652 log_warn("bufio_read");
658 if (bufio_write(&clt->bio) == -1 && errno != EAGAIN) {
659 log_warn("bufio_read");
664 if (clt->route == NULL) {
665 if (http_parse(clt) == -1) {
668 log_warnx("HTTP parse request failed");
671 if (clt->req.method == METHOD_POST &&
672 http_read(clt) == -1) {
675 log_warnx("failed to read POST data");
686 ev = bufio_pollev(&clt->bio);
687 if (ev == POLLIN && clt->done) {
688 goto err; /* done with this client */
691 ev_add(fd, ev, client_ev, clt);
700 web_accept(int psock, int ev, void *d)
705 if ((sock = accept(psock, NULL, NULL)) == -1) {
709 clt = xcalloc(1, sizeof(*clt));
710 if ((clt = calloc(1, sizeof(*clt))) == NULL ||
711 http_init(clt, sock) == -1) {
712 log_warn("failed to initialize client");
718 client_ev(sock, POLLIN, clt);
725 fprintf(stderr, "usage: %s [-v] [-s sock] [-t prefix] [[host] port]\n",
731 main(int argc, char **argv)
733 struct addrinfo hints, *res, *res0;
734 const char *cause = NULL;
735 const char *host = NULL;
736 const char *port = "9090";
738 size_t nsock, error, save_errno;
739 int ch, v, amused_sock, fd;
742 setlocale(LC_ALL, NULL);
744 log_init(1, LOG_DAEMON);
746 if (pledge("stdio rpath unix inet dns", NULL) == -1)
749 while ((ch = getopt(argc, argv, "s:t:v")) != -1) {
756 prefixlen = strlen(prefix);
777 log_setverbose(verbose);
780 xasprintf(&sock, "/tmp/amused-%d", getuid());
782 signal(SIGPIPE, SIG_IGN);
787 amused_sock = dial(sock);
788 imsg_init(&ibuf, amused_sock);
789 imsg_compose(&ibuf, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
790 imsg_compose(&ibuf, IMSG_CTL_STATUS, 0, 0, -1, NULL, 0);
791 imsg_compose(&ibuf, IMSG_CTL_MONITOR, 0, 0, -1, NULL, 0);
792 ev_add(amused_sock, POLLIN|POLLOUT, imsg_dispatch, NULL);
794 memset(&hints, 0, sizeof(hints));
795 hints.ai_family = AF_UNSPEC;
796 hints.ai_socktype = SOCK_STREAM;
797 hints.ai_flags = AI_PASSIVE;
798 error = getaddrinfo(host, port, &hints, &res0);
800 errx(1, "%s", gai_strerror(error));
803 for (res = res0; res; res = res->ai_next) {
804 fd = socket(res->ai_family, res->ai_socktype,
812 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
813 &v, sizeof(v)) == -1)
814 fatal("setsockopt(SO_REUSEADDR)");
816 if (bind(fd, res->ai_addr, res->ai_addrlen) == -1) {
824 if (listen(fd, 5) == -1)
827 if (ev_add(fd, POLLIN, web_accept, NULL) == -1)
835 if (pledge("stdio inet", NULL) == -1)
838 log_info("starting");