2 * uhttpd - Tiny single-threaded httpd - Utility functions
4 * Copyright (C) 2010-2012 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 bool uh_socket_wait(int fd, int sec, bool write)
109 struct timeval timeout;
116 timeout.tv_sec = sec;
119 while (((rv = select(fd+1, write ? NULL : &fds, write ? &fds : NULL,
120 NULL, &timeout)) < 0) && (errno == EINTR))
122 D("IO: Socket(%d) select interrupted: %s\n",
123 fd, strerror(errno));
130 D("IO: Socket(%d) appears dead (rv=%d)\n", fd, rv);
137 static int __uh_raw_send(struct client *cl, const char *buf, int len, int sec,
138 int (*wfn) (struct client *, const char *, int))
145 if ((rv = wfn(cl, buf, len)) < 0)
149 D("IO: Socket(%d) interrupted\n", cl->fd.fd);
152 else if ((sec > 0) && (errno == EAGAIN || errno == EWOULDBLOCK))
154 if (!uh_socket_wait(fd, sec, true))
159 D("IO: Socket(%d) write error: %s\n", fd, strerror(errno));
164 * It is not entirely clear whether rv = 0 on nonblocking sockets
165 * is an error. In real world fuzzing tests, not handling it as close
166 * led to tight infinite loops in this send procedure, so treat it as
167 * closed and break out.
171 D("IO: Socket(%d) closed\n", fd);
176 D("IO: Socket(%d) short write %d/%d bytes\n", fd, rv, len);
183 D("IO: Socket(%d) sent %d/%d bytes\n", fd, rv, len);
189 int uh_tcp_send_lowlevel(struct client *cl, const char *buf, int len)
191 return write(cl->fd.fd, buf, len);
194 int uh_raw_send(int fd, const char *buf, int len, int sec)
196 struct client_light cl = { .fd = { .fd = fd } };
197 return __uh_raw_send((struct client *)&cl, buf, len, sec,
198 uh_tcp_send_lowlevel);
201 int uh_tcp_send(struct client *cl, const char *buf, int len)
203 int seconds = cl->server->conf->network_timeout;
206 return __uh_raw_send(cl, buf, len, seconds,
207 cl->server->conf->tls_send);
209 return __uh_raw_send(cl, buf, len, seconds, uh_tcp_send_lowlevel);
212 static int __uh_raw_recv(struct client *cl, char *buf, int len, int sec,
213 int (*rfn) (struct client *, char *, int))
220 if ((rv = rfn(cl, buf, len)) < 0)
226 else if ((sec > 0) && (errno == EAGAIN || errno == EWOULDBLOCK))
228 if (!uh_socket_wait(fd, sec, false))
233 D("IO: Socket(%d) read error: %s\n", fd, strerror(errno));
239 D("IO: Socket(%d) closed\n", fd);
244 D("IO: Socket(%d) read %d bytes\n", fd, rv);
250 int uh_tcp_recv_lowlevel(struct client *cl, char *buf, int len)
252 return read(cl->fd.fd, buf, len);
255 int uh_raw_recv(int fd, char *buf, int len, int sec)
257 struct client_light cl = { .fd = { .fd = fd } };
258 return __uh_raw_recv((struct client *)&cl, buf, len, sec,
259 uh_tcp_recv_lowlevel);
262 int uh_tcp_recv(struct client *cl, char *buf, int len)
264 int seconds = cl->server->conf->network_timeout;
267 return __uh_raw_recv(cl, buf, len, seconds,
268 cl->server->conf->tls_recv);
270 return __uh_raw_recv(cl, buf, len, seconds, uh_tcp_recv_lowlevel);
274 int uh_http_sendhf(struct client *cl, int code, const char *summary,
275 const char *fmt, ...)
279 char buffer[UH_LIMIT_MSGHEAD];
282 len = snprintf(buffer, sizeof(buffer),
283 "HTTP/1.1 %03i %s\r\n"
284 "Connection: close\r\n"
285 "Content-Type: text/plain\r\n"
286 "Transfer-Encoding: chunked\r\n\r\n",
290 ensure_ret(uh_tcp_send(cl, buffer, len));
293 len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
296 ensure_ret(uh_http_sendc(cl, buffer, len));
297 ensure_ret(uh_http_sendc(cl, NULL, 0));
303 int uh_http_sendc(struct client *cl, const char *data, int len)
313 clen = snprintf(chunk, sizeof(chunk), "%X\r\n", len);
314 ensure_ret(uh_tcp_send(cl, chunk, clen));
315 ensure_ret(uh_tcp_send(cl, data, len));
316 ensure_ret(uh_tcp_send(cl, "\r\n", 2));
320 ensure_ret(uh_tcp_send(cl, "0\r\n\r\n", 5));
326 int uh_http_sendf(struct client *cl, struct http_request *req,
327 const char *fmt, ...)
330 char buffer[UH_LIMIT_MSGHEAD];
334 len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
337 if ((req != NULL) && (req->version > 1.0))
338 ensure_ret(uh_http_sendc(cl, buffer, len));
340 ensure_ret(uh_tcp_send(cl, buffer, len));
345 int uh_http_send(struct client *cl, struct http_request *req,
346 const char *buf, int len)
351 if ((req != NULL) && (req->version > 1.0))
352 ensure_ret(uh_http_sendc(cl, buf, len));
354 ensure_ret(uh_tcp_send(cl, buf, len));
360 /* blen is the size of buf; slen is the length of src. The input-string need
361 ** not be, and the output string will not be, null-terminated. Returns the
362 ** length of the decoded string, -1 on buffer overflow, -2 on malformed string. */
363 int uh_urldecode(char *buf, int blen, const char *src, int slen)
369 (((x) <= '9') ? ((x) - '0') : \
370 (((x) <= 'F') ? ((x) - 'A' + 10) : \
373 for (i = 0; (i < slen) && (len < blen); i++)
377 if (((i+2) < slen) && isxdigit(src[i+1]) && isxdigit(src[i+2]))
379 buf[len++] = (char)(16 * hex(src[i+1]) + hex(src[i+2]));
384 /* Encoding error: it's hard to think of a
385 ** scenario in which returning an incorrect
386 ** 'decoding' of the malformed string is
387 ** preferable to signaling an error condition. */
388 #if 0 /* WORSE_IS_BETTER */
401 return (i == slen) ? len : -1;
404 /* blen is the size of buf; slen is the length of src. The input-string need
405 ** not be, and the output string will not be, null-terminated. Returns the
406 ** length of the encoded string, or -1 on error (buffer overflow) */
407 int uh_urlencode(char *buf, int blen, const char *src, int slen)
411 const char hex[] = "0123456789abcdef";
413 for (i = 0; (i < slen) && (len < blen); i++)
415 if( isalnum(src[i]) || (src[i] == '-') || (src[i] == '_') ||
416 (src[i] == '.') || (src[i] == '~') )
420 else if ((len+3) <= blen)
423 buf[len++] = hex[(src[i] >> 4) & 15];
424 buf[len++] = hex[ src[i] & 15];
433 return (i == slen) ? len : -1;
436 int uh_b64decode(char *buf, int blen, const unsigned char *src, int slen)
441 unsigned int cin = 0;
442 unsigned int cout = 0;
445 for (i = 0; (i <= slen) && (src[i] != 0); i++)
449 if ((cin >= '0') && (cin <= '9'))
450 cin = cin - '0' + 52;
451 else if ((cin >= 'A') && (cin <= 'Z'))
453 else if ((cin >= 'a') && (cin <= 'z'))
454 cin = cin - 'a' + 26;
464 cout = (cout << 6) | cin;
468 if ((len + 3) < blen)
470 buf[len++] = (char)(cout >> 16);
471 buf[len++] = (char)(cout >> 8);
472 buf[len++] = (char)(cout);
485 static char * canonpath(const char *path, char *path_resolved)
487 char path_copy[PATH_MAX];
488 char *path_cpy = path_copy;
489 char *path_res = path_resolved;
494 /* relative -> absolute */
497 getcwd(path_copy, PATH_MAX);
498 strncat(path_copy, "/", PATH_MAX - strlen(path_copy));
499 strncat(path_copy, path, PATH_MAX - strlen(path_copy));
503 strncpy(path_copy, path, PATH_MAX);
507 while ((*path_cpy != '\0') && (path_cpy < (path_copy + PATH_MAX - 2)))
509 if (*path_cpy == '/')
511 /* skip repeating / */
512 if (path_cpy[1] == '/')
519 else if (path_cpy[1] == '.')
522 if ((path_cpy[2] == '/') || (path_cpy[2] == '\0'))
528 /* collapse /x/../ */
529 else if ((path_cpy[2] == '.') &&
530 ((path_cpy[3] == '/') || (path_cpy[3] == '\0')))
532 while ((path_res > path_resolved) && (*--path_res != '/'))
541 *path_res++ = *path_cpy++;
544 /* remove trailing slash if not root / */
545 if ((path_res > (path_resolved+1)) && (path_res[-1] == '/'))
547 else if (path_res == path_resolved)
553 if (!stat(path_resolved, &s) && (s.st_mode & S_IROTH))
554 return path_resolved;
559 /* Returns NULL on error.
560 ** NB: improperly encoded URL should give client 400 [Bad Syntax]; returning
561 ** NULL here causes 404 [Not Found], but that's not too unreasonable. */
562 struct path_info * uh_path_lookup(struct client *cl, const char *url)
564 static char path_phys[PATH_MAX];
565 static char path_info[PATH_MAX];
566 static struct path_info p;
568 char buffer[UH_LIMIT_MSGHEAD];
569 char *docroot = cl->server->conf->docroot;
570 char *pathptr = NULL;
573 int no_sym = cl->server->conf->no_symlinks;
577 /* back out early if url is undefined */
581 memset(path_phys, 0, sizeof(path_phys));
582 memset(path_info, 0, sizeof(path_info));
583 memset(buffer, 0, sizeof(buffer));
584 memset(&p, 0, sizeof(p));
587 memcpy(buffer, docroot,
588 min(strlen(docroot), sizeof(buffer) - 1));
590 /* separate query string from url */
591 if ((pathptr = strchr(url, '?')) != NULL)
593 p.query = pathptr[1] ? pathptr + 1 : NULL;
595 /* urldecode component w/o query */
598 if (uh_urldecode(&buffer[strlen(docroot)],
599 sizeof(buffer) - strlen(docroot) - 1,
600 url, pathptr - url ) < 0)
602 return NULL; /* bad URL */
607 /* no query string, decode all of url */
610 if (uh_urldecode(&buffer[strlen(docroot)],
611 sizeof(buffer) - strlen(docroot) - 1,
612 url, strlen(url) ) < 0)
614 return NULL; /* bad URL */
618 /* create canon path */
619 for (i = strlen(buffer), slash = (buffer[max(0, i-1)] == '/'); i >= 0; i--)
621 if ((buffer[i] == 0) || (buffer[i] == '/'))
623 memset(path_info, 0, sizeof(path_info));
624 memcpy(path_info, buffer, min(i + 1, sizeof(path_info) - 1));
626 if (no_sym ? realpath(path_info, path_phys)
627 : canonpath(path_info, path_phys))
629 memset(path_info, 0, sizeof(path_info));
630 memcpy(path_info, &buffer[i],
631 min(strlen(buffer) - i, sizeof(path_info) - 1));
638 /* check whether found path is within docroot */
639 if (strncmp(path_phys, docroot, strlen(docroot)) ||
640 ((path_phys[strlen(docroot)] != 0) &&
641 (path_phys[strlen(docroot)] != '/')))
646 /* test current path */
647 if (!stat(path_phys, &p.stat))
649 /* is a regular file */
650 if (p.stat.st_mode & S_IFREG)
654 p.name = &path_phys[strlen(docroot)];
655 p.info = path_info[0] ? path_info : NULL;
659 else if ((p.stat.st_mode & S_IFDIR) && !strlen(path_info))
661 /* ensure trailing slash */
662 if (path_phys[strlen(path_phys)-1] != '/')
663 path_phys[strlen(path_phys)] = '/';
665 /* try to locate index file */
666 memset(buffer, 0, sizeof(buffer));
667 memcpy(buffer, path_phys, sizeof(buffer));
668 pathptr = &buffer[strlen(buffer)];
670 /* if requested url resolves to a directory and a trailing slash
671 is missing in the request url, redirect the client to the same
672 url with trailing slash appended */
675 uh_http_sendf(cl, NULL,
676 "HTTP/1.1 302 Found\r\n"
677 "Location: %s%s%s\r\n"
678 "Connection: close\r\n\r\n",
679 &path_phys[strlen(docroot)],
681 p.query ? p.query : ""
686 else if (cl->server->conf->index_file)
688 strncat(buffer, cl->server->conf->index_file, sizeof(buffer));
690 if (!stat(buffer, &s) && (s.st_mode & S_IFREG))
692 memcpy(path_phys, buffer, sizeof(path_phys));
693 memcpy(&p.stat, &s, sizeof(p.stat));
698 for (i = 0; i < array_size(uh_index_files); i++)
700 strncat(buffer, uh_index_files[i], sizeof(buffer));
702 if (!stat(buffer, &s) && (s.st_mode & S_IFREG))
704 memcpy(path_phys, buffer, sizeof(path_phys));
705 memcpy(&p.stat, &s, sizeof(p.stat));
715 p.name = &path_phys[strlen(docroot)];
719 return p.phys ? &p : NULL;
723 static struct auth_realm *uh_realms = NULL;
725 struct auth_realm * uh_auth_add(char *path, char *user, char *pass)
727 struct auth_realm *new = NULL;
734 if((new = (struct auth_realm *)malloc(sizeof(struct auth_realm))) != NULL)
736 memset(new, 0, sizeof(struct auth_realm));
738 memcpy(new->path, path,
739 min(strlen(path), sizeof(new->path) - 1));
741 memcpy(new->user, user,
742 min(strlen(user), sizeof(new->user) - 1));
744 /* given password refers to a passwd entry */
745 if ((strlen(pass) > 3) && !strncmp(pass, "$p$", 3))
748 /* try to resolve shadow entry */
749 if (((spwd = getspnam(&pass[3])) != NULL) && spwd->sp_pwdp)
751 memcpy(new->pass, spwd->sp_pwdp,
752 min(strlen(spwd->sp_pwdp), sizeof(new->pass) - 1));
758 /* try to resolve passwd entry */
759 if (((pwd = getpwnam(&pass[3])) != NULL) && pwd->pw_passwd &&
760 (pwd->pw_passwd[0] != '!') && (pwd->pw_passwd[0] != 0))
762 memcpy(new->pass, pwd->pw_passwd,
763 min(strlen(pwd->pw_passwd), sizeof(new->pass) - 1));
770 memcpy(new->pass, pass,
771 min(strlen(pass), sizeof(new->pass) - 1));
776 new->next = uh_realms;
788 int uh_auth_check(struct client *cl, struct http_request *req,
789 struct path_info *pi)
791 int i, plen, rlen, protected;
792 char buffer[UH_LIMIT_MSGHEAD];
796 struct auth_realm *realm = NULL;
798 plen = strlen(pi->name);
801 /* check whether at least one realm covers the requested url */
802 for (realm = uh_realms; realm; realm = realm->next)
804 rlen = strlen(realm->path);
806 if ((plen >= rlen) && !strncasecmp(pi->name, realm->path, rlen))
814 /* requested resource is covered by a realm */
817 /* try to get client auth info */
818 foreach_header(i, req->headers)
820 if (!strcasecmp(req->headers[i], "Authorization") &&
821 (strlen(req->headers[i+1]) > 6) &&
822 !strncasecmp(req->headers[i+1], "Basic ", 6))
824 memset(buffer, 0, sizeof(buffer));
825 uh_b64decode(buffer, sizeof(buffer) - 1,
826 (unsigned char *) &req->headers[i+1][6],
827 strlen(req->headers[i+1]) - 6);
829 if ((pass = strchr(buffer, ':')) != NULL)
839 /* have client auth */
842 /* find matching realm */
843 for (realm = uh_realms; realm; realm = realm->next)
845 rlen = strlen(realm->path);
847 if ((plen >= rlen) &&
848 !strncasecmp(pi->name, realm->path, rlen) &&
849 !strcmp(user, realm->user))
856 /* found a realm matching the username */
859 /* check user pass */
860 if (!strcmp(pass, realm->pass) ||
861 !strcmp(crypt(pass, realm->pass), realm->pass))
867 uh_http_sendf(cl, NULL,
868 "HTTP/%.1f 401 Authorization Required\r\n"
869 "WWW-Authenticate: Basic realm=\"%s\"\r\n"
870 "Content-Type: text/plain\r\n"
871 "Content-Length: 23\r\n\r\n"
872 "Authorization Required\n",
873 req->version, cl->server->conf->realm
883 static struct listener *uh_listeners = NULL;
884 static struct client *uh_clients = NULL;
886 struct listener * uh_listener_add(int sock, struct config *conf)
888 struct listener *new = NULL;
891 if ((new = (struct listener *)malloc(sizeof(struct listener))) != NULL)
893 memset(new, 0, sizeof(struct listener));
899 /* get local endpoint addr */
900 sl = sizeof(struct sockaddr_in6);
901 memset(&(new->addr), 0, sl);
902 getsockname(sock, (struct sockaddr *) &(new->addr), &sl);
904 new->next = uh_listeners;
913 struct listener * uh_listener_lookup(int sock)
915 struct listener *cur = NULL;
917 for (cur = uh_listeners; cur; cur = cur->next)
918 if (cur->fd.fd == sock)
925 struct client * uh_client_add(int sock, struct listener *serv)
927 struct client *new = NULL;
930 if ((new = (struct client *)malloc(sizeof(struct client))) != NULL)
932 memset(new, 0, sizeof(struct client));
937 /* get remote endpoint addr */
938 sl = sizeof(struct sockaddr_in6);
939 memset(&(new->peeraddr), 0, sl);
940 getpeername(sock, (struct sockaddr *) &(new->peeraddr), &sl);
942 /* get local endpoint addr */
943 sl = sizeof(struct sockaddr_in6);
944 memset(&(new->servaddr), 0, sl);
945 getsockname(sock, (struct sockaddr *) &(new->servaddr), &sl);
947 new->next = uh_clients;
956 struct client * uh_client_lookup(int sock)
958 struct client *cur = NULL;
960 for (cur = uh_clients; cur; cur = cur->next)
961 if (cur->fd.fd == sock)
967 void uh_client_shutdown(struct client *cl)
970 /* free client tls context */
971 if (cl->server && cl->server->conf->tls)
972 cl->server->conf->tls_close(cl);
975 /* remove from global client list */
976 uh_client_remove(cl);
979 void uh_client_remove(struct client *cl)
981 struct client *cur = NULL;
982 struct client *prv = NULL;
984 for (cur = uh_clients; cur; prv = cur, cur = cur->next)
986 if ((cur == cl) || (!cl && cur->dead))
989 prv->next = cur->next;
991 uh_clients = cur->next;
993 if (cur->timeout.pending)
994 uloop_timeout_cancel(&cur->timeout);
997 uloop_process_delete(&cur->proc);
999 uloop_fd_delete(&cur->fd);
1002 D("IO: Socket(%d) closing\n", cur->fd.fd);
1003 cur->server->n_clients--;
1013 static struct interpreter *uh_interpreters = NULL;
1015 struct interpreter * uh_interpreter_add(const char *extn, const char *path)
1017 struct interpreter *new = NULL;
1019 if ((new = (struct interpreter *)malloc(sizeof(struct interpreter))) != NULL)
1021 memset(new, 0, sizeof(struct interpreter));
1023 memcpy(new->extn, extn, min(strlen(extn), sizeof(new->extn)-1));
1024 memcpy(new->path, path, min(strlen(path), sizeof(new->path)-1));
1026 new->next = uh_interpreters;
1027 uh_interpreters = new;
1035 struct interpreter * uh_interpreter_lookup(const char *path)
1037 struct interpreter *cur = NULL;
1040 for (cur = uh_interpreters; cur; cur = cur->next)
1042 e = &path[max(strlen(path) - strlen(cur->extn), 0)];
1044 if (!strcmp(e, cur->extn))