cgi
[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;
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                 if (len < 1) {
150                         lws_return_http_status(wsi,
151                                                 HTTP_STATUS_BAD_REQUEST, NULL);
152                         goto try_to_reuse;
153                 }
154
155                 /* this example server has no concept of directories */
156                 if (strchr((const char *)in + 1, '/')) {
157                         lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
158                         goto try_to_reuse;
159                 }
160
161 #ifdef LWS_WITH_CGI
162                 if (!strcmp(in, "/cgitest")) {
163                         static char *cmd[] = {
164                                 "/bin/sh",
165                                 "-c",
166                                 INSTALL_DATADIR"/libwebsockets-test-server/lws-cgi-test.sh",
167                                 NULL
168                         };
169
170                         lwsl_notice("%s: cgitest\n", __func__);
171                         n = lws_cgi(wsi, cmd, 5);
172                         if (n) {
173                                 lwsl_err("%s: cgi failed\n");
174                                 return -1;
175                         }
176                         p = buffer + LWS_PRE;
177                         end = p + sizeof(buffer) - LWS_PRE;
178
179                         if (lws_add_http_header_status(wsi, 200, &p, end))
180                                 return 1;
181                         if (lws_add_http_header_by_token(wsi,
182                                         WSI_TOKEN_HTTP_CONTENT_TYPE,
183                                         (unsigned char *)"text/plain",
184                                         10, &p, end))
185                                 return 1;
186                         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
187                                         (unsigned char *)"close", 5, &p, end))
188                                 return 1;
189                         if (lws_finalize_http_header(wsi, &p, end))
190                                 return 1;
191                         n = lws_write(wsi, buffer + LWS_PRE,
192                                       p - (buffer + LWS_PRE),
193                                       LWS_WRITE_HTTP_HEADERS);
194                         break;
195                 }
196 #endif
197
198                 /* if a legal POST URL, let it continue and accept data */
199                 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
200                         return 0;
201
202                 /* check for the "send a big file by hand" example case */
203
204                 if (!strcmp((const char *)in, "/leaf.jpg")) {
205                         if (strlen(resource_path) > sizeof(leaf_path) - 10)
206                                 return -1;
207                         sprintf(leaf_path, "%s/leaf.jpg", resource_path);
208
209                         /* well, let's demonstrate how to send the hard way */
210
211                         p = buffer + LWS_PRE;
212                         end = p + sizeof(buffer) - LWS_PRE;
213
214                         pss->fd = lws_plat_file_open(wsi, leaf_path, &file_len,
215                                                      LWS_O_RDONLY);
216
217                         if (pss->fd == LWS_INVALID_FILE) {
218                                 lwsl_err("faild to open file %s\n", leaf_path);
219                                 return -1;
220                         }
221
222                         /*
223                          * we will send a big jpeg file, but it could be
224                          * anything.  Set the Content-Type: appropriately
225                          * so the browser knows what to do with it.
226                          *
227                          * Notice we use the APIs to build the header, which
228                          * will do the right thing for HTTP 1/1.1 and HTTP2
229                          * depending on what connection it happens to be working
230                          * on
231                          */
232                         if (lws_add_http_header_status(wsi, 200, &p, end))
233                                 return 1;
234                         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
235                                         (unsigned char *)"libwebsockets",
236                                         13, &p, end))
237                                 return 1;
238                         if (lws_add_http_header_by_token(wsi,
239                                         WSI_TOKEN_HTTP_CONTENT_TYPE,
240                                         (unsigned char *)"image/jpeg",
241                                         10, &p, end))
242                                 return 1;
243                         if (lws_add_http_header_content_length(wsi,
244                                                                file_len, &p,
245                                                                end))
246                                 return 1;
247                         if (lws_finalize_http_header(wsi, &p, end))
248                                 return 1;
249
250                         /*
251                          * send the http headers...
252                          * this won't block since it's the first payload sent
253                          * on the connection since it was established
254                          * (too small for partial)
255                          *
256                          * Notice they are sent using LWS_WRITE_HTTP_HEADERS
257                          * which also means you can't send body too in one step,
258                          * this is mandated by changes in HTTP2
259                          */
260
261                         *p = '\0';
262                         lwsl_info("%s\n", buffer + LWS_PRE);
263
264                         n = lws_write(wsi, buffer + LWS_PRE,
265                                       p - (buffer + LWS_PRE),
266                                       LWS_WRITE_HTTP_HEADERS);
267                         if (n < 0) {
268                                 lws_plat_file_close(wsi, pss->fd);
269                                 return -1;
270                         }
271                         /*
272                          * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
273                          */
274                         lws_callback_on_writable(wsi);
275                         break;
276                 }
277
278                 /* if not, send a file the easy way */
279                 strcpy(buf, resource_path);
280                 if (strcmp(in, "/")) {
281                         if (*((const char *)in) != '/')
282                                 strcat(buf, "/");
283                         strncat(buf, in, sizeof(buf) - strlen(resource_path));
284                 } else /* default file to serve */
285                         strcat(buf, "/test.html");
286                 buf[sizeof(buf) - 1] = '\0';
287
288                 /* refuse to serve files we don't understand */
289                 mimetype = get_mimetype(buf);
290                 if (!mimetype) {
291                         lwsl_err("Unknown mimetype for %s\n", buf);
292                         lws_return_http_status(wsi,
293                                       HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
294                         return -1;
295                 }
296
297                 /* demonstrates how to set a cookie on / */
298
299                 other_headers = leaf_path;
300                 p = (unsigned char *)leaf_path;
301                 if (!strcmp((const char *)in, "/") &&
302                            !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
303                         /* this isn't very unguessable but it'll do for us */
304                         gettimeofday(&tv, NULL);
305                         n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
306                                 (unsigned int)tv.tv_sec,
307                                 (unsigned int)tv.tv_usec);
308
309                         if (lws_add_http_header_by_name(wsi,
310                                 (unsigned char *)"set-cookie:",
311                                 (unsigned char *)b64, n, &p,
312                                 (unsigned char *)leaf_path + sizeof(leaf_path)))
313                                 return 1;
314                 }
315                 if (lws_is_ssl(wsi) && lws_add_http_header_by_name(wsi,
316                                                 (unsigned char *)
317                                                 "Strict-Transport-Security:",
318                                                 (unsigned char *)
319                                                 "max-age=15768000 ; "
320                                                 "includeSubDomains", 36, &p,
321                                                 (unsigned char *)leaf_path +
322                                                         sizeof(leaf_path)))
323                         return 1;
324                 n = (char *)p - leaf_path;
325
326                 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
327                 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
328                         return -1; /* error or can't reuse connection: close the socket */
329
330                 /*
331                  * notice that the sending of the file completes asynchronously,
332                  * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
333                  * it's done
334                  */
335                 break;
336
337         case LWS_CALLBACK_HTTP_BODY:
338                 strncpy(buf, in, 20);
339                 buf[20] = '\0';
340                 if (len < 20)
341                         buf[len] = '\0';
342
343                 lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
344                                 (const char *)buf, (int)len);
345
346                 break;
347
348         case LWS_CALLBACK_HTTP_BODY_COMPLETION:
349                 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
350                 /* the whole of the sent body arrived, close or reuse the connection */
351                 lws_return_http_status(wsi, HTTP_STATUS_OK, NULL);
352                 goto try_to_reuse;
353
354         case LWS_CALLBACK_HTTP_FILE_COMPLETION:
355                 goto try_to_reuse;
356
357         case LWS_CALLBACK_HTTP_WRITEABLE:
358                 lwsl_info("LWS_CALLBACK_HTTP_WRITEABLE\n");
359
360                 if (pss->fd == LWS_INVALID_FILE)
361                         goto try_to_reuse;
362 #ifdef LWS_WITH_CGI
363                 if (pss->reason_bf) {
364                         lwsl_debug("%s: stdout\n", __func__);
365                         n = read(lws_get_socket_fd(pss->args.stdwsi[LWS_STDOUT]),
366                                         buf + LWS_PRE, sizeof(buf) - LWS_PRE);
367                         //lwsl_notice("read %d (errno %d)\n", n, errno);
368                         if (n < 0 && errno != EAGAIN)
369                                 return -1;
370                         if (n > 0) {
371                                 m = lws_write(wsi, (unsigned char *)buf + LWS_PRE, n,
372                                               LWS_WRITE_HTTP);
373                                 //lwsl_notice("write %d\n", m);
374                                 if (m < 0)
375                                         goto bail;
376                                 pss->reason_bf = 0;
377                         }
378                         break;
379                 }
380 #endif
381                 /*
382                  * we can send more of whatever it is we were sending
383                  */
384                 sent = 0;
385                 do {
386                         /* we'd like the send this much */
387                         n = sizeof(buffer) - LWS_PRE;
388
389                         /* but if the peer told us he wants less, we can adapt */
390                         m = lws_get_peer_write_allowance(wsi);
391
392                         /* -1 means not using a protocol that has this info */
393                         if (m == 0)
394                                 /* right now, peer can't handle anything */
395                                 goto later;
396
397                         if (m != -1 && m < n)
398                                 /* he couldn't handle that much */
399                                 n = m;
400
401                         n = lws_plat_file_read(wsi, pss->fd,
402                                                &amount, buffer + LWS_PRE, n);
403                         /* problem reading, close conn */
404                         if (n < 0) {
405                                 lwsl_err("problem reading file\n");
406                                 goto bail;
407                         }
408                         n = (int)amount;
409                         /* sent it all, close conn */
410                         if (n == 0)
411                                 goto penultimate;
412                         /*
413                          * To support HTTP2, must take care about preamble space
414                          *
415                          * identification of when we send the last payload frame
416                          * is handled by the library itself if you sent a
417                          * content-length header
418                          */
419                         m = lws_write(wsi, buffer + LWS_PRE, n, LWS_WRITE_HTTP);
420                         if (m < 0) {
421                                 lwsl_err("write failed\n");
422                                 /* write failed, close conn */
423                                 goto bail;
424                         }
425                         if (m) /* while still active, extend timeout */
426                                 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, 5);
427                         sent += m;
428
429                 } while (!lws_send_pipe_choked(wsi) && (sent < 1024 * 1024));
430 later:
431                 lws_callback_on_writable(wsi);
432                 break;
433 penultimate:
434                 lws_plat_file_close(wsi, pss->fd);
435                 pss->fd = LWS_INVALID_FILE;
436                 goto try_to_reuse;
437
438 bail:
439                 lws_plat_file_close(wsi, pss->fd);
440
441                 return -1;
442
443         /*
444          * callback for confirming to continue with client IP appear in
445          * protocol 0 callback since no websocket protocol has been agreed
446          * yet.  You can just ignore this if you won't filter on client IP
447          * since the default uhandled callback return is 0 meaning let the
448          * connection continue.
449          */
450         case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
451                 /* if we returned non-zero from here, we kill the connection */
452                 break;
453
454 #ifdef LWS_WITH_CGI
455         /* CGI IO events (POLLIN/OUT) appear here our demo user code policy is
456          *
457          *  - POST data goes on subprocess stdin
458          *  - subprocess stdout goes on http via writeable callback
459          *  - subprocess stderr goes to the logs
460          */
461         case LWS_CALLBACK_CGI:
462                 pss->args = *((struct lws_cgi_args *)in);
463                 //lwsl_notice("LWS_CALLBACK_CGI: ch %d\n", pss->args.ch);
464                 switch (pss->args.ch) { /* which of stdin/out/err ? */
465                 case LWS_STDIN:
466                         /* TBD stdin rx flow control */
467                         break;
468                 case LWS_STDOUT:
469                         pss->reason_bf |= 1 << pss->args.ch;
470                         /* when writing to MASTER would not block */
471                         lws_callback_on_writable(wsi);
472                         break;
473                 case LWS_STDERR:
474                         n = read(lws_get_socket_fd(pss->args.stdwsi[LWS_STDERR]),
475                                         buf, 127);
476                         //lwsl_notice("stderr reads %d\n", n);
477                         if (n > 0) {
478                                 if (buf[n - 1] != '\n')
479                                         buf[n++] = '\n';
480                                 buf[n] = '\0';
481                                 lwsl_notice("CGI-stderr: %s\n", buf);
482                         }
483                         break;
484                 }
485                 break;
486
487         case LWS_CALLBACK_CGI_TERMINATED:
488                 lwsl_notice("LWS_CALLBACK_CGI_TERMINATED\n");
489                 /* because we sent on openended http, close the connection */
490                 return -1;
491
492         case LWS_CALLBACK_CGI_STDIN_DATA:  /* POST body for stdin */
493                 lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA\n");
494                 pss->args = *((struct lws_cgi_args *)in);
495                 n = write(lws_get_socket_fd(pss->args.stdwsi[LWS_STDIN]),
496                           pss->args.data, pss->args.len);
497                 lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: write says %d", n);
498                 if (n < pss->args.len)
499                         lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: sent %d only %d went",
500                                         n, pss->args.len);
501                 return n;
502 #endif
503
504         /*
505          * callbacks for managing the external poll() array appear in
506          * protocol 0 callback
507          */
508
509         case LWS_CALLBACK_LOCK_POLL:
510                 /*
511                  * lock mutex to protect pollfd state
512                  * called before any other POLL related callback
513                  * if protecting wsi lifecycle change, len == 1
514                  */
515                 test_server_lock(len);
516                 break;
517
518         case LWS_CALLBACK_UNLOCK_POLL:
519                 /*
520                  * unlock mutex to protect pollfd state when
521                  * called after any other POLL related callback
522                  * if protecting wsi lifecycle change, len == 1
523                  */
524                 test_server_unlock(len);
525                 break;
526
527 #ifdef EXTERNAL_POLL
528         case LWS_CALLBACK_ADD_POLL_FD:
529
530                 if (count_pollfds >= max_poll_elements) {
531                         lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
532                         return 1;
533                 }
534
535                 fd_lookup[pa->fd] = count_pollfds;
536                 pollfds[count_pollfds].fd = pa->fd;
537                 pollfds[count_pollfds].events = pa->events;
538                 pollfds[count_pollfds++].revents = 0;
539                 break;
540
541         case LWS_CALLBACK_DEL_POLL_FD:
542                 if (!--count_pollfds)
543                         break;
544                 m = fd_lookup[pa->fd];
545                 /* have the last guy take up the vacant slot */
546                 pollfds[m] = pollfds[count_pollfds];
547                 fd_lookup[pollfds[count_pollfds].fd] = m;
548                 break;
549
550         case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
551                 pollfds[fd_lookup[pa->fd]].events = pa->events;
552                 break;
553 #endif
554
555         case LWS_CALLBACK_GET_THREAD_ID:
556                 /*
557                  * if you will call "lws_callback_on_writable"
558                  * from a different thread, return the caller thread ID
559                  * here so lws can use this information to work out if it
560                  * should signal the poll() loop to exit and restart early
561                  */
562
563                 /* return pthread_getthreadid_np(); */
564
565                 break;
566
567         default:
568                 break;
569         }
570
571         return 0;
572
573         /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
574 try_to_reuse:
575         if (lws_http_transaction_completed(wsi))
576                 return -1;
577
578         return 0;
579 }