license clarification and test apps CC zero
[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
133 #ifdef EXTERNAL_POLL
134         struct lws_pollargs *pa = (struct lws_pollargs *)in;
135 #endif
136
137         switch (reason) {
138         case LWS_CALLBACK_HTTP:
139
140                 if (debug_level & LLL_INFO) {
141                         dump_handshake_info(wsi);
142
143                         /* dump the individual URI Arg parameters */
144                         n = 0;
145                         while (lws_hdr_copy_fragment(wsi, buf, sizeof(buf),
146                                                      WSI_TOKEN_HTTP_URI_ARGS, n) > 0) {
147                                 lwsl_notice("URI Arg %d: %s\n", ++n, buf);
148                         }
149                 }
150                 if (len < 1) {
151                         lws_return_http_status(wsi,
152                                                 HTTP_STATUS_BAD_REQUEST, NULL);
153                         goto try_to_reuse;
154                 }
155
156                 /* this example server has no concept of directories */
157                 if (strchr((const char *)in + 1, '/')) {
158                         lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
159                         goto try_to_reuse;
160                 }
161
162                 /* if a legal POST URL, let it continue and accept data */
163                 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
164                         return 0;
165
166                 /* check for the "send a big file by hand" example case */
167
168                 if (!strcmp((const char *)in, "/leaf.jpg")) {
169                         if (strlen(resource_path) > sizeof(leaf_path) - 10)
170                                 return -1;
171                         sprintf(leaf_path, "%s/leaf.jpg", resource_path);
172
173                         /* well, let's demonstrate how to send the hard way */
174
175                         p = buffer + LWS_PRE;
176                         end = p + sizeof(buffer) - LWS_PRE;
177
178                         pss->fd = lws_plat_file_open(wsi, leaf_path, &file_len,
179                                                      LWS_O_RDONLY);
180
181                         if (pss->fd == LWS_INVALID_FILE) {
182                                 lwsl_err("faild to open file %s\n", leaf_path);
183                                 return -1;
184                         }
185
186                         /*
187                          * we will send a big jpeg file, but it could be
188                          * anything.  Set the Content-Type: appropriately
189                          * so the browser knows what to do with it.
190                          *
191                          * Notice we use the APIs to build the header, which
192                          * will do the right thing for HTTP 1/1.1 and HTTP2
193                          * depending on what connection it happens to be working
194                          * on
195                          */
196                         if (lws_add_http_header_status(wsi, 200, &p, end))
197                                 return 1;
198                         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
199                                         (unsigned char *)"libwebsockets",
200                                         13, &p, end))
201                                 return 1;
202                         if (lws_add_http_header_by_token(wsi,
203                                         WSI_TOKEN_HTTP_CONTENT_TYPE,
204                                         (unsigned char *)"image/jpeg",
205                                         10, &p, end))
206                                 return 1;
207                         if (lws_add_http_header_content_length(wsi,
208                                                                file_len, &p,
209                                                                end))
210                                 return 1;
211                         if (lws_finalize_http_header(wsi, &p, end))
212                                 return 1;
213
214                         /*
215                          * send the http headers...
216                          * this won't block since it's the first payload sent
217                          * on the connection since it was established
218                          * (too small for partial)
219                          *
220                          * Notice they are sent using LWS_WRITE_HTTP_HEADERS
221                          * which also means you can't send body too in one step,
222                          * this is mandated by changes in HTTP2
223                          */
224
225                         *p = '\0';
226                         lwsl_info("%s\n", buffer + LWS_PRE);
227
228                         n = lws_write(wsi, buffer + LWS_PRE, p - (buffer + LWS_PRE),
229                                       LWS_WRITE_HTTP_HEADERS);
230                         if (n < 0) {
231                                 lws_plat_file_close(wsi, pss->fd);
232                                 return -1;
233                         }
234                         /*
235                          * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
236                          */
237                         lws_callback_on_writable(wsi);
238                         break;
239                 }
240
241                 /* if not, send a file the easy way */
242                 strcpy(buf, resource_path);
243                 if (strcmp(in, "/")) {
244                         if (*((const char *)in) != '/')
245                                 strcat(buf, "/");
246                         strncat(buf, in, sizeof(buf) - strlen(resource_path));
247                 } else /* default file to serve */
248                         strcat(buf, "/test.html");
249                 buf[sizeof(buf) - 1] = '\0';
250
251                 /* refuse to serve files we don't understand */
252                 mimetype = get_mimetype(buf);
253                 if (!mimetype) {
254                         lwsl_err("Unknown mimetype for %s\n", buf);
255                         lws_return_http_status(wsi,
256                                       HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
257                         return -1;
258                 }
259
260                 /* demonstrates how to set a cookie on / */
261
262                 other_headers = NULL;
263                 n = 0;
264                 if (!strcmp((const char *)in, "/") &&
265                            !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
266                         /* this isn't very unguessable but it'll do for us */
267                         gettimeofday(&tv, NULL);
268                         n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
269                                 (unsigned int)tv.tv_sec,
270                                 (unsigned int)tv.tv_usec);
271
272                         p = (unsigned char *)leaf_path;
273
274                         if (lws_add_http_header_by_name(wsi,
275                                 (unsigned char *)"set-cookie:",
276                                 (unsigned char *)b64, n, &p,
277                                 (unsigned char *)leaf_path + sizeof(leaf_path)))
278                                 return 1;
279                         n = (char *)p - leaf_path;
280                         other_headers = leaf_path;
281                 }
282
283                 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
284                 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
285                         return -1; /* error or can't reuse connection: close the socket */
286
287                 /*
288                  * notice that the sending of the file completes asynchronously,
289                  * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
290                  * it's done
291                  */
292                 break;
293
294         case LWS_CALLBACK_HTTP_BODY:
295                 strncpy(buf, in, 20);
296                 buf[20] = '\0';
297                 if (len < 20)
298                         buf[len] = '\0';
299
300                 lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
301                                 (const char *)buf, (int)len);
302
303                 break;
304
305         case LWS_CALLBACK_HTTP_BODY_COMPLETION:
306                 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
307                 /* the whole of the sent body arrived, close or reuse the connection */
308                 lws_return_http_status(wsi, HTTP_STATUS_OK, NULL);
309                 goto try_to_reuse;
310
311         case LWS_CALLBACK_HTTP_FILE_COMPLETION:
312                 goto try_to_reuse;
313
314         case LWS_CALLBACK_HTTP_WRITEABLE:
315                 lwsl_info("LWS_CALLBACK_HTTP_WRITEABLE\n");
316
317                 if (pss->fd == LWS_INVALID_FILE)
318                         goto try_to_reuse;
319
320                 /*
321                  * we can send more of whatever it is we were sending
322                  */
323                 sent = 0;
324                 do {
325                         /* we'd like the send this much */
326                         n = sizeof(buffer) - LWS_PRE;
327
328                         /* but if the peer told us he wants less, we can adapt */
329                         m = lws_get_peer_write_allowance(wsi);
330
331                         /* -1 means not using a protocol that has this info */
332                         if (m == 0)
333                                 /* right now, peer can't handle anything */
334                                 goto later;
335
336                         if (m != -1 && m < n)
337                                 /* he couldn't handle that much */
338                                 n = m;
339
340                         n = lws_plat_file_read(wsi, pss->fd,
341                                                &amount, buffer + LWS_PRE, n);
342                         /* problem reading, close conn */
343                         if (n < 0) {
344                                 lwsl_err("problem reading file\n");
345                                 goto bail;
346                         }
347                         n = (int)amount;
348                         /* sent it all, close conn */
349                         if (n == 0)
350                                 goto penultimate;
351                         /*
352                          * To support HTTP2, must take care about preamble space
353                          *
354                          * identification of when we send the last payload frame
355                          * is handled by the library itself if you sent a
356                          * content-length header
357                          */
358                         m = lws_write(wsi, buffer + LWS_PRE, n, LWS_WRITE_HTTP);
359                         if (m < 0) {
360                                 lwsl_err("write failed\n");
361                                 /* write failed, close conn */
362                                 goto bail;
363                         }
364                         if (m) /* while still active, extend timeout */
365                                 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, 5);
366                         sent += m;
367
368                 } while (!lws_send_pipe_choked(wsi) && (sent < 1024 * 1024));
369 later:
370                 lws_callback_on_writable(wsi);
371                 break;
372 penultimate:
373                 lws_plat_file_close(wsi, pss->fd);
374                 pss->fd = LWS_INVALID_FILE;
375                 goto try_to_reuse;
376
377 bail:
378                 lws_plat_file_close(wsi, pss->fd);
379
380                 return -1;
381
382         /*
383          * callback for confirming to continue with client IP appear in
384          * protocol 0 callback since no websocket protocol has been agreed
385          * yet.  You can just ignore this if you won't filter on client IP
386          * since the default uhandled callback return is 0 meaning let the
387          * connection continue.
388          */
389         case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
390
391                 /* if we returned non-zero from here, we kill the connection */
392                 break;
393
394         /*
395          * callbacks for managing the external poll() array appear in
396          * protocol 0 callback
397          */
398
399         case LWS_CALLBACK_LOCK_POLL:
400                 /*
401                  * lock mutex to protect pollfd state
402                  * called before any other POLL related callback
403                  * if protecting wsi lifecycle change, len == 1
404                  */
405                 test_server_lock(len);
406                 break;
407
408         case LWS_CALLBACK_UNLOCK_POLL:
409                 /*
410                  * unlock mutex to protect pollfd state when
411                  * called after any other POLL related callback
412                  * if protecting wsi lifecycle change, len == 1
413                  */
414                 test_server_unlock(len);
415                 break;
416
417 #ifdef EXTERNAL_POLL
418         case LWS_CALLBACK_ADD_POLL_FD:
419
420                 if (count_pollfds >= max_poll_elements) {
421                         lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
422                         return 1;
423                 }
424
425                 fd_lookup[pa->fd] = count_pollfds;
426                 pollfds[count_pollfds].fd = pa->fd;
427                 pollfds[count_pollfds].events = pa->events;
428                 pollfds[count_pollfds++].revents = 0;
429                 break;
430
431         case LWS_CALLBACK_DEL_POLL_FD:
432                 if (!--count_pollfds)
433                         break;
434                 m = fd_lookup[pa->fd];
435                 /* have the last guy take up the vacant slot */
436                 pollfds[m] = pollfds[count_pollfds];
437                 fd_lookup[pollfds[count_pollfds].fd] = m;
438                 break;
439
440         case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
441                 pollfds[fd_lookup[pa->fd]].events = pa->events;
442                 break;
443 #endif
444
445         case LWS_CALLBACK_GET_THREAD_ID:
446                 /*
447                  * if you will call "lws_callback_on_writable"
448                  * from a different thread, return the caller thread ID
449                  * here so lws can use this information to work out if it
450                  * should signal the poll() loop to exit and restart early
451                  */
452
453                 /* return pthread_getthreadid_np(); */
454
455                 break;
456
457         default:
458                 break;
459         }
460
461         return 0;
462
463         /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
464 try_to_reuse:
465         if (lws_http_transaction_completed(wsi))
466                 return -1;
467
468         return 0;
469 }