cgi header processing
[platform/upstream/libwebsockets.git] / test-server / test-server-http.c
1 /*
2  * libwebsockets-test-server - libwebsockets test implementation
3  *
4  * Copyright (C) 2010-2016 Andy Green <andy@warmcat.com>
5  *
6  * This file is made available under the Creative Commons CC0 1.0
7  * Universal Public Domain Dedication.
8  *
9  * The person who associated a work with this deed has dedicated
10  * the work to the public domain by waiving all of his or her rights
11  * to the work worldwide under copyright law, including all related
12  * and neighboring rights, to the extent allowed by law. You can copy,
13  * modify, distribute and perform the work, even for commercial purposes,
14  * all without asking permission.
15  *
16  * The test apps are intended to be adapted for use in your code, which
17  * may be proprietary.  So unlike the library itself, they are licensed
18  * Public Domain.
19  */
20 #include "test-server.h"
21
22 /*
23  * This demo server shows how to use libwebsockets for one or more
24  * websocket protocols in the same server
25  *
26  * It defines the following websocket protocols:
27  *
28  *  dumb-increment-protocol:  once the socket is opened, an incrementing
29  *                              ascii string is sent down it every 50ms.
30  *                              If you send "reset\n" on the websocket, then
31  *                              the incrementing number is reset to 0.
32  *
33  *  lws-mirror-protocol: copies any received packet to every connection also
34  *                              using this protocol, including the sender
35  */
36
37 extern int debug_level;
38
39 enum demo_protocols {
40         /* always first */
41         PROTOCOL_HTTP = 0,
42
43         PROTOCOL_DUMB_INCREMENT,
44         PROTOCOL_LWS_MIRROR,
45
46         /* always last */
47         DEMO_PROTOCOL_COUNT
48 };
49
50 /*
51  * We take a strict whitelist approach to stop ../ attacks
52  */
53 struct serveable {
54         const char *urlpath;
55         const char *mimetype;
56 };
57
58 /*
59  * this is just an example of parsing handshake headers, you don't need this
60  * in your code unless you will filter allowing connections by the header
61  * content
62  */
63 void
64 dump_handshake_info(struct lws *wsi)
65 {
66         int n = 0, len;
67         char buf[256];
68         const unsigned char *c;
69
70         do {
71                 c = lws_token_to_string(n);
72                 if (!c) {
73                         n++;
74                         continue;
75                 }
76
77                 len = lws_hdr_total_length(wsi, n);
78                 if (!len || len > sizeof(buf) - 1) {
79                         n++;
80                         continue;
81                 }
82
83                 lws_hdr_copy(wsi, buf, sizeof buf, n);
84                 buf[sizeof(buf) - 1] = '\0';
85
86                 fprintf(stderr, "    %s = %s\n", (char *)c, buf);
87                 n++;
88         } while (c);
89 }
90
91 const char * get_mimetype(const char *file)
92 {
93         int n = strlen(file);
94
95         if (n < 5)
96                 return NULL;
97
98         if (!strcmp(&file[n - 4], ".ico"))
99                 return "image/x-icon";
100
101         if (!strcmp(&file[n - 4], ".png"))
102                 return "image/png";
103
104         if (!strcmp(&file[n - 5], ".html"))
105                 return "text/html";
106
107         return NULL;
108 }
109
110 /* this protocol server (always the first one) handles HTTP,
111  *
112  * Some misc callbacks that aren't associated with a protocol also turn up only
113  * here on the first protocol server.
114  */
115
116 int callback_http(struct lws *wsi, enum lws_callback_reasons reason, void *user,
117                   void *in, size_t len)
118 {
119         struct per_session_data__http *pss =
120                         (struct per_session_data__http *)user, *pss1;
121         unsigned char buffer[4096 + LWS_PRE];
122         unsigned long amount, file_len, sent;
123         char leaf_path[1024];
124         const char *mimetype;
125         char *other_headers;
126         unsigned char *end;
127         struct timeval tv;
128         unsigned char *p;
129         char buf[256];
130         char b64[64];
131         int n, m;
132 #ifdef EXTERNAL_POLL
133         struct lws_pollargs *pa = (struct lws_pollargs *)in;
134 #endif
135
136         switch (reason) {
137         case LWS_CALLBACK_HTTP:
138
139                 if (debug_level & LLL_INFO) {
140                         dump_handshake_info(wsi);
141
142                         /* dump the individual URI Arg parameters */
143                         n = 0;
144                         while (lws_hdr_copy_fragment(wsi, buf, sizeof(buf),
145                                                      WSI_TOKEN_HTTP_URI_ARGS, n) > 0) {
146                                 lwsl_notice("URI Arg %d: %s\n", ++n, buf);
147                         }
148                 }
149
150                 {
151                         char name[100], rip[50];
152                         lws_get_peer_addresses(wsi, lws_get_socket_fd(wsi), name,
153                                                sizeof(name), rip, sizeof(rip));
154                         sprintf(buf, "%s (%s)", name, rip);
155                         lwsl_notice("HTTP connect from %s\n", buf);
156                 }
157
158                 if (len < 1) {
159                         lws_return_http_status(wsi,
160                                                 HTTP_STATUS_BAD_REQUEST, NULL);
161                         goto try_to_reuse;
162                 }
163
164                 /* this example server has no concept of directories */
165                 if (strchr((const char *)in + 1, '/')) {
166                         lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
167                         goto try_to_reuse;
168                 }
169
170 #ifndef LWS_NO_CLIENT
171                 if (!strcmp(in, "/proxytest")) {
172                         struct lws_client_connect_info i;
173
174                         if (lws_get_child(wsi))
175                                 break;
176
177                         pss->client_finished = 0;
178                         memset(&i,0, sizeof(i));
179                         i.context = lws_get_context(wsi);
180                         i.address = "example.com";
181                         i.port = 80;
182                         i.ssl_connection = 0;
183                         i.path = "/";
184                         i.host = "example.com";
185                         i.origin = NULL;
186                         i.method = "GET";
187                         i.parent_wsi = wsi;
188                         if (!lws_client_connect_via_info(&i)) {
189                                 lwsl_err("proxy connect fail\n");
190                                 break;
191                         }
192                         break;
193                 }
194 #endif
195
196 #ifdef LWS_WITH_CGI
197                 if (!strcmp(in, "/cgitest")) {
198                         static char *cmd[] = {
199                                 "/bin/sh",
200                                 "-c",
201                                 INSTALL_DATADIR"/libwebsockets-test-server/lws-cgi-test.sh",
202                                 NULL
203                         };
204
205                         lwsl_notice("%s: cgitest\n", __func__);
206                         n = lws_cgi(wsi, cmd, 5);
207                         if (n) {
208                                 lwsl_err("%s: cgi failed\n");
209                                 return -1;
210                         }
211                         p = buffer + LWS_PRE;
212                         end = p + sizeof(buffer) - LWS_PRE;
213
214                         if (lws_add_http_header_status(wsi, 200, &p, end))
215                                 return 1;
216                         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
217                                         (unsigned char *)"close", 5, &p, end))
218                                 return 1;
219                         n = lws_write(wsi, buffer + LWS_PRE,
220                                       p - (buffer + LWS_PRE),
221                                       LWS_WRITE_HTTP_HEADERS);
222
223                         /* the cgi starts by outputting headers, we can't
224                          *  finalize the headers until we see the end of that
225                          */
226
227                         break;
228                 }
229 #endif
230
231                 /* if a legal POST URL, let it continue and accept data */
232                 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
233                         return 0;
234
235                 /* check for the "send a big file by hand" example case */
236
237                 if (!strcmp((const char *)in, "/leaf.jpg")) {
238                         if (strlen(resource_path) > sizeof(leaf_path) - 10)
239                                 return -1;
240                         sprintf(leaf_path, "%s/leaf.jpg", resource_path);
241
242                         /* well, let's demonstrate how to send the hard way */
243
244                         p = buffer + LWS_PRE;
245                         end = p + sizeof(buffer) - LWS_PRE;
246
247                         pss->fd = lws_plat_file_open(wsi, leaf_path, &file_len,
248                                                      LWS_O_RDONLY);
249
250                         if (pss->fd == LWS_INVALID_FILE) {
251                                 lwsl_err("faild to open file %s\n", leaf_path);
252                                 return -1;
253                         }
254
255                         /*
256                          * we will send a big jpeg file, but it could be
257                          * anything.  Set the Content-Type: appropriately
258                          * so the browser knows what to do with it.
259                          *
260                          * Notice we use the APIs to build the header, which
261                          * will do the right thing for HTTP 1/1.1 and HTTP2
262                          * depending on what connection it happens to be working
263                          * on
264                          */
265                         if (lws_add_http_header_status(wsi, 200, &p, end))
266                                 return 1;
267                         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
268                                         (unsigned char *)"libwebsockets",
269                                         13, &p, end))
270                                 return 1;
271                         if (lws_add_http_header_by_token(wsi,
272                                         WSI_TOKEN_HTTP_CONTENT_TYPE,
273                                         (unsigned char *)"image/jpeg",
274                                         10, &p, end))
275                                 return 1;
276                         if (lws_add_http_header_content_length(wsi,
277                                                                file_len, &p,
278                                                                end))
279                                 return 1;
280                         if (lws_finalize_http_header(wsi, &p, end))
281                                 return 1;
282
283                         /*
284                          * send the http headers...
285                          * this won't block since it's the first payload sent
286                          * on the connection since it was established
287                          * (too small for partial)
288                          *
289                          * Notice they are sent using LWS_WRITE_HTTP_HEADERS
290                          * which also means you can't send body too in one step,
291                          * this is mandated by changes in HTTP2
292                          */
293
294                         *p = '\0';
295                         lwsl_info("%s\n", buffer + LWS_PRE);
296
297                         n = lws_write(wsi, buffer + LWS_PRE,
298                                       p - (buffer + LWS_PRE),
299                                       LWS_WRITE_HTTP_HEADERS);
300                         if (n < 0) {
301                                 lws_plat_file_close(wsi, pss->fd);
302                                 return -1;
303                         }
304                         /*
305                          * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
306                          */
307                         lws_callback_on_writable(wsi);
308                         break;
309                 }
310
311                 /* if not, send a file the easy way */
312                 strcpy(buf, resource_path);
313                 if (strcmp(in, "/")) {
314                         if (*((const char *)in) != '/')
315                                 strcat(buf, "/");
316                         strncat(buf, in, sizeof(buf) - strlen(resource_path));
317                 } else /* default file to serve */
318                         strcat(buf, "/test.html");
319                 buf[sizeof(buf) - 1] = '\0';
320
321                 /* refuse to serve files we don't understand */
322                 mimetype = get_mimetype(buf);
323                 if (!mimetype) {
324                         lwsl_err("Unknown mimetype for %s\n", buf);
325                         lws_return_http_status(wsi,
326                                       HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
327                         return -1;
328                 }
329
330                 /* demonstrates how to set a cookie on / */
331
332                 other_headers = leaf_path;
333                 p = (unsigned char *)leaf_path;
334                 if (!strcmp((const char *)in, "/") &&
335                            !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
336                         /* this isn't very unguessable but it'll do for us */
337                         gettimeofday(&tv, NULL);
338                         n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
339                                 (unsigned int)tv.tv_sec,
340                                 (unsigned int)tv.tv_usec);
341
342                         if (lws_add_http_header_by_name(wsi,
343                                 (unsigned char *)"set-cookie:",
344                                 (unsigned char *)b64, n, &p,
345                                 (unsigned char *)leaf_path + sizeof(leaf_path)))
346                                 return 1;
347                 }
348                 if (lws_is_ssl(wsi) && lws_add_http_header_by_name(wsi,
349                                                 (unsigned char *)
350                                                 "Strict-Transport-Security:",
351                                                 (unsigned char *)
352                                                 "max-age=15768000 ; "
353                                                 "includeSubDomains", 36, &p,
354                                                 (unsigned char *)leaf_path +
355                                                         sizeof(leaf_path)))
356                         return 1;
357                 n = (char *)p - leaf_path;
358
359                 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
360                 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
361                         return -1; /* error or can't reuse connection: close the socket */
362
363                 /*
364                  * notice that the sending of the file completes asynchronously,
365                  * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
366                  * it's done
367                  */
368                 break;
369
370         case LWS_CALLBACK_HTTP_BODY:
371                 strncpy(buf, in, 20);
372                 buf[20] = '\0';
373                 if (len < 20)
374                         buf[len] = '\0';
375
376                 lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
377                                 (const char *)buf, (int)len);
378
379                 break;
380
381         case LWS_CALLBACK_HTTP_BODY_COMPLETION:
382                 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
383                 /* the whole of the sent body arrived, close or reuse the connection */
384                 lws_return_http_status(wsi, HTTP_STATUS_OK, NULL);
385                 goto try_to_reuse;
386
387         case LWS_CALLBACK_HTTP_FILE_COMPLETION:
388                 goto try_to_reuse;
389
390         case LWS_CALLBACK_HTTP_WRITEABLE:
391                 lwsl_info("LWS_CALLBACK_HTTP_WRITEABLE\n");
392
393                 if (pss->client_finished)
394                         return -1;
395
396                 if (pss->fd == LWS_INVALID_FILE)
397                         goto try_to_reuse;
398 #ifdef LWS_WITH_CGI
399                 if (pss->reason_bf) {
400                         if (lws_cgi_write_split_stdout_headers(wsi) < 0)
401                                 goto bail;
402
403                         pss->reason_bf = 0;
404                         break;
405                 }
406 #endif
407                 /*
408                  * we can send more of whatever it is we were sending
409                  */
410                 sent = 0;
411                 do {
412                         /* we'd like the send this much */
413                         n = sizeof(buffer) - LWS_PRE;
414
415                         /* but if the peer told us he wants less, we can adapt */
416                         m = lws_get_peer_write_allowance(wsi);
417
418                         /* -1 means not using a protocol that has this info */
419                         if (m == 0)
420                                 /* right now, peer can't handle anything */
421                                 goto later;
422
423                         if (m != -1 && m < n)
424                                 /* he couldn't handle that much */
425                                 n = m;
426
427                         n = lws_plat_file_read(wsi, pss->fd,
428                                                &amount, buffer + LWS_PRE, n);
429                         /* problem reading, close conn */
430                         if (n < 0) {
431                                 lwsl_err("problem reading file\n");
432                                 goto bail;
433                         }
434                         n = (int)amount;
435                         /* sent it all, close conn */
436                         if (n == 0)
437                                 goto penultimate;
438                         /*
439                          * To support HTTP2, must take care about preamble space
440                          *
441                          * identification of when we send the last payload frame
442                          * is handled by the library itself if you sent a
443                          * content-length header
444                          */
445                         m = lws_write(wsi, buffer + LWS_PRE, n, LWS_WRITE_HTTP);
446                         if (m < 0) {
447                                 lwsl_err("write failed\n");
448                                 /* write failed, close conn */
449                                 goto bail;
450                         }
451                         if (m) /* while still active, extend timeout */
452                                 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, 5);
453                         sent += m;
454
455                 } while (!lws_send_pipe_choked(wsi) && (sent < 1024 * 1024));
456 later:
457                 lws_callback_on_writable(wsi);
458                 break;
459 penultimate:
460                 lws_plat_file_close(wsi, pss->fd);
461                 pss->fd = LWS_INVALID_FILE;
462                 goto try_to_reuse;
463
464 bail:
465                 lws_plat_file_close(wsi, pss->fd);
466
467                 return -1;
468
469         /*
470          * callback for confirming to continue with client IP appear in
471          * protocol 0 callback since no websocket protocol has been agreed
472          * yet.  You can just ignore this if you won't filter on client IP
473          * since the default uhandled callback return is 0 meaning let the
474          * connection continue.
475          */
476         case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
477                 /* if we returned non-zero from here, we kill the connection */
478                 break;
479
480 #ifndef LWS_WITH_CLIENT
481         case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP:
482                 p = buffer + LWS_PRE;
483                 end = p + sizeof(buffer) - LWS_PRE;
484                 if (lws_add_http_header_status(lws_get_parent(wsi), 200, &p, end))
485                         return 1;
486                 if (lws_add_http_header_by_token(lws_get_parent(wsi),
487                                 WSI_TOKEN_HTTP_SERVER,
488                                 (unsigned char *)"libwebsockets",
489                                 13, &p, end))
490                         return 1;
491                 if (lws_add_http_header_by_token(lws_get_parent(wsi),
492                                 WSI_TOKEN_HTTP_CONTENT_TYPE,
493                                 (unsigned char *)"text/html", 9, &p, end))
494                         return 1;
495 #if 0
496                 if (lws_add_http_header_content_length(lws_get_parent(wsi),
497                                                        file_len, &p,
498                                                        end))
499                         return 1;
500 #endif
501                 if (lws_finalize_http_header(lws_get_parent(wsi), &p, end))
502                         return 1;
503
504                 *p = '\0';
505                 lwsl_info("%s\n", buffer + LWS_PRE);
506
507                 n = lws_write(lws_get_parent(wsi), buffer + LWS_PRE,
508                               p - (buffer + LWS_PRE),
509                               LWS_WRITE_HTTP_HEADERS);
510                 if (n < 0)
511                         return -1;
512
513                 break;
514         case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
515                 return -1;
516                 break;
517         case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
518                 m = lws_write(lws_get_parent(wsi), in, len, LWS_WRITE_HTTP);
519                 if (m < 0)
520                         return 1;
521                 break;
522         case LWS_CALLBACK_COMPLETED_CLIENT_HTTP:
523                 pss1 = lws_wsi_user(lws_get_parent(wsi));
524                 pss1->client_finished = 1;
525                 lws_callback_on_writable(lws_get_parent(wsi));
526                 return -1;
527                 break;
528 #endif
529
530 #ifdef LWS_WITH_CGI
531         /* CGI IO events (POLLIN/OUT) appear here our demo user code policy is
532          *
533          *  - POST data goes on subprocess stdin
534          *  - subprocess stdout goes on http via writeable callback
535          *  - subprocess stderr goes to the logs
536          */
537         case LWS_CALLBACK_CGI:
538                 pss->args = *((struct lws_cgi_args *)in);
539                 //lwsl_notice("LWS_CALLBACK_CGI: ch %d\n", pss->args.ch);
540                 switch (pss->args.ch) { /* which of stdin/out/err ? */
541                 case LWS_STDIN:
542                         /* TBD stdin rx flow control */
543                         break;
544                 case LWS_STDOUT:
545                         pss->reason_bf |= 1 << pss->args.ch;
546                         /* when writing to MASTER would not block */
547                         lws_callback_on_writable(wsi);
548                         break;
549                 case LWS_STDERR:
550                         n = read(lws_get_socket_fd(pss->args.stdwsi[LWS_STDERR]),
551                                         buf, 127);
552                         //lwsl_notice("stderr reads %d\n", n);
553                         if (n > 0) {
554                                 if (buf[n - 1] != '\n')
555                                         buf[n++] = '\n';
556                                 buf[n] = '\0';
557                                 lwsl_notice("CGI-stderr: %s\n", buf);
558                         }
559                         break;
560                 }
561                 break;
562
563         case LWS_CALLBACK_CGI_TERMINATED:
564                 lwsl_notice("LWS_CALLBACK_CGI_TERMINATED\n");
565                 /* because we sent on openended http, close the connection */
566                 return -1;
567
568         case LWS_CALLBACK_CGI_STDIN_DATA:  /* POST body for stdin */
569                 lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA\n");
570                 pss->args = *((struct lws_cgi_args *)in);
571                 n = write(lws_get_socket_fd(pss->args.stdwsi[LWS_STDIN]),
572                           pss->args.data, pss->args.len);
573                 lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: write says %d", n);
574                 if (n < pss->args.len)
575                         lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: sent %d only %d went",
576                                         n, pss->args.len);
577                 return n;
578 #endif
579
580         /*
581          * callbacks for managing the external poll() array appear in
582          * protocol 0 callback
583          */
584
585         case LWS_CALLBACK_LOCK_POLL:
586                 /*
587                  * lock mutex to protect pollfd state
588                  * called before any other POLL related callback
589                  * if protecting wsi lifecycle change, len == 1
590                  */
591                 test_server_lock(len);
592                 break;
593
594         case LWS_CALLBACK_UNLOCK_POLL:
595                 /*
596                  * unlock mutex to protect pollfd state when
597                  * called after any other POLL related callback
598                  * if protecting wsi lifecycle change, len == 1
599                  */
600                 test_server_unlock(len);
601                 break;
602
603 #ifdef EXTERNAL_POLL
604         case LWS_CALLBACK_ADD_POLL_FD:
605
606                 if (count_pollfds >= max_poll_elements) {
607                         lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
608                         return 1;
609                 }
610
611                 fd_lookup[pa->fd] = count_pollfds;
612                 pollfds[count_pollfds].fd = pa->fd;
613                 pollfds[count_pollfds].events = pa->events;
614                 pollfds[count_pollfds++].revents = 0;
615                 break;
616
617         case LWS_CALLBACK_DEL_POLL_FD:
618                 if (!--count_pollfds)
619                         break;
620                 m = fd_lookup[pa->fd];
621                 /* have the last guy take up the vacant slot */
622                 pollfds[m] = pollfds[count_pollfds];
623                 fd_lookup[pollfds[count_pollfds].fd] = m;
624                 break;
625
626         case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
627                 pollfds[fd_lookup[pa->fd]].events = pa->events;
628                 break;
629 #endif
630
631         case LWS_CALLBACK_GET_THREAD_ID:
632                 /*
633                  * if you will call "lws_callback_on_writable"
634                  * from a different thread, return the caller thread ID
635                  * here so lws can use this information to work out if it
636                  * should signal the poll() loop to exit and restart early
637                  */
638
639                 /* return pthread_getthreadid_np(); */
640
641                 break;
642
643         default:
644                 break;
645         }
646
647         return 0;
648
649         /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
650 try_to_reuse:
651         if (lws_http_transaction_completed(wsi))
652                 return -1;
653
654         return 0;
655 }