uhttpd: terminate I/O loops if socket writes fail
[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                 "Content-Type: text/plain\r\n"
175                 "Transfer-Encoding: chunked\r\n\r\n",
176                         code, summary
177         );
178
179         ensure(uh_tcp_send(cl, buffer, len));
180
181         va_start(ap, fmt);
182         len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
183         va_end(ap);
184
185         ensure(uh_http_sendc(cl, buffer, len));
186         ensure(uh_http_sendc(cl, NULL, 0));
187
188         return 0;
189 }
190
191
192 int uh_http_sendc(struct client *cl, const char *data, int len)
193 {
194         char chunk[8];
195         int clen;
196
197         if( len == -1 )
198                 len = strlen(data);
199
200         if( len > 0 )
201         {
202                 clen = snprintf(chunk, sizeof(chunk), "%X\r\n", len);
203                 ensure(uh_tcp_send(cl, chunk, clen));
204                 ensure(uh_tcp_send(cl, data, len));
205                 ensure(uh_tcp_send(cl, "\r\n", 2));
206         }
207         else
208         {
209                 ensure(uh_tcp_send(cl, "0\r\n\r\n", 5));
210         }
211
212         return 0;
213 }
214
215 int uh_http_sendf(
216         struct client *cl, struct http_request *req, const char *fmt, ...
217 ) {
218         va_list ap;
219         char buffer[UH_LIMIT_MSGHEAD];
220         int len;
221
222         va_start(ap, fmt);
223         len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
224         va_end(ap);
225
226         if( (req != NULL) && (req->version > 1.0) )
227                 ensure(uh_http_sendc(cl, buffer, len));
228         else if( len > 0 )
229                 ensure(uh_tcp_send(cl, buffer, len));
230
231         return 0;
232 }
233
234 int uh_http_send(
235         struct client *cl, struct http_request *req, const char *buf, int len
236 ) {
237         if( len < 0 )
238                 len = strlen(buf);
239
240         if( (req != NULL) && (req->version > 1.0) )
241                 ensure(uh_http_sendc(cl, buf, len));
242         else if( len > 0 )
243                 ensure(uh_tcp_send(cl, buf, len));
244
245         return 0;
246 }
247
248
249 int uh_urldecode(char *buf, int blen, const char *src, int slen)
250 {
251         int i;
252         int len = 0;
253
254 #define hex(x) \
255         (((x) <= '9') ? ((x) - '0') : \
256                 (((x) <= 'F') ? ((x) - 'A' + 10) : \
257                         ((x) - 'a' + 10)))
258
259         for( i = 0; (i <= slen) && (i <= blen); i++ )
260         {
261                 if( src[i] == '%' )
262                 {
263                         if( ((i+2) <= slen) && isxdigit(src[i+1]) && isxdigit(src[i+2]) )
264                         {
265                                 buf[len++] = (char)(16 * hex(src[i+1]) + hex(src[i+2]));
266                                 i += 2;
267                         }
268                         else
269                         {
270                                 buf[len++] = '%';
271                         }
272                 }
273                 else
274                 {
275                         buf[len++] = src[i];
276                 }
277         }
278
279         return len;
280 }
281
282 int uh_urlencode(char *buf, int blen, const char *src, int slen)
283 {
284         int i;
285         int len = 0;
286         const char hex[] = "0123456789abcdef";
287
288         for( i = 0; (i <= slen) && (i <= blen); i++ )
289         {
290                 if( isalnum(src[i]) || (src[i] == '-') || (src[i] == '_') ||
291                     (src[i] == '.') || (src[i] == '~') )
292                 {
293                         buf[len++] = src[i];
294                 }
295                 else if( (len+3) <= blen )
296                 {
297                         buf[len++] = '%';
298                         buf[len++] = hex[(src[i] >> 4) & 15];
299                         buf[len++] = hex[(src[i] & 15) & 15];
300                 }
301                 else
302                 {
303                         break;
304                 }
305         }
306
307         return len;
308 }
309
310 int uh_b64decode(char *buf, int blen, const unsigned char *src, int slen)
311 {
312         int i = 0;
313         int len = 0;
314
315         unsigned int cin  = 0;
316         unsigned int cout = 0;
317
318
319         for( i = 0; (i <= slen) && (src[i] != 0); i++ )
320         {
321                 cin = src[i];
322
323                 if( (cin >= '0') && (cin <= '9') )
324                         cin = cin - '0' + 52;
325                 else if( (cin >= 'A') && (cin <= 'Z') )
326                         cin = cin - 'A';
327                 else if( (cin >= 'a') && (cin <= 'z') )
328                         cin = cin - 'a' + 26;
329                 else if( cin == '+' )
330                         cin = 62;
331                 else if( cin == '/' )
332                         cin = 63;
333                 else if( cin == '=' )
334                         cin = 0;
335                 else
336                         continue;
337
338                 cout = (cout << 6) | cin;
339
340                 if( (i % 4) == 3 )
341                 {
342                         if( (len + 3) < blen )
343                         {
344                                 buf[len++] = (char)(cout >> 16);
345                                 buf[len++] = (char)(cout >> 8);
346                                 buf[len++] = (char)(cout);
347                         }
348                         else
349                         {
350                                 break;
351                         }
352                 }
353         }
354
355         buf[len++] = 0;
356         return len;
357 }
358
359
360 struct path_info * uh_path_lookup(struct client *cl, const char *url)
361 {
362         static char path_phys[PATH_MAX];
363         static char path_info[PATH_MAX];
364         static struct path_info p;
365
366         char buffer[UH_LIMIT_MSGHEAD];
367         char *docroot = cl->server->conf->docroot;
368         char *pathptr = NULL;
369
370         int i = 0;
371         struct stat s;
372
373
374         memset(path_phys, 0, sizeof(path_phys));
375         memset(path_info, 0, sizeof(path_info));
376         memset(buffer, 0, sizeof(buffer));
377         memset(&p, 0, sizeof(p));
378
379         /* copy docroot */
380         memcpy(buffer, docroot,
381                 min(strlen(docroot), sizeof(buffer) - 1));
382
383         /* separate query string from url */
384         if( (pathptr = strchr(url, '?')) != NULL )
385         {
386                 p.query = pathptr[1] ? pathptr + 1 : NULL;
387
388                 /* urldecode component w/o query */
389                 if( pathptr > url )
390                         uh_urldecode(
391                                 &buffer[strlen(docroot)],
392                                 sizeof(buffer) - strlen(docroot) - 1,
393                                 url, (int)(pathptr - url) - 1
394                         );
395         }
396
397         /* no query string, decode all of url */
398         else
399         {
400                 uh_urldecode(
401                         &buffer[strlen(docroot)],
402                         sizeof(buffer) - strlen(docroot) - 1,
403                         url, strlen(url)
404                 );
405         }
406
407         /* create canon path */
408         for( i = strlen(buffer); i >= 0; i-- )
409         {
410                 if( (buffer[i] == 0) || (buffer[i] == '/') )
411                 {
412                         memset(path_info, 0, sizeof(path_info));
413                         memcpy(path_info, buffer, min(i + 1, sizeof(path_info) - 1));
414
415                         if( realpath(path_info, path_phys) )
416                         {
417                                 memset(path_info, 0, sizeof(path_info));
418                                 memcpy(path_info, &buffer[i],
419                                         min(strlen(buffer) - i, sizeof(path_info) - 1));
420
421                                 break;
422                         }
423                 }
424         }
425
426         /* check whether found path is within docroot */
427         if( strncmp(path_phys, docroot, strlen(docroot)) ||
428             ((path_phys[strlen(docroot)] != 0) &&
429                  (path_phys[strlen(docroot)] != '/'))
430         ) {
431                 return NULL;
432         }
433
434         /* test current path */
435         if( ! stat(path_phys, &p.stat) )
436         {
437                 /* is a regular file */
438                 if( p.stat.st_mode & S_IFREG )
439                 {
440                         p.root = docroot;
441                         p.phys = path_phys;
442                         p.name = &path_phys[strlen(docroot)];
443                         p.info = path_info[0] ? path_info : NULL;
444                 }
445
446                 /* is a directory */
447                 else if( (p.stat.st_mode & S_IFDIR) && !strlen(path_info) )
448                 {
449                         /* ensure trailing slash */
450                         if( path_phys[strlen(path_phys)-1] != '/' )
451                                 path_phys[strlen(path_phys)] = '/';
452
453                         /* try to locate index file */
454                         memset(buffer, 0, sizeof(buffer));
455                         memcpy(buffer, path_phys, sizeof(buffer));
456                         pathptr = &buffer[strlen(buffer)];
457
458                         for( i = 0; i < array_size(uh_index_files); i++ )
459                         {
460                                 strncat(buffer, uh_index_files[i], sizeof(buffer));
461
462                                 if( !stat(buffer, &s) && (s.st_mode & S_IFREG) )
463                                 {
464                                         memcpy(path_phys, buffer, sizeof(path_phys));
465                                         memcpy(&p.stat, &s, sizeof(p.stat));
466                                         break;
467                                 }
468
469                                 *pathptr = 0;
470                         }
471
472                         p.root = docroot;
473                         p.phys = path_phys;
474                         p.name = &path_phys[strlen(docroot)];
475                 }
476         }
477
478         return p.phys ? &p : NULL;
479 }
480
481
482 static char uh_realms[UH_LIMIT_AUTHREALMS * sizeof(struct auth_realm)] = { 0 };
483 static int uh_realm_count = 0;
484
485 struct auth_realm * uh_auth_add(char *path, char *user, char *pass)
486 {
487         struct auth_realm *new = NULL;
488         struct passwd *pwd;
489         struct spwd *spwd;
490
491         if( uh_realm_count < UH_LIMIT_AUTHREALMS )
492         {
493                 new = (struct auth_realm *)
494                         &uh_realms[uh_realm_count * sizeof(struct auth_realm)];
495
496                 memset(new, 0, sizeof(struct auth_realm));
497
498                 memcpy(new->path, path,
499                         min(strlen(path), sizeof(new->path) - 1));
500
501                 memcpy(new->user, user,
502                         min(strlen(user), sizeof(new->user) - 1));
503
504                 /* given password refers to a passwd entry */
505                 if( (strlen(pass) > 3) && !strncmp(pass, "$p$", 3) )
506                 {
507                         /* try to resolve shadow entry */
508                         if( ((spwd = getspnam(&pass[3])) != NULL) && spwd->sp_pwdp )
509                         {
510                                 memcpy(new->pass, spwd->sp_pwdp,
511                                         min(strlen(spwd->sp_pwdp), sizeof(new->pass) - 1));
512                         }
513
514                         /* try to resolve passwd entry */
515                         else if( ((pwd = getpwnam(&pass[3])) != NULL) && pwd->pw_passwd &&
516                                 (pwd->pw_passwd[0] != '!') && (pwd->pw_passwd[0] != 0)
517                         ) {
518                                 memcpy(new->pass, pwd->pw_passwd,
519                                         min(strlen(pwd->pw_passwd), sizeof(new->pass) - 1));
520                         }                       
521                 }
522
523                 /* ordinary pwd */
524                 else
525                 {
526                         memcpy(new->pass, pass,
527                                 min(strlen(pass), sizeof(new->pass) - 1));
528                 }
529
530                 uh_realm_count++;
531         }
532
533         return new;
534 }
535
536 int uh_auth_check(
537         struct client *cl, struct http_request *req, struct path_info *pi
538 ) {
539         int i, plen, rlen, protected;
540         char buffer[UH_LIMIT_MSGHEAD];
541         char *user = NULL;
542         char *pass = NULL;
543
544         struct auth_realm *realm = NULL;
545
546         plen = strlen(pi->name);
547         protected = 0;
548
549         /* check whether at least one realm covers the requested url */
550         for( i = 0; i < uh_realm_count; i++ )
551         {
552                 realm = (struct auth_realm *)
553                         &uh_realms[i * sizeof(struct auth_realm)];
554
555                 rlen = strlen(realm->path);
556
557                 if( (plen >= rlen) && !strncasecmp(pi->name, realm->path, rlen) )
558                 {
559                         req->realm = realm;
560                         protected = 1;
561                         break;
562                 }
563         }
564
565         /* requested resource is covered by a realm */
566         if( protected )
567         {
568                 /* try to get client auth info */
569                 foreach_header(i, req->headers)
570                 {
571                         if( !strcasecmp(req->headers[i], "Authorization") &&
572                                 (strlen(req->headers[i+1]) > 6) &&
573                                 !strncasecmp(req->headers[i+1], "Basic ", 6)
574                         ) {
575                                 memset(buffer, 0, sizeof(buffer));
576                                 uh_b64decode(buffer, sizeof(buffer) - 1,
577                                         (unsigned char *) &req->headers[i+1][6],
578                                         strlen(req->headers[i+1]) - 6);
579
580                                 if( (pass = strchr(buffer, ':')) != NULL )
581                                 {
582                                         user = buffer;
583                                         *pass++ = 0;
584                                 }
585
586                                 break;
587                         }
588                 }
589
590                 /* have client auth */
591                 if( user && pass )
592                 {
593                         /* find matching realm */
594                         for( i = 0, realm = NULL; i < uh_realm_count; i++ )
595                         {
596                                 realm = (struct auth_realm *)
597                                         &uh_realms[i * sizeof(struct auth_realm)];
598
599                                 rlen = strlen(realm->path);
600
601                                 if( (plen >= rlen) &&
602                                     !strncasecmp(pi->name, realm->path, rlen) &&
603                                     !strcmp(user, realm->user)
604                                 ) {
605                                         req->realm = realm;
606                                         break;
607                                 }
608
609                                 realm = NULL;
610                         }
611
612                         /* found a realm matching the username */
613                         if( realm )
614                         {
615                                 /* is a crypt passwd */
616                                 if( realm->pass[0] == '$' )
617                                         pass = crypt(pass, realm->pass);
618
619                                 /* check user pass */
620                                 if( !strcmp(pass, realm->pass) )
621                                         return 1;
622                         }
623                 }
624
625                 /* 401 */
626                 uh_http_sendf(cl, NULL,
627                         "HTTP/%.1f 401 Authorization Required\r\n"
628                         "WWW-Authenticate: Basic realm=\"%s\"\r\n"
629                         "Content-Type: text/plain\r\n"
630                         "Content-Length: 23\r\n\r\n"
631                         "Authorization Required\n",
632                                 req->version, cl->server->conf->realm
633                 );
634
635                 return 0;
636         }
637
638         return 1;
639 }
640
641
642 static char uh_listeners[UH_LIMIT_LISTENERS * sizeof(struct listener)] = { 0 };
643 static char uh_clients[UH_LIMIT_CLIENTS * sizeof(struct client)] = { 0 };
644
645 static int uh_listener_count = 0;
646 static int uh_client_count = 0;
647
648
649 struct listener * uh_listener_add(int sock, struct config *conf)
650 {
651         struct listener *new = NULL;
652         socklen_t sl;
653
654         if( uh_listener_count < UH_LIMIT_LISTENERS )
655         {
656                 new = (struct listener *)
657                         &uh_listeners[uh_listener_count * sizeof(struct listener)];
658
659                 new->socket = sock;
660                 new->conf   = conf;
661
662                 /* get local endpoint addr */
663                 sl = sizeof(struct sockaddr_in6);
664                 memset(&(new->addr), 0, sl);
665                 getsockname(sock, (struct sockaddr *) &(new->addr), &sl);
666
667                 uh_listener_count++;
668         }
669
670         return new;
671 }
672
673 struct listener * uh_listener_lookup(int sock)
674 {
675         struct listener *cur = NULL;
676         int i;
677
678         for( i = 0; i < uh_listener_count; i++ )
679         {
680                 cur = (struct listener *) &uh_listeners[i * sizeof(struct listener)];
681
682                 if( cur->socket == sock )
683                         return cur;
684         }
685
686         return NULL;
687 }
688
689
690 struct client * uh_client_add(int sock, struct listener *serv)
691 {
692         struct client *new = NULL;
693         socklen_t sl;
694
695         if( uh_client_count < UH_LIMIT_CLIENTS )
696         {
697                 new = (struct client *)
698                         &uh_clients[uh_client_count * sizeof(struct client)];
699
700                 new->socket = sock;
701                 new->server = serv;
702
703                 /* get remote endpoint addr */
704                 sl = sizeof(struct sockaddr_in6);
705                 memset(&(new->peeraddr), 0, sl);
706                 getpeername(sock, (struct sockaddr *) &(new->peeraddr), &sl);
707
708                 /* get local endpoint addr */
709                 sl = sizeof(struct sockaddr_in6);
710                 memset(&(new->servaddr), 0, sl);
711                 getsockname(sock, (struct sockaddr *) &(new->servaddr), &sl);
712
713                 uh_client_count++;
714         }
715
716         return new;
717 }
718
719 struct client * uh_client_lookup(int sock)
720 {
721         struct client *cur = NULL;
722         int i;
723
724         for( i = 0; i < uh_client_count; i++ )
725         {
726                 cur = (struct client *) &uh_clients[i * sizeof(struct client)];
727
728                 if( cur->socket == sock )
729                         return cur;
730         }
731
732         return NULL;
733 }
734
735 void uh_client_remove(int sock)
736 {
737         struct client *del = uh_client_lookup(sock);
738
739         if( del )
740         {
741                 memmove(del, del + 1,
742                         sizeof(uh_clients) - (int)((char *)del - uh_clients) - sizeof(struct client));
743
744                 uh_client_count--;
745         }
746 }
747
748