Blob


1 /*
2 * Copyright (c) 2023 Omar Polo <op@omarpolo.com>
3 * Copyright (c) 2014 Reyk Floeter <reyk@openbsd.org>
4 *
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.
8 *
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.
16 */
18 #include "config.h"
20 #include <sys/socket.h>
21 #include <sys/types.h>
22 #include <sys/un.h>
24 #include <ctype.h>
25 #include <errno.h>
26 #include <fnmatch.h>
27 #include <limits.h>
28 #include <locale.h>
29 #include <netdb.h>
30 #include <poll.h>
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <syslog.h>
36 #include <unistd.h>
38 #include "amused.h"
39 #include "bufio.h"
40 #include "ev.h"
41 #include "http.h"
42 #include "log.h"
43 #include "playlist.h"
44 #include "ws.h"
45 #include "xmalloc.h"
47 #ifndef nitems
48 #define nitems(x) (sizeof(x)/sizeof(x[0]))
49 #endif
51 #define FORM_URLENCODED "application/x-www-form-urlencoded"
53 #define ICON_REPEAT_ALL "🔁"
54 #define ICON_REPEAT_ONE "🔂"
55 #define ICON_PREV "⏮"
56 #define ICON_NEXT "⏭"
57 #define ICON_STOP "⏹"
58 #define ICON_PAUSE "⏸"
59 #define ICON_TOGGLE "⏯"
60 #define ICON_PLAY "⏵"
62 static struct clthead clients;
63 static struct imsgbuf ibuf;
64 static struct playlist playlist_tmp;
65 static struct player_status player_status;
66 static uint64_t position, duration;
68 static void client_ev(int, int, void *);
70 const char *head = "<!doctype html>"
71 "<html>"
72 "<head>"
73 "<meta name='viewport' content='width=device-width, initial-scale=1'/>"
74 "<title>Amused Web</title>"
75 "<link rel='stylesheet' href='/style.css?v=0'>"
76 "</style>"
77 "</head>"
78 "<body>";
80 const char *css = "*{box-sizing:border-box}"
81 "html,body{"
82 " padding: 0;"
83 " border: 0;"
84 " margin: 0;"
85 "}"
86 "main{"
87 " display: flex;"
88 " flex-direction: column;"
89 "}"
90 "button{cursor:pointer}"
91 ".searchbox{"
92 " position: sticky;"
93 " top: 0;"
94 "}"
95 ".searchbox input{"
96 " width: 100%;"
97 " padding: 9px;"
98 "}"
99 ".playlist-wrapper{min-height:80vh}"
100 ".playlist{"
101 " list-style: none;"
102 " padding: 0;"
103 " margin: 0;"
104 "}"
105 ".playlist button{"
106 " font-family: monospace;"
107 " text-align: left;"
108 " width: 100%;"
109 " padding: 5px;"
110 " border: 0;"
111 " background: transparent;"
112 " transition: background-color .25s ease-in-out;"
113 "}"
114 ".playlist button::before{"
115 " content: \"\";"
116 " width: 2ch;"
117 " display: inline-block;"
118 "}"
119 ".playlist button:hover{"
120 " background-color: #dfdddd;"
121 "}"
122 ".playlist #current button{"
123 " font-weight: bold;"
124 "}"
125 ".playlist #current button::before{"
126 " content: \"→ \";"
127 " font-weight: bold;"
128 "}"
129 ".controls{"
130 " position: sticky;"
131 " width: 100%;"
132 " max-width: 800px;"
133 " margin: 0 auto;"
134 " bottom: 0;"
135 " background-color: white;"
136 " background: #3d3d3d;"
137 " color: white;"
138 " border-radius: 10px 10px 0 0;"
139 " padding: 10px;"
140 " text-align: center;"
141 " order: 2;"
142 "}"
143 ".controls p{"
144 " margin: .4rem;"
145 "}"
146 ".controls a{"
147 " color: white;"
148 "}"
149 ".controls .status{"
150 " font-size: 0.9rem;"
151 "}"
152 ".controls button{"
153 " margin: 5px;"
154 " padding: 5px 20px;"
155 "}"
156 ".mode-active{"
157 " color: #0064ff;"
158 "}";
160 const char *js =
161 "var ws;"
162 "let pos=0, dur=0;"
163 "const playlist=document.querySelector('.playlist');"
164 "function cur(e) {"
165 " if (e) {e.preventDefault()}"
166 " let cur = document.querySelector('#current');"
167 " if (cur) {cur.scrollIntoView(); window.scrollBy(0, -100);}"
168 "};"
169 "function b(x){return x=='on'};"
170 "function c(p, c){"
171 " const l=document.createElement('li');"
172 " if(c){l.id='current'};"
173 " const b=document.createElement('button');"
174 " b.type='submit'; b.name='jump'; b.value=p;"
175 " b.innerText=p;"
176 " l.appendChild(b);"
177 " playlist.appendChild(l);"
178 "}"
179 "function d(t){"
180 " const [, type, payload] = t.split(/^(.):(.*)$/);"
181 " if (type=='s'){"
182 " let s=payload.split(' ');"
183 " pos=s[0], dur=s[1];"
184 " } else if (type=='S') {"
185 " const btn=document.querySelector('#toggle');"
186 " if (payload=='playing') {"
187 " btn.innerHTML='"ICON_PAUSE"';"
188 " btn.value='pause';"
189 " } else {"
190 " btn.innerHTML='"ICON_PLAY"';"
191 " btn.value='play';"
192 " }"
193 " } else if (type=='r') {"
194 " const btn=document.querySelector('#rone');"
195 " btn.className=b(payload)?'mode-active':'';"
196 " } else if (type=='R') {"
197 " const btn=document.querySelector('#rall');"
198 " btn.className=b(payload)?'mode-active':'';"
199 " } else if (type=='c') {"
200 /* consume */
201 " } else if (type=='x') {"
202 " playlist.innerHTML='';"
203 " } else if (type=='X') {"
204 " dofilt();" /* done with the list */
205 " } else if (type=='A') {"
206 " c(payload, true);"
207 " } else if (type=='a') {"
208 " c(payload, false);"
209 " } else if (type=='C') {"
210 " const t=document.querySelector('.controls>p>a');"
211 " t.innerText = payload.replace(/.*\\//, '');"
212 " cur();"
213 " } else {"
214 " console.log('unknown:',t);"
215 " }"
216 "};"
217 "function w(){"
218 " ws = new WebSocket((location.protocol=='http:'?'ws://':'wss://')"
219 " + location.host + '/ws');"
220 " ws.addEventListener('open', () => console.log('ws: connected'));"
221 " ws.addEventListener('close', () => {"
222 " alert('Websocket closed. The interface won\\'t update itself.'"
223 " + ' Please refresh the page');"
224 " });"
225 " ws.addEventListener('message', e => d(e.data))"
226 "};"
227 "w();"
228 "cur();"
229 "document.querySelector('.controls a').addEventListener('click',cur);"
230 "document.querySelectorAll('form').forEach(f => {"
231 " f.action='/a/'+f.getAttribute('action');"
232 " f.addEventListener('submit', e => {"
233 " e.preventDefault();"
234 " const fd = new FormData(f);"
235 " if (e.submitter && e.submitter.value && e.submitter.value != '')"
236 " fd.append(e.submitter.name, e.submitter.value);"
237 " fetch(f.action, {"
238 " method:'POST',"
239 " body: new URLSearchParams(fd)"
240 " })"
241 " .catch(x => console.log('failed to submit form:', x));"
242 " });"
243 "});"
244 "const sb = document.createElement('section');"
245 "sb.className = 'searchbox';"
246 "const filter = document.createElement('input');"
247 "filter.type = 'search';"
248 "filter.setAttribute('aria-label', 'Filter Playlist');"
249 "filter.placeholder = 'Filter Playlist';"
250 "sb.append(filter);"
251 "document.querySelector('main').prepend(sb);"
252 "function dofilt() {"
253 " let t = filter.value.toLowerCase();"
254 " document.querySelectorAll('.playlist li').forEach(e => {"
255 " if (e.querySelector('button').value.toLowerCase().indexOf(t) == -1)"
256 " e.setAttribute('hidden', 'true');"
257 " else"
258 " e.removeAttribute('hidden');"
259 " });"
260 "};"
261 "function dbc(fn, wait) {"
262 " let tout;"
263 " return function() {"
264 " let later = () => {tout = null; fn()};"
265 " clearTimeout(tout);"
266 " if (!tout) fn();"
267 " tout = setTimeout(later, wait);"
268 " };"
269 "};"
270 "filter.addEventListener('input', dbc(dofilt, 400));"
273 const char *foot = "<script src='/app.js?v=0'></script></body></html>";
275 static int
276 dial(const char *sock)
278 struct sockaddr_un sa;
279 size_t len;
280 int s;
282 memset(&sa, 0, sizeof(sa));
283 sa.sun_family = AF_UNIX;
284 len = strlcpy(sa.sun_path, sock, sizeof(sa.sun_path));
285 if (len >= sizeof(sa.sun_path))
286 err(1, "path too long: %s", sock);
288 if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
289 err(1, "socket");
290 if (connect(s, (struct sockaddr *)&sa, sizeof(sa)) == -1)
291 err(1, "failed to connect to %s", sock);
293 return s;
296 /*
297 * Adapted from usr.sbin/httpd/httpd.c' url_decode.
298 */
299 static int
300 url_decode(char *url)
302 char*p, *q;
303 char hex[3] = {0};
304 unsigned long x;
306 p = q = url;
307 while (*p != '\0') {
308 switch (*p) {
309 case '%':
310 /* Encoding character is followed by two hex chars */
311 if (!isxdigit((unsigned char)p[1]) ||
312 !isxdigit((unsigned char)p[2]) ||
313 (p[1] == '0' && p[2] == '0'))
314 return (-1);
316 hex[0] = p[1];
317 hex[1] = p[2];
319 /*
320 * We don't have to validate "hex" because it is
321 * guaranteed to include two hex chars followed
322 * by NUL.
323 */
324 x = strtoul(hex, NULL, 16);
325 *q = (char)x;
326 p += 2;
327 break;
328 case '+':
329 *q = ' ';
330 break;
331 default:
332 *q = *p;
333 break;
335 p++;
336 q++;
338 *q = '\0';
340 return (0);
343 static int
344 dispatch_event(const char *msg)
346 struct client *clt;
347 size_t len;
348 int ret = 0;
350 len = strlen(msg);
351 TAILQ_FOREACH(clt, &clients, clients) {
352 if (!clt->ws || clt->done || clt->err)
353 continue;
355 if (ws_compose(clt, WST_TEXT, msg, len) == -1)
356 ret = -1;
358 ev_add(clt->bio.fd, POLLIN|POLLOUT, client_ev, clt);
361 return (ret);
364 static int
365 dispatch_event_status(void)
367 const char *status;
368 char buf[PATH_MAX + 2];
369 int r;
371 switch (player_status.status) {
372 case STATE_STOPPED: status = "stopped"; break;
373 case STATE_PLAYING: status = "playing"; break;
374 case STATE_PAUSED: status = "paused"; break;
375 default: status = "unknown";
378 r = snprintf(buf, sizeof(buf), "S:%s", status);
379 if (r < 0 || (size_t)r >= sizeof(buf)) {
380 log_warn("snprintf");
381 return -1;
383 dispatch_event(buf);
385 r = snprintf(buf, sizeof(buf), "r:%s",
386 player_status.mode.repeat_one == MODE_ON ? "on" : "off");
387 if (r < 0 || (size_t)r >= sizeof(buf)) {
388 log_warn("snprintf");
389 return -1;
391 dispatch_event(buf);
393 r = snprintf(buf, sizeof(buf), "R:%s",
394 player_status.mode.repeat_all == MODE_ON ? "on" : "off");
395 if (r < 0 || (size_t)r >= sizeof(buf)) {
396 log_warn("snprintf");
397 return -1;
399 dispatch_event(buf);
401 r = snprintf(buf, sizeof(buf), "c:%s",
402 player_status.mode.consume == MODE_ON ? "on" : "off");
403 if (r < 0 || (size_t)r >= sizeof(buf)) {
404 log_warn("snprintf");
405 return -1;
407 dispatch_event(buf);
409 r = snprintf(buf, sizeof(buf), "C:%s", player_status.path);
410 if (r < 0 || (size_t)r >= sizeof(buf)) {
411 log_warn("snprintf");
412 return -1;
414 dispatch_event(buf);
416 return 0;
419 static int
420 dispatch_event_track(struct player_status *ps)
422 char p[PATH_MAX + 2];
423 int r;
425 r = snprintf(p, sizeof(p), "%c:%s",
426 ps->status == STATE_PLAYING ? 'A' : 'a', ps->path);
427 if (r < 0 || (size_t)r >= sizeof(p))
428 return (-1);
430 return dispatch_event(p);
433 static void
434 imsg_dispatch(int fd, int ev, void *d)
436 static ssize_t off;
437 static int off_found;
438 char seekmsg[128];
439 struct imsg imsg;
440 struct player_status ps;
441 struct player_event event;
442 const char *msg;
443 ssize_t n;
444 size_t datalen;
445 int r;
447 if (ev & (POLLIN|POLLHUP)) {
448 if ((n = imsg_read(&ibuf)) == -1 && errno != EAGAIN)
449 fatal("imsg_read");
450 if (n == 0)
451 fatalx("pipe closed");
453 if (ev & POLLOUT) {
454 if ((n = msgbuf_write(&ibuf.w)) == -1 && errno != EAGAIN)
455 fatal("msgbuf_write");
456 if (n == 0)
457 fatalx("pipe closed");
460 for (;;) {
461 if ((n = imsg_get(&ibuf, &imsg)) == -1)
462 fatal("imsg_get");
463 if (n == 0)
464 break;
466 datalen = IMSG_DATA_SIZE(imsg);
468 switch (imsg.hdr.type) {
469 case IMSG_CTL_ERR:
470 msg = imsg.data;
471 if (datalen == 0 || msg[datalen - 1] != '\0')
472 fatalx("malformed error message");
473 log_warnx("error: %s", msg);
474 break;
476 case IMSG_CTL_ADD:
477 playlist_free(&playlist_tmp);
478 imsg_compose(&ibuf, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
479 break;
481 case IMSG_CTL_MONITOR:
482 if (datalen != sizeof(event))
483 fatalx("corrupted IMSG_CTL_MONITOR");
484 memcpy(&event, imsg.data, sizeof(event));
485 switch (event.event) {
486 case IMSG_CTL_PLAY:
487 case IMSG_CTL_PAUSE:
488 case IMSG_CTL_STOP:
489 case IMSG_CTL_MODE:
490 imsg_compose(&ibuf, IMSG_CTL_STATUS, 0, 0, -1,
491 NULL, 0);
492 break;
494 case IMSG_CTL_NEXT:
495 case IMSG_CTL_PREV:
496 case IMSG_CTL_JUMP:
497 case IMSG_CTL_COMMIT:
498 imsg_compose(&ibuf, IMSG_CTL_SHOW, 0, 0, -1,
499 NULL, 0);
500 imsg_compose(&ibuf, IMSG_CTL_STATUS, 0, 0, -1,
501 NULL, 0);
502 break;
504 case IMSG_CTL_SEEK:
505 position = event.position;
506 duration = event.duration;
507 r = snprintf(seekmsg, sizeof(seekmsg),
508 "s:%lld %lld", (long long)position,
509 (long long)duration);
510 if (r < 0 || (size_t)r >= sizeof(seekmsg)) {
511 log_warn("snprintf failed");
512 break;
514 dispatch_event(seekmsg);
515 break;
517 default:
518 log_debug("ignoring event %d", event.event);
519 break;
521 break;
523 case IMSG_CTL_SHOW:
524 if (datalen == 0) {
525 if (playlist_tmp.len == 0) {
526 dispatch_event("x:");
527 off = -1;
528 } else if (playlist_tmp.len == off)
529 off = -1;
530 dispatch_event("X:");
531 playlist_swap(&playlist_tmp, off);
532 memset(&playlist_tmp, 0, sizeof(playlist_tmp));
533 off = 0;
534 off_found = 0;
535 break;
537 if (datalen != sizeof(ps))
538 fatalx("corrupted IMSG_CTL_SHOW");
539 memcpy(&ps, imsg.data, sizeof(ps));
540 if (ps.path[sizeof(ps.path) - 1] != '\0')
541 fatalx("corrupted IMSG_CTL_SHOW");
542 if (playlist_tmp.len == 0)
543 dispatch_event("x:");
544 dispatch_event_track(&ps);
545 playlist_push(&playlist_tmp, ps.path);
546 if (ps.status == STATE_PLAYING)
547 off_found = 1;
548 if (!off_found)
549 off++;
550 break;
552 case IMSG_CTL_STATUS:
553 if (datalen != sizeof(player_status))
554 fatalx("corrupted IMSG_CTL_STATUS");
555 memcpy(&player_status, imsg.data, datalen);
556 if (player_status.path[sizeof(player_status.path) - 1]
557 != '\0')
558 fatalx("corrupted IMSG_CTL_STATUS");
559 dispatch_event_status();
560 break;
564 ev = POLLIN;
565 if (ibuf.w.queued)
566 ev |= POLLOUT;
567 ev_add(fd, ev, imsg_dispatch, NULL);
570 static void
571 route_notfound(struct client *clt)
573 if (http_reply(clt, 404, "Not Found", "text/plain") == -1 ||
574 http_writes(clt, "Page not found\n") == -1)
575 return;
578 static void
579 render_playlist(struct client *clt)
581 ssize_t i;
582 const char *path;
583 int current;
585 http_writes(clt, "<section class='playlist-wrapper'>");
586 http_writes(clt, "<form action=jump method=post"
587 " enctype='"FORM_URLENCODED"'>");
588 http_writes(clt, "<ul class=playlist>");
590 for (i = 0; i < playlist.len; ++i) {
591 current = play_off == i;
593 path = playlist.songs[i];
595 http_fmt(clt, "<li%s>", current ? " id=current" : "");
596 http_writes(clt, "<button type=submit name=jump value=\"");
597 http_htmlescape(clt, path);
598 http_writes(clt, "\">");
599 http_htmlescape(clt, path);
600 http_writes(clt, "</button></li>");
603 http_writes(clt, "</ul>");
604 http_writes(clt, "</form>");
605 http_writes(clt, "</section>");
608 static void
609 render_controls(struct client *clt)
611 const char *oc, *ac, *p;
612 int playing;
614 ac = player_status.mode.repeat_all ? " class='mode-active'" : "";
615 oc = player_status.mode.repeat_one ? " class='mode-active'" : "";
616 playing = player_status.status == STATE_PLAYING;
618 if ((p = strrchr(player_status.path, '/')) != NULL)
619 p++;
620 else
621 p = player_status.path;
623 if (http_writes(clt, "<section class=controls>") == -1 ||
624 http_writes(clt, "<p><a href='#current'>") == -1 ||
625 http_htmlescape(clt, p) == -1 ||
626 http_writes(clt, "</a></p>") == -1 ||
627 http_writes(clt, "<form action=ctrls method=post"
628 " enctype='"FORM_URLENCODED"'>") == -1 ||
629 http_writes(clt, "<button type=submit name=ctl value=prev>"
630 ICON_PREV"</button>") == -1 ||
631 http_fmt(clt, "<button id='toggle' type=submit name=ctl value=%s>"
632 "%s</button>", playing ? "pause" : "play",
633 playing ? ICON_PAUSE : ICON_PLAY) == -1 ||
634 http_writes(clt, "<button type=submit name=ctl value=next>"
635 ICON_NEXT"</button>") == -1 ||
636 http_writes(clt, "</form>") == -1 ||
637 http_writes(clt, "<form action=mode method=post"
638 " enctype='"FORM_URLENCODED"'>") == -1 ||
639 http_fmt(clt, "<button%s id=rall type=submit name=mode value=all>"
640 ICON_REPEAT_ALL"</button>", ac) == -1 ||
641 http_fmt(clt, "<button%s id=rone type=submit name=mode value=one>"
642 ICON_REPEAT_ONE"</button>", oc) == -1 ||
643 http_writes(clt, "</form>") == -1 ||
644 http_writes(clt, "</section>") == -1)
645 return;
648 static void
649 route_home(struct client *clt)
651 if (http_reply(clt, 200, "OK", "text/html;charset=UTF-8") == -1)
652 return;
654 if (http_write(clt, head, strlen(head)) == -1)
655 return;
657 if (http_writes(clt, "<main>") == -1)
658 return;
660 render_controls(clt);
661 render_playlist(clt);
663 if (http_writes(clt, "</main>") == -1)
664 return;
666 http_write(clt, foot, strlen(foot));
669 static void
670 route_jump(struct client *clt)
672 char path[PATH_MAX];
673 char *form, *field;
674 int found = 0;
676 http_postdata(clt, &form, NULL);
677 while ((field = strsep(&form, "&")) != NULL) {
678 if (url_decode(field) == -1)
679 goto badreq;
681 if (strncmp(field, "jump=", 5) != 0)
682 continue;
683 field += 5;
684 found = 1;
686 memset(&path, 0, sizeof(path));
687 if (strlcpy(path, field, sizeof(path)) >= sizeof(path))
688 goto badreq;
690 imsg_compose(&ibuf, IMSG_CTL_JUMP, 0, 0, -1,
691 path, sizeof(path));
692 ev_add(ibuf.w.fd, POLLIN|POLLOUT, imsg_dispatch, NULL);
693 break;
696 if (!found)
697 goto badreq;
699 if (!strncmp(clt->req.path, "/a/", 2))
700 http_reply(clt, 200, "OK", "text/plain");
701 else
702 http_reply(clt, 302, "See Other", "/");
703 return;
705 badreq:
706 http_reply(clt, 400, "Bad Request", "text/plain");
707 http_writes(clt, "Bad Request.\n");
710 static void
711 route_controls(struct client *clt)
713 char *form, *field;
714 int cmd, found = 0;
716 http_postdata(clt, &form, NULL);
717 while ((field = strsep(&form, "&")) != NULL) {
718 if (url_decode(field) == -1)
719 goto badreq;
721 if (strncmp(field, "ctl=", 4) != 0)
722 continue;
723 field += 4;
724 found = 1;
726 if (!strcmp(field, "play"))
727 cmd = IMSG_CTL_PLAY;
728 else if (!strcmp(field, "pause"))
729 cmd = IMSG_CTL_PAUSE;
730 else if (!strcmp(field, "next"))
731 cmd = IMSG_CTL_NEXT;
732 else if (!strcmp(field, "prev"))
733 cmd = IMSG_CTL_PREV;
734 else
735 goto badreq;
737 imsg_compose(&ibuf, cmd, 0, 0, -1, NULL, 0);
738 imsg_flush(&ibuf);
739 break;
742 if (!found)
743 goto badreq;
745 if (!strncmp(clt->req.path, "/a/", 2))
746 http_reply(clt, 200, "OK", "text/plain");
747 else
748 http_reply(clt, 302, "See Other", "/");
749 return;
751 badreq:
752 http_reply(clt, 400, "Bad Request", "text/plain");
753 http_writes(clt, "Bad Request.\n");
756 static void
757 route_mode(struct client *clt)
759 char *form, *field;
760 int found = 0;
761 struct player_mode pm;
763 pm.repeat_one = pm.repeat_all = pm.consume = MODE_UNDEF;
765 http_postdata(clt, &form, NULL);
766 while ((field = strsep(&form, "&")) != NULL) {
767 if (url_decode(field) == -1)
768 goto badreq;
770 if (strncmp(field, "mode=", 5) != 0)
771 continue;
772 field += 5;
773 found = 1;
775 if (!strcmp(field, "all"))
776 pm.repeat_all = MODE_TOGGLE;
777 else if (!strcmp(field, "one"))
778 pm.repeat_one = MODE_TOGGLE;
779 else
780 goto badreq;
782 imsg_compose(&ibuf, IMSG_CTL_MODE, 0, 0, -1, &pm, sizeof(pm));
783 ev_add(ibuf.w.fd, POLLIN|POLLOUT, imsg_dispatch, NULL);
784 break;
787 if (!found)
788 goto badreq;
790 if (!strncmp(clt->req.path, "/a/", 2))
791 http_reply(clt, 200, "OK", "text/plain");
792 else
793 http_reply(clt, 302, "See Other", "/");
794 return;
796 badreq:
797 http_reply(clt, 400, "Bad Request", "text/plain");
798 http_writes(clt, "Bad Request.\n");
801 static void
802 route_handle_ws(struct client *clt)
804 struct buffer *rbuf = &clt->bio.rbuf;
805 int type;
806 size_t len;
808 if (ws_read(clt, &type, &len) == -1) {
809 if (errno != EAGAIN) {
810 log_warn("ws_read");
811 clt->done = 1;
813 return;
816 switch (type) {
817 case WST_PING:
818 ws_compose(clt, WST_PONG, rbuf->buf, len);
819 break;
820 case WST_TEXT:
821 /* log_info("<<< %.*s", (int)len, rbuf->buf); */
822 break;
823 case WST_CLOSE:
824 /* TODO send a close too (ack) */
825 clt->done = 1;
826 break;
827 default:
828 log_info("got unexpected ws frame type 0x%02x", type);
829 break;
832 buf_drain(rbuf, len);
835 static void
836 route_init_ws(struct client *clt)
838 if (!(clt->req.flags & (R_CONNUPGR|R_UPGRADEWS|R_WSVERSION)) ||
839 clt->req.secret == NULL) {
840 http_reply(clt, 400, "Bad Request", "text/plain");
841 http_writes(clt, "Invalid websocket handshake.\r\n");
842 return;
845 clt->ws = 1;
846 clt->done = 0;
847 clt->route = route_handle_ws;
848 http_reply(clt, 101, "Switching Protocols", NULL);
851 static void
852 route_assets(struct client *clt)
854 if (!strcmp(clt->req.path, "/style.css")) {
855 http_reply(clt, 200, "OK", "text/css");
856 http_write(clt, css, strlen(css));
857 return;
860 if (!strcmp(clt->req.path, "/app.js")) {
861 http_reply(clt, 200, "OK", "application/javascript");
862 http_write(clt, js, strlen(js));
863 return;
866 route_notfound(clt);
869 static void
870 route_dispatch(struct client *clt)
872 static const struct route {
873 int method;
874 const char *path;
875 route_fn route;
876 } routes[] = {
877 { METHOD_GET, "/", &route_home },
879 { METHOD_POST, "/jump", &route_jump },
880 { METHOD_POST, "/ctrls", &route_controls },
881 { METHOD_POST, "/mode", &route_mode },
883 { METHOD_POST, "/a/jump", &route_jump },
884 { METHOD_POST, "/a/ctrls", &route_controls },
885 { METHOD_POST, "/a/mode", &route_mode },
887 { METHOD_GET, "/ws", &route_init_ws },
889 { METHOD_GET, "/style.css", &route_assets },
890 { METHOD_GET, "/app.js", &route_assets },
892 { METHOD_GET, "*", &route_notfound },
893 { METHOD_POST, "*", &route_notfound },
894 };
895 struct request *req = &clt->req;
896 size_t i;
898 if ((req->method != METHOD_GET && req->method != METHOD_POST) ||
899 (req->ctype != NULL && strcmp(req->ctype, FORM_URLENCODED) != 0) ||
900 req->path == NULL) {
901 http_reply(clt, 400, "Bad Request", NULL);
902 return;
905 for (i = 0; i < nitems(routes); ++i) {
906 if (req->method != routes[i].method ||
907 fnmatch(routes[i].path, req->path, 0) != 0)
908 continue;
909 clt->done = 1; /* assume with one round is done */
910 clt->route = routes[i].route;
911 clt->route(clt);
912 if (clt->done)
913 http_close(clt);
914 return;
918 static void
919 client_ev(int fd, int ev, void *d)
921 struct client *clt = d;
923 if (ev & (POLLIN|POLLHUP)) {
924 if (bufio_read(&clt->bio) == -1 && errno != EAGAIN) {
925 log_warn("bufio_read");
926 goto err;
930 if (ev & POLLOUT) {
931 if (bufio_write(&clt->bio) == -1 && errno != EAGAIN) {
932 log_warn("bufio_write");
933 goto err;
937 if (clt->route == NULL) {
938 if (http_parse(clt) == -1) {
939 if (errno == EAGAIN)
940 goto again;
941 log_warnx("HTTP parse request failed");
942 goto err;
944 if (clt->req.method == METHOD_POST &&
945 http_read(clt) == -1) {
946 if (errno == EAGAIN)
947 goto again;
948 log_warnx("failed to read POST data");
949 goto err;
951 route_dispatch(clt);
952 goto again;
955 if (!clt->done && !clt->err)
956 clt->route(clt);
958 again:
959 ev = bufio_pollev(&clt->bio);
960 if (ev == POLLIN && (clt->done || clt->err)) {
961 goto err; /* done with this client */
964 ev_add(fd, ev, client_ev, clt);
965 return;
967 err:
968 ev_del(fd);
969 TAILQ_REMOVE(&clients, clt, clients);
970 http_free(clt);
973 static void
974 web_accept(int psock, int ev, void *d)
976 struct client *clt;
977 int sock;
979 if ((sock = accept(psock, NULL, NULL)) == -1) {
980 warn("accept");
981 return;
983 if ((clt = calloc(1, sizeof(*clt))) == NULL ||
984 http_init(clt, sock) == -1) {
985 log_warn("failed to initialize client");
986 free(clt);
987 close(sock);
988 return;
991 TAILQ_INSERT_TAIL(&clients, clt, clients);
993 client_ev(sock, POLLIN, clt);
994 return;
997 void __dead
998 usage(void)
1000 fprintf(stderr, "usage: %s [-v] [-s sock] [[host] port]\n",
1001 getprogname());
1002 exit(1);
1005 int
1006 main(int argc, char **argv)
1008 struct addrinfo hints, *res, *res0;
1009 const char *cause = NULL;
1010 const char *host = NULL;
1011 const char *port = "9090";
1012 char *sock = NULL;
1013 size_t nsock, error, save_errno;
1014 int ch, v, amused_sock, fd;
1015 int verbose = 0;
1017 TAILQ_INIT(&clients);
1018 setlocale(LC_ALL, NULL);
1020 log_init(1, LOG_DAEMON);
1022 if (pledge("stdio rpath unix inet dns", NULL) == -1)
1023 err(1, "pledge");
1025 while ((ch = getopt(argc, argv, "s:v")) != -1) {
1026 switch (ch) {
1027 case 's':
1028 sock = optarg;
1029 break;
1030 case 'v':
1031 verbose = 1;
1032 break;
1033 default:
1034 usage();
1037 argc -= optind;
1038 argv += optind;
1040 if (argc == 1)
1041 port = argv[0];
1042 if (argc == 2) {
1043 host = argv[0];
1044 port = argv[1];
1046 if (argc > 2)
1047 usage();
1049 log_setverbose(verbose);
1051 if (sock == NULL) {
1052 const char *tmpdir;
1054 if ((tmpdir = getenv("TMPDIR")) == NULL)
1055 tmpdir = "/tmp";
1057 xasprintf(&sock, "%s/amused-%d", tmpdir, getuid());
1060 signal(SIGPIPE, SIG_IGN);
1062 if (ev_init() == -1)
1063 fatal("ev_init");
1065 amused_sock = dial(sock);
1066 imsg_init(&ibuf, amused_sock);
1067 imsg_compose(&ibuf, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
1068 imsg_compose(&ibuf, IMSG_CTL_STATUS, 0, 0, -1, NULL, 0);
1069 imsg_compose(&ibuf, IMSG_CTL_MONITOR, 0, 0, -1, NULL, 0);
1070 ev_add(amused_sock, POLLIN|POLLOUT, imsg_dispatch, NULL);
1072 memset(&hints, 0, sizeof(hints));
1073 hints.ai_family = AF_UNSPEC;
1074 hints.ai_socktype = SOCK_STREAM;
1075 hints.ai_flags = AI_PASSIVE;
1076 error = getaddrinfo(host, port, &hints, &res0);
1077 if (error)
1078 errx(1, "%s", gai_strerror(error));
1080 nsock = 0;
1081 for (res = res0; res; res = res->ai_next) {
1082 fd = socket(res->ai_family, res->ai_socktype,
1083 res->ai_protocol);
1084 if (fd == -1) {
1085 cause = "socket";
1086 continue;
1089 v = 1;
1090 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1091 &v, sizeof(v)) == -1)
1092 fatal("setsockopt(SO_REUSEADDR)");
1094 if (bind(fd, res->ai_addr, res->ai_addrlen) == -1) {
1095 cause = "bind";
1096 save_errno = errno;
1097 close(fd);
1098 errno = save_errno;
1099 continue;
1102 if (listen(fd, 5) == -1)
1103 err(1, "listen");
1105 if (ev_add(fd, POLLIN, web_accept, NULL) == -1)
1106 fatal("ev_add");
1107 nsock++;
1109 if (nsock == 0)
1110 err(1, "%s", cause);
1111 freeaddrinfo(res0);
1113 if (pledge("stdio inet", NULL) == -1)
1114 err(1, "pledge");
1116 log_info("listening on port %s", port);
1117 ev_loop();
1118 return (1);