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
] )
91 /* interruptable select() */
92 int select_intr(int n
, fd_set
*r
, fd_set
*w
, fd_set
*e
, struct timeval
*t
)
99 sigaddset(&ssn
, SIGCHLD
);
100 sigprocmask(SIG_UNBLOCK
, &ssn
, &sso
);
102 rv
= select(n
, r
, w
, e
, t
);
104 /* restore signal mask */
105 sigprocmask(SIG_SETMASK
, &sso
, NULL
);
111 int uh_tcp_send(struct client
*cl
, const char *buf
, int len
)
114 struct timeval timeout
;
117 FD_SET(cl
->socket
, &writer
);
119 timeout
.tv_sec
= cl
->server
->conf
->network_timeout
;
122 if( select(cl
->socket
+ 1, NULL
, &writer
, NULL
, &timeout
) > 0 )
126 return cl
->server
->conf
->tls_send(cl
, (void *)buf
, len
);
129 return send(cl
->socket
, buf
, len
, 0);
135 int uh_tcp_peek(struct client
*cl
, char *buf
, int len
)
137 int sz
= uh_tcp_recv(cl
, buf
, len
);
139 /* store received data in peek buffer */
143 memcpy(cl
->peekbuf
, buf
, sz
);
149 int uh_tcp_recv(struct client
*cl
, char *buf
, int len
)
154 /* first serve data from peek buffer */
155 if( cl
->peeklen
> 0 )
157 sz
= min(cl
->peeklen
, len
);
158 len
-= sz
; cl
->peeklen
-= sz
;
160 memcpy(buf
, cl
->peekbuf
, sz
);
161 memmove(cl
->peekbuf
, &cl
->peekbuf
[sz
], cl
->peeklen
);
164 /* caller wants more */
169 rsz
= cl
->server
->conf
->tls_recv(cl
, (void *)&buf
[sz
], len
);
172 rsz
= recv(cl
->socket
, (void *)&buf
[sz
], len
, 0);
174 if( (sz
== 0) || (rsz
> 0) )
182 do { if( x < 0 ) return -1; } while(0)
184 int uh_http_sendhf(struct client
*cl
, int code
, const char *summary
, const char *fmt
, ...)
188 char buffer
[UH_LIMIT_MSGHEAD
];
191 len
= snprintf(buffer
, sizeof(buffer
),
192 "HTTP/1.1 %03i %s\r\n"
193 "Connection: close\r\n"
194 "Content-Type: text/plain\r\n"
195 "Transfer-Encoding: chunked\r\n\r\n",
199 ensure(uh_tcp_send(cl
, buffer
, len
));
202 len
= vsnprintf(buffer
, sizeof(buffer
), fmt
, ap
);
205 ensure(uh_http_sendc(cl
, buffer
, len
));
206 ensure(uh_http_sendc(cl
, NULL
, 0));
212 int uh_http_sendc(struct client
*cl
, const char *data
, int len
)
222 clen
= snprintf(chunk
, sizeof(chunk
), "%X\r\n", len
);
223 ensure(uh_tcp_send(cl
, chunk
, clen
));
224 ensure(uh_tcp_send(cl
, data
, len
));
225 ensure(uh_tcp_send(cl
, "\r\n", 2));
229 ensure(uh_tcp_send(cl
, "0\r\n\r\n", 5));
236 struct client
*cl
, struct http_request
*req
, const char *fmt
, ...
239 char buffer
[UH_LIMIT_MSGHEAD
];
243 len
= vsnprintf(buffer
, sizeof(buffer
), fmt
, ap
);
246 if( (req
!= NULL
) && (req
->version
> 1.0) )
247 ensure(uh_http_sendc(cl
, buffer
, len
));
249 ensure(uh_tcp_send(cl
, buffer
, len
));
255 struct client
*cl
, struct http_request
*req
, const char *buf
, int len
260 if( (req
!= NULL
) && (req
->version
> 1.0) )
261 ensure(uh_http_sendc(cl
, buf
, len
));
263 ensure(uh_tcp_send(cl
, buf
, len
));
269 int uh_urldecode(char *buf
, int blen
, const char *src
, int slen
)
275 (((x) <= '9') ? ((x) - '0') : \
276 (((x) <= 'F') ? ((x) - 'A' + 10) : \
279 for( i
= 0; (i
<= slen
) && (i
<= blen
); i
++ )
283 if( ((i
+2) <= slen
) && isxdigit(src
[i
+1]) && isxdigit(src
[i
+2]) )
285 buf
[len
++] = (char)(16 * hex(src
[i
+1]) + hex(src
[i
+2]));
302 int uh_urlencode(char *buf
, int blen
, const char *src
, int slen
)
306 const char hex
[] = "0123456789abcdef";
308 for( i
= 0; (i
<= slen
) && (i
<= blen
); i
++ )
310 if( isalnum(src
[i
]) || (src
[i
] == '-') || (src
[i
] == '_') ||
311 (src
[i
] == '.') || (src
[i
] == '~') )
315 else if( (len
+3) <= blen
)
318 buf
[len
++] = hex
[(src
[i
] >> 4) & 15];
319 buf
[len
++] = hex
[(src
[i
] & 15) & 15];
330 int uh_b64decode(char *buf
, int blen
, const unsigned char *src
, int slen
)
335 unsigned int cin
= 0;
336 unsigned int cout
= 0;
339 for( i
= 0; (i
<= slen
) && (src
[i
] != 0); i
++ )
343 if( (cin
>= '0') && (cin
<= '9') )
344 cin
= cin
- '0' + 52;
345 else if( (cin
>= 'A') && (cin
<= 'Z') )
347 else if( (cin
>= 'a') && (cin
<= 'z') )
348 cin
= cin
- 'a' + 26;
349 else if( cin
== '+' )
351 else if( cin
== '/' )
353 else if( cin
== '=' )
358 cout
= (cout
<< 6) | cin
;
362 if( (len
+ 3) < blen
)
364 buf
[len
++] = (char)(cout
>> 16);
365 buf
[len
++] = (char)(cout
>> 8);
366 buf
[len
++] = (char)(cout
);
379 static char * canonpath(const char *path
, char *path_resolved
)
381 char path_copy
[PATH_MAX
];
382 char *path_cpy
= path_copy
;
383 char *path_res
= path_resolved
;
388 /* relative -> absolute */
391 getcwd(path_copy
, PATH_MAX
);
392 strncat(path_copy
, "/", PATH_MAX
- strlen(path_copy
));
393 strncat(path_copy
, path
, PATH_MAX
- strlen(path_copy
));
397 strncpy(path_copy
, path
, PATH_MAX
);
401 while( (*path_cpy
!= '\0') && (path_cpy
< (path_copy
+ PATH_MAX
- 2)) )
403 if( *path_cpy
== '/' )
405 /* skip repeating / */
406 if( path_cpy
[1] == '/' )
413 else if( path_cpy
[1] == '.' )
416 if( (path_cpy
[2] == '/') || (path_cpy
[2] == '\0') )
422 /* collapse /x/../ */
423 else if( (path_cpy
[2] == '.') &&
424 ((path_cpy
[3] == '/') || (path_cpy
[3] == '\0'))
426 while( (path_res
> path_resolved
) && (*--path_res
!= '/') )
435 *path_res
++ = *path_cpy
++;
438 /* remove trailing slash if not root / */
439 if( (path_res
> (path_resolved
+1)) && (path_res
[-1] == '/') )
441 else if( path_res
== path_resolved
)
447 if( !stat(path_resolved
, &s
) && (s
.st_mode
& S_IROTH
) )
448 return path_resolved
;
453 struct path_info
* uh_path_lookup(struct client
*cl
, const char *url
)
455 static char path_phys
[PATH_MAX
];
456 static char path_info
[PATH_MAX
];
457 static struct path_info p
;
459 char buffer
[UH_LIMIT_MSGHEAD
];
460 char *docroot
= cl
->server
->conf
->docroot
;
461 char *pathptr
= NULL
;
463 int no_sym
= cl
->server
->conf
->no_symlinks
;
468 memset(path_phys
, 0, sizeof(path_phys
));
469 memset(path_info
, 0, sizeof(path_info
));
470 memset(buffer
, 0, sizeof(buffer
));
471 memset(&p
, 0, sizeof(p
));
474 memcpy(buffer
, docroot
,
475 min(strlen(docroot
), sizeof(buffer
) - 1));
477 /* separate query string from url */
478 if( (pathptr
= strchr(url
, '?')) != NULL
)
480 p
.query
= pathptr
[1] ? pathptr
+ 1 : NULL
;
482 /* urldecode component w/o query */
485 &buffer
[strlen(docroot
)],
486 sizeof(buffer
) - strlen(docroot
) - 1,
487 url
, (int)(pathptr
- url
) - 1
491 /* no query string, decode all of url */
495 &buffer
[strlen(docroot
)],
496 sizeof(buffer
) - strlen(docroot
) - 1,
501 /* create canon path */
502 for( i
= strlen(buffer
); i
>= 0; i
-- )
504 if( (buffer
[i
] == 0) || (buffer
[i
] == '/') )
506 memset(path_info
, 0, sizeof(path_info
));
507 memcpy(path_info
, buffer
, min(i
+ 1, sizeof(path_info
) - 1));
509 if( no_sym
? realpath(path_info
, path_phys
)
510 : canonpath(path_info
, path_phys
)
512 memset(path_info
, 0, sizeof(path_info
));
513 memcpy(path_info
, &buffer
[i
],
514 min(strlen(buffer
) - i
, sizeof(path_info
) - 1));
521 /* check whether found path is within docroot */
522 if( strncmp(path_phys
, docroot
, strlen(docroot
)) ||
523 ((path_phys
[strlen(docroot
)] != 0) &&
524 (path_phys
[strlen(docroot
)] != '/'))
529 /* test current path */
530 if( ! stat(path_phys
, &p
.stat
) )
532 /* is a regular file */
533 if( p
.stat
.st_mode
& S_IFREG
)
537 p
.name
= &path_phys
[strlen(docroot
)];
538 p
.info
= path_info
[0] ? path_info
: NULL
;
542 else if( (p
.stat
.st_mode
& S_IFDIR
) && !strlen(path_info
) )
544 /* ensure trailing slash */
545 if( path_phys
[strlen(path_phys
)-1] != '/' )
546 path_phys
[strlen(path_phys
)] = '/';
548 /* try to locate index file */
549 memset(buffer
, 0, sizeof(buffer
));
550 memcpy(buffer
, path_phys
, sizeof(buffer
));
551 pathptr
= &buffer
[strlen(buffer
)];
553 for( i
= 0; i
< array_size(uh_index_files
); i
++ )
555 strncat(buffer
, uh_index_files
[i
], sizeof(buffer
));
557 if( !stat(buffer
, &s
) && (s
.st_mode
& S_IFREG
) )
559 memcpy(path_phys
, buffer
, sizeof(path_phys
));
560 memcpy(&p
.stat
, &s
, sizeof(p
.stat
));
569 p
.name
= &path_phys
[strlen(docroot
)];
573 return p
.phys
? &p
: NULL
;
577 static char uh_realms
[UH_LIMIT_AUTHREALMS
* sizeof(struct auth_realm
)] = { 0 };
578 static int uh_realm_count
= 0;
580 struct auth_realm
* uh_auth_add(char *path
, char *user
, char *pass
)
582 struct auth_realm
*new = NULL
;
586 if( uh_realm_count
< UH_LIMIT_AUTHREALMS
)
588 new = (struct auth_realm
*)
589 &uh_realms
[uh_realm_count
* sizeof(struct auth_realm
)];
591 memset(new, 0, sizeof(struct auth_realm
));
593 memcpy(new->path
, path
,
594 min(strlen(path
), sizeof(new->path
) - 1));
596 memcpy(new->user
, user
,
597 min(strlen(user
), sizeof(new->user
) - 1));
599 /* given password refers to a passwd entry */
600 if( (strlen(pass
) > 3) && !strncmp(pass
, "$p$", 3) )
602 /* try to resolve shadow entry */
603 if( ((spwd
= getspnam(&pass
[3])) != NULL
) && spwd
->sp_pwdp
)
605 memcpy(new->pass
, spwd
->sp_pwdp
,
606 min(strlen(spwd
->sp_pwdp
), sizeof(new->pass
) - 1));
609 /* try to resolve passwd entry */
610 else if( ((pwd
= getpwnam(&pass
[3])) != NULL
) && pwd
->pw_passwd
&&
611 (pwd
->pw_passwd
[0] != '!') && (pwd
->pw_passwd
[0] != 0)
613 memcpy(new->pass
, pwd
->pw_passwd
,
614 min(strlen(pwd
->pw_passwd
), sizeof(new->pass
) - 1));
621 memcpy(new->pass
, pass
,
622 min(strlen(pass
), sizeof(new->pass
) - 1));
636 struct client
*cl
, struct http_request
*req
, struct path_info
*pi
638 int i
, plen
, rlen
, protected;
639 char buffer
[UH_LIMIT_MSGHEAD
];
643 struct auth_realm
*realm
= NULL
;
645 plen
= strlen(pi
->name
);
648 /* check whether at least one realm covers the requested url */
649 for( i
= 0; i
< uh_realm_count
; i
++ )
651 realm
= (struct auth_realm
*)
652 &uh_realms
[i
* sizeof(struct auth_realm
)];
654 rlen
= strlen(realm
->path
);
656 if( (plen
>= rlen
) && !strncasecmp(pi
->name
, realm
->path
, rlen
) )
664 /* requested resource is covered by a realm */
667 /* try to get client auth info */
668 foreach_header(i
, req
->headers
)
670 if( !strcasecmp(req
->headers
[i
], "Authorization") &&
671 (strlen(req
->headers
[i
+1]) > 6) &&
672 !strncasecmp(req
->headers
[i
+1], "Basic ", 6)
674 memset(buffer
, 0, sizeof(buffer
));
675 uh_b64decode(buffer
, sizeof(buffer
) - 1,
676 (unsigned char *) &req
->headers
[i
+1][6],
677 strlen(req
->headers
[i
+1]) - 6);
679 if( (pass
= strchr(buffer
, ':')) != NULL
)
689 /* have client auth */
692 /* find matching realm */
693 for( i
= 0, realm
= NULL
; i
< uh_realm_count
; i
++ )
695 realm
= (struct auth_realm
*)
696 &uh_realms
[i
* sizeof(struct auth_realm
)];
698 rlen
= strlen(realm
->path
);
700 if( (plen
>= rlen
) &&
701 !strncasecmp(pi
->name
, realm
->path
, rlen
) &&
702 !strcmp(user
, realm
->user
)
711 /* found a realm matching the username */
714 /* is a crypt passwd */
715 if( realm
->pass
[0] == '$' )
716 pass
= crypt(pass
, realm
->pass
);
718 /* check user pass */
719 if( !strcmp(pass
, realm
->pass
) )
725 uh_http_sendf(cl
, NULL
,
726 "HTTP/%.1f 401 Authorization Required\r\n"
727 "WWW-Authenticate: Basic realm=\"%s\"\r\n"
728 "Content-Type: text/plain\r\n"
729 "Content-Length: 23\r\n\r\n"
730 "Authorization Required\n",
731 req
->version
, cl
->server
->conf
->realm
741 static char uh_listeners
[UH_LIMIT_LISTENERS
* sizeof(struct listener
)] = { 0 };
742 static char uh_clients
[UH_LIMIT_CLIENTS
* sizeof(struct client
)] = { 0 };
744 static int uh_listener_count
= 0;
745 static int uh_client_count
= 0;
748 struct listener
* uh_listener_add(int sock
, struct config
*conf
)
750 struct listener
*new = NULL
;
753 if( uh_listener_count
< UH_LIMIT_LISTENERS
)
755 new = (struct listener
*)
756 &uh_listeners
[uh_listener_count
* sizeof(struct listener
)];
761 /* get local endpoint addr */
762 sl
= sizeof(struct sockaddr_in6
);
763 memset(&(new->addr
), 0, sl
);
764 getsockname(sock
, (struct sockaddr
*) &(new->addr
), &sl
);
772 struct listener
* uh_listener_lookup(int sock
)
774 struct listener
*cur
= NULL
;
777 for( i
= 0; i
< uh_listener_count
; i
++ )
779 cur
= (struct listener
*) &uh_listeners
[i
* sizeof(struct listener
)];
781 if( cur
->socket
== sock
)
789 struct client
* uh_client_add(int sock
, struct listener
*serv
)
791 struct client
*new = NULL
;
794 if( uh_client_count
< UH_LIMIT_CLIENTS
)
796 new = (struct client
*)
797 &uh_clients
[uh_client_count
* sizeof(struct client
)];
802 /* get remote endpoint addr */
803 sl
= sizeof(struct sockaddr_in6
);
804 memset(&(new->peeraddr
), 0, sl
);
805 getpeername(sock
, (struct sockaddr
*) &(new->peeraddr
), &sl
);
807 /* get local endpoint addr */
808 sl
= sizeof(struct sockaddr_in6
);
809 memset(&(new->servaddr
), 0, sl
);
810 getsockname(sock
, (struct sockaddr
*) &(new->servaddr
), &sl
);
818 struct client
* uh_client_lookup(int sock
)
820 struct client
*cur
= NULL
;
823 for( i
= 0; i
< uh_client_count
; i
++ )
825 cur
= (struct client
*) &uh_clients
[i
* sizeof(struct client
)];
827 if( cur
->socket
== sock
)
834 void uh_client_remove(int sock
)
836 struct client
*del
= uh_client_lookup(sock
);
840 memmove(del
, del
+ 1,
841 sizeof(uh_clients
) - (int)((char *)del
- uh_clients
) - sizeof(struct client
));
This page took 0.11136 seconds and 5 git commands to generate.