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>
27 /* --- Logic driving what the web server's responses are. --- */
29 enum { /* connctx states */
38 int datalen
, datasize
;
39 char *method
, *url
, *headers
, *auth
;
44 * Called when a new connection arrives on a listening socket.
45 * Returns a connctx for the new connection.
47 struct connctx
*new_connection(const void *t
)
49 struct connctx
*cctx
= snew(struct connctx
);
52 cctx
->datalen
= cctx
->datasize
= 0;
53 cctx
->state
= READING_REQ_LINE
;
54 cctx
->method
= cctx
->url
= cctx
->headers
= cctx
->auth
= NULL
;
58 void free_connection(struct connctx
*cctx
)
64 static char *http_error(char *code
, char *errmsg
, char *extraheader
,
67 return dupfmt("HTTP/1.1 %s %s\r\n"
70 "Connection: close\r\n"
72 "Content-Type: text/html; charset=US-ASCII\r\n"
74 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
76 "<TITLE>%s %s</TITLE>\r\n"
80 "</BODY></HTML>\r\n", code
, errmsg
,
81 extraheader ? extraheader
: "",
82 code
, errmsg
, code
, errmsg
, errtext
);
85 static char *http_success(char *mimetype
, int stuff_cr
, char *document
)
87 return dupfmt("HTTP/1.1 200 OK\r\n"
91 "Connection: close\r\n"
92 "Content-Type: %s\r\n"
94 "%S", mimetype
, stuff_cr
, document
);
98 * Called when data comes in on a connection.
100 * If this function returns NULL, the platform code continues
101 * reading from the socket. Otherwise, it returns some dynamically
102 * allocated data which the platform code will then write to the
103 * socket before closing it.
105 char *got_data(struct connctx
*ctx
, char *data
, int length
,
106 int magic_access
, const char *auth_string
,
107 const struct html_config
*cfg
)
109 char *line
, *p
, *q
, *r
, *z1
, *z2
, c1
, c2
;
110 int auth_provided
= 0, auth_correct
= 0;
112 char *document
, *ret
;
115 * Add the data we've just received to our buffer.
117 if (ctx
->datasize
< ctx
->datalen
+ length
) {
118 ctx
->datasize
= (ctx
->datalen
+ length
) * 3 / 2 + 4096;
119 ctx
->data
= sresize(ctx
->data
, ctx
->datasize
, char);
121 memcpy(ctx
->data
+ ctx
->datalen
, data
, length
);
122 ctx
->datalen
+= length
;
125 * Gradually process the HTTP request as we receive it.
127 if (ctx
->state
== READING_REQ_LINE
) {
129 * We're waiting for the first line of the input, which
130 * contains the main HTTP request. See if we've got it
136 * RFC 2616 section 4.1: `In the interest of robustness,
137 * [...] if the server is reading the protocol stream at
138 * the beginning of a message and receives a CRLF first,
139 * it should ignore the CRLF.'
141 while (line
- ctx
->data
< ctx
->datalen
&&
142 (*line
== '\r' || *line
== '\n'))
145 while (q
- ctx
->data
< ctx
->datalen
&& *q
!= '\n')
147 if (q
- ctx
->data
>= ctx
->datalen
)
148 return NULL
; /* not got request line yet */
151 * We've got the first line of the request. Zero-terminate
152 * and parse it into method, URL and optional HTTP
157 if (q
> line
&& q
[-1] == '\r')
162 while (*p
&& !isspace((unsigned char)*p
)) p
++;
168 while (*p
&& isspace((unsigned char)*p
)) p
++;
170 while (*q
&& !isspace((unsigned char)*q
)) q
++;
174 while (*q
&& isspace((unsigned char)*q
)) q
++;
177 * Now `line' points at the method name; p points at the
178 * URL, if any; q points at the HTTP version, if any.
182 * There should _be_ a URL, on any request type at all.
186 /* Restore the request to the way we received it. */
189 text
= dupfmt("<code>agedu</code> received the HTTP request"
190 " \"<code>%h</code>\", which contains no URL.",
192 ret
= http_error("400", "Bad request", NULL
, text
);
201 * If there was an HTTP version, we might need to see
202 * headers. Otherwise, the request is done.
205 ctx
->state
= READING_HEADERS
;
211 if (ctx
->state
== READING_HEADERS
) {
213 * While we're receiving the HTTP request headers, all we
214 * do is to keep scanning to see if we find two newlines
215 * next to each other.
217 q
= ctx
->data
+ ctx
->datalen
;
218 for (p
= ctx
->headers
; p
< q
; p
++) {
220 ((p
+1 < q
&& p
[1] == '\n') ||
221 (p
+2 < q
&& p
[1] == '\r' && p
[2] == '\n'))) {
229 if (ctx
->state
== DONE
) {
231 * Now we have the entire HTTP request. Decide what to do
236 * Search the request headers for Authorization.
238 q
= ctx
->data
+ ctx
->datalen
;
239 for (p
= ctx
->headers
; p
< q
; p
++) {
240 const char *hdr
= "Authorization:";
242 for (i
= 0; hdr
[i
]; i
++) {
243 if (p
>= q
|| tolower((unsigned char)*p
) !=
244 tolower((unsigned char)hdr
[i
]))
249 break; /* found our header */
250 p
= memchr(p
, '\n', q
- p
);
256 while (p
< q
&& isspace((unsigned char)*p
))
259 while (p
< q
&& !isspace((unsigned char)*p
))
263 if (!strcasecmp(r
, "Basic")) {
264 while (p
< q
&& isspace((unsigned char)*p
))
267 while (p
< q
&& !isspace((unsigned char)*p
))
271 if (!strcmp(r
, auth_string
))
279 if (!magic_access
&& !auth_correct
) {
280 if (auth_string
&& !auth_provided
) {
281 ret
= http_error("401", "Unauthorized",
282 "WWW-Authenticate: Basic realm=\"agedu\"\r\n",
283 "Please authenticate to view these pages.");
285 ret
= http_error("403", "Forbidden", NULL
,
286 "This is a restricted-access set of pages.");
290 p
+= strspn(p
, "/?");
291 index
= strtoul(p
, NULL
, 10);
292 document
= html_query(ctx
->t
, index
, cfg
);
294 ret
= http_success("text/html", 1, document
);
297 ret
= http_error("404", "Not Found", NULL
,
298 "Pathname index out of range.");
306 /* --- Platform support for running a web server. --- */
308 enum { FD_CLIENT
, FD_LISTENER
, FD_CONNECTION
};
315 int wdatalen
, wdatapos
;
317 struct connctx
*cctx
;
320 struct fd
*fds
= NULL
;
321 int nfds
= 0, fdsize
= 0;
323 struct fd
*new_fdstruct(int fd
, int type
)
327 if (nfds
>= fdsize
) {
328 fdsize
= nfds
* 3 / 2 + 32;
329 fds
= sresize(fds
, fdsize
, struct fd
);
337 ret
->wdatalen
= ret
->wdatapos
= 0;
340 ret
->magic_access
= 0;
345 int check_owning_uid(int fd
, int flip
)
347 struct sockaddr_in sock
, peer
;
349 char linebuf
[4096], matchbuf
[80];
352 addrlen
= sizeof(sock
);
353 if (getsockname(fd
, (struct sockaddr
*)&sock
, &addrlen
)) {
354 fprintf(stderr
, "getsockname: %s\n", strerror(errno
));
357 addrlen
= sizeof(peer
);
358 if (getpeername(fd
, (struct sockaddr
*)&peer
, &addrlen
)) {
359 if (errno
== ENOTCONN
) {
360 peer
.sin_addr
.s_addr
= htonl(0);
361 peer
.sin_port
= htons(0);
363 fprintf(stderr
, "getpeername: %s\n", strerror(errno
));
369 struct sockaddr_in tmp
= sock
;
374 sprintf(matchbuf
, "%08X:%04X %08X:%04X",
375 peer
.sin_addr
.s_addr
, ntohs(peer
.sin_port
),
376 sock
.sin_addr
.s_addr
, ntohs(sock
.sin_port
));
377 fp
= fopen("/proc/net/tcp", "r");
379 while (fgets(linebuf
, sizeof(linebuf
), fp
)) {
380 if (strlen(linebuf
) >= 75 &&
381 !strncmp(linebuf
+6, matchbuf
, strlen(matchbuf
))) {
382 return atoi(linebuf
+ 75);
390 void check_magic_access(struct fd
*fd
)
392 if (check_owning_uid(fd
->fd
, 0) == getuid())
393 fd
->magic_access
= 1;
396 static void base64_encode_atom(unsigned char *data
, int n
, char *out
)
398 static const char base64_chars
[] =
399 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
403 word
= data
[0] << 16;
405 word
|= data
[1] << 8;
408 out
[0] = base64_chars
[(word
>> 18) & 0x3F];
409 out
[1] = base64_chars
[(word
>> 12) & 0x3F];
411 out
[2] = base64_chars
[(word
>> 6) & 0x3F];
415 out
[3] = base64_chars
[word
& 0x3F];
420 void run_httpd(const void *t
, int authmask
, const struct httpd_config
*dcfg
,
421 const struct html_config
*incfg
)
425 char *authstring
= NULL
;
426 unsigned long ipaddr
;
428 struct sockaddr_in addr
;
430 struct html_config cfg
= *incfg
;
432 cfg
.format
= "%.0lu";
435 * Establish the listening socket and retrieve its port
438 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
440 fprintf(stderr
, "socket(PF_INET): %s\n", strerror(errno
));
443 addr
.sin_family
= AF_INET
;
444 if (!dcfg
->address
) {
447 ipaddr
+= (1 + rand() % 255) << 16;
448 ipaddr
+= (1 + rand() % 255) << 8;
449 ipaddr
+= (1 + rand() % 255);
450 addr
.sin_addr
.s_addr
= htonl(ipaddr
);
451 addr
.sin_port
= htons(0);
453 addr
.sin_addr
.s_addr
= inet_addr(dcfg
->address
);
454 addr
.sin_port
= dcfg
->port ?
htons(dcfg
->port
) : 80;
456 addrlen
= sizeof(addr
);
457 if (bind(fd
, (struct sockaddr
*)&addr
, addrlen
) < 0) {
458 fprintf(stderr
, "bind: %s\n", strerror(errno
));
461 if (listen(fd
, 5) < 0) {
462 fprintf(stderr
, "listen: %s\n", strerror(errno
));
465 addrlen
= sizeof(addr
);
466 if (getsockname(fd
, (struct sockaddr
*)&addr
, &addrlen
)) {
467 fprintf(stderr
, "getsockname: %s\n", strerror(errno
));
470 if ((authmask
& HTTPD_AUTH_MAGIC
) &&
471 (check_owning_uid(fd
, 1) == getuid())) {
472 authtype
= HTTPD_AUTH_MAGIC
;
473 if (authmask
!= HTTPD_AUTH_MAGIC
)
474 printf("Using Linux /proc/net magic authentication\n");
475 } else if ((authmask
& HTTPD_AUTH_BASIC
)) {
476 char username
[128], password
[128], userpassbuf
[259];
477 const char *userpass
;
479 unsigned char passbuf
[10];
482 authtype
= HTTPD_AUTH_BASIC
;
484 if (authmask
!= HTTPD_AUTH_BASIC
)
485 printf("Using HTTP Basic authentication\n");
487 if (dcfg
->basicauthdata
) {
488 userpass
= dcfg
->basicauthdata
;
490 sprintf(username
, "agedu");
491 rname
= "/dev/urandom";
492 fd
= open(rname
, O_RDONLY
);
495 rname
= "/dev/random";
496 fd
= open(rname
, O_RDONLY
);
499 fprintf(stderr
, "/dev/urandom: open: %s\n", strerror(err
));
500 fprintf(stderr
, "/dev/random: open: %s\n", strerror(err2
));
504 for (i
= 0; i
< 10 ;) {
505 j
= read(fd
, passbuf
+ i
, 10 - i
);
507 fprintf(stderr
, "%s: read: %s\n", rname
,
508 j
< 0 ?
strerror(errno
) : "unexpected EOF");
514 for (i
= 0; i
< 16; i
++) {
516 * 32 characters out of the 36 alphanumerics gives
517 * me the latitude to discard i,l,o for being too
518 * numeric-looking, and w because it has two too
519 * many syllables and one too many presidential
522 static const char chars
[32] =
523 "0123456789abcdefghjkmnpqrstuvxyz";
527 for (j
= 0; j
< 5; j
++)
528 v
|= ((passbuf
[k
+j
] >> (i
%8)) & 1) << j
;
530 password
[i
] = chars
[v
];
534 sprintf(userpassbuf
, "%s:%s", username
, password
);
535 userpass
= userpassbuf
;
537 printf("Username: %s\nPassword: %s\n", username
, password
);
540 k
= strlen(userpass
);
541 authstring
= snewn(k
* 4 / 3 + 16, char);
542 for (i
= j
= 0; i
< k
;) {
543 int s
= k
-i
< 3 ? k
-i
: 3;
544 base64_encode_atom((unsigned char *)(userpass
+i
), s
, authstring
+j
);
548 authstring
[j
] = '\0';
549 } else if ((authmask
& HTTPD_AUTH_NONE
)) {
550 authtype
= HTTPD_AUTH_NONE
;
551 if (authmask
!= HTTPD_AUTH_NONE
)
552 printf("Web server is unauthenticated\n");
554 fprintf(stderr
, "agedu: authentication method not supported\n");
557 if (!dcfg
->address
) {
558 if (ntohs(addr
.sin_port
) == 80) {
559 printf("URL: http://%s/\n", inet_ntoa(addr
.sin_addr
));
561 printf("URL: http://%s:%d/\n",
562 inet_ntoa(addr
.sin_addr
), ntohs(addr
.sin_port
));
567 * Now construct an fd structure to hold it.
569 f
= new_fdstruct(fd
, FD_LISTENER
);
572 * Read from standard input, and treat EOF as a notification
575 new_fdstruct(0, FD_CLIENT
);
578 * Now we're ready to run our main loop. Keep looping round on
583 int i
, j
, maxfd
, ret
;
585 #define FD_SET_MAX(fd, set, max) \
586 do { FD_SET((fd),(set)); (max) = ((max)<=(fd)?(fd)+1:(max)); } while(0)
589 * Loop round the fd list putting fds into our select
590 * sets. Also in this loop we remove any that were marked
591 * as deleted in the previous loop.
596 for (i
= j
= 0; j
< nfds
; j
++) {
598 if (fds
[j
].deleted
) {
600 free_connection(fds
[j
].cctx
);
605 switch (fds
[i
].type
) {
608 FD_SET_MAX(fds
[i
].fd
, &rfds
, maxfd
);
612 * Always read from a connection socket. Even
613 * after we've started writing, the peer might
614 * still be sending (e.g. because we shamefully
615 * jumped the gun before waiting for the end of
616 * the HTTP request) and so we should be prepared
617 * to read data and throw it away.
619 FD_SET_MAX(fds
[i
].fd
, &rfds
, maxfd
);
621 * Also attempt to write, if we have data to write.
623 if (fds
[i
].wdatapos
< fds
[i
].wdatalen
)
624 FD_SET_MAX(fds
[i
].fd
, &wfds
, maxfd
);
632 ret
= select(maxfd
, &rfds
, &wfds
, NULL
, NULL
);
634 if (ret
< 0 && (errno
!= EINTR
)) {
635 fprintf(stderr
, "select: %s", strerror(errno
));
641 for (i
= 0; i
< nfds
; i
++) {
642 switch (fds
[i
].type
) {
644 if (FD_ISSET(fds
[i
].fd
, &rfds
)) {
646 int ret
= read(fds
[i
].fd
, buf
, sizeof(buf
));
649 fprintf(stderr
, "standard input: read: %s\n",
658 if (FD_ISSET(fds
[i
].fd
, &rfds
)) {
660 * New connection has come in. Accept it.
663 struct sockaddr_in addr
;
664 socklen_t addrlen
= sizeof(addr
);
665 int newfd
= accept(fds
[i
].fd
, (struct sockaddr
*)&addr
,
668 break; /* not sure what happened there */
670 f
= new_fdstruct(newfd
, FD_CONNECTION
);
671 f
->cctx
= new_connection(t
);
672 if (authtype
== HTTPD_AUTH_MAGIC
)
673 check_magic_access(f
);
677 if (FD_ISSET(fds
[i
].fd
, &rfds
)) {
679 * There's data to be read.
684 ret
= read(fds
[i
].fd
, readbuf
, sizeof(readbuf
));
687 * This shouldn't happen in a sensible
688 * HTTP connection, so we abandon the
689 * connection if it does.
697 * If we haven't got an HTTP response
698 * yet, keep processing data in the
699 * hope of acquiring one.
701 fds
[i
].wdata
= got_data
702 (fds
[i
].cctx
, readbuf
, ret
,
703 (authtype
== HTTPD_AUTH_NONE
||
704 fds
[i
].magic_access
), authstring
, &cfg
);
706 fds
[i
].wdatalen
= strlen(fds
[i
].wdata
);
711 * Otherwise, just drop our read data
717 if (FD_ISSET(fds
[i
].fd
, &wfds
) &&
718 fds
[i
].wdatapos
< fds
[i
].wdatalen
) {
720 * The socket is writable, and we have data to
723 int ret
= write(fds
[i
].fd
, fds
[i
].wdata
+ fds
[i
].wdatapos
,
724 fds
[i
].wdatalen
- fds
[i
].wdatapos
);
727 * Shouldn't happen; abandon the connection.
733 fds
[i
].wdatapos
+= ret
;
734 if (fds
[i
].wdatapos
== fds
[i
].wdatalen
) {
735 shutdown(fds
[i
].fd
, SHUT_WR
);