2 * uhttpd - Tiny single-threaded httpd - Utility functions
4 * Copyright (C) 2010 Jo-Philipp Wich <xm@subsignal.org>
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
19 #define _XOPEN_SOURCE 500 /* crypt() */
20 #define _BSD_SOURCE /* strcasecmp(), strncasecmp() */
23 #include "uhttpd-utils.h"
26 #include "uhttpd-tls.h"
30 static char *uh_index_files[] = {
38 const char * sa_straddr(void *sa)
40 static char str[INET6_ADDRSTRLEN];
41 struct sockaddr_in *v4 = (struct sockaddr_in *)sa;
42 struct sockaddr_in6 *v6 = (struct sockaddr_in6 *)sa;
44 if( v4->sin_family == AF_INET )
45 return inet_ntop(AF_INET, &(v4->sin_addr), str, sizeof(str));
47 return inet_ntop(AF_INET6, &(v6->sin6_addr), str, sizeof(str));
50 const char * sa_strport(void *sa)
53 snprintf(str, sizeof(str), "%i", sa_port(sa));
59 return ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
62 /* Simple strstr() like function that takes len arguments for both haystack and needle. */
63 char *strfind(char *haystack, int hslen, const char *needle, int ndlen)
68 for( i = 0; i < hslen; i++ )
70 if( haystack[i] == needle[0] )
72 match = ((ndlen == 1) || ((i + ndlen) <= hslen));
74 for( j = 1; (j < ndlen) && ((i + j) < hslen); j++ )
76 if( haystack[i+j] != needle[j] )
92 int uh_tcp_send(struct client *cl, const char *buf, int len)
95 struct timeval timeout;
98 FD_SET(cl->socket, &writer);
101 timeout.tv_usec = 500000;
103 if( select(cl->socket + 1, NULL, &writer, NULL, &timeout) > 0 )
107 return cl->server->conf->tls_send(cl, (void *)buf, len);
110 return send(cl->socket, buf, len, 0);
116 int uh_tcp_peek(struct client *cl, char *buf, int len)
118 int sz = uh_tcp_recv(cl, buf, len);
120 /* store received data in peek buffer */
124 memcpy(cl->peekbuf, buf, sz);
130 int uh_tcp_recv(struct client *cl, char *buf, int len)
135 /* first serve data from peek buffer */
136 if( cl->peeklen > 0 )
138 sz = min(cl->peeklen, len);
139 len -= sz; cl->peeklen -= sz;
141 memcpy(buf, cl->peekbuf, sz);
142 memmove(cl->peekbuf, &cl->peekbuf[sz], cl->peeklen);
145 /* caller wants more */
150 rsz = cl->server->conf->tls_recv(cl, (void *)&buf[sz], len);
153 rsz = recv(cl->socket, (void *)&buf[sz], len, 0);
155 if( (sz == 0) || (rsz > 0) )
163 do { if( x < 0 ) return -1; } while(0)
165 int uh_http_sendhf(struct client *cl, int code, const char *summary, const char *fmt, ...)
169 char buffer[UH_LIMIT_MSGHEAD];
172 len = snprintf(buffer, sizeof(buffer),
173 "HTTP/1.1 %03i %s\r\n"
174 "Connection: close\r\n"
175 "Content-Type: text/plain\r\n"
176 "Transfer-Encoding: chunked\r\n\r\n",
180 ensure(uh_tcp_send(cl, buffer, len));
183 len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
186 ensure(uh_http_sendc(cl, buffer, len));
187 ensure(uh_http_sendc(cl, NULL, 0));
193 int uh_http_sendc(struct client *cl, const char *data, int len)
203 clen = snprintf(chunk, sizeof(chunk), "%X\r\n", len);
204 ensure(uh_tcp_send(cl, chunk, clen));
205 ensure(uh_tcp_send(cl, data, len));
206 ensure(uh_tcp_send(cl, "\r\n", 2));
210 ensure(uh_tcp_send(cl, "0\r\n\r\n", 5));
217 struct client *cl, struct http_request *req, const char *fmt, ...
220 char buffer[UH_LIMIT_MSGHEAD];
224 len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
227 if( (req != NULL) && (req->version > 1.0) )
228 ensure(uh_http_sendc(cl, buffer, len));
230 ensure(uh_tcp_send(cl, buffer, len));
236 struct client *cl, struct http_request *req, const char *buf, int len
241 if( (req != NULL) && (req->version > 1.0) )
242 ensure(uh_http_sendc(cl, buf, len));
244 ensure(uh_tcp_send(cl, buf, len));
250 int uh_urldecode(char *buf, int blen, const char *src, int slen)
256 (((x) <= '9') ? ((x) - '0') : \
257 (((x) <= 'F') ? ((x) - 'A' + 10) : \
260 for( i = 0; (i <= slen) && (i <= blen); i++ )
264 if( ((i+2) <= slen) && isxdigit(src[i+1]) && isxdigit(src[i+2]) )
266 buf[len++] = (char)(16 * hex(src[i+1]) + hex(src[i+2]));
283 int uh_urlencode(char *buf, int blen, const char *src, int slen)
287 const char hex[] = "0123456789abcdef";
289 for( i = 0; (i <= slen) && (i <= blen); i++ )
291 if( isalnum(src[i]) || (src[i] == '-') || (src[i] == '_') ||
292 (src[i] == '.') || (src[i] == '~') )
296 else if( (len+3) <= blen )
299 buf[len++] = hex[(src[i] >> 4) & 15];
300 buf[len++] = hex[(src[i] & 15) & 15];
311 int uh_b64decode(char *buf, int blen, const unsigned char *src, int slen)
316 unsigned int cin = 0;
317 unsigned int cout = 0;
320 for( i = 0; (i <= slen) && (src[i] != 0); i++ )
324 if( (cin >= '0') && (cin <= '9') )
325 cin = cin - '0' + 52;
326 else if( (cin >= 'A') && (cin <= 'Z') )
328 else if( (cin >= 'a') && (cin <= 'z') )
329 cin = cin - 'a' + 26;
330 else if( cin == '+' )
332 else if( cin == '/' )
334 else if( cin == '=' )
339 cout = (cout << 6) | cin;
343 if( (len + 3) < blen )
345 buf[len++] = (char)(cout >> 16);
346 buf[len++] = (char)(cout >> 8);
347 buf[len++] = (char)(cout);
361 struct path_info * uh_path_lookup(struct client *cl, const char *url)
363 static char path_phys[PATH_MAX];
364 static char path_info[PATH_MAX];
365 static struct path_info p;
367 char buffer[UH_LIMIT_MSGHEAD];
368 char *docroot = cl->server->conf->docroot;
369 char *pathptr = NULL;
375 memset(path_phys, 0, sizeof(path_phys));
376 memset(path_info, 0, sizeof(path_info));
377 memset(buffer, 0, sizeof(buffer));
378 memset(&p, 0, sizeof(p));
381 memcpy(buffer, docroot,
382 min(strlen(docroot), sizeof(buffer) - 1));
384 /* separate query string from url */
385 if( (pathptr = strchr(url, '?')) != NULL )
387 p.query = pathptr[1] ? pathptr + 1 : NULL;
389 /* urldecode component w/o query */
392 &buffer[strlen(docroot)],
393 sizeof(buffer) - strlen(docroot) - 1,
394 url, (int)(pathptr - url) - 1
398 /* no query string, decode all of url */
402 &buffer[strlen(docroot)],
403 sizeof(buffer) - strlen(docroot) - 1,
408 /* create canon path */
409 for( i = strlen(buffer); i >= 0; i-- )
411 if( (buffer[i] == 0) || (buffer[i] == '/') )
413 memset(path_info, 0, sizeof(path_info));
414 memcpy(path_info, buffer, min(i + 1, sizeof(path_info) - 1));
416 if( realpath(path_info, path_phys) )
418 memset(path_info, 0, sizeof(path_info));
419 memcpy(path_info, &buffer[i],
420 min(strlen(buffer) - i, sizeof(path_info) - 1));
427 /* check whether found path is within docroot */
428 if( strncmp(path_phys, docroot, strlen(docroot)) ||
429 ((path_phys[strlen(docroot)] != 0) &&
430 (path_phys[strlen(docroot)] != '/'))
435 /* test current path */
436 if( ! stat(path_phys, &p.stat) )
438 /* is a regular file */
439 if( p.stat.st_mode & S_IFREG )
443 p.name = &path_phys[strlen(docroot)];
444 p.info = path_info[0] ? path_info : NULL;
448 else if( (p.stat.st_mode & S_IFDIR) && !strlen(path_info) )
450 /* ensure trailing slash */
451 if( path_phys[strlen(path_phys)-1] != '/' )
452 path_phys[strlen(path_phys)] = '/';
454 /* try to locate index file */
455 memset(buffer, 0, sizeof(buffer));
456 memcpy(buffer, path_phys, sizeof(buffer));
457 pathptr = &buffer[strlen(buffer)];
459 for( i = 0; i < array_size(uh_index_files); i++ )
461 strncat(buffer, uh_index_files[i], sizeof(buffer));
463 if( !stat(buffer, &s) && (s.st_mode & S_IFREG) )
465 memcpy(path_phys, buffer, sizeof(path_phys));
466 memcpy(&p.stat, &s, sizeof(p.stat));
475 p.name = &path_phys[strlen(docroot)];
479 return p.phys ? &p : NULL;
483 static char uh_realms[UH_LIMIT_AUTHREALMS * sizeof(struct auth_realm)] = { 0 };
484 static int uh_realm_count = 0;
486 struct auth_realm * uh_auth_add(char *path, char *user, char *pass)
488 struct auth_realm *new = NULL;
492 if( uh_realm_count < UH_LIMIT_AUTHREALMS )
494 new = (struct auth_realm *)
495 &uh_realms[uh_realm_count * sizeof(struct auth_realm)];
497 memset(new, 0, sizeof(struct auth_realm));
499 memcpy(new->path, path,
500 min(strlen(path), sizeof(new->path) - 1));
502 memcpy(new->user, user,
503 min(strlen(user), sizeof(new->user) - 1));
505 /* given password refers to a passwd entry */
506 if( (strlen(pass) > 3) && !strncmp(pass, "$p$", 3) )
508 /* try to resolve shadow entry */
509 if( ((spwd = getspnam(&pass[3])) != NULL) && spwd->sp_pwdp )
511 memcpy(new->pass, spwd->sp_pwdp,
512 min(strlen(spwd->sp_pwdp), sizeof(new->pass) - 1));
515 /* try to resolve passwd entry */
516 else if( ((pwd = getpwnam(&pass[3])) != NULL) && pwd->pw_passwd &&
517 (pwd->pw_passwd[0] != '!') && (pwd->pw_passwd[0] != 0)
519 memcpy(new->pass, pwd->pw_passwd,
520 min(strlen(pwd->pw_passwd), sizeof(new->pass) - 1));
527 memcpy(new->pass, pass,
528 min(strlen(pass), sizeof(new->pass) - 1));
538 struct client *cl, struct http_request *req, struct path_info *pi
540 int i, plen, rlen, protected;
541 char buffer[UH_LIMIT_MSGHEAD];
545 struct auth_realm *realm = NULL;
547 plen = strlen(pi->name);
550 /* check whether at least one realm covers the requested url */
551 for( i = 0; i < uh_realm_count; i++ )
553 realm = (struct auth_realm *)
554 &uh_realms[i * sizeof(struct auth_realm)];
556 rlen = strlen(realm->path);
558 if( (plen >= rlen) && !strncasecmp(pi->name, realm->path, rlen) )
566 /* requested resource is covered by a realm */
569 /* try to get client auth info */
570 foreach_header(i, req->headers)
572 if( !strcasecmp(req->headers[i], "Authorization") &&
573 (strlen(req->headers[i+1]) > 6) &&
574 !strncasecmp(req->headers[i+1], "Basic ", 6)
576 memset(buffer, 0, sizeof(buffer));
577 uh_b64decode(buffer, sizeof(buffer) - 1,
578 (unsigned char *) &req->headers[i+1][6],
579 strlen(req->headers[i+1]) - 6);
581 if( (pass = strchr(buffer, ':')) != NULL )
591 /* have client auth */
594 /* find matching realm */
595 for( i = 0, realm = NULL; i < uh_realm_count; i++ )
597 realm = (struct auth_realm *)
598 &uh_realms[i * sizeof(struct auth_realm)];
600 rlen = strlen(realm->path);
602 if( (plen >= rlen) &&
603 !strncasecmp(pi->name, realm->path, rlen) &&
604 !strcmp(user, realm->user)
613 /* found a realm matching the username */
616 /* is a crypt passwd */
617 if( realm->pass[0] == '$' )
618 pass = crypt(pass, realm->pass);
620 /* check user pass */
621 if( !strcmp(pass, realm->pass) )
627 uh_http_sendf(cl, NULL,
628 "HTTP/%.1f 401 Authorization Required\r\n"
629 "WWW-Authenticate: Basic realm=\"%s\"\r\n"
630 "Content-Type: text/plain\r\n"
631 "Content-Length: 23\r\n\r\n"
632 "Authorization Required\n",
633 req->version, cl->server->conf->realm
643 static char uh_listeners[UH_LIMIT_LISTENERS * sizeof(struct listener)] = { 0 };
644 static char uh_clients[UH_LIMIT_CLIENTS * sizeof(struct client)] = { 0 };
646 static int uh_listener_count = 0;
647 static int uh_client_count = 0;
650 struct listener * uh_listener_add(int sock, struct config *conf)
652 struct listener *new = NULL;
655 if( uh_listener_count < UH_LIMIT_LISTENERS )
657 new = (struct listener *)
658 &uh_listeners[uh_listener_count * sizeof(struct listener)];
663 /* get local endpoint addr */
664 sl = sizeof(struct sockaddr_in6);
665 memset(&(new->addr), 0, sl);
666 getsockname(sock, (struct sockaddr *) &(new->addr), &sl);
674 struct listener * uh_listener_lookup(int sock)
676 struct listener *cur = NULL;
679 for( i = 0; i < uh_listener_count; i++ )
681 cur = (struct listener *) &uh_listeners[i * sizeof(struct listener)];
683 if( cur->socket == sock )
691 struct client * uh_client_add(int sock, struct listener *serv)
693 struct client *new = NULL;
696 if( uh_client_count < UH_LIMIT_CLIENTS )
698 new = (struct client *)
699 &uh_clients[uh_client_count * sizeof(struct client)];
704 /* get remote endpoint addr */
705 sl = sizeof(struct sockaddr_in6);
706 memset(&(new->peeraddr), 0, sl);
707 getpeername(sock, (struct sockaddr *) &(new->peeraddr), &sl);
709 /* get local endpoint addr */
710 sl = sizeof(struct sockaddr_in6);
711 memset(&(new->servaddr), 0, sl);
712 getsockname(sock, (struct sockaddr *) &(new->servaddr), &sl);
720 struct client * uh_client_lookup(int sock)
722 struct client *cur = NULL;
725 for( i = 0; i < uh_client_count; i++ )
727 cur = (struct client *) &uh_clients[i * sizeof(struct client)];
729 if( cur->socket == sock )
736 void uh_client_remove(int sock)
738 struct client *del = uh_client_lookup(sock);
742 memmove(del, del + 1,
743 sizeof(uh_clients) - (int)((char *)del - uh_clients) - sizeof(struct client));