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
)
171 struct timeval timeout
;
173 /* first serve data from peek buffer */
174 if( cl
->peeklen
> 0 )
176 sz
= min(cl
->peeklen
, len
);
177 len
-= sz
; cl
->peeklen
-= sz
;
179 memcpy(buf
, cl
->peekbuf
, sz
);
180 memmove(cl
->peekbuf
, &cl
->peekbuf
[sz
], cl
->peeklen
);
183 /* caller wants more */
187 FD_SET(cl
->socket
, &reader
);
189 timeout
.tv_sec
= cl
->server
->conf
->network_timeout
;
192 if( select(cl
->socket
+ 1, &reader
, NULL
, NULL
, &timeout
) > 0 )
196 rsz
= cl
->server
->conf
->tls_recv(cl
, (void *)&buf
[sz
], len
);
199 rsz
= recv(cl
->socket
, (void *)&buf
[sz
], len
, 0);
201 if( (sz
== 0) || (rsz
> 0) )
214 int uh_http_sendhf(struct client
*cl
, int code
, const char *summary
, const char *fmt
, ...)
218 char buffer
[UH_LIMIT_MSGHEAD
];
221 len
= snprintf(buffer
, sizeof(buffer
),
222 "HTTP/1.1 %03i %s\r\n"
223 "Connection: close\r\n"
224 "Content-Type: text/plain\r\n"
225 "Transfer-Encoding: chunked\r\n\r\n",
229 ensure_ret(uh_tcp_send(cl
, buffer
, len
));
232 len
= vsnprintf(buffer
, sizeof(buffer
), fmt
, ap
);
235 ensure_ret(uh_http_sendc(cl
, buffer
, len
));
236 ensure_ret(uh_http_sendc(cl
, NULL
, 0));
242 int uh_http_sendc(struct client
*cl
, const char *data
, int len
)
252 clen
= snprintf(chunk
, sizeof(chunk
), "%X\r\n", len
);
253 ensure_ret(uh_tcp_send(cl
, chunk
, clen
));
254 ensure_ret(uh_tcp_send(cl
, data
, len
));
255 ensure_ret(uh_tcp_send(cl
, "\r\n", 2));
259 ensure_ret(uh_tcp_send(cl
, "0\r\n\r\n", 5));
266 struct client
*cl
, struct http_request
*req
, const char *fmt
, ...
269 char buffer
[UH_LIMIT_MSGHEAD
];
273 len
= vsnprintf(buffer
, sizeof(buffer
), fmt
, ap
);
276 if( (req
!= NULL
) && (req
->version
> 1.0) )
277 ensure_ret(uh_http_sendc(cl
, buffer
, len
));
279 ensure_ret(uh_tcp_send(cl
, buffer
, len
));
285 struct client
*cl
, struct http_request
*req
, const char *buf
, int len
290 if( (req
!= NULL
) && (req
->version
> 1.0) )
291 ensure_ret(uh_http_sendc(cl
, buf
, len
));
293 ensure_ret(uh_tcp_send(cl
, buf
, len
));
299 int uh_urldecode(char *buf
, int blen
, const char *src
, int slen
)
305 (((x) <= '9') ? ((x) - '0') : \
306 (((x) <= 'F') ? ((x) - 'A' + 10) : \
309 for( i
= 0; (i
<= slen
) && (i
<= blen
); i
++ )
313 if( ((i
+2) <= slen
) && isxdigit(src
[i
+1]) && isxdigit(src
[i
+2]) )
315 buf
[len
++] = (char)(16 * hex(src
[i
+1]) + hex(src
[i
+2]));
332 int uh_urlencode(char *buf
, int blen
, const char *src
, int slen
)
336 const char hex
[] = "0123456789abcdef";
338 for( i
= 0; (i
<= slen
) && (i
<= blen
); i
++ )
340 if( isalnum(src
[i
]) || (src
[i
] == '-') || (src
[i
] == '_') ||
341 (src
[i
] == '.') || (src
[i
] == '~') )
345 else if( (len
+3) <= blen
)
348 buf
[len
++] = hex
[(src
[i
] >> 4) & 15];
349 buf
[len
++] = hex
[(src
[i
] & 15) & 15];
360 int uh_b64decode(char *buf
, int blen
, const unsigned char *src
, int slen
)
365 unsigned int cin
= 0;
366 unsigned int cout
= 0;
369 for( i
= 0; (i
<= slen
) && (src
[i
] != 0); i
++ )
373 if( (cin
>= '0') && (cin
<= '9') )
374 cin
= cin
- '0' + 52;
375 else if( (cin
>= 'A') && (cin
<= 'Z') )
377 else if( (cin
>= 'a') && (cin
<= 'z') )
378 cin
= cin
- 'a' + 26;
379 else if( cin
== '+' )
381 else if( cin
== '/' )
383 else if( cin
== '=' )
388 cout
= (cout
<< 6) | cin
;
392 if( (len
+ 3) < blen
)
394 buf
[len
++] = (char)(cout
>> 16);
395 buf
[len
++] = (char)(cout
>> 8);
396 buf
[len
++] = (char)(cout
);
409 static char * canonpath(const char *path
, char *path_resolved
)
411 char path_copy
[PATH_MAX
];
412 char *path_cpy
= path_copy
;
413 char *path_res
= path_resolved
;
418 /* relative -> absolute */
421 getcwd(path_copy
, PATH_MAX
);
422 strncat(path_copy
, "/", PATH_MAX
- strlen(path_copy
));
423 strncat(path_copy
, path
, PATH_MAX
- strlen(path_copy
));
427 strncpy(path_copy
, path
, PATH_MAX
);
431 while( (*path_cpy
!= '\0') && (path_cpy
< (path_copy
+ PATH_MAX
- 2)) )
433 if( *path_cpy
== '/' )
435 /* skip repeating / */
436 if( path_cpy
[1] == '/' )
443 else if( path_cpy
[1] == '.' )
446 if( (path_cpy
[2] == '/') || (path_cpy
[2] == '\0') )
452 /* collapse /x/../ */
453 else if( (path_cpy
[2] == '.') &&
454 ((path_cpy
[3] == '/') || (path_cpy
[3] == '\0'))
456 while( (path_res
> path_resolved
) && (*--path_res
!= '/') )
465 *path_res
++ = *path_cpy
++;
468 /* remove trailing slash if not root / */
469 if( (path_res
> (path_resolved
+1)) && (path_res
[-1] == '/') )
471 else if( path_res
== path_resolved
)
477 if( !stat(path_resolved
, &s
) && (s
.st_mode
& S_IROTH
) )
478 return path_resolved
;
483 struct path_info
* uh_path_lookup(struct client
*cl
, const char *url
)
485 static char path_phys
[PATH_MAX
];
486 static char path_info
[PATH_MAX
];
487 static struct path_info p
;
489 char buffer
[UH_LIMIT_MSGHEAD
];
490 char *docroot
= cl
->server
->conf
->docroot
;
491 char *pathptr
= NULL
;
494 int no_sym
= cl
->server
->conf
->no_symlinks
;
498 /* back out early if url is undefined */
502 memset(path_phys
, 0, sizeof(path_phys
));
503 memset(path_info
, 0, sizeof(path_info
));
504 memset(buffer
, 0, sizeof(buffer
));
505 memset(&p
, 0, sizeof(p
));
508 memcpy(buffer
, docroot
,
509 min(strlen(docroot
), sizeof(buffer
) - 1));
511 /* separate query string from url */
512 if( (pathptr
= strchr(url
, '?')) != NULL
)
514 p
.query
= pathptr
[1] ? pathptr
+ 1 : NULL
;
516 /* urldecode component w/o query */
519 &buffer
[strlen(docroot
)],
520 sizeof(buffer
) - strlen(docroot
) - 1,
521 url
, (int)(pathptr
- url
) - 1
525 /* no query string, decode all of url */
529 &buffer
[strlen(docroot
)],
530 sizeof(buffer
) - strlen(docroot
) - 1,
535 /* create canon path */
536 for( i
= strlen(buffer
), slash
= (buffer
[max(0, i
-1)] == '/'); i
>= 0; i
-- )
538 if( (buffer
[i
] == 0) || (buffer
[i
] == '/') )
540 memset(path_info
, 0, sizeof(path_info
));
541 memcpy(path_info
, buffer
, min(i
+ 1, sizeof(path_info
) - 1));
543 if( no_sym
? realpath(path_info
, path_phys
)
544 : canonpath(path_info
, path_phys
)
546 memset(path_info
, 0, sizeof(path_info
));
547 memcpy(path_info
, &buffer
[i
],
548 min(strlen(buffer
) - i
, sizeof(path_info
) - 1));
555 /* check whether found path is within docroot */
556 if( strncmp(path_phys
, docroot
, strlen(docroot
)) ||
557 ((path_phys
[strlen(docroot
)] != 0) &&
558 (path_phys
[strlen(docroot
)] != '/'))
563 /* test current path */
564 if( ! stat(path_phys
, &p
.stat
) )
566 /* is a regular file */
567 if( p
.stat
.st_mode
& S_IFREG
)
571 p
.name
= &path_phys
[strlen(docroot
)];
572 p
.info
= path_info
[0] ? path_info
: NULL
;
576 else if( (p
.stat
.st_mode
& S_IFDIR
) && !strlen(path_info
) )
578 /* ensure trailing slash */
579 if( path_phys
[strlen(path_phys
)-1] != '/' )
580 path_phys
[strlen(path_phys
)] = '/';
582 /* try to locate index file */
583 memset(buffer
, 0, sizeof(buffer
));
584 memcpy(buffer
, path_phys
, sizeof(buffer
));
585 pathptr
= &buffer
[strlen(buffer
)];
587 /* if requested url resolves to a directory and a trailing slash
588 is missing in the request url, redirect the client to the same
589 url with trailing slash appended */
592 uh_http_sendf(cl
, NULL
,
593 "HTTP/1.1 302 Found\r\n"
594 "Location: %s%s%s\r\n"
595 "Connection: close\r\n\r\n",
596 &path_phys
[strlen(docroot
)],
598 p
.query
? p
.query
: ""
603 else if( cl
->server
->conf
->index_file
)
605 strncat(buffer
, cl
->server
->conf
->index_file
, sizeof(buffer
));
607 if( !stat(buffer
, &s
) && (s
.st_mode
& S_IFREG
) )
609 memcpy(path_phys
, buffer
, sizeof(path_phys
));
610 memcpy(&p
.stat
, &s
, sizeof(p
.stat
));
615 for( i
= 0; i
< array_size(uh_index_files
); i
++ )
617 strncat(buffer
, uh_index_files
[i
], sizeof(buffer
));
619 if( !stat(buffer
, &s
) && (s
.st_mode
& S_IFREG
) )
621 memcpy(path_phys
, buffer
, sizeof(path_phys
));
622 memcpy(&p
.stat
, &s
, sizeof(p
.stat
));
632 p
.name
= &path_phys
[strlen(docroot
)];
636 return p
.phys
? &p
: NULL
;
640 static struct auth_realm
*uh_realms
= NULL
;
642 struct auth_realm
* uh_auth_add(char *path
, char *user
, char *pass
)
644 struct auth_realm
*new = NULL
;
651 if((new = (struct auth_realm
*)malloc(sizeof(struct auth_realm
))) != NULL
)
653 memset(new, 0, sizeof(struct auth_realm
));
655 memcpy(new->path
, path
,
656 min(strlen(path
), sizeof(new->path
) - 1));
658 memcpy(new->user
, user
,
659 min(strlen(user
), sizeof(new->user
) - 1));
661 /* given password refers to a passwd entry */
662 if( (strlen(pass
) > 3) && !strncmp(pass
, "$p$", 3) )
665 /* try to resolve shadow entry */
666 if( ((spwd
= getspnam(&pass
[3])) != NULL
) && spwd
->sp_pwdp
)
668 memcpy(new->pass
, spwd
->sp_pwdp
,
669 min(strlen(spwd
->sp_pwdp
), sizeof(new->pass
) - 1));
675 /* try to resolve passwd entry */
676 if( ((pwd
= getpwnam(&pass
[3])) != NULL
) && pwd
->pw_passwd
&&
677 (pwd
->pw_passwd
[0] != '!') && (pwd
->pw_passwd
[0] != 0)
679 memcpy(new->pass
, pwd
->pw_passwd
,
680 min(strlen(pwd
->pw_passwd
), sizeof(new->pass
) - 1));
687 memcpy(new->pass
, pass
,
688 min(strlen(pass
), sizeof(new->pass
) - 1));
693 new->next
= uh_realms
;
706 struct client
*cl
, struct http_request
*req
, struct path_info
*pi
708 int i
, plen
, rlen
, protected;
709 char buffer
[UH_LIMIT_MSGHEAD
];
713 struct auth_realm
*realm
= NULL
;
715 plen
= strlen(pi
->name
);
718 /* check whether at least one realm covers the requested url */
719 for( realm
= uh_realms
; realm
; realm
= realm
->next
)
721 rlen
= strlen(realm
->path
);
723 if( (plen
>= rlen
) && !strncasecmp(pi
->name
, realm
->path
, rlen
) )
731 /* requested resource is covered by a realm */
734 /* try to get client auth info */
735 foreach_header(i
, req
->headers
)
737 if( !strcasecmp(req
->headers
[i
], "Authorization") &&
738 (strlen(req
->headers
[i
+1]) > 6) &&
739 !strncasecmp(req
->headers
[i
+1], "Basic ", 6)
741 memset(buffer
, 0, sizeof(buffer
));
742 uh_b64decode(buffer
, sizeof(buffer
) - 1,
743 (unsigned char *) &req
->headers
[i
+1][6],
744 strlen(req
->headers
[i
+1]) - 6);
746 if( (pass
= strchr(buffer
, ':')) != NULL
)
756 /* have client auth */
759 /* find matching realm */
760 for( realm
= uh_realms
; realm
; realm
= realm
->next
)
762 rlen
= strlen(realm
->path
);
764 if( (plen
>= rlen
) &&
765 !strncasecmp(pi
->name
, realm
->path
, rlen
) &&
766 !strcmp(user
, realm
->user
)
773 /* found a realm matching the username */
776 /* is a crypt passwd */
777 if( realm
->pass
[0] == '$' )
778 pass
= crypt(pass
, realm
->pass
);
780 /* check user pass */
781 if( !strcmp(pass
, realm
->pass
) )
787 uh_http_sendf(cl
, NULL
,
788 "HTTP/%.1f 401 Authorization Required\r\n"
789 "WWW-Authenticate: Basic realm=\"%s\"\r\n"
790 "Content-Type: text/plain\r\n"
791 "Content-Length: 23\r\n\r\n"
792 "Authorization Required\n",
793 req
->version
, cl
->server
->conf
->realm
803 static struct listener
*uh_listeners
= NULL
;
804 static struct client
*uh_clients
= NULL
;
806 struct listener
* uh_listener_add(int sock
, struct config
*conf
)
808 struct listener
*new = NULL
;
811 if( (new = (struct listener
*)malloc(sizeof(struct listener
))) != NULL
)
813 memset(new, 0, sizeof(struct listener
));
818 /* get local endpoint addr */
819 sl
= sizeof(struct sockaddr_in6
);
820 memset(&(new->addr
), 0, sl
);
821 getsockname(sock
, (struct sockaddr
*) &(new->addr
), &sl
);
823 new->next
= uh_listeners
;
832 struct listener
* uh_listener_lookup(int sock
)
834 struct listener
*cur
= NULL
;
836 for( cur
= uh_listeners
; cur
; cur
= cur
->next
)
837 if( cur
->socket
== sock
)
844 struct client
* uh_client_add(int sock
, struct listener
*serv
)
846 struct client
*new = NULL
;
849 if( (new = (struct client
*)malloc(sizeof(struct client
))) != NULL
)
851 memset(new, 0, sizeof(struct client
));
856 /* get remote endpoint addr */
857 sl
= sizeof(struct sockaddr_in6
);
858 memset(&(new->peeraddr
), 0, sl
);
859 getpeername(sock
, (struct sockaddr
*) &(new->peeraddr
), &sl
);
861 /* get local endpoint addr */
862 sl
= sizeof(struct sockaddr_in6
);
863 memset(&(new->servaddr
), 0, sl
);
864 getsockname(sock
, (struct sockaddr
*) &(new->servaddr
), &sl
);
866 new->next
= uh_clients
;
873 struct client
* uh_client_lookup(int sock
)
875 struct client
*cur
= NULL
;
877 for( cur
= uh_clients
; cur
; cur
= cur
->next
)
878 if( cur
->socket
== sock
)
884 void uh_client_remove(int sock
)
886 struct client
*cur
= NULL
;
887 struct client
*prv
= NULL
;
889 for( cur
= uh_clients
; cur
; prv
= cur
, cur
= cur
->next
)
891 if( cur
->socket
== sock
)
894 prv
->next
= cur
->next
;
896 uh_clients
= cur
->next
;
906 static struct interpreter
*uh_interpreters
= NULL
;
908 struct interpreter
* uh_interpreter_add(const char *extn
, const char *path
)
910 struct interpreter
*new = NULL
;
912 if( (new = (struct interpreter
*)
913 malloc(sizeof(struct interpreter
))) != NULL
)
915 memset(new, 0, sizeof(struct interpreter
));
917 memcpy(new->extn
, extn
, min(strlen(extn
), sizeof(new->extn
)-1));
918 memcpy(new->path
, path
, min(strlen(path
), sizeof(new->path
)-1));
920 new->next
= uh_interpreters
;
921 uh_interpreters
= new;
929 struct interpreter
* uh_interpreter_lookup(const char *path
)
931 struct interpreter
*cur
= NULL
;
934 for( cur
= uh_interpreters
; cur
; cur
= cur
->next
)
936 e
= &path
[max(strlen(path
) - strlen(cur
->extn
), 0)];
938 if( !strcmp(e
, cur
->extn
) )
This page took 0.092176 seconds and 5 git commands to generate.