549ad88d0772432a88ed2697ef1b84fefe89eaaf
[project/luci.git] / contrib / package / uhttpd / src / uhttpd-utils.c
1 /*
2  * uhttpd - Tiny non-forking httpd - Utility functions
3  *
4  *   Copyright (C) 2010 Jo-Philipp Wich <xm@subsignal.org>
5  *
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
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
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.
17  */
18
19 #define _XOPEN_SOURCE 500       /* crypt() */
20 #define _BSD_SOURCE                     /* strcasecmp(), strncasecmp() */
21
22 #include "uhttpd.h"
23 #include "uhttpd-utils.h"
24
25 #ifdef HAVE_TLS
26 #include "uhttpd-tls.h"
27 #endif
28
29
30 static char *uh_index_files[] = {
31         "index.html",
32         "index.htm",
33         "default.html",
34         "default.htm"
35 };
36
37
38 const char * sa_straddr(void *sa)
39 {
40         static char str[INET6_ADDRSTRLEN];
41         struct sockaddr_in *v4 = (struct sockaddr_in *)sa;
42         struct sockaddr_in6 *v6 = (struct sockaddr_in6 *)sa;
43
44         if( v4->sin_family == AF_INET )
45                 return inet_ntop(AF_INET, &(v4->sin_addr), str, sizeof(str));
46         else
47                 return inet_ntop(AF_INET6, &(v6->sin6_addr), str, sizeof(str));
48 }
49
50 const char * sa_strport(void *sa)
51 {
52         static char str[6];
53         snprintf(str, sizeof(str), "%i", sa_port(sa));
54         return str;
55 }
56
57 int sa_port(void *sa)
58 {
59         return ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
60 }
61
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)
64 {
65         int match = 0;
66         int i, j;
67
68         for( i = 0; i < hslen; i++ )
69         {
70                 if( haystack[i] == needle[0] )
71                 {
72                         match = ((ndlen == 1) || ((i + ndlen) <= hslen));
73
74                         for( j = 1; (j < ndlen) && ((i + j) < hslen); j++ )
75                         {
76                                 if( haystack[i+j] != needle[j] )
77                                 {
78                                         match = 0;
79                                         break;
80                                 }
81                         }
82
83                         if( match )
84                                 return &haystack[i];
85                 }
86         }
87
88         return NULL;
89 }
90
91
92 int uh_tcp_send(struct client *cl, const char *buf, int len)
93 {
94         fd_set writer;
95         struct timeval timeout;
96
97         FD_ZERO(&writer);
98         FD_SET(cl->socket, &writer);
99
100         timeout.tv_sec = 0;
101         timeout.tv_usec = 500000;
102
103         if( select(cl->socket + 1, NULL, &writer, NULL, &timeout) > 0 )
104         {
105 #ifdef HAVE_TLS
106                 if( cl->tls )
107                         return SSL_write(cl->tls, buf, len);
108                 else
109 #endif
110                         return send(cl->socket, buf, len, 0);
111         }
112
113         return -1;
114 }
115
116 int uh_tcp_peek(struct client *cl, char *buf, int len)
117 {
118         int sz = uh_tcp_recv(cl, buf, len);
119
120         /* store received data in peek buffer */
121         if( sz > 0 )
122         {
123                 cl->peeklen = sz;
124                 memcpy(cl->peekbuf, buf, sz);
125         }
126
127         return sz;
128 }
129
130 int uh_tcp_recv(struct client *cl, char *buf, int len)
131 {
132         int sz = 0;
133         int rsz = 0;
134
135         /* first serve data from peek buffer */
136         if( cl->peeklen > 0 )
137         {
138                 sz = min(cl->peeklen, len);
139                 len -= sz; cl->peeklen -= sz;
140
141                 memcpy(buf, cl->peekbuf, sz);
142                 memmove(cl->peekbuf, &cl->peekbuf[sz], cl->peeklen);
143         }
144
145         /* caller wants more */
146         if( len > 0 )
147         {
148 #ifdef HAVE_TLS
149                 if( cl->tls )
150                         rsz = SSL_read(cl->tls, (void *)&buf[sz], len);
151                 else
152 #endif
153                         rsz = recv(cl->socket, (void *)&buf[sz], len, 0);
154
155                 if( (sz == 0) || (rsz > 0) )
156                         sz += rsz;
157         }
158
159         return sz;
160 }
161
162 #define ensure(x) \
163         do { if( x < 0 ) return -1; } while(0)
164
165 int uh_http_sendhf(struct client *cl, int code, const char *summary, const char *fmt, ...)
166 {
167         va_list ap;
168
169         char buffer[UH_LIMIT_MSGHEAD];
170         int len;
171
172         len = snprintf(buffer, sizeof(buffer),
173                 "HTTP/1.1 %03i %s\r\n"
174                 "Connection: close\r\n"
175                 "Content-Type: text/plain\r\n"
176                 "Transfer-Encoding: chunked\r\n\r\n",
177                         code, summary
178         );
179
180         ensure(uh_tcp_send(cl, buffer, len));
181
182         va_start(ap, fmt);
183         len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
184         va_end(ap);
185
186         ensure(uh_http_sendc(cl, buffer, len));
187         ensure(uh_http_sendc(cl, NULL, 0));
188
189         return 0;
190 }
191
192
193 int uh_http_sendc(struct client *cl, const char *data, int len)
194 {
195         char chunk[8];
196         int clen;
197
198         if( len == -1 )
199                 len = strlen(data);
200
201         if( len > 0 )
202         {
203                 clen = snprintf(chunk, sizeof(chunk), "%X\r\n", len);
204                 ensure(uh_tcp_send(cl, chunk, clen));
205                 ensure(uh_tcp_send(cl, data, len));
206                 ensure(uh_tcp_send(cl, "\r\n", 2));
207         }
208         else
209         {
210                 ensure(uh_tcp_send(cl, "0\r\n\r\n", 5));
211         }
212
213         return 0;
214 }
215
216 int uh_http_sendf(
217         struct client *cl, struct http_request *req, const char *fmt, ...
218 ) {
219         va_list ap;
220         char buffer[UH_LIMIT_MSGHEAD];
221         int len;
222
223         va_start(ap, fmt);
224         len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
225         va_end(ap);
226
227         if( (req != NULL) && (req->version > 1.0) )
228                 ensure(uh_http_sendc(cl, buffer, len));
229         else if( len > 0 )
230                 ensure(uh_tcp_send(cl, buffer, len));
231
232         return 0;
233 }
234
235 int uh_http_send(
236         struct client *cl, struct http_request *req, const char *buf, int len
237 ) {
238         if( len < 0 )
239                 len = strlen(buf);
240
241         if( (req != NULL) && (req->version > 1.0) )
242                 ensure(uh_http_sendc(cl, buf, len));
243         else if( len > 0 )
244                 ensure(uh_tcp_send(cl, buf, len));
245
246         return 0;
247 }
248
249
250 int uh_urldecode(char *buf, int blen, const char *src, int slen)
251 {
252         int i;
253         int len = 0;
254
255 #define hex(x) \
256         (((x) <= '9') ? ((x) - '0') : \
257                 (((x) <= 'F') ? ((x) - 'A' + 10) : \
258                         ((x) - 'a' + 10)))
259
260         for( i = 0; (i <= slen) && (i <= blen); i++ )
261         {
262                 if( src[i] == '%' )
263                 {
264                         if( ((i+2) <= slen) && isxdigit(src[i+1]) && isxdigit(src[i+2]) )
265                         {
266                                 buf[len++] = (char)(16 * hex(src[i+1]) + hex(src[i+2]));
267                                 i += 2;
268                         }
269                         else
270                         {
271                                 buf[len++] = '%';
272                         }
273                 }
274                 else
275                 {
276                         buf[len++] = src[i];
277                 }
278         }
279
280         return len;
281 }
282
283 int uh_urlencode(char *buf, int blen, const char *src, int slen)
284 {
285         int i;
286         int len = 0;
287         const char hex[] = "0123456789abcdef";
288
289         for( i = 0; (i <= slen) && (i <= blen); i++ )
290         {
291                 if( isalnum(src[i]) || (src[i] == '-') || (src[i] == '_') ||
292                     (src[i] == '.') || (src[i] == '~') )
293                 {
294                         buf[len++] = src[i];
295                 }
296                 else if( (len+3) <= blen )
297                 {
298                         buf[len++] = '%';
299                         buf[len++] = hex[(src[i] >> 4) & 15];
300                         buf[len++] = hex[(src[i] & 15) & 15];
301                 }
302                 else
303                 {
304                         break;
305                 }
306         }
307
308         return len;
309 }
310
311 int uh_b64decode(char *buf, int blen, const unsigned char *src, int slen)
312 {
313         int i = 0;
314         int len = 0;
315
316         unsigned int cin  = 0;
317         unsigned int cout = 0;
318
319
320         for( i = 0; (i <= slen) && (src[i] != 0); i++ )
321         {
322                 cin = src[i];
323
324                 if( (cin >= '0') && (cin <= '9') )
325                         cin = cin - '0' + 52;
326                 else if( (cin >= 'A') && (cin <= 'Z') )
327                         cin = cin - 'A';
328                 else if( (cin >= 'a') && (cin <= 'z') )
329                         cin = cin - 'a' + 26;
330                 else if( cin == '+' )
331                         cin = 62;
332                 else if( cin == '/' )
333                         cin = 63;
334                 else if( cin == '=' )
335                         cin = 0;
336                 else
337                         continue;
338
339                 cout = (cout << 6) | cin;
340
341                 if( (i % 4) == 3 )
342                 {
343                         if( (len + 3) < blen )
344                         {
345                                 buf[len++] = (char)(cout >> 16);
346                                 buf[len++] = (char)(cout >> 8);
347                                 buf[len++] = (char)(cout);
348                         }
349                         else
350                         {
351                                 break;
352                         }
353                 }
354         }
355
356         buf[len++] = 0;
357         return len;
358 }
359
360
361 struct path_info * uh_path_lookup(struct client *cl, const char *url)
362 {
363         static char path_phys[PATH_MAX];
364         static char path_info[PATH_MAX];
365         static struct path_info p;
366
367         char buffer[UH_LIMIT_MSGHEAD];
368         char *docroot = cl->server->conf->docroot;
369         char *pathptr = NULL;
370
371         int i = 0;
372         struct stat s;
373
374
375         memset(path_phys, 0, sizeof(path_phys));
376         memset(path_info, 0, sizeof(path_info));
377         memset(buffer, 0, sizeof(buffer));
378         memset(&p, 0, sizeof(p));
379
380         /* copy docroot */
381         memcpy(buffer, docroot,
382                 min(strlen(docroot), sizeof(buffer) - 1));
383
384         /* separate query string from url */
385         if( (pathptr = strchr(url, '?')) != NULL )
386         {
387                 p.query = pathptr[1] ? pathptr + 1 : NULL;
388
389                 /* urldecode component w/o query */
390                 if( pathptr > url )
391                         uh_urldecode(
392                                 &buffer[strlen(docroot)],
393                                 sizeof(buffer) - strlen(docroot) - 1,
394                                 url, (int)(pathptr - url) - 1
395                         );
396         }
397
398         /* no query string, decode all of url */
399         else
400         {
401                 uh_urldecode(
402                         &buffer[strlen(docroot)],
403                         sizeof(buffer) - strlen(docroot) - 1,
404                         url, strlen(url)
405                 );
406         }
407
408         /* create canon path */
409         for( i = strlen(buffer); i >= 0; i-- )
410         {
411                 if( (buffer[i] == 0) || (buffer[i] == '/') )
412                 {
413                         memset(path_info, 0, sizeof(path_info));
414                         memcpy(path_info, buffer, min(i + 1, sizeof(path_info) - 1));
415
416                         if( realpath(path_info, path_phys) )
417                         {
418                                 memset(path_info, 0, sizeof(path_info));
419                                 memcpy(path_info, &buffer[i],
420                                         min(strlen(buffer) - i, sizeof(path_info) - 1));
421
422                                 break;
423                         }
424                 }
425         }
426
427         /* check whether found path is within docroot */
428         if( strncmp(path_phys, docroot, strlen(docroot)) ||
429             ((path_phys[strlen(docroot)] != 0) &&
430                  (path_phys[strlen(docroot)] != '/'))
431         ) {
432                 return NULL;
433         }
434
435         /* test current path */
436         if( ! stat(path_phys, &p.stat) )
437         {
438                 /* is a regular file */
439                 if( p.stat.st_mode & S_IFREG )
440                 {
441                         p.root = docroot;
442                         p.phys = path_phys;
443                         p.name = &path_phys[strlen(docroot)];
444                         p.info = path_info[0] ? path_info : NULL;
445                 }
446
447                 /* is a directory */
448                 else if( (p.stat.st_mode & S_IFDIR) && !strlen(path_info) )
449                 {
450                         /* ensure trailing slash */
451                         if( path_phys[strlen(path_phys)-1] != '/' )
452                                 path_phys[strlen(path_phys)] = '/';
453
454                         /* try to locate index file */
455                         memset(buffer, 0, sizeof(buffer));
456                         memcpy(buffer, path_phys, sizeof(buffer));
457                         pathptr = &buffer[strlen(buffer)];
458
459                         for( i = 0; i < array_size(uh_index_files); i++ )
460                         {
461                                 strncat(buffer, uh_index_files[i], sizeof(buffer));
462
463                                 if( !stat(buffer, &s) && (s.st_mode & S_IFREG) )
464                                 {
465                                         memcpy(path_phys, buffer, sizeof(path_phys));
466                                         memcpy(&p.stat, &s, sizeof(p.stat));
467                                         break;
468                                 }
469
470                                 *pathptr = 0;
471                         }
472
473                         p.root = docroot;
474                         p.phys = path_phys;
475                         p.name = &path_phys[strlen(docroot)];
476                 }
477         }
478
479         return p.phys ? &p : NULL;
480 }
481
482
483 static char uh_realms[UH_LIMIT_AUTHREALMS * sizeof(struct auth_realm)] = { 0 };
484 static int uh_realm_count = 0;
485
486 struct auth_realm * uh_auth_add(char *path, char *user, char *pass)
487 {
488         struct auth_realm *new = NULL;
489         struct passwd *pwd;
490         struct spwd *spwd;
491
492         if( uh_realm_count < UH_LIMIT_AUTHREALMS )
493         {
494                 new = (struct auth_realm *)
495                         &uh_realms[uh_realm_count * sizeof(struct auth_realm)];
496
497                 memset(new, 0, sizeof(struct auth_realm));
498
499                 memcpy(new->path, path,
500                         min(strlen(path), sizeof(new->path) - 1));
501
502                 memcpy(new->user, user,
503                         min(strlen(user), sizeof(new->user) - 1));
504
505                 /* given password refers to a passwd entry */
506                 if( (strlen(pass) > 3) && !strncmp(pass, "$p$", 3) )
507                 {
508                         /* try to resolve shadow entry */
509                         if( ((spwd = getspnam(&pass[3])) != NULL) && spwd->sp_pwdp )
510                         {
511                                 memcpy(new->pass, spwd->sp_pwdp,
512                                         min(strlen(spwd->sp_pwdp), sizeof(new->pass) - 1));
513                         }
514
515                         /* try to resolve passwd entry */
516                         else if( ((pwd = getpwnam(&pass[3])) != NULL) && pwd->pw_passwd &&
517                                 (pwd->pw_passwd[0] != '!') && (pwd->pw_passwd[0] != 0)
518                         ) {
519                                 memcpy(new->pass, pwd->pw_passwd,
520                                         min(strlen(pwd->pw_passwd), sizeof(new->pass) - 1));
521                         }                       
522                 }
523
524                 /* ordinary pwd */
525                 else
526                 {
527                         memcpy(new->pass, pass,
528                                 min(strlen(pass), sizeof(new->pass) - 1));
529                 }
530
531                 uh_realm_count++;
532         }
533
534         return new;
535 }
536
537 int uh_auth_check(
538         struct client *cl, struct http_request *req, struct path_info *pi
539 ) {
540         int i, plen, rlen, protected;
541         char buffer[UH_LIMIT_MSGHEAD];
542         char *user = NULL;
543         char *pass = NULL;
544
545         struct auth_realm *realm = NULL;
546
547         plen = strlen(pi->name);
548         protected = 0;
549
550         /* check whether at least one realm covers the requested url */
551         for( i = 0; i < uh_realm_count; i++ )
552         {
553                 realm = (struct auth_realm *)
554                         &uh_realms[i * sizeof(struct auth_realm)];
555
556                 rlen = strlen(realm->path);
557
558                 if( (plen >= rlen) && !strncasecmp(pi->name, realm->path, rlen) )
559                 {
560                         req->realm = realm;
561                         protected = 1;
562                         break;
563                 }
564         }
565
566         /* requested resource is covered by a realm */
567         if( protected )
568         {
569                 /* try to get client auth info */
570                 foreach_header(i, req->headers)
571                 {
572                         if( !strcasecmp(req->headers[i], "Authorization") &&
573                                 (strlen(req->headers[i+1]) > 6) &&
574                                 !strncasecmp(req->headers[i+1], "Basic ", 6)
575                         ) {
576                                 memset(buffer, 0, sizeof(buffer));
577                                 uh_b64decode(buffer, sizeof(buffer) - 1,
578                                         (unsigned char *) &req->headers[i+1][6],
579                                         strlen(req->headers[i+1]) - 6);
580
581                                 if( (pass = strchr(buffer, ':')) != NULL )
582                                 {
583                                         user = buffer;
584                                         *pass++ = 0;
585                                 }
586
587                                 break;
588                         }
589                 }
590
591                 /* have client auth */
592                 if( user && pass )
593                 {
594                         /* find matching realm */
595                         for( i = 0, realm = NULL; i < uh_realm_count; i++ )
596                         {
597                                 realm = (struct auth_realm *)
598                                         &uh_realms[i * sizeof(struct auth_realm)];
599
600                                 rlen = strlen(realm->path);
601
602                                 if( (plen >= rlen) &&
603                                     !strncasecmp(pi->name, realm->path, rlen) &&
604                                     !strcmp(user, realm->user)
605                                 ) {
606                                         req->realm = realm;
607                                         break;
608                                 }
609
610                                 realm = NULL;
611                         }
612
613                         /* found a realm matching the username */
614                         if( realm )
615                         {
616                                 /* is a crypt passwd */
617                                 if( realm->pass[0] == '$' )
618                                         pass = crypt(pass, realm->pass);
619
620                                 /* check user pass */
621                                 if( !strcmp(pass, realm->pass) )
622                                         return 1;
623                         }
624                 }
625
626                 /* 401 */
627                 uh_http_sendf(cl, NULL,
628                         "HTTP/%.1f 401 Authorization Required\r\n"
629                         "WWW-Authenticate: Basic realm=\"%s\"\r\n"
630                         "Content-Type: text/plain\r\n"
631                         "Content-Length: 23\r\n\r\n"
632                         "Authorization Required\n",
633                                 req->version, cl->server->conf->realm
634                 );
635
636                 return 0;
637         }
638
639         return 1;
640 }
641
642
643 static char uh_listeners[UH_LIMIT_LISTENERS * sizeof(struct listener)] = { 0 };
644 static char uh_clients[UH_LIMIT_CLIENTS * sizeof(struct client)] = { 0 };
645
646 static int uh_listener_count = 0;
647 static int uh_client_count = 0;
648
649
650 struct listener * uh_listener_add(int sock, struct config *conf)
651 {
652         struct listener *new = NULL;
653         socklen_t sl;
654
655         if( uh_listener_count < UH_LIMIT_LISTENERS )
656         {
657                 new = (struct listener *)
658                         &uh_listeners[uh_listener_count * sizeof(struct listener)];
659
660                 new->socket = sock;
661                 new->conf   = conf;
662
663                 /* get local endpoint addr */
664                 sl = sizeof(struct sockaddr_in6);
665                 memset(&(new->addr), 0, sl);
666                 getsockname(sock, (struct sockaddr *) &(new->addr), &sl);
667
668                 uh_listener_count++;
669         }
670
671         return new;
672 }
673
674 struct listener * uh_listener_lookup(int sock)
675 {
676         struct listener *cur = NULL;
677         int i;
678
679         for( i = 0; i < uh_listener_count; i++ )
680         {
681                 cur = (struct listener *) &uh_listeners[i * sizeof(struct listener)];
682
683                 if( cur->socket == sock )
684                         return cur;
685         }
686
687         return NULL;
688 }
689
690
691 struct client * uh_client_add(int sock, struct listener *serv)
692 {
693         struct client *new = NULL;
694         socklen_t sl;
695
696         if( uh_client_count < UH_LIMIT_CLIENTS )
697         {
698                 new = (struct client *)
699                         &uh_clients[uh_client_count * sizeof(struct client)];
700
701                 new->socket = sock;
702                 new->server = serv;
703
704                 /* get remote endpoint addr */
705                 sl = sizeof(struct sockaddr_in6);
706                 memset(&(new->peeraddr), 0, sl);
707                 getpeername(sock, (struct sockaddr *) &(new->peeraddr), &sl);
708
709                 /* get local endpoint addr */
710                 sl = sizeof(struct sockaddr_in6);
711                 memset(&(new->servaddr), 0, sl);
712                 getsockname(sock, (struct sockaddr *) &(new->servaddr), &sl);
713
714                 uh_client_count++;
715         }
716
717         return new;
718 }
719
720 struct client * uh_client_lookup(int sock)
721 {
722         struct client *cur = NULL;
723         int i;
724
725         for( i = 0; i < uh_client_count; i++ )
726         {
727                 cur = (struct client *) &uh_clients[i * sizeof(struct client)];
728
729                 if( cur->socket == sock )
730                         return cur;
731         }
732
733         return NULL;
734 }
735
736 void uh_client_remove(int sock)
737 {
738         struct client *del = uh_client_lookup(sock);
739
740         if( del )
741         {
742                 memmove(del, del + 1,
743                         sizeof(uh_clients) - (int)((char *)del - uh_clients) - sizeof(struct client));
744
745                 uh_client_count--;
746         }
747 }
748
749