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