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 imsgbuf;
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(&imsgbuf)) == -1 && errno != EAGAIN)
449 fatal("imsg_read");
450 if (n == 0)
451 fatalx("pipe closed");
453 if (ev & POLLOUT) {
454 if ((n = msgbuf_write(&imsgbuf.w)) == -1 && errno != EAGAIN)
455 fatal("msgbuf_write");
456 if (n == 0)
457 fatalx("pipe closed");
460 for (;;) {
461 if ((n = imsg_get(&imsgbuf, &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(&imsgbuf, IMSG_CTL_SHOW, 0, 0, -1,
479 NULL, 0);
480 break;
482 case IMSG_CTL_MONITOR:
483 if (datalen != sizeof(event))
484 fatalx("corrupted IMSG_CTL_MONITOR");
485 memcpy(&event, imsg.data, sizeof(event));
486 switch (event.event) {
487 case IMSG_CTL_PLAY:
488 case IMSG_CTL_PAUSE:
489 case IMSG_CTL_STOP:
490 case IMSG_CTL_MODE:
491 imsg_compose(&imsgbuf, IMSG_CTL_STATUS, 0, 0,
492 -1, NULL, 0);
493 break;
495 case IMSG_CTL_NEXT:
496 case IMSG_CTL_PREV:
497 case IMSG_CTL_JUMP:
498 case IMSG_CTL_COMMIT:
499 imsg_compose(&imsgbuf, IMSG_CTL_SHOW, 0, 0, -1,
500 NULL, 0);
501 imsg_compose(&imsgbuf, IMSG_CTL_STATUS, 0, 0,
502 -1, NULL, 0);
503 break;
505 case IMSG_CTL_SEEK:
506 position = event.position;
507 duration = event.duration;
508 r = snprintf(seekmsg, sizeof(seekmsg),
509 "s:%lld %lld", (long long)position,
510 (long long)duration);
511 if (r < 0 || (size_t)r >= sizeof(seekmsg)) {
512 log_warn("snprintf failed");
513 break;
515 dispatch_event(seekmsg);
516 break;
518 default:
519 log_debug("ignoring event %d", event.event);
520 break;
522 break;
524 case IMSG_CTL_SHOW:
525 if (datalen == 0) {
526 if (playlist_tmp.len == 0) {
527 dispatch_event("x:");
528 off = -1;
529 } else if (playlist_tmp.len == off)
530 off = -1;
531 dispatch_event("X:");
532 playlist_swap(&playlist_tmp, off);
533 memset(&playlist_tmp, 0, sizeof(playlist_tmp));
534 off = 0;
535 off_found = 0;
536 break;
538 if (datalen != sizeof(ps))
539 fatalx("corrupted IMSG_CTL_SHOW");
540 memcpy(&ps, imsg.data, sizeof(ps));
541 if (ps.path[sizeof(ps.path) - 1] != '\0')
542 fatalx("corrupted IMSG_CTL_SHOW");
543 if (playlist_tmp.len == 0)
544 dispatch_event("x:");
545 dispatch_event_track(&ps);
546 playlist_push(&playlist_tmp, ps.path);
547 if (ps.status == STATE_PLAYING)
548 off_found = 1;
549 if (!off_found)
550 off++;
551 break;
553 case IMSG_CTL_STATUS:
554 if (datalen != sizeof(player_status))
555 fatalx("corrupted IMSG_CTL_STATUS");
556 memcpy(&player_status, imsg.data, datalen);
557 if (player_status.path[sizeof(player_status.path) - 1]
558 != '\0')
559 fatalx("corrupted IMSG_CTL_STATUS");
560 dispatch_event_status();
561 break;
565 ev = POLLIN;
566 if (imsgbuf.w.queued)
567 ev |= POLLOUT;
568 ev_add(fd, ev, imsg_dispatch, NULL);
571 static void
572 route_notfound(struct client *clt)
574 if (http_reply(clt, 404, "Not Found", "text/plain") == -1 ||
575 http_writes(clt, "Page not found\n") == -1)
576 return;
579 static void
580 render_playlist(struct client *clt)
582 ssize_t i;
583 const char *path;
584 int current;
586 http_writes(clt, "<section class='playlist-wrapper'>");
587 http_writes(clt, "<form action=jump method=post"
588 " enctype='"FORM_URLENCODED"'>");
589 http_writes(clt, "<ul class=playlist>");
591 for (i = 0; i < playlist.len; ++i) {
592 current = play_off == i;
594 path = playlist.songs[i];
596 http_fmt(clt, "<li%s>", current ? " id=current" : "");
597 http_writes(clt, "<button type=submit name=jump value=\"");
598 http_htmlescape(clt, path);
599 http_writes(clt, "\">");
600 http_htmlescape(clt, path);
601 http_writes(clt, "</button></li>");
604 http_writes(clt, "</ul>");
605 http_writes(clt, "</form>");
606 http_writes(clt, "</section>");
609 static void
610 render_controls(struct client *clt)
612 const char *oc, *ac, *p;
613 int playing;
615 ac = player_status.mode.repeat_all ? " class='mode-active'" : "";
616 oc = player_status.mode.repeat_one ? " class='mode-active'" : "";
617 playing = player_status.status == STATE_PLAYING;
619 if ((p = strrchr(player_status.path, '/')) != NULL)
620 p++;
621 else
622 p = player_status.path;
624 if (http_writes(clt, "<section class=controls>") == -1 ||
625 http_writes(clt, "<p><a href='#current'>") == -1 ||
626 http_htmlescape(clt, p) == -1 ||
627 http_writes(clt, "</a></p>") == -1 ||
628 http_writes(clt, "<form action=ctrls method=post"
629 " enctype='"FORM_URLENCODED"'>") == -1 ||
630 http_writes(clt, "<button type=submit name=ctl value=prev>"
631 ICON_PREV"</button>") == -1 ||
632 http_fmt(clt, "<button id='toggle' type=submit name=ctl value=%s>"
633 "%s</button>", playing ? "pause" : "play",
634 playing ? ICON_PAUSE : ICON_PLAY) == -1 ||
635 http_writes(clt, "<button type=submit name=ctl value=next>"
636 ICON_NEXT"</button>") == -1 ||
637 http_writes(clt, "</form>") == -1 ||
638 http_writes(clt, "<form action=mode method=post"
639 " enctype='"FORM_URLENCODED"'>") == -1 ||
640 http_fmt(clt, "<button%s id=rall type=submit name=mode value=all>"
641 ICON_REPEAT_ALL"</button>", ac) == -1 ||
642 http_fmt(clt, "<button%s id=rone type=submit name=mode value=one>"
643 ICON_REPEAT_ONE"</button>", oc) == -1 ||
644 http_writes(clt, "</form>") == -1 ||
645 http_writes(clt, "</section>") == -1)
646 return;
649 static void
650 route_home(struct client *clt)
652 if (http_reply(clt, 200, "OK", "text/html;charset=UTF-8") == -1)
653 return;
655 if (http_write(clt, head, strlen(head)) == -1)
656 return;
658 if (http_writes(clt, "<main>") == -1)
659 return;
661 render_controls(clt);
662 render_playlist(clt);
664 if (http_writes(clt, "</main>") == -1)
665 return;
667 http_write(clt, foot, strlen(foot));
670 static void
671 route_jump(struct client *clt)
673 char path[PATH_MAX];
674 char *form, *field;
675 int found = 0;
677 http_postdata(clt, &form, NULL);
678 while ((field = strsep(&form, "&")) != NULL) {
679 if (url_decode(field) == -1)
680 goto badreq;
682 if (strncmp(field, "jump=", 5) != 0)
683 continue;
684 field += 5;
685 found = 1;
687 memset(&path, 0, sizeof(path));
688 if (strlcpy(path, field, sizeof(path)) >= sizeof(path))
689 goto badreq;
691 imsg_compose(&imsgbuf, IMSG_CTL_JUMP, 0, 0, -1,
692 path, sizeof(path));
693 ev_add(imsgbuf.w.fd, POLLIN|POLLOUT, imsg_dispatch, NULL);
694 break;
697 if (!found)
698 goto badreq;
700 if (!strncmp(clt->req.path, "/a/", 2))
701 http_reply(clt, 200, "OK", "text/plain");
702 else
703 http_reply(clt, 302, "See Other", "/");
704 return;
706 badreq:
707 http_reply(clt, 400, "Bad Request", "text/plain");
708 http_writes(clt, "Bad Request.\n");
711 static void
712 route_controls(struct client *clt)
714 char *form, *field;
715 int cmd, found = 0;
717 http_postdata(clt, &form, NULL);
718 while ((field = strsep(&form, "&")) != NULL) {
719 if (url_decode(field) == -1)
720 goto badreq;
722 if (strncmp(field, "ctl=", 4) != 0)
723 continue;
724 field += 4;
725 found = 1;
727 if (!strcmp(field, "play"))
728 cmd = IMSG_CTL_PLAY;
729 else if (!strcmp(field, "pause"))
730 cmd = IMSG_CTL_PAUSE;
731 else if (!strcmp(field, "next"))
732 cmd = IMSG_CTL_NEXT;
733 else if (!strcmp(field, "prev"))
734 cmd = IMSG_CTL_PREV;
735 else
736 goto badreq;
738 imsg_compose(&imsgbuf, cmd, 0, 0, -1, NULL, 0);
739 imsg_flush(&imsgbuf);
740 break;
743 if (!found)
744 goto badreq;
746 if (!strncmp(clt->req.path, "/a/", 2))
747 http_reply(clt, 200, "OK", "text/plain");
748 else
749 http_reply(clt, 302, "See Other", "/");
750 return;
752 badreq:
753 http_reply(clt, 400, "Bad Request", "text/plain");
754 http_writes(clt, "Bad Request.\n");
757 static void
758 route_mode(struct client *clt)
760 char *form, *field;
761 int found = 0;
762 struct player_mode pm;
764 pm.repeat_one = pm.repeat_all = pm.consume = MODE_UNDEF;
766 http_postdata(clt, &form, NULL);
767 while ((field = strsep(&form, "&")) != NULL) {
768 if (url_decode(field) == -1)
769 goto badreq;
771 if (strncmp(field, "mode=", 5) != 0)
772 continue;
773 field += 5;
774 found = 1;
776 if (!strcmp(field, "all"))
777 pm.repeat_all = MODE_TOGGLE;
778 else if (!strcmp(field, "one"))
779 pm.repeat_one = MODE_TOGGLE;
780 else
781 goto badreq;
783 imsg_compose(&imsgbuf, IMSG_CTL_MODE, 0, 0, -1,
784 &pm, sizeof(pm));
785 ev_add(imsgbuf.w.fd, POLLIN|POLLOUT, imsg_dispatch, NULL);
786 break;
789 if (!found)
790 goto badreq;
792 if (!strncmp(clt->req.path, "/a/", 2))
793 http_reply(clt, 200, "OK", "text/plain");
794 else
795 http_reply(clt, 302, "See Other", "/");
796 return;
798 badreq:
799 http_reply(clt, 400, "Bad Request", "text/plain");
800 http_writes(clt, "Bad Request.\n");
803 static void
804 route_handle_ws(struct client *clt)
806 struct buffer *rbuf = &clt->bio.rbuf;
807 int type;
808 size_t len;
810 if (ws_read(clt, &type, &len) == -1) {
811 if (errno != EAGAIN) {
812 log_warn("ws_read");
813 clt->done = 1;
815 return;
818 switch (type) {
819 case WST_PING:
820 ws_compose(clt, WST_PONG, rbuf->buf, len);
821 break;
822 case WST_TEXT:
823 /* log_info("<<< %.*s", (int)len, rbuf->buf); */
824 break;
825 case WST_CLOSE:
826 /* TODO send a close too (ack) */
827 clt->done = 1;
828 break;
829 default:
830 log_info("got unexpected ws frame type 0x%02x", type);
831 break;
834 buf_drain(rbuf, len);
837 static void
838 route_init_ws(struct client *clt)
840 if (!(clt->req.flags & (R_CONNUPGR|R_UPGRADEWS|R_WSVERSION)) ||
841 clt->req.secret == NULL) {
842 http_reply(clt, 400, "Bad Request", "text/plain");
843 http_writes(clt, "Invalid websocket handshake.\r\n");
844 return;
847 clt->ws = 1;
848 clt->done = 0;
849 clt->route = route_handle_ws;
850 http_reply(clt, 101, "Switching Protocols", NULL);
853 static void
854 route_assets(struct client *clt)
856 if (!strcmp(clt->req.path, "/style.css")) {
857 http_reply(clt, 200, "OK", "text/css");
858 http_write(clt, css, strlen(css));
859 return;
862 if (!strcmp(clt->req.path, "/app.js")) {
863 http_reply(clt, 200, "OK", "application/javascript");
864 http_write(clt, js, strlen(js));
865 return;
868 route_notfound(clt);
871 static void
872 route_dispatch(struct client *clt)
874 static const struct route {
875 int method;
876 const char *path;
877 route_fn route;
878 } routes[] = {
879 { METHOD_GET, "/", &route_home },
881 { METHOD_POST, "/jump", &route_jump },
882 { METHOD_POST, "/ctrls", &route_controls },
883 { METHOD_POST, "/mode", &route_mode },
885 { METHOD_POST, "/a/jump", &route_jump },
886 { METHOD_POST, "/a/ctrls", &route_controls },
887 { METHOD_POST, "/a/mode", &route_mode },
889 { METHOD_GET, "/ws", &route_init_ws },
891 { METHOD_GET, "/style.css", &route_assets },
892 { METHOD_GET, "/app.js", &route_assets },
894 { METHOD_GET, "*", &route_notfound },
895 { METHOD_POST, "*", &route_notfound },
896 };
897 struct request *req = &clt->req;
898 size_t i;
900 if ((req->method != METHOD_GET && req->method != METHOD_POST) ||
901 (req->ctype != NULL && strcmp(req->ctype, FORM_URLENCODED) != 0) ||
902 req->path == NULL) {
903 http_reply(clt, 400, "Bad Request", NULL);
904 return;
907 for (i = 0; i < nitems(routes); ++i) {
908 if (req->method != routes[i].method ||
909 fnmatch(routes[i].path, req->path, 0) != 0)
910 continue;
911 clt->done = 1; /* assume with one round is done */
912 clt->route = routes[i].route;
913 clt->route(clt);
914 if (clt->done)
915 http_close(clt);
916 return;
920 static void
921 client_ev(int fd, int ev, void *d)
923 struct client *clt = d;
925 if (ev & (POLLIN|POLLHUP)) {
926 if (bufio_read(&clt->bio) == -1 && errno != EAGAIN) {
927 log_warn("bufio_read");
928 goto err;
932 if (ev & POLLOUT) {
933 if (bufio_write(&clt->bio) == -1 && errno != EAGAIN) {
934 log_warn("bufio_write");
935 goto err;
939 if (clt->route == NULL) {
940 if (http_parse(clt) == -1) {
941 if (errno == EAGAIN)
942 goto again;
943 log_warnx("HTTP parse request failed");
944 goto err;
946 if (clt->req.method == METHOD_POST &&
947 http_read(clt) == -1) {
948 if (errno == EAGAIN)
949 goto again;
950 log_warnx("failed to read POST data");
951 goto err;
953 route_dispatch(clt);
954 goto again;
957 if (!clt->done && !clt->err)
958 clt->route(clt);
960 again:
961 ev = bufio_pollev(&clt->bio);
962 if (ev == POLLIN && (clt->done || clt->err)) {
963 goto err; /* done with this client */
966 ev_add(fd, ev, client_ev, clt);
967 return;
969 err:
970 ev_del(fd);
971 TAILQ_REMOVE(&clients, clt, clients);
972 http_free(clt);
975 static void
976 web_accept(int psock, int ev, void *d)
978 struct client *clt;
979 int sock;
981 if ((sock = accept(psock, NULL, NULL)) == -1) {
982 warn("accept");
983 return;
985 if ((clt = calloc(1, sizeof(*clt))) == NULL ||
986 http_init(clt, sock) == -1) {
987 log_warn("failed to initialize client");
988 free(clt);
989 close(sock);
990 return;
993 TAILQ_INSERT_TAIL(&clients, clt, clients);
995 client_ev(sock, POLLIN, clt);
996 return;
999 void __dead
1000 usage(void)
1002 fprintf(stderr, "usage: %s [-v] [-s sock] [[host] port]\n",
1003 getprogname());
1004 exit(1);
1007 int
1008 main(int argc, char **argv)
1010 struct addrinfo hints, *res, *res0;
1011 const char *cause = NULL;
1012 const char *host = NULL;
1013 const char *port = "9090";
1014 char *sock = NULL;
1015 size_t nsock, error, save_errno;
1016 int ch, v, amused_sock, fd;
1017 int verbose = 0;
1019 TAILQ_INIT(&clients);
1020 setlocale(LC_ALL, NULL);
1022 log_init(1, LOG_DAEMON);
1024 if (pledge("stdio rpath unix inet dns", NULL) == -1)
1025 err(1, "pledge");
1027 while ((ch = getopt(argc, argv, "s:v")) != -1) {
1028 switch (ch) {
1029 case 's':
1030 sock = optarg;
1031 break;
1032 case 'v':
1033 verbose = 1;
1034 break;
1035 default:
1036 usage();
1039 argc -= optind;
1040 argv += optind;
1042 if (argc == 1)
1043 port = argv[0];
1044 if (argc == 2) {
1045 host = argv[0];
1046 port = argv[1];
1048 if (argc > 2)
1049 usage();
1051 log_setverbose(verbose);
1053 if (sock == NULL) {
1054 const char *tmpdir;
1056 if ((tmpdir = getenv("TMPDIR")) == NULL)
1057 tmpdir = "/tmp";
1059 xasprintf(&sock, "%s/amused-%d", tmpdir, getuid());
1062 signal(SIGPIPE, SIG_IGN);
1064 if (ev_init() == -1)
1065 fatal("ev_init");
1067 amused_sock = dial(sock);
1068 imsg_init(&imsgbuf, amused_sock);
1069 imsg_compose(&imsgbuf, IMSG_CTL_SHOW, 0, 0, -1, NULL, 0);
1070 imsg_compose(&imsgbuf, IMSG_CTL_STATUS, 0, 0, -1, NULL, 0);
1071 imsg_compose(&imsgbuf, IMSG_CTL_MONITOR, 0, 0, -1, NULL, 0);
1072 ev_add(amused_sock, POLLIN|POLLOUT, imsg_dispatch, NULL);
1074 memset(&hints, 0, sizeof(hints));
1075 hints.ai_family = AF_UNSPEC;
1076 hints.ai_socktype = SOCK_STREAM;
1077 hints.ai_flags = AI_PASSIVE;
1078 error = getaddrinfo(host, port, &hints, &res0);
1079 if (error)
1080 errx(1, "%s", gai_strerror(error));
1082 nsock = 0;
1083 for (res = res0; res; res = res->ai_next) {
1084 fd = socket(res->ai_family, res->ai_socktype,
1085 res->ai_protocol);
1086 if (fd == -1) {
1087 cause = "socket";
1088 continue;
1091 v = 1;
1092 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1093 &v, sizeof(v)) == -1)
1094 fatal("setsockopt(SO_REUSEADDR)");
1096 if (bind(fd, res->ai_addr, res->ai_addrlen) == -1) {
1097 cause = "bind";
1098 save_errno = errno;
1099 close(fd);
1100 errno = save_errno;
1101 continue;
1104 if (listen(fd, 5) == -1)
1105 err(1, "listen");
1107 if (ev_add(fd, POLLIN, web_accept, NULL) == -1)
1108 fatal("ev_add");
1109 nsock++;
1111 if (nsock == 0)
1112 err(1, "%s", cause);
1113 freeaddrinfo(res0);
1115 if (pledge("stdio inet", NULL) == -1)
1116 err(1, "pledge");
1118 log_info("listening on port %s", port);
1119 ev_loop();
1120 return (1);