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(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 )
142 return cl->server->conf->tls_send(cl, (void *)buf, len);
145 return send(cl->socket, buf, len, 0);
151 int uh_tcp_peek(struct client *cl, char *buf, int len)
153 int sz = uh_tcp_recv(cl, buf, len);
155 /* store received data in peek buffer */
159 memcpy(cl->peekbuf, buf, sz);
165 int uh_tcp_recv(struct client *cl, char *buf, int len)
170 /* first serve data from peek buffer */
171 if( cl->peeklen > 0 )
173 sz = min(cl->peeklen, len);
174 len -= sz; cl->peeklen -= sz;
176 memcpy(buf, cl->peekbuf, sz);
177 memmove(cl->peekbuf, &cl->peekbuf[sz], cl->peeklen);
180 /* caller wants more */
185 rsz = cl->server->conf->tls_recv(cl, (void *)&buf[sz], len);
188 rsz = recv(cl->socket, (void *)&buf[sz], len, 0);
190 if( (sz == 0) || (rsz > 0) )
198 int uh_http_sendhf(struct client *cl, int code, const char *summary, const char *fmt, ...)
202 char buffer[UH_LIMIT_MSGHEAD];
205 len = snprintf(buffer, sizeof(buffer),
206 "HTTP/1.1 %03i %s\r\n"
207 "Connection: close\r\n"
208 "Content-Type: text/plain\r\n"
209 "Transfer-Encoding: chunked\r\n\r\n",
213 ensure_ret(uh_tcp_send(cl, buffer, len));
216 len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
219 ensure_ret(uh_http_sendc(cl, buffer, len));
220 ensure_ret(uh_http_sendc(cl, NULL, 0));
226 int uh_http_sendc(struct client *cl, const char *data, int len)
236 clen = snprintf(chunk, sizeof(chunk), "%X\r\n", len);
237 ensure_ret(uh_tcp_send(cl, chunk, clen));
238 ensure_ret(uh_tcp_send(cl, data, len));
239 ensure_ret(uh_tcp_send(cl, "\r\n", 2));
243 ensure_ret(uh_tcp_send(cl, "0\r\n\r\n", 5));
250 struct client *cl, struct http_request *req, const char *fmt, ...
253 char buffer[UH_LIMIT_MSGHEAD];
257 len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
260 if( (req != NULL) && (req->version > 1.0) )
261 ensure_ret(uh_http_sendc(cl, buffer, len));
263 ensure_ret(uh_tcp_send(cl, buffer, len));
269 struct client *cl, struct http_request *req, const char *buf, int len
274 if( (req != NULL) && (req->version > 1.0) )
275 ensure_ret(uh_http_sendc(cl, buf, len));
277 ensure_ret(uh_tcp_send(cl, buf, len));
283 int uh_urldecode(char *buf, int blen, const char *src, int slen)
289 (((x) <= '9') ? ((x) - '0') : \
290 (((x) <= 'F') ? ((x) - 'A' + 10) : \
293 for( i = 0; (i <= slen) && (i <= blen); i++ )
297 if( ((i+2) <= slen) && isxdigit(src[i+1]) && isxdigit(src[i+2]) )
299 buf[len++] = (char)(16 * hex(src[i+1]) + hex(src[i+2]));
316 int uh_urlencode(char *buf, int blen, const char *src, int slen)
320 const char hex[] = "0123456789abcdef";
322 for( i = 0; (i <= slen) && (i <= blen); i++ )
324 if( isalnum(src[i]) || (src[i] == '-') || (src[i] == '_') ||
325 (src[i] == '.') || (src[i] == '~') )
329 else if( (len+3) <= blen )
332 buf[len++] = hex[(src[i] >> 4) & 15];
333 buf[len++] = hex[(src[i] & 15) & 15];
344 int uh_b64decode(char *buf, int blen, const unsigned char *src, int slen)
349 unsigned int cin = 0;
350 unsigned int cout = 0;
353 for( i = 0; (i <= slen) && (src[i] != 0); i++ )
357 if( (cin >= '0') && (cin <= '9') )
358 cin = cin - '0' + 52;
359 else if( (cin >= 'A') && (cin <= 'Z') )
361 else if( (cin >= 'a') && (cin <= 'z') )
362 cin = cin - 'a' + 26;
363 else if( cin == '+' )
365 else if( cin == '/' )
367 else if( cin == '=' )
372 cout = (cout << 6) | cin;
376 if( (len + 3) < blen )
378 buf[len++] = (char)(cout >> 16);
379 buf[len++] = (char)(cout >> 8);
380 buf[len++] = (char)(cout);
393 static char * canonpath(const char *path, char *path_resolved)
395 char path_copy[PATH_MAX];
396 char *path_cpy = path_copy;
397 char *path_res = path_resolved;
402 /* relative -> absolute */
405 getcwd(path_copy, PATH_MAX);
406 strncat(path_copy, "/", PATH_MAX - strlen(path_copy));
407 strncat(path_copy, path, PATH_MAX - strlen(path_copy));
411 strncpy(path_copy, path, PATH_MAX);
415 while( (*path_cpy != '\0') && (path_cpy < (path_copy + PATH_MAX - 2)) )
417 if( *path_cpy == '/' )
419 /* skip repeating / */
420 if( path_cpy[1] == '/' )
427 else if( path_cpy[1] == '.' )
430 if( (path_cpy[2] == '/') || (path_cpy[2] == '\0') )
436 /* collapse /x/../ */
437 else if( (path_cpy[2] == '.') &&
438 ((path_cpy[3] == '/') || (path_cpy[3] == '\0'))
440 while( (path_res > path_resolved) && (*--path_res != '/') )
449 *path_res++ = *path_cpy++;
452 /* remove trailing slash if not root / */
453 if( (path_res > (path_resolved+1)) && (path_res[-1] == '/') )
455 else if( path_res == path_resolved )
461 if( !stat(path_resolved, &s) && (s.st_mode & S_IROTH) )
462 return path_resolved;
467 struct path_info * uh_path_lookup(struct client *cl, const char *url)
469 static char path_phys[PATH_MAX];
470 static char path_info[PATH_MAX];
471 static struct path_info p;
473 char buffer[UH_LIMIT_MSGHEAD];
474 char *docroot = cl->server->conf->docroot;
475 char *pathptr = NULL;
477 int no_sym = cl->server->conf->no_symlinks;
481 /* back out early if url is undefined */
485 memset(path_phys, 0, sizeof(path_phys));
486 memset(path_info, 0, sizeof(path_info));
487 memset(buffer, 0, sizeof(buffer));
488 memset(&p, 0, sizeof(p));
491 memcpy(buffer, docroot,
492 min(strlen(docroot), sizeof(buffer) - 1));
494 /* separate query string from url */
495 if( (pathptr = strchr(url, '?')) != NULL )
497 p.query = pathptr[1] ? pathptr + 1 : NULL;
499 /* urldecode component w/o query */
502 &buffer[strlen(docroot)],
503 sizeof(buffer) - strlen(docroot) - 1,
504 url, (int)(pathptr - url) - 1
508 /* no query string, decode all of url */
512 &buffer[strlen(docroot)],
513 sizeof(buffer) - strlen(docroot) - 1,
518 /* create canon path */
519 for( i = strlen(buffer); i >= 0; i-- )
521 if( (buffer[i] == 0) || (buffer[i] == '/') )
523 memset(path_info, 0, sizeof(path_info));
524 memcpy(path_info, buffer, min(i + 1, sizeof(path_info) - 1));
526 if( no_sym ? realpath(path_info, path_phys)
527 : canonpath(path_info, path_phys)
529 memset(path_info, 0, sizeof(path_info));
530 memcpy(path_info, &buffer[i],
531 min(strlen(buffer) - i, sizeof(path_info) - 1));
538 /* check whether found path is within docroot */
539 if( strncmp(path_phys, docroot, strlen(docroot)) ||
540 ((path_phys[strlen(docroot)] != 0) &&
541 (path_phys[strlen(docroot)] != '/'))
546 /* test current path */
547 if( ! stat(path_phys, &p.stat) )
549 /* is a regular file */
550 if( p.stat.st_mode & S_IFREG )
554 p.name = &path_phys[strlen(docroot)];
555 p.info = path_info[0] ? path_info : NULL;
559 else if( (p.stat.st_mode & S_IFDIR) && !strlen(path_info) )
561 /* ensure trailing slash */
562 if( path_phys[strlen(path_phys)-1] != '/' )
563 path_phys[strlen(path_phys)] = '/';
565 /* try to locate index file */
566 memset(buffer, 0, sizeof(buffer));
567 memcpy(buffer, path_phys, sizeof(buffer));
568 pathptr = &buffer[strlen(buffer)];
570 if( cl->server->conf->index_file )
572 strncat(buffer, cl->server->conf->index_file, sizeof(buffer));
574 if( !stat(buffer, &s) && (s.st_mode & S_IFREG) )
576 memcpy(path_phys, buffer, sizeof(path_phys));
577 memcpy(&p.stat, &s, sizeof(p.stat));
582 for( i = 0; i < array_size(uh_index_files); i++ )
584 strncat(buffer, uh_index_files[i], sizeof(buffer));
586 if( !stat(buffer, &s) && (s.st_mode & S_IFREG) )
588 memcpy(path_phys, buffer, sizeof(path_phys));
589 memcpy(&p.stat, &s, sizeof(p.stat));
599 p.name = &path_phys[strlen(docroot)];
603 return p.phys ? &p : NULL;
607 static struct auth_realm *uh_realms = NULL;
609 struct auth_realm * uh_auth_add(char *path, char *user, char *pass)
611 struct auth_realm *new = NULL;
618 if((new = (struct auth_realm *)malloc(sizeof(struct auth_realm))) != NULL)
620 memset(new, 0, sizeof(struct auth_realm));
622 memcpy(new->path, path,
623 min(strlen(path), sizeof(new->path) - 1));
625 memcpy(new->user, user,
626 min(strlen(user), sizeof(new->user) - 1));
628 /* given password refers to a passwd entry */
629 if( (strlen(pass) > 3) && !strncmp(pass, "$p$", 3) )
632 /* try to resolve shadow entry */
633 if( ((spwd = getspnam(&pass[3])) != NULL) && spwd->sp_pwdp )
635 memcpy(new->pass, spwd->sp_pwdp,
636 min(strlen(spwd->sp_pwdp), sizeof(new->pass) - 1));
642 /* try to resolve passwd entry */
643 if( ((pwd = getpwnam(&pass[3])) != NULL) && pwd->pw_passwd &&
644 (pwd->pw_passwd[0] != '!') && (pwd->pw_passwd[0] != 0)
646 memcpy(new->pass, pwd->pw_passwd,
647 min(strlen(pwd->pw_passwd), sizeof(new->pass) - 1));
654 memcpy(new->pass, pass,
655 min(strlen(pass), sizeof(new->pass) - 1));
660 new->next = uh_realms;
673 struct client *cl, struct http_request *req, struct path_info *pi
675 int i, plen, rlen, protected;
676 char buffer[UH_LIMIT_MSGHEAD];
680 struct auth_realm *realm = NULL;
682 plen = strlen(pi->name);
685 /* check whether at least one realm covers the requested url */
686 for( realm = uh_realms; realm; realm = realm->next )
688 rlen = strlen(realm->path);
690 if( (plen >= rlen) && !strncasecmp(pi->name, realm->path, rlen) )
698 /* requested resource is covered by a realm */
701 /* try to get client auth info */
702 foreach_header(i, req->headers)
704 if( !strcasecmp(req->headers[i], "Authorization") &&
705 (strlen(req->headers[i+1]) > 6) &&
706 !strncasecmp(req->headers[i+1], "Basic ", 6)
708 memset(buffer, 0, sizeof(buffer));
709 uh_b64decode(buffer, sizeof(buffer) - 1,
710 (unsigned char *) &req->headers[i+1][6],
711 strlen(req->headers[i+1]) - 6);
713 if( (pass = strchr(buffer, ':')) != NULL )
723 /* have client auth */
726 /* find matching realm */
727 for( realm = uh_realms; realm; realm = realm->next )
729 rlen = strlen(realm->path);
731 if( (plen >= rlen) &&
732 !strncasecmp(pi->name, realm->path, rlen) &&
733 !strcmp(user, realm->user)
740 /* found a realm matching the username */
743 /* is a crypt passwd */
744 if( realm->pass[0] == '$' )
745 pass = crypt(pass, realm->pass);
747 /* check user pass */
748 if( !strcmp(pass, realm->pass) )
754 uh_http_sendf(cl, NULL,
755 "HTTP/%.1f 401 Authorization Required\r\n"
756 "WWW-Authenticate: Basic realm=\"%s\"\r\n"
757 "Content-Type: text/plain\r\n"
758 "Content-Length: 23\r\n\r\n"
759 "Authorization Required\n",
760 req->version, cl->server->conf->realm
770 static struct listener *uh_listeners = NULL;
771 static struct client *uh_clients = NULL;
773 struct listener * uh_listener_add(int sock, struct config *conf)
775 struct listener *new = NULL;
778 if( (new = (struct listener *)malloc(sizeof(struct listener))) != NULL )
780 memset(new, 0, sizeof(struct listener));
785 /* get local endpoint addr */
786 sl = sizeof(struct sockaddr_in6);
787 memset(&(new->addr), 0, sl);
788 getsockname(sock, (struct sockaddr *) &(new->addr), &sl);
790 new->next = uh_listeners;
799 struct listener * uh_listener_lookup(int sock)
801 struct listener *cur = NULL;
803 for( cur = uh_listeners; cur; cur = cur->next )
804 if( cur->socket == sock )
811 struct client * uh_client_add(int sock, struct listener *serv)
813 struct client *new = NULL;
816 if( (new = (struct client *)malloc(sizeof(struct client))) != NULL )
818 memset(new, 0, sizeof(struct client));
823 /* get remote endpoint addr */
824 sl = sizeof(struct sockaddr_in6);
825 memset(&(new->peeraddr), 0, sl);
826 getpeername(sock, (struct sockaddr *) &(new->peeraddr), &sl);
828 /* get local endpoint addr */
829 sl = sizeof(struct sockaddr_in6);
830 memset(&(new->servaddr), 0, sl);
831 getsockname(sock, (struct sockaddr *) &(new->servaddr), &sl);
833 new->next = uh_clients;
840 struct client * uh_client_lookup(int sock)
842 struct client *cur = NULL;
844 for( cur = uh_clients; cur; cur = cur->next )
845 if( cur->socket == sock )
851 void uh_client_remove(int sock)
853 struct client *cur = NULL;
854 struct client *prv = NULL;
856 for( cur = uh_clients; cur; prv = cur, cur = cur->next )
858 if( cur->socket == sock )
861 prv->next = cur->next;
863 uh_clients = cur->next;
873 static struct interpreter *uh_interpreters = NULL;
875 struct interpreter * uh_interpreter_add(const char *extn, const char *path)
877 struct interpreter *new = NULL;
879 if( (new = (struct interpreter *)
880 malloc(sizeof(struct interpreter))) != NULL )
882 memset(new, 0, sizeof(struct interpreter));
884 memcpy(new->extn, extn, min(strlen(extn), sizeof(new->extn)-1));
885 memcpy(new->path, path, min(strlen(path), sizeof(new->path)-1));
887 new->next = uh_interpreters;
888 uh_interpreters = new;
896 struct interpreter * uh_interpreter_lookup(const char *path)
898 struct interpreter *cur = NULL;
901 for( cur = uh_interpreters; cur; cur = cur->next )
903 e = &path[max(strlen(path) - strlen(cur->extn), 0)];
905 if( !strcmp(e, cur->extn) )