Don't rebase ib->currroot if it was NULL.
[sgt/agedu] / httpd.c
1 /*
2 * httpd.c: implementation of httpd.h.
3 */
4
5 #include "agedu.h"
6 #include "alloc.h"
7 #include "html.h"
8 #include "httpd.h"
9
10 /* --- Logic driving what the web server's responses are. --- */
11
12 enum { /* connctx states */
13 READING_REQ_LINE,
14 READING_HEADERS,
15 DONE
16 };
17
18 struct connctx {
19 const void *t;
20 char *data;
21 int datalen, datasize;
22 char *method, *url, *headers, *auth;
23 int state;
24 };
25
26 /*
27 * Called when a new connection arrives on a listening socket.
28 * Returns a connctx for the new connection.
29 */
30 struct connctx *new_connection(const void *t)
31 {
32 struct connctx *cctx = snew(struct connctx);
33 cctx->t = t;
34 cctx->data = NULL;
35 cctx->datalen = cctx->datasize = 0;
36 cctx->state = READING_REQ_LINE;
37 cctx->method = cctx->url = cctx->headers = cctx->auth = NULL;
38 return cctx;
39 }
40
41 void free_connection(struct connctx *cctx)
42 {
43 sfree(cctx->data);
44 sfree(cctx);
45 }
46
47 static char *http_error(char *code, char *errmsg, char *extraheader,
48 char *errtext, ...)
49 {
50 return dupfmt("HTTP/1.1 %s %s\r\n"
51 "Date: %D\r\n"
52 "Server: " PNAME "\r\n"
53 "Connection: close\r\n"
54 "%s"
55 "Content-Type: text/html; charset=US-ASCII\r\n"
56 "\r\n"
57 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
58 "<HTML><HEAD>\r\n"
59 "<TITLE>%s %s</TITLE>\r\n"
60 "</HEAD><BODY>\r\n"
61 "<H1>%s %s</H1>\r\n"
62 "<P>%s</P>\r\n"
63 "</BODY></HTML>\r\n", code, errmsg,
64 extraheader ? extraheader : "",
65 code, errmsg, code, errmsg, errtext);
66 }
67
68 static char *http_success(char *mimetype, int stuff_cr, char *document)
69 {
70 return dupfmt("HTTP/1.1 200 OK\r\n"
71 "Date: %D\r\n"
72 "Expires: %D\r\n"
73 "Server: " PNAME "\r\n"
74 "Connection: close\r\n"
75 "Content-Type: %s\r\n"
76 "\r\n"
77 "%S", mimetype, stuff_cr, document);
78 }
79
80 /*
81 * Called when data comes in on a connection.
82 *
83 * If this function returns NULL, the platform code continues
84 * reading from the socket. Otherwise, it returns some dynamically
85 * allocated data which the platform code will then write to the
86 * socket before closing it.
87 */
88 char *got_data(struct connctx *ctx, char *data, int length,
89 int magic_access, const char *auth_string,
90 const struct html_config *cfg)
91 {
92 char *line, *p, *q, *r, *z1, *z2, c1, c2;
93 int auth_provided = 0, auth_correct = 0;
94 unsigned long index;
95 char *document, *ret;
96
97 /*
98 * Add the data we've just received to our buffer.
99 */
100 if (ctx->datasize < ctx->datalen + length) {
101 ctx->datasize = (ctx->datalen + length) * 3 / 2 + 4096;
102 ctx->data = sresize(ctx->data, ctx->datasize, char);
103 }
104 memcpy(ctx->data + ctx->datalen, data, length);
105 ctx->datalen += length;
106
107 /*
108 * Gradually process the HTTP request as we receive it.
109 */
110 if (ctx->state == READING_REQ_LINE) {
111 /*
112 * We're waiting for the first line of the input, which
113 * contains the main HTTP request. See if we've got it
114 * yet.
115 */
116
117 line = ctx->data;
118 /*
119 * RFC 2616 section 4.1: `In the interest of robustness,
120 * [...] if the server is reading the protocol stream at
121 * the beginning of a message and receives a CRLF first,
122 * it should ignore the CRLF.'
123 */
124 while (line - ctx->data < ctx->datalen &&
125 (*line == '\r' || *line == '\n'))
126 line++;
127 q = line;
128 while (q - ctx->data < ctx->datalen && *q != '\n')
129 q++;
130 if (q - ctx->data >= ctx->datalen)
131 return NULL; /* not got request line yet */
132
133 /*
134 * We've got the first line of the request. Zero-terminate
135 * and parse it into method, URL and optional HTTP
136 * version.
137 */
138 *q = '\0';
139 ctx->headers = q+1;
140 if (q > line && q[-1] == '\r')
141 *--q = '\0';
142 z1 = z2 = q;
143 c1 = c2 = *q;
144 p = line;
145 while (*p && !isspace((unsigned char)*p)) p++;
146 if (*p) {
147 z1 = p++;
148 c1 = *z1;
149 *z1 = '\0';
150 }
151 while (*p && isspace((unsigned char)*p)) p++;
152 q = p;
153 while (*q && !isspace((unsigned char)*q)) q++;
154 z2 = q++;
155 c2 = *z2;
156 *z2 = '\0';
157 while (*q && isspace((unsigned char)*q)) q++;
158
159 /*
160 * Now `line' points at the method name; p points at the
161 * URL, if any; q points at the HTTP version, if any.
162 */
163
164 /*
165 * There should _be_ a URL, on any request type at all.
166 */
167 if (!*p) {
168 char *ret, *text;
169 /* Restore the request to the way we received it. */
170 *z2 = c2;
171 *z1 = c1;
172 text = dupfmt("<code>" PNAME "</code> received the HTTP request"
173 " \"<code>%h</code>\", which contains no URL.",
174 line);
175 ret = http_error("400", "Bad request", NULL, text);
176 sfree(text);
177 return ret;
178 }
179
180 ctx->method = line;
181 ctx->url = p;
182
183 /*
184 * If there was an HTTP version, we might need to see
185 * headers. Otherwise, the request is done.
186 */
187 if (*q) {
188 ctx->state = READING_HEADERS;
189 } else {
190 ctx->state = DONE;
191 }
192 }
193
194 if (ctx->state == READING_HEADERS) {
195 /*
196 * While we're receiving the HTTP request headers, all we
197 * do is to keep scanning to see if we find two newlines
198 * next to each other.
199 */
200 q = ctx->data + ctx->datalen;
201 for (p = ctx->headers; p < q; p++) {
202 if (*p == '\n' &&
203 ((p+1 < q && p[1] == '\n') ||
204 (p+2 < q && p[1] == '\r' && p[2] == '\n'))) {
205 p[1] = '\0';
206 ctx->state = DONE;
207 break;
208 }
209 }
210 }
211
212 if (ctx->state == DONE) {
213 /*
214 * Now we have the entire HTTP request. Decide what to do
215 * with it.
216 */
217 if (auth_string) {
218 /*
219 * Search the request headers for Authorization.
220 */
221 q = ctx->data + ctx->datalen;
222 for (p = ctx->headers; p < q; p++) {
223 const char *hdr = "Authorization:";
224 int i;
225 for (i = 0; hdr[i]; i++) {
226 if (p >= q || tolower((unsigned char)*p) !=
227 tolower((unsigned char)hdr[i]))
228 break;
229 p++;
230 }
231 if (!hdr[i])
232 break; /* found our header */
233 p = memchr(p, '\n', q - p);
234 if (!p)
235 p = q;
236 }
237 if (p < q) {
238 auth_provided = 1;
239 while (p < q && isspace((unsigned char)*p))
240 p++;
241 r = p;
242 while (p < q && !isspace((unsigned char)*p))
243 p++;
244 if (p < q) {
245 *p++ = '\0';
246 if (!strcasecmp(r, "Basic")) {
247 while (p < q && isspace((unsigned char)*p))
248 p++;
249 r = p;
250 while (p < q && !isspace((unsigned char)*p))
251 p++;
252 if (p < q) {
253 *p++ = '\0';
254 if (!strcmp(r, auth_string))
255 auth_correct = 1;
256 }
257 }
258 }
259 }
260 }
261
262 if (!magic_access && !auth_correct) {
263 if (auth_string) {
264 ret = http_error("401", "Unauthorized",
265 "WWW-Authenticate: Basic realm=\""PNAME"\"\r\n",
266 "\nYou must authenticate to view these pages.");
267 } else {
268 ret = http_error("403", "Forbidden", NULL,
269 "This is a restricted-access set of pages.");
270 }
271 } else {
272 char *q;
273 p = ctx->url;
274 p += strspn(p, "/?");
275 index = strtoul(p, &q, 10);
276 if (*q) {
277 ret = http_error("404", "Not Found", NULL,
278 "This is not a valid pathname index.");
279 } else {
280 document = html_query(ctx->t, index, cfg);
281 if (document) {
282 ret = http_success("text/html", 1, document);
283 sfree(document);
284 } else {
285 ret = http_error("404", "Not Found", NULL,
286 "Pathname index out of range.");
287 }
288 }
289 }
290 return ret;
291 } else
292 return NULL;
293 }
294
295 /* --- Platform support for running a web server. --- */
296
297 enum { FD_CLIENT, FD_LISTENER, FD_CONNECTION };
298
299 struct fd {
300 int fd;
301 int type;
302 int deleted;
303 char *wdata;
304 int wdatalen, wdatapos;
305 int magic_access;
306 struct connctx *cctx;
307 };
308
309 struct fd *fds = NULL;
310 int nfds = 0, fdsize = 0;
311
312 struct fd *new_fdstruct(int fd, int type)
313 {
314 struct fd *ret;
315
316 if (nfds >= fdsize) {
317 fdsize = nfds * 3 / 2 + 32;
318 fds = sresize(fds, fdsize, struct fd);
319 }
320
321 ret = &fds[nfds++];
322
323 ret->fd = fd;
324 ret->type = type;
325 ret->wdata = NULL;
326 ret->wdatalen = ret->wdatapos = 0;
327 ret->cctx = NULL;
328 ret->deleted = 0;
329 ret->magic_access = 0;
330
331 return ret;
332 }
333
334 int check_owning_uid(int fd, int flip)
335 {
336 struct sockaddr_in sock, peer;
337 socklen_t addrlen;
338 char linebuf[4096], matchbuf[80];
339 FILE *fp;
340
341 addrlen = sizeof(sock);
342 if (getsockname(fd, (struct sockaddr *)&sock, &addrlen)) {
343 fprintf(stderr, "getsockname: %s\n", strerror(errno));
344 exit(1);
345 }
346 addrlen = sizeof(peer);
347 if (getpeername(fd, (struct sockaddr *)&peer, &addrlen)) {
348 if (errno == ENOTCONN) {
349 peer.sin_addr.s_addr = htonl(0);
350 peer.sin_port = htons(0);
351 } else {
352 fprintf(stderr, "getpeername: %s\n", strerror(errno));
353 exit(1);
354 }
355 }
356
357 if (flip) {
358 struct sockaddr_in tmp = sock;
359 sock = peer;
360 peer = tmp;
361 }
362
363 sprintf(matchbuf, "%08X:%04X %08X:%04X",
364 peer.sin_addr.s_addr, ntohs(peer.sin_port),
365 sock.sin_addr.s_addr, ntohs(sock.sin_port));
366 fp = fopen("/proc/net/tcp", "r");
367 if (fp) {
368 while (fgets(linebuf, sizeof(linebuf), fp)) {
369 if (strlen(linebuf) >= 75 &&
370 !strncmp(linebuf+6, matchbuf, strlen(matchbuf))) {
371 fclose(fp);
372 return atoi(linebuf + 75);
373 }
374 }
375 fclose(fp);
376 }
377
378 return -1;
379 }
380
381 void check_magic_access(struct fd *fd)
382 {
383 if (check_owning_uid(fd->fd, 0) == getuid())
384 fd->magic_access = 1;
385 }
386
387 static void base64_encode_atom(unsigned char *data, int n, char *out)
388 {
389 static const char base64_chars[] =
390 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
391
392 unsigned word;
393
394 word = data[0] << 16;
395 if (n > 1)
396 word |= data[1] << 8;
397 if (n > 2)
398 word |= data[2];
399 out[0] = base64_chars[(word >> 18) & 0x3F];
400 out[1] = base64_chars[(word >> 12) & 0x3F];
401 if (n > 1)
402 out[2] = base64_chars[(word >> 6) & 0x3F];
403 else
404 out[2] = '=';
405 if (n > 2)
406 out[3] = base64_chars[word & 0x3F];
407 else
408 out[3] = '=';
409 }
410
411 void run_httpd(const void *t, int authmask, const struct httpd_config *dcfg,
412 const struct html_config *incfg)
413 {
414 int fd, ret;
415 int authtype;
416 char *authstring = NULL;
417 unsigned long ipaddr;
418 struct fd *f;
419 struct sockaddr_in addr;
420 socklen_t addrlen;
421 struct html_config cfg = *incfg;
422
423 cfg.format = "%.0lu";
424
425 /*
426 * Establish the listening socket and retrieve its port
427 * number.
428 */
429 fd = socket(PF_INET, SOCK_STREAM, 0);
430 if (fd < 0) {
431 fprintf(stderr, "socket(PF_INET): %s\n", strerror(errno));
432 exit(1);
433 }
434 addr.sin_family = AF_INET;
435 if (!dcfg->address) {
436 srand(0L);
437 ipaddr = 0x7f000000;
438 ipaddr += (1 + rand() % 255) << 16;
439 ipaddr += (1 + rand() % 255) << 8;
440 ipaddr += (1 + rand() % 255);
441 addr.sin_addr.s_addr = htonl(ipaddr);
442 addr.sin_port = htons(0);
443
444 } else {
445 addr.sin_addr.s_addr = inet_addr(dcfg->address);
446 addr.sin_port = dcfg->port ? htons(dcfg->port) : 0;
447 }
448 addrlen = sizeof(addr);
449 ret = bind(fd, (const struct sockaddr *)&addr, addrlen);
450 if (ret < 0 && errno == EADDRNOTAVAIL && !dcfg->address) {
451 /*
452 * Some systems don't like us binding to random weird
453 * localhost-space addresses. Try again with the official
454 * INADDR_LOOPBACK.
455 */
456 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
457 addr.sin_port = htons(0);
458 ret = bind(fd, (const struct sockaddr *)&addr, addrlen);
459 }
460 if (ret < 0) {
461 fprintf(stderr, "bind: %s\n", strerror(errno));
462 exit(1);
463 }
464 if (listen(fd, 5) < 0) {
465 fprintf(stderr, "listen: %s\n", strerror(errno));
466 exit(1);
467 }
468 addrlen = sizeof(addr);
469 if (getsockname(fd, (struct sockaddr *)&addr, &addrlen)) {
470 fprintf(stderr, "getsockname: %s\n", strerror(errno));
471 exit(1);
472 }
473 if ((authmask & HTTPD_AUTH_MAGIC) &&
474 (check_owning_uid(fd, 1) == getuid())) {
475 authtype = HTTPD_AUTH_MAGIC;
476 if (authmask != HTTPD_AUTH_MAGIC)
477 printf("Using Linux /proc/net magic authentication\n");
478 } else if ((authmask & HTTPD_AUTH_BASIC)) {
479 char username[128], password[128], userpassbuf[259];
480 const char *userpass;
481 const char *rname;
482 unsigned char passbuf[10];
483 int i, j, k, fd;
484
485 authtype = HTTPD_AUTH_BASIC;
486
487 if (authmask != HTTPD_AUTH_BASIC)
488 printf("Using HTTP Basic authentication\n");
489
490 if (dcfg->basicauthdata) {
491 userpass = dcfg->basicauthdata;
492 } else {
493 strcpy(username, PNAME);
494 rname = "/dev/urandom";
495 fd = open(rname, O_RDONLY);
496 if (fd < 0) {
497 int err = errno;
498 rname = "/dev/random";
499 fd = open(rname, O_RDONLY);
500 if (fd < 0) {
501 int err2 = errno;
502 fprintf(stderr, "/dev/urandom: open: %s\n", strerror(err));
503 fprintf(stderr, "/dev/random: open: %s\n", strerror(err2));
504 exit(1);
505 }
506 }
507 for (i = 0; i < 10 ;) {
508 j = read(fd, passbuf + i, 10 - i);
509 if (j <= 0) {
510 fprintf(stderr, "%s: read: %s\n", rname,
511 j < 0 ? strerror(errno) : "unexpected EOF");
512 exit(1);
513 }
514 i += j;
515 }
516 close(fd);
517 for (i = 0; i < 16; i++) {
518 /*
519 * 32 characters out of the 36 alphanumerics gives
520 * me the latitude to discard i,l,o for being too
521 * numeric-looking, and w because it has two too
522 * many syllables and one too many presidential
523 * associations.
524 */
525 static const char chars[32] =
526 "0123456789abcdefghjkmnpqrstuvxyz";
527 int v = 0;
528
529 k = i / 8 * 5;
530 for (j = 0; j < 5; j++)
531 v |= ((passbuf[k+j] >> (i%8)) & 1) << j;
532
533 password[i] = chars[v];
534 }
535 password[i] = '\0';
536
537 sprintf(userpassbuf, "%s:%s", username, password);
538 userpass = userpassbuf;
539
540 printf("Username: %s\nPassword: %s\n", username, password);
541 }
542
543 k = strlen(userpass);
544 authstring = snewn(k * 4 / 3 + 16, char);
545 for (i = j = 0; i < k ;) {
546 int s = k-i < 3 ? k-i : 3;
547 base64_encode_atom((unsigned char *)(userpass+i), s, authstring+j);
548 i += s;
549 j += 4;
550 }
551 authstring[j] = '\0';
552 } else if ((authmask & HTTPD_AUTH_NONE)) {
553 authtype = HTTPD_AUTH_NONE;
554 if (authmask != HTTPD_AUTH_NONE)
555 printf("Web server is unauthenticated\n");
556 } else {
557 fprintf(stderr, PNAME ": authentication method not supported\n");
558 exit(1);
559 }
560 if (ntohs(addr.sin_addr.s_addr) == INADDR_ANY) {
561 printf("Server port: %d\n", ntohs(addr.sin_port));
562 } else if (ntohs(addr.sin_port) == 80) {
563 printf("URL: http://%s/\n", inet_ntoa(addr.sin_addr));
564 } else {
565 printf("URL: http://%s:%d/\n",
566 inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
567 }
568
569 /*
570 * Now construct an fd structure to hold it.
571 */
572 f = new_fdstruct(fd, FD_LISTENER);
573
574 /*
575 * Read from standard input, and treat EOF as a notification
576 * to exit.
577 */
578 new_fdstruct(0, FD_CLIENT);
579
580 /*
581 * Now we're ready to run our main loop. Keep looping round on
582 * select.
583 */
584 while (1) {
585 fd_set rfds, wfds;
586 int i, j;
587 SELECT_TYPE_ARG1 maxfd;
588 int ret;
589
590 #define FD_SET_MAX(fd, set, max) \
591 do { FD_SET((fd),(set)); (max) = ((max)<=(fd)?(fd)+1:(max)); } while(0)
592
593 /*
594 * Loop round the fd list putting fds into our select
595 * sets. Also in this loop we remove any that were marked
596 * as deleted in the previous loop.
597 */
598 FD_ZERO(&rfds);
599 FD_ZERO(&wfds);
600 maxfd = 0;
601 for (i = j = 0; j < nfds; j++) {
602
603 if (fds[j].deleted) {
604 sfree(fds[j].wdata);
605 free_connection(fds[j].cctx);
606 continue;
607 }
608 fds[i] = fds[j];
609
610 switch (fds[i].type) {
611 case FD_CLIENT:
612 FD_SET_MAX(fds[i].fd, &rfds, maxfd);
613 break;
614 case FD_LISTENER:
615 FD_SET_MAX(fds[i].fd, &rfds, maxfd);
616 break;
617 case FD_CONNECTION:
618 /*
619 * Always read from a connection socket. Even
620 * after we've started writing, the peer might
621 * still be sending (e.g. because we shamefully
622 * jumped the gun before waiting for the end of
623 * the HTTP request) and so we should be prepared
624 * to read data and throw it away.
625 */
626 FD_SET_MAX(fds[i].fd, &rfds, maxfd);
627 /*
628 * Also attempt to write, if we have data to write.
629 */
630 if (fds[i].wdatapos < fds[i].wdatalen)
631 FD_SET_MAX(fds[i].fd, &wfds, maxfd);
632 break;
633 }
634
635 i++;
636 }
637 nfds = i;
638
639 ret = select(maxfd, SELECT_TYPE_ARG234 &rfds,
640 SELECT_TYPE_ARG234 &wfds, SELECT_TYPE_ARG234 NULL,
641 SELECT_TYPE_ARG5 NULL);
642 if (ret <= 0) {
643 if (ret < 0 && (errno != EINTR)) {
644 fprintf(stderr, "select: %s", strerror(errno));
645 exit(1);
646 }
647 continue;
648 }
649
650 for (i = 0; i < nfds; i++) {
651 switch (fds[i].type) {
652 case FD_CLIENT:
653 if (FD_ISSET(fds[i].fd, &rfds)) {
654 char buf[4096];
655 int ret = read(fds[i].fd, buf, sizeof(buf));
656 if (ret <= 0) {
657 if (ret < 0) {
658 fprintf(stderr, "standard input: read: %s\n",
659 strerror(errno));
660 exit(1);
661 }
662 return;
663 }
664 }
665 break;
666 case FD_LISTENER:
667 if (FD_ISSET(fds[i].fd, &rfds)) {
668 /*
669 * New connection has come in. Accept it.
670 */
671 struct fd *f;
672 struct sockaddr_in addr;
673 socklen_t addrlen = sizeof(addr);
674 int newfd = accept(fds[i].fd, (struct sockaddr *)&addr,
675 &addrlen);
676 if (newfd < 0)
677 break; /* not sure what happened there */
678
679 f = new_fdstruct(newfd, FD_CONNECTION);
680 f->cctx = new_connection(t);
681 if (authtype == HTTPD_AUTH_MAGIC)
682 check_magic_access(f);
683 }
684 break;
685 case FD_CONNECTION:
686 if (FD_ISSET(fds[i].fd, &rfds)) {
687 /*
688 * There's data to be read.
689 */
690 char readbuf[4096];
691 int ret;
692
693 ret = read(fds[i].fd, readbuf, sizeof(readbuf));
694 if (ret <= 0) {
695 /*
696 * This shouldn't happen in a sensible
697 * HTTP connection, so we abandon the
698 * connection if it does.
699 */
700 close(fds[i].fd);
701 fds[i].deleted = 1;
702 break;
703 } else {
704 if (!fds[i].wdata) {
705 /*
706 * If we haven't got an HTTP response
707 * yet, keep processing data in the
708 * hope of acquiring one.
709 */
710 fds[i].wdata = got_data
711 (fds[i].cctx, readbuf, ret,
712 (authtype == HTTPD_AUTH_NONE ||
713 fds[i].magic_access), authstring, &cfg);
714 if (fds[i].wdata) {
715 fds[i].wdatalen = strlen(fds[i].wdata);
716 fds[i].wdatapos = 0;
717 }
718 } else {
719 /*
720 * Otherwise, just drop our read data
721 * on the floor.
722 */
723 }
724 }
725 }
726 if (FD_ISSET(fds[i].fd, &wfds) &&
727 fds[i].wdatapos < fds[i].wdatalen) {
728 /*
729 * The socket is writable, and we have data to
730 * write. Write it.
731 */
732 int ret = write(fds[i].fd, fds[i].wdata + fds[i].wdatapos,
733 fds[i].wdatalen - fds[i].wdatapos);
734 if (ret <= 0) {
735 /*
736 * Shouldn't happen; abandon the connection.
737 */
738 close(fds[i].fd);
739 fds[i].deleted = 1;
740 break;
741 } else {
742 fds[i].wdatapos += ret;
743 if (fds[i].wdatapos == fds[i].wdatalen) {
744 shutdown(fds[i].fd, SHUT_WR);
745 }
746 }
747 }
748 break;
749 }
750 }
751
752 }
753 }