2 * httpd.c: implementation of httpd.h.
10 /* --- Logic driving what the web server's responses are. --- */
12 enum { /* connctx states */
21 int datalen
, datasize
;
22 char *method
, *url
, *headers
, *auth
;
27 * Called when a new connection arrives on a listening socket.
28 * Returns a connctx for the new connection.
30 struct connctx
*new_connection(const void *t
)
32 struct connctx
*cctx
= snew(struct connctx
);
35 cctx
->datalen
= cctx
->datasize
= 0;
36 cctx
->state
= READING_REQ_LINE
;
37 cctx
->method
= cctx
->url
= cctx
->headers
= cctx
->auth
= NULL
;
41 void free_connection(struct connctx
*cctx
)
47 static char *http_error(char *code
, char *errmsg
, char *extraheader
,
50 return dupfmt("HTTP/1.1 %s %s\r\n"
52 "Server: " PNAME
"\r\n"
53 "Connection: close\r\n"
55 "Content-Type: text/html; charset=US-ASCII\r\n"
57 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
59 "<TITLE>%s %s</TITLE>\r\n"
63 "</BODY></HTML>\r\n", code
, errmsg
,
64 extraheader ? extraheader
: "",
65 code
, errmsg
, code
, errmsg
, errtext
);
68 static char *http_success(char *mimetype
, int stuff_cr
, char *document
)
70 return dupfmt("HTTP/1.1 200 OK\r\n"
73 "Server: " PNAME
"\r\n"
74 "Connection: close\r\n"
75 "Content-Type: %s\r\n"
77 "%S", mimetype
, stuff_cr
, document
);
81 * Called when data comes in on a connection.
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.
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
)
92 char *line
, *p
, *q
, *r
, *z1
, *z2
, c1
, c2
;
93 int auth_provided
= 0, auth_correct
= 0;
98 * Add the data we've just received to our buffer.
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);
104 memcpy(ctx
->data
+ ctx
->datalen
, data
, length
);
105 ctx
->datalen
+= length
;
108 * Gradually process the HTTP request as we receive it.
110 if (ctx
->state
== READING_REQ_LINE
) {
112 * We're waiting for the first line of the input, which
113 * contains the main HTTP request. See if we've got it
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.'
124 while (line
- ctx
->data
< ctx
->datalen
&&
125 (*line
== '\r' || *line
== '\n'))
128 while (q
- ctx
->data
< ctx
->datalen
&& *q
!= '\n')
130 if (q
- ctx
->data
>= ctx
->datalen
)
131 return NULL
; /* not got request line yet */
134 * We've got the first line of the request. Zero-terminate
135 * and parse it into method, URL and optional HTTP
140 if (q
> line
&& q
[-1] == '\r')
145 while (*p
&& !isspace((unsigned char)*p
)) p
++;
151 while (*p
&& isspace((unsigned char)*p
)) p
++;
153 while (*q
&& !isspace((unsigned char)*q
)) q
++;
157 while (*q
&& isspace((unsigned char)*q
)) q
++;
160 * Now `line' points at the method name; p points at the
161 * URL, if any; q points at the HTTP version, if any.
165 * There should _be_ a URL, on any request type at all.
169 /* Restore the request to the way we received it. */
172 text
= dupfmt("<code>" PNAME
"</code> received the HTTP request"
173 " \"<code>%h</code>\", which contains no URL.",
175 ret
= http_error("400", "Bad request", NULL
, text
);
184 * If there was an HTTP version, we might need to see
185 * headers. Otherwise, the request is done.
188 ctx
->state
= READING_HEADERS
;
194 if (ctx
->state
== READING_HEADERS
) {
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.
200 q
= ctx
->data
+ ctx
->datalen
;
201 for (p
= ctx
->headers
; p
< q
; p
++) {
203 ((p
+1 < q
&& p
[1] == '\n') ||
204 (p
+2 < q
&& p
[1] == '\r' && p
[2] == '\n'))) {
212 if (ctx
->state
== DONE
) {
214 * Now we have the entire HTTP request. Decide what to do
219 * Search the request headers for Authorization.
221 q
= ctx
->data
+ ctx
->datalen
;
222 for (p
= ctx
->headers
; p
< q
; p
++) {
223 const char *hdr
= "Authorization:";
225 for (i
= 0; hdr
[i
]; i
++) {
226 if (p
>= q
|| tolower((unsigned char)*p
) !=
227 tolower((unsigned char)hdr
[i
]))
232 break; /* found our header */
233 p
= memchr(p
, '\n', q
- p
);
239 while (p
< q
&& isspace((unsigned char)*p
))
242 while (p
< q
&& !isspace((unsigned char)*p
))
246 if (!strcasecmp(r
, "Basic")) {
247 while (p
< q
&& isspace((unsigned char)*p
))
250 while (p
< q
&& !isspace((unsigned char)*p
))
254 if (!strcmp(r
, auth_string
))
262 if (!magic_access
&& !auth_correct
) {
264 ret
= http_error("401", "Unauthorized",
265 "WWW-Authenticate: Basic realm=\""PNAME
"\"\r\n",
266 "\nYou must authenticate to view these pages.");
268 ret
= http_error("403", "Forbidden", NULL
,
269 "This is a restricted-access set of pages.");
274 p
+= strspn(p
, "/?");
275 index
= strtoul(p
, &q
, 10);
277 ret
= http_error("404", "Not Found", NULL
,
278 "This is not a valid pathname index.");
280 document
= html_query(ctx
->t
, index
, cfg
);
282 ret
= http_success("text/html", 1, document
);
285 ret
= http_error("404", "Not Found", NULL
,
286 "Pathname index out of range.");
295 /* --- Platform support for running a web server. --- */
297 enum { FD_CLIENT
, FD_LISTENER
, FD_CONNECTION
};
304 int wdatalen
, wdatapos
;
306 struct connctx
*cctx
;
309 struct fd
*fds
= NULL
;
310 int nfds
= 0, fdsize
= 0;
312 struct fd
*new_fdstruct(int fd
, int type
)
316 if (nfds
>= fdsize
) {
317 fdsize
= nfds
* 3 / 2 + 32;
318 fds
= sresize(fds
, fdsize
, struct fd
);
326 ret
->wdatalen
= ret
->wdatapos
= 0;
329 ret
->magic_access
= 0;
334 int check_owning_uid(int fd
, int flip
)
336 struct sockaddr_in sock
, peer
;
338 char linebuf
[4096], matchbuf
[80];
341 addrlen
= sizeof(sock
);
342 if (getsockname(fd
, (struct sockaddr
*)&sock
, &addrlen
)) {
343 fprintf(stderr
, "getsockname: %s\n", strerror(errno
));
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);
352 fprintf(stderr
, "getpeername: %s\n", strerror(errno
));
358 struct sockaddr_in tmp
= sock
;
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");
368 while (fgets(linebuf
, sizeof(linebuf
), fp
)) {
369 if (strlen(linebuf
) >= 75 &&
370 !strncmp(linebuf
+6, matchbuf
, strlen(matchbuf
))) {
372 return atoi(linebuf
+ 75);
381 void check_magic_access(struct fd
*fd
)
383 if (check_owning_uid(fd
->fd
, 0) == getuid())
384 fd
->magic_access
= 1;
387 static void base64_encode_atom(unsigned char *data
, int n
, char *out
)
389 static const char base64_chars
[] =
390 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
394 word
= data
[0] << 16;
396 word
|= data
[1] << 8;
399 out
[0] = base64_chars
[(word
>> 18) & 0x3F];
400 out
[1] = base64_chars
[(word
>> 12) & 0x3F];
402 out
[2] = base64_chars
[(word
>> 6) & 0x3F];
406 out
[3] = base64_chars
[word
& 0x3F];
411 void run_httpd(const void *t
, int authmask
, const struct httpd_config
*dcfg
,
412 const struct html_config
*incfg
)
416 char *authstring
= NULL
;
418 struct sockaddr_in addr
;
420 struct html_config cfg
= *incfg
;
422 cfg
.format
= "%.0lu";
425 * Establish the listening socket and retrieve its port
428 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
430 fprintf(stderr
, "socket(PF_INET): %s\n", strerror(errno
));
433 addr
.sin_family
= AF_INET
;
434 if (!dcfg
->address
) {
435 #ifdef RANDOM_LOCALHOST
436 unsigned long ipaddr
;
439 ipaddr
+= (1 + rand() % 255) << 16;
440 ipaddr
+= (1 + rand() % 255) << 8;
441 ipaddr
+= (1 + rand() % 255);
442 addr
.sin_addr
.s_addr
= htonl(ipaddr
);
444 addr
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
446 addr
.sin_port
= htons(0);
448 addr
.sin_addr
.s_addr
= inet_addr(dcfg
->address
);
449 addr
.sin_port
= dcfg
->port ?
htons(dcfg
->port
) : 0;
451 addrlen
= sizeof(addr
);
452 ret
= bind(fd
, (const struct sockaddr
*)&addr
, addrlen
);
453 #ifdef RANDOM_LOCALHOST
454 if (ret
< 0 && errno
== EADDRNOTAVAIL
&& !dcfg
->address
) {
456 * Some systems don't like us binding to random weird
457 * localhost-space addresses. Try again with the official
460 addr
.sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
461 addr
.sin_port
= htons(0);
462 ret
= bind(fd
, (const struct sockaddr
*)&addr
, addrlen
);
466 fprintf(stderr
, "bind: %s\n", strerror(errno
));
469 if (listen(fd
, 5) < 0) {
470 fprintf(stderr
, "listen: %s\n", strerror(errno
));
473 addrlen
= sizeof(addr
);
474 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
)) {
475 fprintf(stderr
, "getsockname: %s\n", strerror(errno
));
478 if ((authmask
& HTTPD_AUTH_MAGIC
) &&
479 (check_owning_uid(fd
, 1) == getuid())) {
480 authtype
= HTTPD_AUTH_MAGIC
;
481 if (authmask
!= HTTPD_AUTH_MAGIC
)
482 printf("Using Linux /proc/net magic authentication\n");
483 } else if ((authmask
& HTTPD_AUTH_BASIC
)) {
484 char username
[128], password
[128], userpassbuf
[259];
485 const char *userpass
;
487 unsigned char passbuf
[10];
490 authtype
= HTTPD_AUTH_BASIC
;
492 if (authmask
!= HTTPD_AUTH_BASIC
)
493 printf("Using HTTP Basic authentication\n");
495 if (dcfg
->basicauthdata
) {
496 userpass
= dcfg
->basicauthdata
;
498 strcpy(username
, PNAME
);
499 rname
= "/dev/urandom";
500 fd
= open(rname
, O_RDONLY
);
503 rname
= "/dev/random";
504 fd
= open(rname
, O_RDONLY
);
507 fprintf(stderr
, "/dev/urandom: open: %s\n", strerror(err
));
508 fprintf(stderr
, "/dev/random: open: %s\n", strerror(err2
));
512 for (i
= 0; i
< 10 ;) {
513 j
= read(fd
, passbuf
+ i
, 10 - i
);
515 fprintf(stderr
, "%s: read: %s\n", rname
,
516 j
< 0 ?
strerror(errno
) : "unexpected EOF");
522 for (i
= 0; i
< 16; i
++) {
524 * 32 characters out of the 36 alphanumerics gives
525 * me the latitude to discard i,l,o for being too
526 * numeric-looking, and w because it has two too
527 * many syllables and one too many presidential
530 static const char chars
[32] =
531 "0123456789abcdefghjkmnpqrstuvxyz";
535 for (j
= 0; j
< 5; j
++)
536 v
|= ((passbuf
[k
+j
] >> (i
%8)) & 1) << j
;
538 password
[i
] = chars
[v
];
542 sprintf(userpassbuf
, "%s:%s", username
, password
);
543 userpass
= userpassbuf
;
545 printf("Username: %s\nPassword: %s\n", username
, password
);
548 k
= strlen(userpass
);
549 authstring
= snewn(k
* 4 / 3 + 16, char);
550 for (i
= j
= 0; i
< k
;) {
551 int s
= k
-i
< 3 ? k
-i
: 3;
552 base64_encode_atom((unsigned char *)(userpass
+i
), s
, authstring
+j
);
556 authstring
[j
] = '\0';
557 } else if ((authmask
& HTTPD_AUTH_NONE
)) {
558 authtype
= HTTPD_AUTH_NONE
;
559 if (authmask
!= HTTPD_AUTH_NONE
)
560 printf("Web server is unauthenticated\n");
562 fprintf(stderr
, PNAME
": authentication method not supported\n");
565 if (ntohs(addr
.sin_addr
.s_addr
) == INADDR_ANY
) {
566 printf("Server port: %d\n", ntohs(addr
.sin_port
));
567 } else if (ntohs(addr
.sin_port
) == 80) {
568 printf("URL: http://%s/\n", inet_ntoa(addr
.sin_addr
));
570 printf("URL: http://%s:%d/\n",
571 inet_ntoa(addr
.sin_addr
), ntohs(addr
.sin_port
));
575 * Now construct an fd structure to hold it.
577 f
= new_fdstruct(fd
, FD_LISTENER
);
580 * Read from standard input, and treat EOF as a notification
583 new_fdstruct(0, FD_CLIENT
);
586 * Now we're ready to run our main loop. Keep looping round on
592 SELECT_TYPE_ARG1 maxfd
;
595 #define FD_SET_MAX(fd, set, max) \
596 do { FD_SET((fd),(set)); (max) = ((max)<=(fd)?(fd)+1:(max)); } while(0)
599 * Loop round the fd list putting fds into our select
600 * sets. Also in this loop we remove any that were marked
601 * as deleted in the previous loop.
606 for (i
= j
= 0; j
< nfds
; j
++) {
608 if (fds
[j
].deleted
) {
610 free_connection(fds
[j
].cctx
);
615 switch (fds
[i
].type
) {
617 FD_SET_MAX(fds
[i
].fd
, &rfds
, maxfd
);
620 FD_SET_MAX(fds
[i
].fd
, &rfds
, maxfd
);
624 * Always read from a connection socket. Even
625 * after we've started writing, the peer might
626 * still be sending (e.g. because we shamefully
627 * jumped the gun before waiting for the end of
628 * the HTTP request) and so we should be prepared
629 * to read data and throw it away.
631 FD_SET_MAX(fds
[i
].fd
, &rfds
, maxfd
);
633 * Also attempt to write, if we have data to write.
635 if (fds
[i
].wdatapos
< fds
[i
].wdatalen
)
636 FD_SET_MAX(fds
[i
].fd
, &wfds
, maxfd
);
644 ret
= select(maxfd
, SELECT_TYPE_ARG234
&rfds
,
645 SELECT_TYPE_ARG234
&wfds
, SELECT_TYPE_ARG234 NULL
,
646 SELECT_TYPE_ARG5 NULL
);
648 if (ret
< 0 && (errno
!= EINTR
)) {
649 fprintf(stderr
, "select: %s", strerror(errno
));
655 for (i
= 0; i
< nfds
; i
++) {
656 switch (fds
[i
].type
) {
658 if (FD_ISSET(fds
[i
].fd
, &rfds
)) {
660 int ret
= read(fds
[i
].fd
, buf
, sizeof(buf
));
663 fprintf(stderr
, "standard input: read: %s\n",
672 if (FD_ISSET(fds
[i
].fd
, &rfds
)) {
674 * New connection has come in. Accept it.
677 struct sockaddr_in addr
;
678 socklen_t addrlen
= sizeof(addr
);
679 int newfd
= accept(fds
[i
].fd
, (struct sockaddr
*)&addr
,
682 break; /* not sure what happened there */
684 f
= new_fdstruct(newfd
, FD_CONNECTION
);
685 f
->cctx
= new_connection(t
);
686 if (authtype
== HTTPD_AUTH_MAGIC
)
687 check_magic_access(f
);
691 if (FD_ISSET(fds
[i
].fd
, &rfds
)) {
693 * There's data to be read.
698 ret
= read(fds
[i
].fd
, readbuf
, sizeof(readbuf
));
701 * This shouldn't happen in a sensible
702 * HTTP connection, so we abandon the
703 * connection if it does.
711 * If we haven't got an HTTP response
712 * yet, keep processing data in the
713 * hope of acquiring one.
715 fds
[i
].wdata
= got_data
716 (fds
[i
].cctx
, readbuf
, ret
,
717 (authtype
== HTTPD_AUTH_NONE
||
718 fds
[i
].magic_access
), authstring
, &cfg
);
720 fds
[i
].wdatalen
= strlen(fds
[i
].wdata
);
725 * Otherwise, just drop our read data
731 if (FD_ISSET(fds
[i
].fd
, &wfds
) &&
732 fds
[i
].wdatapos
< fds
[i
].wdatalen
) {
734 * The socket is writable, and we have data to
737 int ret
= write(fds
[i
].fd
, fds
[i
].wdata
+ fds
[i
].wdatapos
,
738 fds
[i
].wdatalen
- fds
[i
].wdatapos
);
741 * Shouldn't happen; abandon the connection.
747 fds
[i
].wdatapos
+= ret
;
748 if (fds
[i
].wdatapos
== fds
[i
].wdatalen
) {
749 shutdown(fds
[i
].fd
, SHUT_WR
);