12d68ff8622747068145f353bb5749341d183f5c
[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 #include "uhttpd.h"
20 #include "uhttpd-utils.h"
21
22 #ifdef HAVE_TLS
23 #include "uhttpd-tls.h"
24 #endif
25
26
27 static char *uh_index_files[] = {
28         "index.html",
29         "index.htm",
30         "default.html",
31         "default.htm"
32 };
33
34
35 const char * sa_straddr(void *sa)
36 {
37         static char str[INET6_ADDRSTRLEN];
38         struct sockaddr_in *v4 = (struct sockaddr_in *)sa;
39         struct sockaddr_in6 *v6 = (struct sockaddr_in6 *)sa;
40
41         if( v4->sin_family == AF_INET )
42                 return inet_ntop(AF_INET, &(v4->sin_addr), str, sizeof(str));
43         else
44                 return inet_ntop(AF_INET6, &(v6->sin6_addr), str, sizeof(str));
45 }
46
47 const char * sa_strport(void *sa)
48 {
49         static char str[6];
50         snprintf(str, sizeof(str), "%i", sa_port(sa));
51         return str;
52 }
53
54 int sa_port(void *sa)
55 {
56         return ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
57 }
58
59 /* Simple strstr() like function that takes len arguments for both haystack and needle. */
60 char *strfind(char *haystack, int hslen, const char *needle, int ndlen)
61 {
62         int match = 0;
63         int i, j;
64
65         for( i = 0; i < hslen; i++ )
66         {
67                 if( haystack[i] == needle[0] )
68                 {
69                         match = ((ndlen == 1) || ((i + ndlen) <= hslen));
70
71                         for( j = 1; (j < ndlen) && ((i + j) < hslen); j++ )
72                         {
73                                 if( haystack[i+j] != needle[j] )
74                                 {
75                                         match = 0;
76                                         break;
77                                 }
78                         }
79
80                         if( match )
81                                 return &haystack[i];
82                 }
83         }
84
85         return NULL;
86 }
87
88
89 int uh_tcp_send(struct client *cl, const char *buf, int len)
90 {
91         fd_set writer;
92         struct timeval timeout;
93
94         FD_ZERO(&writer);
95         FD_SET(cl->socket, &writer);
96
97         timeout.tv_sec = 0;
98         timeout.tv_usec = 500000;
99
100         if( select(cl->socket + 1, NULL, &writer, NULL, &timeout) > 0 )
101         {
102 #ifdef HAVE_TLS
103                 if( cl->tls )
104                         return SSL_write(cl->tls, buf, len);
105                 else
106 #endif
107                         return send(cl->socket, buf, len, 0);
108         }
109
110         return -1;
111 }
112
113 int uh_tcp_peek(struct client *cl, char *buf, int len)
114 {
115         int sz = uh_tcp_recv(cl, buf, len);
116
117         /* store received data in peek buffer */
118         if( sz > 0 )
119         {
120                 cl->peeklen = sz;
121                 memcpy(cl->peekbuf, buf, sz);
122         }
123
124         return sz;
125 }
126
127 int uh_tcp_recv(struct client *cl, char *buf, int len)
128 {
129         int sz = 0;
130         int rsz = 0;
131
132         /* first serve data from peek buffer */
133         if( cl->peeklen > 0 )
134         {
135                 sz = min(cl->peeklen, len);
136                 len -= sz; cl->peeklen -= sz;
137
138                 memcpy(buf, cl->peekbuf, sz);
139                 memmove(cl->peekbuf, &cl->peekbuf[sz], cl->peeklen);
140         }
141
142         /* caller wants more */
143         if( len > 0 )
144         {
145 #ifdef HAVE_TLS
146                 if( cl->tls )
147                         rsz = SSL_read(cl->tls, (void *)&buf[sz], len);
148                 else
149 #endif
150                         rsz = recv(cl->socket, (void *)&buf[sz], len, 0);
151
152                 if( (sz == 0) || (rsz > 0) )
153                         sz += rsz;
154         }
155
156         return sz;
157 }
158
159 #define ensure(x) \
160         do { if( x < 0 ) return -1; } while(0)
161
162 int uh_http_sendhf(struct client *cl, int code, const char *summary, const char *fmt, ...)
163 {
164         va_list ap;
165
166         char buffer[UH_LIMIT_MSGHEAD];
167         int len;
168
169         len = snprintf(buffer, sizeof(buffer),
170                 "HTTP/1.1 %03i %s\r\n"
171                 "Content-Type: text/plain\r\n"
172                 "Transfer-Encoding: chunked\r\n\r\n",
173                         code, summary
174         );
175
176         ensure(uh_tcp_send(cl, buffer, len));
177
178         va_start(ap, fmt);
179         len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
180         va_end(ap);
181
182         ensure(uh_http_sendc(cl, buffer, len));
183         ensure(uh_http_sendc(cl, NULL, 0));
184
185         return 0;
186 }
187
188
189 int uh_http_sendc(struct client *cl, const char *data, int len)
190 {
191         char chunk[8];
192         int clen;
193
194         if( len == -1 )
195                 len = strlen(data);
196
197         if( len > 0 )
198         {
199                 clen = snprintf(chunk, sizeof(chunk), "%X\r\n", len);
200                 ensure(uh_tcp_send(cl, chunk, clen));
201                 ensure(uh_tcp_send(cl, data, len));
202                 ensure(uh_tcp_send(cl, "\r\n", 2));
203         }
204         else
205         {
206                 ensure(uh_tcp_send(cl, "0\r\n\r\n", 5));
207         }
208
209         return 0;
210 }
211
212 int uh_http_sendf(
213         struct client *cl, struct http_request *req, const char *fmt, ...
214 ) {
215         va_list ap;
216         char buffer[UH_LIMIT_MSGHEAD];
217         int len;
218
219         va_start(ap, fmt);
220         len = vsnprintf(buffer, sizeof(buffer), fmt, ap);
221         va_end(ap);
222
223         if( (req != NULL) && (req->version > 1.0) )
224                 ensure(uh_http_sendc(cl, buffer, len));
225         else if( len > 0 )
226                 ensure(uh_tcp_send(cl, buffer, len));
227
228         return 0;
229 }
230
231 int uh_http_send(
232         struct client *cl, struct http_request *req, const char *buf, int len
233 ) {
234         if( len < 0 )
235                 len = strlen(buf);
236
237         if( (req != NULL) && (req->version > 1.0) )
238                 ensure(uh_http_sendc(cl, buf, len));
239         else if( len > 0 )
240                 ensure(uh_tcp_send(cl, buf, len));
241
242         return 0;
243 }
244
245
246 int uh_urldecode(char *buf, int blen, const char *src, int slen)
247 {
248         int i;
249         int len = 0;
250
251 #define hex(x) \
252         (((x) <= '9') ? ((x) - '0') : \
253                 (((x) <= 'F') ? ((x) - 'A' + 10) : \
254                         ((x) - 'a' + 10)))
255
256         for( i = 0; (i <= slen) && (i <= blen); i++ )
257         {
258                 if( src[i] == '%' )
259                 {
260                         if( ((i+2) <= slen) && isxdigit(src[i+1]) && isxdigit(src[i+2]) )
261                         {
262                                 buf[len++] = (char)(16 * hex(src[i+1]) + hex(src[i+2]));
263                                 i += 2;
264                         }
265                         else
266                         {
267                                 buf[len++] = '%';
268                         }
269                 }
270                 else
271                 {
272                         buf[len++] = src[i];
273                 }
274         }
275
276         return len;
277 }
278
279 int uh_urlencode(char *buf, int blen, const char *src, int slen)
280 {
281         int i;
282         int len = 0;
283         const char hex[] = "0123456789abcdef";
284
285         for( i = 0; (i <= slen) && (i <= blen); i++ )
286         {
287                 if( isalnum(src[i]) || (src[i] == '-') || (src[i] == '_') ||
288                     (src[i] == '.') || (src[i] == '~') )
289                 {
290                         buf[len++] = src[i];
291                 }
292                 else if( (len+3) <= blen )
293                 {
294                         buf[len++] = '%';
295                         buf[len++] = hex[(src[i] >> 4) & 15];
296                         buf[len++] = hex[(src[i] & 15) & 15];
297                 }
298                 else
299                 {
300                         break;
301                 }
302         }
303
304         return len;
305 }
306
307 int uh_path_normalize(char *buf, int blen, const char *src, int slen)
308 {
309         int i, skip;
310         int len = 0;
311
312         for( i = 0, skip = 1; (i <= slen) && (src[i] != 0); i++ )
313         {
314                 /* collapse multiple "/" into one */
315                 if( src[i] == '/' )
316                 {
317                         /* collapse "/../" to "/" */
318                         if( ((i+2) <= slen) && (src[i+1] == '.') && (src[i+2] == '.') &&
319                                 (((i+3) > slen) || (src[i+3] == '/'))
320                         ) {
321                                 i += 2;
322                                 continue;
323                         }
324
325                         /* collapse "/./" to "/" */
326                         else if( ((i+1) <= slen) && (src[i+1] == '.') &&
327                             (((i+2) > slen) || (src[i+2] == '/'))
328                         ) {
329                                 i += 1;
330                                 continue;
331                         }
332
333                         /* skip repeating "/" */
334                         else if( skip )
335                         {
336                                 continue;
337                         }
338
339                         skip++;
340                 }
341
342                 /* finally a harmless char */
343                 else
344                 {
345                         skip = 0;
346                 }
347
348                 buf[len++] = src[i];
349         }
350
351         return len;
352 }
353
354
355 struct path_info * uh_path_lookup(struct client *cl, const char *url)
356 {
357         static char path_phys[PATH_MAX];
358         static char path_info[PATH_MAX];
359         static struct path_info p;
360
361         char buffer[UH_LIMIT_MSGHEAD];
362         char *docroot = cl->server->conf->docroot;
363         char *pathptr = NULL;
364
365         int i = 0;
366         struct stat s;
367
368
369         memset(path_phys, 0, sizeof(path_phys));
370         memset(path_info, 0, sizeof(path_info));
371         memset(buffer, 0, sizeof(buffer));
372         memset(&p, 0, sizeof(p));
373
374         /* copy docroot */
375         memcpy(buffer, docroot, sizeof(buffer));
376
377         /* separate query string from url */
378         if( (pathptr = strchr(url, '?')) != NULL )
379         {
380                 p.query = pathptr[1] ? pathptr + 1 : NULL;
381
382                 /* urldecode component w/o query */
383                 if( pathptr > url )
384                         uh_urldecode(
385                                 &buffer[strlen(docroot)],
386                                 sizeof(buffer) - strlen(docroot) - 1,
387                                 url, (int)(pathptr - url) - 1
388                         );
389         }
390
391         /* no query string, decode all of url */
392         else
393         {
394                 uh_urldecode(
395                         &buffer[strlen(docroot)],
396                         sizeof(buffer) - strlen(docroot) - 1,
397                         url, strlen(url)
398                 );
399         }
400
401         /* create canon path */
402         for( i = strlen(buffer); i >= 0; i-- )
403         {
404                 if( (buffer[i] == 0) || (buffer[i] == '/') )
405                 {
406                         memset(path_info, 0, sizeof(path_info));
407                         memcpy(path_info, buffer, min(i + 1, sizeof(path_info) - 1));
408
409                         if( realpath(path_info, path_phys) )
410                         {
411                                 memset(path_info, 0, sizeof(path_info));
412                                 memcpy(path_info, &buffer[i],
413                                         min(strlen(buffer) - i, sizeof(path_info) - 1));
414
415                                 break;
416                         }
417                 }
418         }
419
420         /* check whether found path is within docroot */
421         if( strncmp(path_phys, docroot, strlen(docroot)) ||
422             ((path_phys[strlen(docroot)] != 0) &&
423                  (path_phys[strlen(docroot)] != '/'))
424         ) {
425                 return NULL;
426         }
427
428         /* test current path */
429         if( ! stat(path_phys, &p.stat) )
430         {
431                 /* is a regular file */
432                 if( p.stat.st_mode & S_IFREG )
433                 {
434                         p.root = docroot;
435                         p.phys = path_phys;
436                         p.name = &path_phys[strlen(docroot)];
437                         p.info = path_info[0] ? path_info : NULL;
438                 }
439
440                 /* is a directory */
441                 else if( (p.stat.st_mode & S_IFDIR) && !strlen(path_info) )
442                 {
443                         /* ensure trailing slash */
444                         if( path_phys[strlen(path_phys)-1] != '/' )
445                                 path_phys[strlen(path_phys)] = '/';
446
447                         /* try to locate index file */
448                         memset(buffer, 0, sizeof(buffer));
449                         memcpy(buffer, path_phys, sizeof(buffer));
450                         pathptr = &buffer[strlen(buffer)];
451
452                         for( i = 0; i < array_size(uh_index_files); i++ )
453                         {
454                                 strncat(buffer, uh_index_files[i], sizeof(buffer));
455
456                                 if( !stat(buffer, &s) && (s.st_mode & S_IFREG) )
457                                 {
458                                         memcpy(path_phys, buffer, sizeof(path_phys));
459                                         memcpy(&p.stat, &s, sizeof(p.stat));
460                                         break;
461                                 }
462
463                                 *pathptr = 0;
464                         }
465
466                         p.root = docroot;
467                         p.phys = path_phys;
468                         p.name = &path_phys[strlen(docroot)];
469                 }
470         }
471
472         return p.phys ? &p : NULL;
473 }
474
475
476 static char uh_listeners[UH_LIMIT_LISTENERS * sizeof(struct listener)] = { 0 };
477 static char uh_clients[UH_LIMIT_CLIENTS * sizeof(struct client)] = { 0 };
478
479 static int uh_listener_count = 0;
480 static int uh_client_count = 0;
481
482
483 struct listener * uh_listener_add(int sock, struct config *conf)
484 {
485         struct listener *new = NULL;
486         socklen_t sl;
487
488         if( uh_listener_count < UH_LIMIT_LISTENERS )
489         {
490                 new = (struct listener *)
491                         &uh_listeners[uh_listener_count * sizeof(struct listener)];
492
493                 new->socket = sock;
494                 new->conf   = conf;
495
496                 /* get local endpoint addr */
497                 sl = sizeof(struct sockaddr_in6);
498                 memset(&(new->addr), 0, sl);
499                 getsockname(sock, (struct sockaddr *) &(new->addr), &sl);
500
501                 uh_listener_count++;
502         }
503
504         return new;
505 }
506
507 struct listener * uh_listener_lookup(int sock)
508 {
509         struct listener *cur = NULL;
510         int i;
511
512         for( i = 0; i < uh_listener_count; i++ )
513         {
514                 cur = (struct listener *) &uh_listeners[i * sizeof(struct listener)];
515
516                 if( cur->socket == sock )
517                         return cur;
518         }
519
520         return NULL;
521 }
522
523
524 struct client * uh_client_add(int sock, struct listener *serv)
525 {
526         struct client *new = NULL;
527         socklen_t sl;
528
529         if( uh_client_count < UH_LIMIT_CLIENTS )
530         {
531                 new = (struct client *)
532                         &uh_clients[uh_client_count * sizeof(struct client)];
533
534                 new->socket = sock;
535                 new->server = serv;
536
537                 /* get remote endpoint addr */
538                 sl = sizeof(struct sockaddr_in6);
539                 memset(&(new->peeraddr), 0, sl);
540                 getpeername(sock, (struct sockaddr *) &(new->peeraddr), &sl);
541
542                 /* get local endpoint addr */
543                 sl = sizeof(struct sockaddr_in6);
544                 memset(&(new->servaddr), 0, sl);
545                 getsockname(sock, (struct sockaddr *) &(new->servaddr), &sl);
546
547                 uh_client_count++;
548         }
549
550         return new;
551 }
552
553 struct client * uh_client_lookup(int sock)
554 {
555         struct client *cur = NULL;
556         int i;
557
558         for( i = 0; i < uh_client_count; i++ )
559         {
560                 cur = (struct client *) &uh_clients[i * sizeof(struct client)];
561
562                 if( cur->socket == sock )
563                         return cur;
564         }
565
566         return NULL;
567 }
568
569 void uh_client_remove(int sock)
570 {
571         struct client *del = uh_client_lookup(sock);
572
573         if( del )
574         {
575                 memmove(del, del + 1,
576                         sizeof(uh_clients) - (int)((char *)del - uh_clients) - sizeof(struct client));
577
578                 uh_client_count--;
579         }
580 }
581
582