2 * httpd.c: implementation of httpd.h.
15 #include <sys/types.h>
18 #include <sys/socket.h>
19 #include <arpa/inet.h>
20 #include <netinet/in.h>
28 /* --- Logic driving what the web server's responses are. --- */
30 enum { /* connctx states */
39 int datalen
, datasize
;
40 char *method
, *url
, *headers
, *auth
;
45 * Called when a new connection arrives on a listening socket.
46 * Returns a connctx for the new connection.
48 struct connctx
*new_connection(const void *t
)
50 struct connctx
*cctx
= snew(struct connctx
);
53 cctx
->datalen
= cctx
->datasize
= 0;
54 cctx
->state
= READING_REQ_LINE
;
55 cctx
->method
= cctx
->url
= cctx
->headers
= cctx
->auth
= NULL
;
59 void free_connection(struct connctx
*cctx
)
65 static char *http_error(char *code
, char *errmsg
, char *extraheader
,
68 return dupfmt("HTTP/1.1 %s %s\r\n"
70 "Server: " PNAME
"\r\n"
71 "Connection: close\r\n"
73 "Content-Type: text/html; charset=US-ASCII\r\n"
75 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
77 "<TITLE>%s %s</TITLE>\r\n"
81 "</BODY></HTML>\r\n", code
, errmsg
,
82 extraheader ? extraheader
: "",
83 code
, errmsg
, code
, errmsg
, errtext
);
86 static char *http_success(char *mimetype
, int stuff_cr
, char *document
)
88 return dupfmt("HTTP/1.1 200 OK\r\n"
91 "Server: " PNAME
"\r\n"
92 "Connection: close\r\n"
93 "Content-Type: %s\r\n"
95 "%S", mimetype
, stuff_cr
, document
);
99 * Called when data comes in on a connection.
101 * If this function returns NULL, the platform code continues
102 * reading from the socket. Otherwise, it returns some dynamically
103 * allocated data which the platform code will then write to the
104 * socket before closing it.
106 char *got_data(struct connctx
*ctx
, char *data
, int length
,
107 int magic_access
, const char *auth_string
,
108 const struct html_config
*cfg
)
110 char *line
, *p
, *q
, *r
, *z1
, *z2
, c1
, c2
;
111 int auth_provided
= 0, auth_correct
= 0;
113 char *document
, *ret
;
116 * Add the data we've just received to our buffer.
118 if (ctx
->datasize
< ctx
->datalen
+ length
) {
119 ctx
->datasize
= (ctx
->datalen
+ length
) * 3 / 2 + 4096;
120 ctx
->data
= sresize(ctx
->data
, ctx
->datasize
, char);
122 memcpy(ctx
->data
+ ctx
->datalen
, data
, length
);
123 ctx
->datalen
+= length
;
126 * Gradually process the HTTP request as we receive it.
128 if (ctx
->state
== READING_REQ_LINE
) {
130 * We're waiting for the first line of the input, which
131 * contains the main HTTP request. See if we've got it
137 * RFC 2616 section 4.1: `In the interest of robustness,
138 * [...] if the server is reading the protocol stream at
139 * the beginning of a message and receives a CRLF first,
140 * it should ignore the CRLF.'
142 while (line
- ctx
->data
< ctx
->datalen
&&
143 (*line
== '\r' || *line
== '\n'))
146 while (q
- ctx
->data
< ctx
->datalen
&& *q
!= '\n')
148 if (q
- ctx
->data
>= ctx
->datalen
)
149 return NULL
; /* not got request line yet */
152 * We've got the first line of the request. Zero-terminate
153 * and parse it into method, URL and optional HTTP
158 if (q
> line
&& q
[-1] == '\r')
163 while (*p
&& !isspace((unsigned char)*p
)) p
++;
169 while (*p
&& isspace((unsigned char)*p
)) p
++;
171 while (*q
&& !isspace((unsigned char)*q
)) q
++;
175 while (*q
&& isspace((unsigned char)*q
)) q
++;
178 * Now `line' points at the method name; p points at the
179 * URL, if any; q points at the HTTP version, if any.
183 * There should _be_ a URL, on any request type at all.
187 /* Restore the request to the way we received it. */
190 text
= dupfmt("<code>" PNAME
"</code> received the HTTP request"
191 " \"<code>%h</code>\", which contains no URL.",
193 ret
= http_error("400", "Bad request", NULL
, text
);
202 * If there was an HTTP version, we might need to see
203 * headers. Otherwise, the request is done.
206 ctx
->state
= READING_HEADERS
;
212 if (ctx
->state
== READING_HEADERS
) {
214 * While we're receiving the HTTP request headers, all we
215 * do is to keep scanning to see if we find two newlines
216 * next to each other.
218 q
= ctx
->data
+ ctx
->datalen
;
219 for (p
= ctx
->headers
; p
< q
; p
++) {
221 ((p
+1 < q
&& p
[1] == '\n') ||
222 (p
+2 < q
&& p
[1] == '\r' && p
[2] == '\n'))) {
230 if (ctx
->state
== DONE
) {
232 * Now we have the entire HTTP request. Decide what to do
237 * Search the request headers for Authorization.
239 q
= ctx
->data
+ ctx
->datalen
;
240 for (p
= ctx
->headers
; p
< q
; p
++) {
241 const char *hdr
= "Authorization:";
243 for (i
= 0; hdr
[i
]; i
++) {
244 if (p
>= q
|| tolower((unsigned char)*p
) !=
245 tolower((unsigned char)hdr
[i
]))
250 break; /* found our header */
251 p
= memchr(p
, '\n', q
- p
);
257 while (p
< q
&& isspace((unsigned char)*p
))
260 while (p
< q
&& !isspace((unsigned char)*p
))
264 if (!strcasecmp(r
, "Basic")) {
265 while (p
< q
&& isspace((unsigned char)*p
))
268 while (p
< q
&& !isspace((unsigned char)*p
))
272 if (!strcmp(r
, auth_string
))
280 if (!magic_access
&& !auth_correct
) {
282 ret
= http_error("401", "Unauthorized",
283 "WWW-Authenticate: Basic realm=\""PNAME
"\"\r",
284 "\nYou must authenticate to view these pages.");
286 ret
= http_error("403", "Forbidden", NULL
,
287 "This is a restricted-access set of pages.");
291 p
+= strspn(p
, "/?");
292 index
= strtoul(p
, NULL
, 10);
293 document
= html_query(ctx
->t
, index
, cfg
);
295 ret
= http_success("text/html", 1, document
);
298 ret
= http_error("404", "Not Found", NULL
,
299 "Pathname index out of range.");
307 /* --- Platform support for running a web server. --- */
309 enum { FD_CLIENT
, FD_LISTENER
, FD_CONNECTION
};
316 int wdatalen
, wdatapos
;
318 struct connctx
*cctx
;
321 struct fd
*fds
= NULL
;
322 int nfds
= 0, fdsize
= 0;
324 struct fd
*new_fdstruct(int fd
, int type
)
328 if (nfds
>= fdsize
) {
329 fdsize
= nfds
* 3 / 2 + 32;
330 fds
= sresize(fds
, fdsize
, struct fd
);
338 ret
->wdatalen
= ret
->wdatapos
= 0;
341 ret
->magic_access
= 0;
346 int check_owning_uid(int fd
, int flip
)
348 struct sockaddr_in sock
, peer
;
350 char linebuf
[4096], matchbuf
[80];
353 addrlen
= sizeof(sock
);
354 if (getsockname(fd
, (struct sockaddr
*)&sock
, &addrlen
)) {
355 fprintf(stderr
, "getsockname: %s\n", strerror(errno
));
358 addrlen
= sizeof(peer
);
359 if (getpeername(fd
, (struct sockaddr
*)&peer
, &addrlen
)) {
360 if (errno
== ENOTCONN
) {
361 peer
.sin_addr
.s_addr
= htonl(0);
362 peer
.sin_port
= htons(0);
364 fprintf(stderr
, "getpeername: %s\n", strerror(errno
));
370 struct sockaddr_in tmp
= sock
;
375 sprintf(matchbuf
, "%08X:%04X %08X:%04X",
376 peer
.sin_addr
.s_addr
, ntohs(peer
.sin_port
),
377 sock
.sin_addr
.s_addr
, ntohs(sock
.sin_port
));
378 fp
= fopen("/proc/net/tcp", "r");
380 while (fgets(linebuf
, sizeof(linebuf
), fp
)) {
381 if (strlen(linebuf
) >= 75 &&
382 !strncmp(linebuf
+6, matchbuf
, strlen(matchbuf
))) {
383 return atoi(linebuf
+ 75);
391 void check_magic_access(struct fd
*fd
)
393 if (check_owning_uid(fd
->fd
, 0) == getuid())
394 fd
->magic_access
= 1;
397 static void base64_encode_atom(unsigned char *data
, int n
, char *out
)
399 static const char base64_chars
[] =
400 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
404 word
= data
[0] << 16;
406 word
|= data
[1] << 8;
409 out
[0] = base64_chars
[(word
>> 18) & 0x3F];
410 out
[1] = base64_chars
[(word
>> 12) & 0x3F];
412 out
[2] = base64_chars
[(word
>> 6) & 0x3F];
416 out
[3] = base64_chars
[word
& 0x3F];
421 void run_httpd(const void *t
, int authmask
, const struct httpd_config
*dcfg
,
422 const struct html_config
*incfg
)
426 char *authstring
= NULL
;
427 unsigned long ipaddr
;
429 struct sockaddr_in addr
;
431 struct html_config cfg
= *incfg
;
433 cfg
.format
= "%.0lu";
436 * Establish the listening socket and retrieve its port
439 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
441 fprintf(stderr
, "socket(PF_INET): %s\n", strerror(errno
));
444 addr
.sin_family
= AF_INET
;
445 if (!dcfg
->address
) {
448 ipaddr
+= (1 + rand() % 255) << 16;
449 ipaddr
+= (1 + rand() % 255) << 8;
450 ipaddr
+= (1 + rand() % 255);
451 addr
.sin_addr
.s_addr
= htonl(ipaddr
);
452 addr
.sin_port
= htons(0);
454 addr
.sin_addr
.s_addr
= inet_addr(dcfg
->address
);
455 addr
.sin_port
= dcfg
->port ?
htons(dcfg
->port
) : 80;
457 addrlen
= sizeof(addr
);
458 if (bind(fd
, (struct sockaddr
*)&addr
, addrlen
) < 0) {
459 fprintf(stderr
, "bind: %s\n", strerror(errno
));
462 if (listen(fd
, 5) < 0) {
463 fprintf(stderr
, "listen: %s\n", strerror(errno
));
466 addrlen
= sizeof(addr
);
467 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
)) {
468 fprintf(stderr
, "getsockname: %s\n", strerror(errno
));
471 if ((authmask
& HTTPD_AUTH_MAGIC
) &&
472 (check_owning_uid(fd
, 1) == getuid())) {
473 authtype
= HTTPD_AUTH_MAGIC
;
474 if (authmask
!= HTTPD_AUTH_MAGIC
)
475 printf("Using Linux /proc/net magic authentication\n");
476 } else if ((authmask
& HTTPD_AUTH_BASIC
)) {
477 char username
[128], password
[128], userpassbuf
[259];
478 const char *userpass
;
480 unsigned char passbuf
[10];
483 authtype
= HTTPD_AUTH_BASIC
;
485 if (authmask
!= HTTPD_AUTH_BASIC
)
486 printf("Using HTTP Basic authentication\n");
488 if (dcfg
->basicauthdata
) {
489 userpass
= dcfg
->basicauthdata
;
491 strcpy(username
, PNAME
);
492 rname
= "/dev/urandom";
493 fd
= open(rname
, O_RDONLY
);
496 rname
= "/dev/random";
497 fd
= open(rname
, O_RDONLY
);
500 fprintf(stderr
, "/dev/urandom: open: %s\n", strerror(err
));
501 fprintf(stderr
, "/dev/random: open: %s\n", strerror(err2
));
505 for (i
= 0; i
< 10 ;) {
506 j
= read(fd
, passbuf
+ i
, 10 - i
);
508 fprintf(stderr
, "%s: read: %s\n", rname
,
509 j
< 0 ?
strerror(errno
) : "unexpected EOF");
515 for (i
= 0; i
< 16; i
++) {
517 * 32 characters out of the 36 alphanumerics gives
518 * me the latitude to discard i,l,o for being too
519 * numeric-looking, and w because it has two too
520 * many syllables and one too many presidential
523 static const char chars
[32] =
524 "0123456789abcdefghjkmnpqrstuvxyz";
528 for (j
= 0; j
< 5; j
++)
529 v
|= ((passbuf
[k
+j
] >> (i
%8)) & 1) << j
;
531 password
[i
] = chars
[v
];
535 sprintf(userpassbuf
, "%s:%s", username
, password
);
536 userpass
= userpassbuf
;
538 printf("Username: %s\nPassword: %s\n", username
, password
);
541 k
= strlen(userpass
);
542 authstring
= snewn(k
* 4 / 3 + 16, char);
543 for (i
= j
= 0; i
< k
;) {
544 int s
= k
-i
< 3 ? k
-i
: 3;
545 base64_encode_atom((unsigned char *)(userpass
+i
), s
, authstring
+j
);
549 authstring
[j
] = '\0';
550 } else if ((authmask
& HTTPD_AUTH_NONE
)) {
551 authtype
= HTTPD_AUTH_NONE
;
552 if (authmask
!= HTTPD_AUTH_NONE
)
553 printf("Web server is unauthenticated\n");
555 fprintf(stderr
, PNAME
": authentication method not supported\n");
558 if (!dcfg
->address
) {
559 if (ntohs(addr
.sin_port
) == 80) {
560 printf("URL: http://%s/\n", inet_ntoa(addr
.sin_addr
));
562 printf("URL: http://%s:%d/\n",
563 inet_ntoa(addr
.sin_addr
), ntohs(addr
.sin_port
));
568 * Now construct an fd structure to hold it.
570 f
= new_fdstruct(fd
, FD_LISTENER
);
573 * Read from standard input, and treat EOF as a notification
576 new_fdstruct(0, FD_CLIENT
);
579 * Now we're ready to run our main loop. Keep looping round on
584 int i
, j
, maxfd
, ret
;
586 #define FD_SET_MAX(fd, set, max) \
587 do { FD_SET((fd),(set)); (max) = ((max)<=(fd)?(fd)+1:(max)); } while(0)
590 * Loop round the fd list putting fds into our select
591 * sets. Also in this loop we remove any that were marked
592 * as deleted in the previous loop.
597 for (i
= j
= 0; j
< nfds
; j
++) {
599 if (fds
[j
].deleted
) {
601 free_connection(fds
[j
].cctx
);
606 switch (fds
[i
].type
) {
609 FD_SET_MAX(fds
[i
].fd
, &rfds
, maxfd
);
613 * Always read from a connection socket. Even
614 * after we've started writing, the peer might
615 * still be sending (e.g. because we shamefully
616 * jumped the gun before waiting for the end of
617 * the HTTP request) and so we should be prepared
618 * to read data and throw it away.
620 FD_SET_MAX(fds
[i
].fd
, &rfds
, maxfd
);
622 * Also attempt to write, if we have data to write.
624 if (fds
[i
].wdatapos
< fds
[i
].wdatalen
)
625 FD_SET_MAX(fds
[i
].fd
, &wfds
, maxfd
);
633 ret
= select(maxfd
, &rfds
, &wfds
, NULL
, NULL
);
635 if (ret
< 0 && (errno
!= EINTR
)) {
636 fprintf(stderr
, "select: %s", strerror(errno
));
642 for (i
= 0; i
< nfds
; i
++) {
643 switch (fds
[i
].type
) {
645 if (FD_ISSET(fds
[i
].fd
, &rfds
)) {
647 int ret
= read(fds
[i
].fd
, buf
, sizeof(buf
));
650 fprintf(stderr
, "standard input: read: %s\n",
659 if (FD_ISSET(fds
[i
].fd
, &rfds
)) {
661 * New connection has come in. Accept it.
664 struct sockaddr_in addr
;
665 socklen_t addrlen
= sizeof(addr
);
666 int newfd
= accept(fds
[i
].fd
, (struct sockaddr
*)&addr
,
669 break; /* not sure what happened there */
671 f
= new_fdstruct(newfd
, FD_CONNECTION
);
672 f
->cctx
= new_connection(t
);
673 if (authtype
== HTTPD_AUTH_MAGIC
)
674 check_magic_access(f
);
678 if (FD_ISSET(fds
[i
].fd
, &rfds
)) {
680 * There's data to be read.
685 ret
= read(fds
[i
].fd
, readbuf
, sizeof(readbuf
));
688 * This shouldn't happen in a sensible
689 * HTTP connection, so we abandon the
690 * connection if it does.
698 * If we haven't got an HTTP response
699 * yet, keep processing data in the
700 * hope of acquiring one.
702 fds
[i
].wdata
= got_data
703 (fds
[i
].cctx
, readbuf
, ret
,
704 (authtype
== HTTPD_AUTH_NONE
||
705 fds
[i
].magic_access
), authstring
, &cfg
);
707 fds
[i
].wdatalen
= strlen(fds
[i
].wdata
);
712 * Otherwise, just drop our read data
718 if (FD_ISSET(fds
[i
].fd
, &wfds
) &&
719 fds
[i
].wdatapos
< fds
[i
].wdatalen
) {
721 * The socket is writable, and we have data to
724 int ret
= write(fds
[i
].fd
, fds
[i
].wdata
+ fds
[i
].wdatapos
,
725 fds
[i
].wdatalen
- fds
[i
].wdatapos
);
728 * Shouldn't happen; abandon the connection.
734 fds
[i
].wdatapos
+= ret
;
735 if (fds
[i
].wdatapos
== fds
[i
].wdatalen
) {
736 shutdown(fds
[i
].fd
, SHUT_WR
);