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 int sa_rfc1918(void *sa)
64 struct sockaddr_in *v4 = (struct sockaddr_in *)sa;
65 unsigned long a = htonl(v4->sin_addr.s_addr);
67 if( v4->sin_family == AF_INET )
69 return ((a >= 0x0A000000) && (a <= 0x0AFFFFFF)) ||
70 ((a >= 0xAC100000) && (a <= 0xAC1FFFFF)) ||
71 ((a >= 0xC0A80000) && (a <= 0xC0A8FFFF));
77 /* Simple strstr() like function that takes len arguments for both haystack and needle. */
78 char *strfind(char *haystack, int hslen, const char *needle, int ndlen)
83 for( i = 0; i < hslen; i++ )
85 if( haystack[i] == needle[0] )
87 match = ((ndlen == 1) || ((i + ndlen) <= hslen));
89 for( j = 1; (j < ndlen) && ((i + j) < hslen); j++ )
91 if( haystack[i+j] != needle[j] )
106 /* interruptable select() */
107 int select_intr(int n, fd_set *r, fd_set *w, fd_set *e, struct timeval *t)
112 /* unblock SIGCHLD */
114 sigaddset(&ssn, SIGCHLD);
115 sigaddset(&ssn, SIGPIPE);
116 sigprocmask(SIG_UNBLOCK, &ssn, &sso);
118 rv = select(n, r, w, e, t);
120 /* restore signal mask */
121 sigprocmask(SIG_SETMASK, &sso, NULL);
127 int uh_tcp_send_lowlevel(struct client *cl, const char *buf, int len)
130 struct timeval timeout;
133 FD_SET(cl->socket, &writer);
135 timeout.tv_sec = cl->server->conf->network_timeout;
138 if (select(cl->socket + 1, NULL, &writer, NULL, &timeout) > 0)
139 return send(cl->socket, buf, len, 0);
144 int uh_tcp_send(struct client *cl, const char *buf, int len)
148 return cl->server->conf->tls_send(cl, (void *)buf, len);
151 return uh_tcp_send_lowlevel(cl, buf, len);
154 int uh_tcp_peek(struct client *cl, char *buf, int len)
156 /* sanity check, prevent overflowing peek buffer */
157 if (len > sizeof(cl->peekbuf))
160 int sz = uh_tcp_recv(cl, buf, len);
162 /* store received data in peek buffer */
166 memcpy(cl->peekbuf, buf, sz);
172 int uh_tcp_recv_lowlevel(struct client *cl, char *buf, int len)
175 struct timeval timeout;
178 FD_SET(cl->socket, &reader);
180 timeout.tv_sec = cl->server->conf->network_timeout;
183 if (select(cl->socket + 1, &reader, NULL, NULL, &timeout) > 0)
184 return recv(cl->socket, buf, len, 0);
189 int uh_tcp_recv(struct client *cl, char *buf, int len)
194 /* first serve data from peek buffer */
197 sz = min(cl->peeklen, len);
198 len -= sz; cl->peeklen -= sz;
199 memcpy(buf, cl->peekbuf, sz);
200 memmove(cl->peekbuf, &cl->peekbuf[sz], cl->peeklen);
203 /* caller wants more */
208 rsz = cl->server->conf->tls_recv(cl, (void *)&buf[sz], len);
211 rsz = uh_tcp_recv_lowlevel(cl, (void *)&buf[sz], len);
223 int uh_http_sendhf(struct client *cl, int code, const char *summary, const char *fmt, ...)
227 char buffer[UH_LIMIT_MSGHEAD];
230 len = snprintf(buffer, sizeof(buffer),
231 "HTTP/1.1 %03i %s\r\n"
232 "Connection: close\r\n"
233 "Content-Type: text/plain\r\n"
234 "Transfer-Encoding: chunked\r\n\r\n",
238 ensure_ret(uh_tcp_send(cl, buffer, len));
241 len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
244 ensure_ret(uh_http_sendc(cl, buffer, len));
245 ensure_ret(uh_http_sendc(cl, NULL, 0));
251 int uh_http_sendc(struct client *cl, const char *data, int len)
261 clen = snprintf(chunk, sizeof(chunk), "%X\r\n", len);
262 ensure_ret(uh_tcp_send(cl, chunk, clen));
263 ensure_ret(uh_tcp_send(cl, data, len));
264 ensure_ret(uh_tcp_send(cl, "\r\n", 2));
268 ensure_ret(uh_tcp_send(cl, "0\r\n\r\n", 5));
275 struct client *cl, struct http_request *req, const char *fmt, ...
278 char buffer[UH_LIMIT_MSGHEAD];
282 len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
285 if( (req != NULL) && (req->version > 1.0) )
286 ensure_ret(uh_http_sendc(cl, buffer, len));
288 ensure_ret(uh_tcp_send(cl, buffer, len));
294 struct client *cl, struct http_request *req, const char *buf, int len
299 if( (req != NULL) && (req->version > 1.0) )
300 ensure_ret(uh_http_sendc(cl, buf, len));
302 ensure_ret(uh_tcp_send(cl, buf, len));
308 int uh_urldecode(char *buf, int blen, const char *src, int slen)
314 (((x) <= '9') ? ((x) - '0') : \
315 (((x) <= 'F') ? ((x) - 'A' + 10) : \
318 for( i = 0; (i <= slen) && (i <= blen); i++ )
322 if( ((i+2) <= slen) && isxdigit(src[i+1]) && isxdigit(src[i+2]) )
324 buf[len++] = (char)(16 * hex(src[i+1]) + hex(src[i+2]));
341 int uh_urlencode(char *buf, int blen, const char *src, int slen)
345 const char hex[] = "0123456789abcdef";
347 for( i = 0; (i <= slen) && (i <= blen); i++ )
349 if( isalnum(src[i]) || (src[i] == '-') || (src[i] == '_') ||
350 (src[i] == '.') || (src[i] == '~') )
354 else if( (len+3) <= blen )
357 buf[len++] = hex[(src[i] >> 4) & 15];
358 buf[len++] = hex[(src[i] & 15) & 15];
369 int uh_b64decode(char *buf, int blen, const unsigned char *src, int slen)
374 unsigned int cin = 0;
375 unsigned int cout = 0;
378 for( i = 0; (i <= slen) && (src[i] != 0); i++ )
382 if( (cin >= '0') && (cin <= '9') )
383 cin = cin - '0' + 52;
384 else if( (cin >= 'A') && (cin <= 'Z') )
386 else if( (cin >= 'a') && (cin <= 'z') )
387 cin = cin - 'a' + 26;
388 else if( cin == '+' )
390 else if( cin == '/' )
392 else if( cin == '=' )
397 cout = (cout << 6) | cin;
401 if( (len + 3) < blen )
403 buf[len++] = (char)(cout >> 16);
404 buf[len++] = (char)(cout >> 8);
405 buf[len++] = (char)(cout);
418 static char * canonpath(const char *path, char *path_resolved)
420 char path_copy[PATH_MAX];
421 char *path_cpy = path_copy;
422 char *path_res = path_resolved;
427 /* relative -> absolute */
430 getcwd(path_copy, PATH_MAX);
431 strncat(path_copy, "/", PATH_MAX - strlen(path_copy));
432 strncat(path_copy, path, PATH_MAX - strlen(path_copy));
436 strncpy(path_copy, path, PATH_MAX);
440 while( (*path_cpy != '\0') && (path_cpy < (path_copy + PATH_MAX - 2)) )
442 if( *path_cpy == '/' )
444 /* skip repeating / */
445 if( path_cpy[1] == '/' )
452 else if( path_cpy[1] == '.' )
455 if( (path_cpy[2] == '/') || (path_cpy[2] == '\0') )
461 /* collapse /x/../ */
462 else if( (path_cpy[2] == '.') &&
463 ((path_cpy[3] == '/') || (path_cpy[3] == '\0'))
465 while( (path_res > path_resolved) && (*--path_res != '/') )
474 *path_res++ = *path_cpy++;
477 /* remove trailing slash if not root / */
478 if( (path_res > (path_resolved+1)) && (path_res[-1] == '/') )
480 else if( path_res == path_resolved )
486 if( !stat(path_resolved, &s) && (s.st_mode & S_IROTH) )
487 return path_resolved;
492 struct path_info * uh_path_lookup(struct client *cl, const char *url)
494 static char path_phys[PATH_MAX];
495 static char path_info[PATH_MAX];
496 static struct path_info p;
498 char buffer[UH_LIMIT_MSGHEAD];
499 char *docroot = cl->server->conf->docroot;
500 char *pathptr = NULL;
503 int no_sym = cl->server->conf->no_symlinks;
507 /* back out early if url is undefined */
511 memset(path_phys, 0, sizeof(path_phys));
512 memset(path_info, 0, sizeof(path_info));
513 memset(buffer, 0, sizeof(buffer));
514 memset(&p, 0, sizeof(p));
517 memcpy(buffer, docroot,
518 min(strlen(docroot), sizeof(buffer) - 1));
520 /* separate query string from url */
521 if( (pathptr = strchr(url, '?')) != NULL )
523 p.query = pathptr[1] ? pathptr + 1 : NULL;
525 /* urldecode component w/o query */
528 &buffer[strlen(docroot)],
529 sizeof(buffer) - strlen(docroot) - 1,
530 url, (int)(pathptr - url) - 1
534 /* no query string, decode all of url */
538 &buffer[strlen(docroot)],
539 sizeof(buffer) - strlen(docroot) - 1,
544 /* create canon path */
545 for( i = strlen(buffer), slash = (buffer[max(0, i-1)] == '/'); i >= 0; i-- )
547 if( (buffer[i] == 0) || (buffer[i] == '/') )
549 memset(path_info, 0, sizeof(path_info));
550 memcpy(path_info, buffer, min(i + 1, sizeof(path_info) - 1));
552 if( no_sym ? realpath(path_info, path_phys)
553 : canonpath(path_info, path_phys)
555 memset(path_info, 0, sizeof(path_info));
556 memcpy(path_info, &buffer[i],
557 min(strlen(buffer) - i, sizeof(path_info) - 1));
564 /* check whether found path is within docroot */
565 if( strncmp(path_phys, docroot, strlen(docroot)) ||
566 ((path_phys[strlen(docroot)] != 0) &&
567 (path_phys[strlen(docroot)] != '/'))
572 /* test current path */
573 if( ! stat(path_phys, &p.stat) )
575 /* is a regular file */
576 if( p.stat.st_mode & S_IFREG )
580 p.name = &path_phys[strlen(docroot)];
581 p.info = path_info[0] ? path_info : NULL;
585 else if( (p.stat.st_mode & S_IFDIR) && !strlen(path_info) )
587 /* ensure trailing slash */
588 if( path_phys[strlen(path_phys)-1] != '/' )
589 path_phys[strlen(path_phys)] = '/';
591 /* try to locate index file */
592 memset(buffer, 0, sizeof(buffer));
593 memcpy(buffer, path_phys, sizeof(buffer));
594 pathptr = &buffer[strlen(buffer)];
596 /* if requested url resolves to a directory and a trailing slash
597 is missing in the request url, redirect the client to the same
598 url with trailing slash appended */
601 uh_http_sendf(cl, NULL,
602 "HTTP/1.1 302 Found\r\n"
603 "Location: %s%s%s\r\n"
604 "Connection: close\r\n\r\n",
605 &path_phys[strlen(docroot)],
607 p.query ? p.query : ""
612 else if( cl->server->conf->index_file )
614 strncat(buffer, cl->server->conf->index_file, sizeof(buffer));
616 if( !stat(buffer, &s) && (s.st_mode & S_IFREG) )
618 memcpy(path_phys, buffer, sizeof(path_phys));
619 memcpy(&p.stat, &s, sizeof(p.stat));
624 for( i = 0; i < array_size(uh_index_files); i++ )
626 strncat(buffer, uh_index_files[i], sizeof(buffer));
628 if( !stat(buffer, &s) && (s.st_mode & S_IFREG) )
630 memcpy(path_phys, buffer, sizeof(path_phys));
631 memcpy(&p.stat, &s, sizeof(p.stat));
641 p.name = &path_phys[strlen(docroot)];
645 return p.phys ? &p : NULL;
649 static struct auth_realm *uh_realms = NULL;
651 struct auth_realm * uh_auth_add(char *path, char *user, char *pass)
653 struct auth_realm *new = NULL;
660 if((new = (struct auth_realm *)malloc(sizeof(struct auth_realm))) != NULL)
662 memset(new, 0, sizeof(struct auth_realm));
664 memcpy(new->path, path,
665 min(strlen(path), sizeof(new->path) - 1));
667 memcpy(new->user, user,
668 min(strlen(user), sizeof(new->user) - 1));
670 /* given password refers to a passwd entry */
671 if( (strlen(pass) > 3) && !strncmp(pass, "$p$", 3) )
674 /* try to resolve shadow entry */
675 if( ((spwd = getspnam(&pass[3])) != NULL) && spwd->sp_pwdp )
677 memcpy(new->pass, spwd->sp_pwdp,
678 min(strlen(spwd->sp_pwdp), sizeof(new->pass) - 1));
684 /* try to resolve passwd entry */
685 if( ((pwd = getpwnam(&pass[3])) != NULL) && pwd->pw_passwd &&
686 (pwd->pw_passwd[0] != '!') && (pwd->pw_passwd[0] != 0)
688 memcpy(new->pass, pwd->pw_passwd,
689 min(strlen(pwd->pw_passwd), sizeof(new->pass) - 1));
696 memcpy(new->pass, pass,
697 min(strlen(pass), sizeof(new->pass) - 1));
702 new->next = uh_realms;
715 struct client *cl, struct http_request *req, struct path_info *pi
717 int i, plen, rlen, protected;
718 char buffer[UH_LIMIT_MSGHEAD];
722 struct auth_realm *realm = NULL;
724 plen = strlen(pi->name);
727 /* check whether at least one realm covers the requested url */
728 for( realm = uh_realms; realm; realm = realm->next )
730 rlen = strlen(realm->path);
732 if( (plen >= rlen) && !strncasecmp(pi->name, realm->path, rlen) )
740 /* requested resource is covered by a realm */
743 /* try to get client auth info */
744 foreach_header(i, req->headers)
746 if( !strcasecmp(req->headers[i], "Authorization") &&
747 (strlen(req->headers[i+1]) > 6) &&
748 !strncasecmp(req->headers[i+1], "Basic ", 6)
750 memset(buffer, 0, sizeof(buffer));
751 uh_b64decode(buffer, sizeof(buffer) - 1,
752 (unsigned char *) &req->headers[i+1][6],
753 strlen(req->headers[i+1]) - 6);
755 if( (pass = strchr(buffer, ':')) != NULL )
765 /* have client auth */
768 /* find matching realm */
769 for( realm = uh_realms; realm; realm = realm->next )
771 rlen = strlen(realm->path);
773 if( (plen >= rlen) &&
774 !strncasecmp(pi->name, realm->path, rlen) &&
775 !strcmp(user, realm->user)
782 /* found a realm matching the username */
785 /* check user pass */
786 if (!strcmp(pass, realm->pass) ||
787 !strcmp(crypt(pass, realm->pass), realm->pass))
793 uh_http_sendf(cl, NULL,
794 "HTTP/%.1f 401 Authorization Required\r\n"
795 "WWW-Authenticate: Basic realm=\"%s\"\r\n"
796 "Content-Type: text/plain\r\n"
797 "Content-Length: 23\r\n\r\n"
798 "Authorization Required\n",
799 req->version, cl->server->conf->realm
809 static struct listener *uh_listeners = NULL;
810 static struct client *uh_clients = NULL;
812 struct listener * uh_listener_add(int sock, struct config *conf)
814 struct listener *new = NULL;
817 if( (new = (struct listener *)malloc(sizeof(struct listener))) != NULL )
819 memset(new, 0, sizeof(struct listener));
824 /* get local endpoint addr */
825 sl = sizeof(struct sockaddr_in6);
826 memset(&(new->addr), 0, sl);
827 getsockname(sock, (struct sockaddr *) &(new->addr), &sl);
829 new->next = uh_listeners;
838 struct listener * uh_listener_lookup(int sock)
840 struct listener *cur = NULL;
842 for( cur = uh_listeners; cur; cur = cur->next )
843 if( cur->socket == sock )
850 struct client * uh_client_add(int sock, struct listener *serv)
852 struct client *new = NULL;
855 if( (new = (struct client *)malloc(sizeof(struct client))) != NULL )
857 memset(new, 0, sizeof(struct client));
862 /* get remote endpoint addr */
863 sl = sizeof(struct sockaddr_in6);
864 memset(&(new->peeraddr), 0, sl);
865 getpeername(sock, (struct sockaddr *) &(new->peeraddr), &sl);
867 /* get local endpoint addr */
868 sl = sizeof(struct sockaddr_in6);
869 memset(&(new->servaddr), 0, sl);
870 getsockname(sock, (struct sockaddr *) &(new->servaddr), &sl);
872 new->next = uh_clients;
879 struct client * uh_client_lookup(int sock)
881 struct client *cur = NULL;
883 for( cur = uh_clients; cur; cur = cur->next )
884 if( cur->socket == sock )
890 void uh_client_remove(int sock)
892 struct client *cur = NULL;
893 struct client *prv = NULL;
895 for( cur = uh_clients; cur; prv = cur, cur = cur->next )
897 if( cur->socket == sock )
900 prv->next = cur->next;
902 uh_clients = cur->next;
912 static struct interpreter *uh_interpreters = NULL;
914 struct interpreter * uh_interpreter_add(const char *extn, const char *path)
916 struct interpreter *new = NULL;
918 if( (new = (struct interpreter *)
919 malloc(sizeof(struct interpreter))) != NULL )
921 memset(new, 0, sizeof(struct interpreter));
923 memcpy(new->extn, extn, min(strlen(extn), sizeof(new->extn)-1));
924 memcpy(new->path, path, min(strlen(path), sizeof(new->path)-1));
926 new->next = uh_interpreters;
927 uh_interpreters = new;
935 struct interpreter * uh_interpreter_lookup(const char *path)
937 struct interpreter *cur = NULL;
940 for( cur = uh_interpreters; cur; cur = cur->next )
942 e = &path[max(strlen(path) - strlen(cur->extn), 0)];
944 if( !strcmp(e, cur->extn) )