lwsws cgi integration
[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         if (!strcmp(&file[n - 4], ".css"))
108                 return "text/css";
109
110         return NULL;
111 }
112
113 /* this protocol server (always the first one) handles HTTP,
114  *
115  * Some misc callbacks that aren't associated with a protocol also turn up only
116  * here on the first protocol server.
117  */
118
119 int callback_http(struct lws *wsi, enum lws_callback_reasons reason, void *user,
120                   void *in, size_t len)
121 {
122         struct per_session_data__http *pss =
123                         (struct per_session_data__http *)user;
124         unsigned char buffer[4096 + LWS_PRE];
125         unsigned long amount, file_len, sent;
126         char leaf_path[1024];
127         const char *mimetype;
128         char *other_headers;
129         unsigned char *end;
130         struct timeval tv;
131         unsigned char *p;
132 #ifndef LWS_NO_CLIENT
133         struct per_session_data__http *pss1;
134         struct lws *wsi1;
135 #endif
136         char buf[256];
137         char b64[64];
138         int n, m;
139 #ifdef EXTERNAL_POLL
140         struct lws_pollargs *pa = (struct lws_pollargs *)in;
141 #endif
142
143
144         switch (reason) {
145         case LWS_CALLBACK_HTTP:
146
147                 lwsl_notice("lws_http_serve: %s\n",in);
148
149                 if (debug_level & LLL_INFO) {
150                         dump_handshake_info(wsi);
151
152                         /* dump the individual URI Arg parameters */
153                         n = 0;
154                         while (lws_hdr_copy_fragment(wsi, buf, sizeof(buf),
155                                                      WSI_TOKEN_HTTP_URI_ARGS, n) > 0) {
156                                 lwsl_notice("URI Arg %d: %s\n", ++n, buf);
157                         }
158                 }
159
160                 {
161                         char name[100], rip[50];
162                         lws_get_peer_addresses(wsi, lws_get_socket_fd(wsi), name,
163                                                sizeof(name), rip, sizeof(rip));
164                         sprintf(buf, "%s (%s)", name, rip);
165                         lwsl_notice("HTTP connect from %s\n", buf);
166                 }
167
168                 if (len < 1) {
169                         lws_return_http_status(wsi,
170                                                 HTTP_STATUS_BAD_REQUEST, NULL);
171                         goto try_to_reuse;
172                 }
173
174 #ifndef LWS_NO_CLIENT
175                 if (!strncmp(in, "/proxytest", 10)) {
176                         struct lws_client_connect_info i;
177                         char *rootpath = "/";
178                         const char *p = (const char *)in;
179
180                         if (lws_get_child(wsi))
181                                 break;
182
183                         pss->client_finished = 0;
184                         memset(&i,0, sizeof(i));
185                         i.context = lws_get_context(wsi);
186                         i.address = "git.libwebsockets.org";
187                         i.port = 80;
188                         i.ssl_connection = 0;
189                         if (p[10])
190                                 i.path = (char *)in + 10;
191                         else
192                                 i.path = rootpath;
193                         i.host = "git.libwebsockets.org";
194                         i.origin = NULL;
195                         i.method = "GET";
196                         i.parent_wsi = wsi;
197                         i.uri_replace_from = "git.libwebsockets.org/";
198                         i.uri_replace_to = "/proxytest/";
199                         if (!lws_client_connect_via_info(&i)) {
200                                 lwsl_err("proxy connect fail\n");
201                                 break;
202                         }
203
204
205
206                         break;
207                 }
208 #endif
209
210 #if 1
211                 /* this example server has no concept of directories */
212                 if (strchr((const char *)in + 1, '/')) {
213                         lws_return_http_status(wsi, HTTP_STATUS_NOT_ACCEPTABLE, NULL);
214                         goto try_to_reuse;
215                 }
216 #endif
217
218                 /* if a legal POST URL, let it continue and accept data */
219                 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
220                         return 0;
221
222                 /* check for the "send a big file by hand" example case */
223
224                 if (!strcmp((const char *)in, "/leaf.jpg")) {
225                         if (strlen(resource_path) > sizeof(leaf_path) - 10)
226                                 return -1;
227                         sprintf(leaf_path, "%s/leaf.jpg", resource_path);
228
229                         /* well, let's demonstrate how to send the hard way */
230
231                         p = buffer + LWS_PRE;
232                         end = p + sizeof(buffer) - LWS_PRE;
233
234                         pss->fd = lws_plat_file_open(wsi, leaf_path, &file_len,
235                                                      LWS_O_RDONLY);
236
237                         if (pss->fd == LWS_INVALID_FILE) {
238                                 lwsl_err("faild to open file %s\n", leaf_path);
239                                 return -1;
240                         }
241
242                         /*
243                          * we will send a big jpeg file, but it could be
244                          * anything.  Set the Content-Type: appropriately
245                          * so the browser knows what to do with it.
246                          *
247                          * Notice we use the APIs to build the header, which
248                          * will do the right thing for HTTP 1/1.1 and HTTP2
249                          * depending on what connection it happens to be working
250                          * on
251                          */
252                         if (lws_add_http_header_status(wsi, 200, &p, end))
253                                 return 1;
254                         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
255                                         (unsigned char *)"libwebsockets",
256                                         13, &p, end))
257                                 return 1;
258                         if (lws_add_http_header_by_token(wsi,
259                                         WSI_TOKEN_HTTP_CONTENT_TYPE,
260                                         (unsigned char *)"image/jpeg",
261                                         10, &p, end))
262                                 return 1;
263                         if (lws_add_http_header_content_length(wsi,
264                                                                file_len, &p,
265                                                                end))
266                                 return 1;
267                         if (lws_finalize_http_header(wsi, &p, end))
268                                 return 1;
269
270                         /*
271                          * send the http headers...
272                          * this won't block since it's the first payload sent
273                          * on the connection since it was established
274                          * (too small for partial)
275                          *
276                          * Notice they are sent using LWS_WRITE_HTTP_HEADERS
277                          * which also means you can't send body too in one step,
278                          * this is mandated by changes in HTTP2
279                          */
280
281                         *p = '\0';
282                         lwsl_info("%s\n", buffer + LWS_PRE);
283
284                         n = lws_write(wsi, buffer + LWS_PRE,
285                                       p - (buffer + LWS_PRE),
286                                       LWS_WRITE_HTTP_HEADERS);
287                         if (n < 0) {
288                                 lws_plat_file_close(wsi, pss->fd);
289                                 return -1;
290                         }
291                         /*
292                          * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
293                          */
294                         lws_callback_on_writable(wsi);
295                         break;
296                 }
297
298                 /* if not, send a file the easy way */
299                 if (!strncmp(in, "/cgit-data/", 11)) {
300                         in = (char *)in + 11;
301                         strcpy(buf, "/usr/share/cgit");
302                 } else
303                         strcpy(buf, resource_path);
304
305                 if (strcmp(in, "/")) {
306                         if (*((const char *)in) != '/')
307                                 strcat(buf, "/");
308                         strncat(buf, in, sizeof(buf) - strlen(buf) - 1);
309                 } else /* default file to serve */
310                         strcat(buf, "/test.html");
311                 buf[sizeof(buf) - 1] = '\0';
312
313                 /* refuse to serve files we don't understand */
314                 mimetype = get_mimetype(buf);
315                 if (!mimetype) {
316                         lwsl_err("Unknown mimetype for %s\n", buf);
317                         lws_return_http_status(wsi,
318                                       HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
319                         return -1;
320                 }
321
322                 /* demonstrates how to set a cookie on / */
323
324                 other_headers = leaf_path;
325                 p = (unsigned char *)leaf_path;
326                 if (!strcmp((const char *)in, "/") &&
327                            !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
328                         /* this isn't very unguessable but it'll do for us */
329                         gettimeofday(&tv, NULL);
330                         n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
331                                 (unsigned int)tv.tv_sec,
332                                 (unsigned int)tv.tv_usec);
333
334                         if (lws_add_http_header_by_name(wsi,
335                                 (unsigned char *)"set-cookie:",
336                                 (unsigned char *)b64, n, &p,
337                                 (unsigned char *)leaf_path + sizeof(leaf_path)))
338                                 return 1;
339                 }
340                 if (lws_is_ssl(wsi) && lws_add_http_header_by_name(wsi,
341                                                 (unsigned char *)
342                                                 "Strict-Transport-Security:",
343                                                 (unsigned char *)
344                                                 "max-age=15768000 ; "
345                                                 "includeSubDomains", 36, &p,
346                                                 (unsigned char *)leaf_path +
347                                                         sizeof(leaf_path)))
348                         return 1;
349                 n = (char *)p - leaf_path;
350
351                 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
352                 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
353                         return -1; /* error or can't reuse connection: close the socket */
354
355                 /*
356                  * notice that the sending of the file completes asynchronously,
357                  * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
358                  * it's done
359                  */
360                 break;
361
362         case LWS_CALLBACK_HTTP_BODY:
363                 strncpy(buf, in, 20);
364                 buf[20] = '\0';
365                 if (len < 20)
366                         buf[len] = '\0';
367
368                 lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
369                                 (const char *)buf, (int)len);
370
371                 break;
372
373         case LWS_CALLBACK_HTTP_BODY_COMPLETION:
374                 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
375                 /* the whole of the sent body arrived, close or reuse the connection */
376                 lws_return_http_status(wsi, HTTP_STATUS_OK, NULL);
377                 goto try_to_reuse;
378
379         case LWS_CALLBACK_HTTP_FILE_COMPLETION:
380                 goto try_to_reuse;
381
382         case LWS_CALLBACK_HTTP_WRITEABLE:
383                 lwsl_info("LWS_CALLBACK_HTTP_WRITEABLE\n");
384
385                 if (pss->client_finished)
386                         return -1;
387
388                 if (pss->fd == LWS_INVALID_FILE)
389                         goto try_to_reuse;
390
391 #ifndef LWS_NO_CLIENT
392                 if (pss->reason_bf & 2) {
393                         char *px = buf + LWS_PRE;
394                         int lenx = sizeof(buf) - LWS_PRE;
395                         /*
396                          * our sink is writeable and our source has something
397                          * to read.  So read a lump of source material of
398                          * suitable size to send or what's available, whichever
399                          * is the smaller.
400                          */
401                         pss->reason_bf &= ~2;
402                         wsi1 = lws_get_child(wsi);
403                         if (!wsi1)
404                                 break;
405                         if (lws_http_client_read(wsi1, &px, &lenx) < 0)
406                                 goto bail;
407
408                         if (pss->client_finished)
409                                 return -1;
410                         break;
411                 }
412 #endif
413                 /*
414                  * we can send more of whatever it is we were sending
415                  */
416                 sent = 0;
417                 do {
418                         /* we'd like the send this much */
419                         n = sizeof(buffer) - LWS_PRE;
420
421                         /* but if the peer told us he wants less, we can adapt */
422                         m = lws_get_peer_write_allowance(wsi);
423
424                         /* -1 means not using a protocol that has this info */
425                         if (m == 0)
426                                 /* right now, peer can't handle anything */
427                                 goto later;
428
429                         if (m != -1 && m < n)
430                                 /* he couldn't handle that much */
431                                 n = m;
432
433                         n = lws_plat_file_read(wsi, pss->fd,
434                                                &amount, buffer + LWS_PRE, n);
435                         /* problem reading, close conn */
436                         if (n < 0) {
437                                 lwsl_err("problem reading file\n");
438                                 goto bail;
439                         }
440                         n = (int)amount;
441                         /* sent it all, close conn */
442                         if (n == 0)
443                                 goto penultimate;
444                         /*
445                          * To support HTTP2, must take care about preamble space
446                          *
447                          * identification of when we send the last payload frame
448                          * is handled by the library itself if you sent a
449                          * content-length header
450                          */
451                         m = lws_write(wsi, buffer + LWS_PRE, n, LWS_WRITE_HTTP);
452                         if (m < 0) {
453                                 lwsl_err("write failed\n");
454                                 /* write failed, close conn */
455                                 goto bail;
456                         }
457                         if (m) /* while still active, extend timeout */
458                                 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, 5);
459                         sent += m;
460
461                 } while (!lws_send_pipe_choked(wsi) && (sent < 1024 * 1024));
462 later:
463                 lws_callback_on_writable(wsi);
464                 break;
465 penultimate:
466                 lws_plat_file_close(wsi, pss->fd);
467                 pss->fd = LWS_INVALID_FILE;
468                 goto try_to_reuse;
469
470 bail:
471                 lws_plat_file_close(wsi, pss->fd);
472
473                 return -1;
474
475         /*
476          * callback for confirming to continue with client IP appear in
477          * protocol 0 callback since no websocket protocol has been agreed
478          * yet.  You can just ignore this if you won't filter on client IP
479          * since the default unhandled callback return is 0 meaning let the
480          * connection continue.
481          */
482         case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
483                 /* if we returned non-zero from here, we kill the connection */
484                 break;
485
486 #ifndef LWS_NO_CLIENT
487         case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP: {
488                 char ctype[64], ctlen = 0;
489                 lwsl_err("LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP\n");
490                 p = buffer + LWS_PRE;
491                 end = p + sizeof(buffer) - LWS_PRE;
492                 if (lws_add_http_header_status(lws_get_parent(wsi), 200, &p, end))
493                         return 1;
494                 if (lws_add_http_header_by_token(lws_get_parent(wsi),
495                                 WSI_TOKEN_HTTP_SERVER,
496                                 (unsigned char *)"libwebsockets",
497                                 13, &p, end))
498                         return 1;
499
500                 ctlen = lws_hdr_copy(wsi, ctype, sizeof(ctype), WSI_TOKEN_HTTP_CONTENT_TYPE);
501                 if (ctlen > 0) {
502                         if (lws_add_http_header_by_token(lws_get_parent(wsi),
503                                 WSI_TOKEN_HTTP_CONTENT_TYPE,
504                                 (unsigned char *)ctype, ctlen, &p, end))
505                                 return 1;
506                 }
507 #if 0
508                 if (lws_add_http_header_content_length(lws_get_parent(wsi),
509                                                        file_len, &p, end))
510                         return 1;
511 #endif
512                 if (lws_finalize_http_header(lws_get_parent(wsi), &p, end))
513                         return 1;
514
515                 *p = '\0';
516                 lwsl_info("%s\n", buffer + LWS_PRE);
517
518                 n = lws_write(lws_get_parent(wsi), buffer + LWS_PRE,
519                               p - (buffer + LWS_PRE),
520                               LWS_WRITE_HTTP_HEADERS);
521                 if (n < 0)
522                         return -1;
523
524                 break; }
525         case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
526                 //lwsl_err("LWS_CALLBACK_CLOSED_CLIENT_HTTP\n");
527                 return -1;
528                 break;
529         case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
530                 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p\n", wsi);
531                 assert(lws_get_parent(wsi));
532                 if (!lws_get_parent(wsi))
533                         break;
534                 // lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p: sock: %d, parent_wsi: %p, parent_sock:%d,  len %d\n",
535                 //              wsi, lws_get_socket_fd(wsi),
536                 //              lws_get_parent(wsi),
537                 //              lws_get_socket_fd(lws_get_parent(wsi)), len);
538                 pss1 = lws_wsi_user(lws_get_parent(wsi));
539                 pss1->reason_bf |= 2;
540                 lws_callback_on_writable(lws_get_parent(wsi));
541                 break;
542         case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:
543                 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ len %d\n", len);
544                 assert(lws_get_parent(wsi));
545                 m = lws_write(lws_get_parent(wsi), (unsigned char *)in,
546                                 len, LWS_WRITE_HTTP);
547                 if (m < 0)
548                         return -1;
549                 break;
550         case LWS_CALLBACK_COMPLETED_CLIENT_HTTP:
551                 //lwsl_err("LWS_CALLBACK_COMPLETED_CLIENT_HTTP\n");
552                 assert(lws_get_parent(wsi));
553                 if (!lws_get_parent(wsi))
554                         break;
555                 pss1 = lws_wsi_user(lws_get_parent(wsi));
556                 pss1->client_finished = 1;
557                 break;
558 #endif
559
560         /*
561          * callbacks for managing the external poll() array appear in
562          * protocol 0 callback
563          */
564
565         case LWS_CALLBACK_LOCK_POLL:
566                 /*
567                  * lock mutex to protect pollfd state
568                  * called before any other POLL related callback
569                  * if protecting wsi lifecycle change, len == 1
570                  */
571                 test_server_lock(len);
572                 break;
573
574         case LWS_CALLBACK_UNLOCK_POLL:
575                 /*
576                  * unlock mutex to protect pollfd state when
577                  * called after any other POLL related callback
578                  * if protecting wsi lifecycle change, len == 1
579                  */
580                 test_server_unlock(len);
581                 break;
582
583 #ifdef EXTERNAL_POLL
584         case LWS_CALLBACK_ADD_POLL_FD:
585
586                 if (count_pollfds >= max_poll_elements) {
587                         lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
588                         return 1;
589                 }
590
591                 fd_lookup[pa->fd] = count_pollfds;
592                 pollfds[count_pollfds].fd = pa->fd;
593                 pollfds[count_pollfds].events = pa->events;
594                 pollfds[count_pollfds++].revents = 0;
595                 break;
596
597         case LWS_CALLBACK_DEL_POLL_FD:
598                 if (!--count_pollfds)
599                         break;
600                 m = fd_lookup[pa->fd];
601                 /* have the last guy take up the vacant slot */
602                 pollfds[m] = pollfds[count_pollfds];
603                 fd_lookup[pollfds[count_pollfds].fd] = m;
604                 break;
605
606         case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
607                 pollfds[fd_lookup[pa->fd]].events = pa->events;
608                 break;
609 #endif
610
611         case LWS_CALLBACK_GET_THREAD_ID:
612                 /*
613                  * if you will call "lws_callback_on_writable"
614                  * from a different thread, return the caller thread ID
615                  * here so lws can use this information to work out if it
616                  * should signal the poll() loop to exit and restart early
617                  */
618
619                 /* return pthread_getthreadid_np(); */
620
621                 break;
622
623         default:
624                 break;
625         }
626
627         return 0;
628
629         /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
630 try_to_reuse:
631         if (lws_http_transaction_completed(wsi))
632                 return -1;
633
634         return 0;
635 }