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 const char *prefix = "";
63 static size_t prefixlen;
65 const char *head = "<!doctype html>"
68 "<meta name='viewport' content='width=device-width, initial-scale=1'/>"
69 "<title>Amused Web</title>"
71 "*{box-sizing:border-box}"
79 " flex-direction: column;"
81 "button{cursor:pointer}"
90 ".playlist-wrapper{min-height:80vh}"
97 " font-family: monospace;"
102 " background: transparent;"
103 " transition: background-color .25s ease-in-out;"
105 ".playlist button::before{"
108 " display: inline-block;"
110 ".playlist button:hover{"
111 " background-color: #dfdddd;"
113 ".playlist #current button{"
114 " font-weight: bold;"
116 ".playlist #current button::before{"
118 " font-weight: bold;"
126 " background-color: white;"
127 " background: #3d3d3d;"
129 " border-radius: 10px 10px 0 0;"
131 " text-align: center;"
141 " font-size: 0.9rem;"
145 " padding: 5px 20px;"
154 const char *foot = "<script>"
156 " if (e) {e.preventDefault()}"
157 " let cur = document.querySelector('#current');"
158 " if (cur) {cur.scrollIntoView(); window.scrollBy(0, -100);}"
161 "document.querySelector('.controls a').addEventListener('click',cur)"
162 "</script></body></html>";
165 dial(const char *sock)
167 struct sockaddr_un sa;
171 memset(&sa, 0, sizeof(sa));
172 sa.sun_family = AF_UNIX;
173 len = strlcpy(sa.sun_path, sock, sizeof(sa.sun_path));
174 if (len >= sizeof(sa.sun_path))
175 err(1, "path too long: %s", sock);
177 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
179 if (connect(s, (struct sockaddr *)&sa, sizeof(sa)) == -1)
180 err(1, "failed to connect to %s", sock);
187 * Adapted from usr.sbin/httpd/httpd.c' url_decode.
190 url_decode(char *url)
200 /* Encoding character is followed by two hex chars */
201 if (!isxdigit((unsigned char)p[1]) ||
202 !isxdigit((unsigned char)p[2]) ||
203 (p[1] == '0' && p[2] == '0'))
210 * We don't have to validate "hex" because it is
211 * guaranteed to include two hex chars followed
214 x = strtoul(hex, NULL, 16);
234 unexpected_imsg(struct imsg *imsg, const char *expected)
239 if (imsg->hdr.type != IMSG_CTL_ERR) {
240 log_warnx("got event %d while expecting %s",
241 imsg->hdr.type, expected);
245 datalen = IMSG_DATA_SIZE(*imsg);
247 if (datalen == 0 || msg[datalen - 1] != '\0')
248 fatalx("malformed error message");
249 log_warnx("failure: %s", msg);
253 route_notfound(struct client *clt)
255 if (http_reply(clt, 404, "Not Found", "text/plain") == -1 ||
256 http_writes(clt, "Page not found\n") == -1)
261 render_playlist(struct client *clt)
264 struct player_status ps;
269 imsg_compose(&ibuf, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
272 http_writes(clt, "<section class='playlist-wrapper'>");
273 http_writes(clt, "<form action=jump method=post"
274 " enctype='"FORM_URLENCODED"'>");
275 http_writes(clt, "<ul class=playlist>");
279 if ((n = imsg_read(&ibuf)) == -1)
282 fatalx("pipe closed");
285 if ((n = imsg_get(&ibuf, &imsg)) == -1)
290 if (imsg.hdr.type != IMSG_CTL_SHOW) {
291 unexpected_imsg(&imsg, "IMSG_CTL_SHOW");
296 if (IMSG_DATA_SIZE(imsg) == 0) {
301 if (IMSG_DATA_SIZE(imsg) != sizeof(ps))
302 fatalx("wrong size for seek ctl");
303 memcpy(&ps, imsg.data, sizeof(ps));
304 if (ps.path[sizeof(ps.path) - 1] != '\0')
305 fatalx("received corrupted data");
307 current = ps.status == STATE_PLAYING;
310 if (!strncmp(p, prefix, prefixlen))
313 http_fmt(clt, "<li%s>",
314 current ? " id=current" : "");
316 "<button type=submit name=jump value=\"");
317 http_htmlescape(clt, ps.path);
318 http_writes(clt, "\">");
319 http_htmlescape(clt, p);
320 http_writes(clt, "</button></li>");
326 http_writes(clt, "</ul>");
327 http_writes(clt, "</form>");
328 http_writes(clt, "</section>");
332 render_controls(struct client *clt)
335 struct player_status ps;
337 const char *oc, *ac, *p;
340 imsg_compose(&ibuf, IMSG_CTL_STATUS, 0, 0, -1, NULL, 0);
343 if ((n = imsg_read(&ibuf)) == -1)
346 fatalx("pipe closed");
348 if ((n = imsg_get(&ibuf, &imsg)) == -1)
353 if (imsg.hdr.type != IMSG_CTL_STATUS) {
354 unexpected_imsg(&imsg, "IMSG_CTL_STATUS");
357 if (IMSG_DATA_SIZE(imsg) != sizeof(ps))
358 fatalx("wrong size for IMSG_CTL_STATUS");
359 memcpy(&ps, imsg.data, sizeof(ps));
360 if (ps.path[sizeof(ps.path) - 1] != '\0')
361 fatalx("received corrupted data");
363 ac = ps.mode.repeat_all ? " class='mode-active'" : "";
364 oc = ps.mode.repeat_one ? " class='mode-active'" : "";
365 playing = ps.status == STATE_PLAYING;
367 if ((p = strrchr(ps.path, '/')) != NULL)
372 if (http_writes(clt, "<section class=controls>") == -1 ||
373 http_writes(clt, "<p><a href='#current'>") == -1 ||
374 http_htmlescape(clt, p) == -1 ||
375 http_writes(clt, "</a></p>") == -1 ||
376 http_writes(clt, "<form action=ctrls method=post"
377 " enctype='"FORM_URLENCODED"'>") == -1 ||
378 http_writes(clt, "<button type=submit name=ctl value=prev>"
379 ICON_PREV"</button>") == -1 ||
380 http_fmt(clt, "<button type=submit name=ctl value=%s>"
381 "%s</button>", playing ? "pause" : "play",
382 playing ? ICON_PAUSE : ICON_PLAY) == -1 ||
383 http_writes(clt, "<button type=submit name=ctl value=next>"
384 ICON_NEXT"</button>") == -1 ||
385 http_writes(clt, "</form>") == -1 ||
386 http_writes(clt, "<form action=mode method=post"
387 " enctype='"FORM_URLENCODED"'>") == -1 ||
388 http_fmt(clt, "<button%s type=submit name=mode value=all>"
389 ICON_REPEAT_ALL"</button>", ac) == -1 ||
390 http_fmt(clt, "<button%s type=submit name=mode value=one>"
391 ICON_REPEAT_ONE"</button>", oc) == -1 ||
392 http_writes(clt, "</form>") == -1 ||
393 http_writes(clt, "</section>") == -1)
401 route_home(struct client *clt)
403 if (http_reply(clt, 200, "OK", "text/html;charset=UTF-8") == -1)
406 if (http_write(clt, head, strlen(head)) == -1)
409 if (http_writes(clt, "<main>") == -1)
412 if (http_writes(clt, "<section class=searchbox>"
413 "<input type=search name=filter aria-label='Filter playlist'"
414 " placeholder='Filter playlist' id=search />"
418 render_controls(clt);
419 render_playlist(clt);
421 if (http_writes(clt, "</main>") == -1)
424 http_write(clt, foot, strlen(foot));
428 route_jump(struct client *clt)
431 struct player_status ps;
438 while ((field = strsep(&form, "&")) != NULL) {
439 if (url_decode(field) == -1)
442 if (strncmp(field, "jump=", 5) != 0)
447 memset(&path, 0, sizeof(path));
448 if (strlcpy(path, field, sizeof(path)) >= sizeof(path))
451 log_warnx("path is %s", path);
452 imsg_compose(&ibuf, IMSG_CTL_JUMP, 0, 0, -1,
456 if ((n = imsg_read(&ibuf)) == -1)
459 fatalx("pipe closed");
462 if ((n = imsg_get(&ibuf, &imsg)) == -1)
467 if (imsg.hdr.type != IMSG_CTL_STATUS) {
468 unexpected_imsg(&imsg, "IMSG_CTL_STATUS");
473 if (IMSG_DATA_SIZE(imsg) != sizeof(ps))
474 fatalx("data size mismatch");
475 memcpy(&ps, imsg.data, sizeof(ps));
476 if (ps.path[sizeof(ps.path) - 1] != '\0')
477 fatalx("received corrupted data");
478 log_debug("jumped to %s", ps.path);
487 http_reply(clt, 302, "See Other", "/");
491 http_reply(clt, 400, "Bad Request", "text/plain");
492 http_writes(clt, "Bad Request.\n");
496 route_controls(struct client *clt)
502 while ((field = strsep(&form, "&")) != NULL) {
503 if (url_decode(field) == -1)
506 if (strncmp(field, "ctl=", 4) != 0)
511 if (!strcmp(field, "play"))
513 else if (!strcmp(field, "pause"))
514 cmd = IMSG_CTL_PAUSE;
515 else if (!strcmp(field, "next"))
517 else if (!strcmp(field, "prev"))
522 imsg_compose(&ibuf, cmd, 0, 0, -1, NULL, 0);
530 http_reply(clt, 302, "See Other", "/");
534 http_reply(clt, 400, "Bad Request", "text/plain");
535 http_writes(clt, "Bad Request.\n");
539 route_mode(struct client *clt)
544 struct player_status ps;
545 struct player_mode pm;
548 pm.repeat_one = pm.repeat_all = pm.consume = MODE_UNDEF;
551 while ((field = strsep(&form, "&")) != NULL) {
552 if (url_decode(field) == -1)
555 if (strncmp(field, "mode=", 5) != 0)
560 if (!strcmp(field, "all"))
561 pm.repeat_all = MODE_TOGGLE;
562 else if (!strcmp(field, "one"))
563 pm.repeat_one = MODE_TOGGLE;
567 imsg_compose(&ibuf, IMSG_CTL_MODE, 0, 0, -1, &pm, sizeof(pm));
570 if ((n = imsg_read(&ibuf)) == -1)
573 fatalx("pipe closed");
576 if ((n = imsg_get(&ibuf, &imsg)) == -1)
581 if (imsg.hdr.type != IMSG_CTL_STATUS) {
582 unexpected_imsg(&imsg, "IMSG_CTL_STATUS");
587 if (IMSG_DATA_SIZE(imsg) != sizeof(ps))
588 fatalx("data size mismatch");
589 memcpy(&ps, imsg.data, sizeof(ps));
590 if (ps.path[sizeof(ps.path) - 1] != '\0')
591 fatalx("received corrupted data");
600 http_reply(clt, 302, "See Other", "/");
604 http_reply(clt, 400, "Bad Request", "text/plain");
605 http_writes(clt, "Bad Request.\n");
609 route_dispatch(struct client *clt)
611 static const struct route {
616 { METHOD_GET, "/", &route_home },
617 { METHOD_POST, "/jump", &route_jump },
618 { METHOD_POST, "/ctrls", &route_controls },
619 { METHOD_POST, "/mode", &route_mode },
621 { METHOD_GET, "*", &route_notfound },
622 { METHOD_POST, "*", &route_notfound },
624 struct request *req = &clt->req;
627 if ((req->method != METHOD_GET && req->method != METHOD_POST) ||
628 (req->ctype != NULL && strcmp(req->ctype, FORM_URLENCODED) != 0) ||
630 http_reply(clt, 400, "Bad Request", NULL);
634 for (i = 0; i < nitems(routes); ++i) {
635 if (req->method != routes[i].method ||
636 fnmatch(routes[i].path, req->path, 0) != 0)
638 clt->done = 1; /* assume with one round is done */
639 clt->route = routes[i].route;
648 client_ev(int fd, int ev, void *d)
650 struct client *clt = d;
652 if (ev & (POLLIN|POLLHUP)) {
653 if (bufio_read(&clt->bio) == -1 && errno != EAGAIN) {
654 log_warn("bufio_read");
660 if (bufio_write(&clt->bio) == -1 && errno != EAGAIN) {
661 log_warn("bufio_read");
666 if (clt->route == NULL) {
667 if (http_parse(clt) == -1) {
670 log_warnx("HTTP parse request failed");
673 if (clt->req.method == METHOD_POST &&
674 http_read(clt) == -1) {
677 log_warnx("failed to read POST data");
688 ev = bufio_pollev(&clt->bio);
689 if (ev == POLLIN && clt->done) {
690 goto err; /* done with this client */
693 ev_add(fd, ev, client_ev, clt);
702 web_accept(int psock, int ev, void *d)
707 if ((sock = accept(psock, NULL, NULL)) == -1) {
711 clt = xcalloc(1, sizeof(*clt));
712 if ((clt = calloc(1, sizeof(*clt))) == NULL ||
713 http_init(clt, sock) == -1) {
714 log_warn("failed to initialize client");
720 client_ev(sock, POLLIN, clt);
727 fprintf(stderr, "usage: %s [-v] [-s sock] [-t prefix] [[host] port]\n",
733 main(int argc, char **argv)
735 struct addrinfo hints, *res, *res0;
736 const char *cause = NULL;
737 const char *host = NULL;
738 const char *port = "9090";
740 size_t nsock, error, save_errno;
741 int ch, v, amused_sock, fd;
744 setlocale(LC_ALL, NULL);
746 log_init(1, LOG_DAEMON);
748 if (pledge("stdio rpath unix inet dns", NULL) == -1)
751 while ((ch = getopt(argc, argv, "s:t:v")) != -1) {
758 prefixlen = strlen(prefix);
779 log_setverbose(verbose);
782 xasprintf(&sock, "/tmp/amused-%d", getuid());
784 signal(SIGPIPE, SIG_IGN);
789 amused_sock = dial(sock);
790 imsg_init(&ibuf, amused_sock);
792 memset(&hints, 0, sizeof(hints));
793 hints.ai_family = AF_UNSPEC;
794 hints.ai_socktype = SOCK_STREAM;
795 hints.ai_flags = AI_PASSIVE;
796 error = getaddrinfo(host, port, &hints, &res0);
798 errx(1, "%s", gai_strerror(error));
801 for (res = res0; res; res = res->ai_next) {
802 fd = socket(res->ai_family, res->ai_socktype,
810 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
811 &v, sizeof(v)) == -1)
812 fatal("setsockopt(SO_REUSEADDR)");
814 if (bind(fd, res->ai_addr, res->ai_addrlen) == -1) {
822 if (listen(fd, 5) == -1)
825 if (ev_add(fd, POLLIN, web_accept, NULL) == -1)
833 if (pledge("stdio inet", NULL) == -1)
836 log_info("starting");