multithread stability
[platform/upstream/libwebsockets.git] / test-server / test-server-http.c
1 /*
2  * libwebsockets-test-server - libwebsockets test implementation
3  *
4  * Copyright (C) 2010-2015 Andy Green <andy@warmcat.com>
5  *
6  *  This library is free software; you can redistribute it and/or
7  *  modify it under the terms of the GNU Lesser General Public
8  *  License as published by the Free Software Foundation:
9  *  version 2.1 of the License.
10  *
11  *  This library is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  *  Lesser General Public License for more details.
15  *
16  *  You should have received a copy of the GNU Lesser General Public
17  *  License along with this library; if not, write to the Free Software
18  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19  *  MA  02110-1301  USA
20  */
21 #include "test-server.h"
22
23 /*
24  * This demo server shows how to use libwebsockets for one or more
25  * websocket protocols in the same server
26  *
27  * It defines the following websocket protocols:
28  *
29  *  dumb-increment-protocol:  once the socket is opened, an incrementing
30  *                              ascii string is sent down it every 50ms.
31  *                              If you send "reset\n" on the websocket, then
32  *                              the incrementing number is reset to 0.
33  *
34  *  lws-mirror-protocol: copies any received packet to every connection also
35  *                              using this protocol, including the sender
36  */
37
38 extern int debug_level;
39
40 enum demo_protocols {
41         /* always first */
42         PROTOCOL_HTTP = 0,
43
44         PROTOCOL_DUMB_INCREMENT,
45         PROTOCOL_LWS_MIRROR,
46
47         /* always last */
48         DEMO_PROTOCOL_COUNT
49 };
50
51 /*
52  * We take a strict whitelist approach to stop ../ attacks
53  */
54 struct serveable {
55         const char *urlpath;
56         const char *mimetype;
57 };
58
59 /*
60  * this is just an example of parsing handshake headers, you don't need this
61  * in your code unless you will filter allowing connections by the header
62  * content
63  */
64 void
65 dump_handshake_info(struct lws *wsi)
66 {
67         int n = 0, len;
68         char buf[256];
69         const unsigned char *c;
70
71         do {
72                 c = lws_token_to_string(n);
73                 if (!c) {
74                         n++;
75                         continue;
76                 }
77
78                 len = lws_hdr_total_length(wsi, n);
79                 if (!len || len > sizeof(buf) - 1) {
80                         n++;
81                         continue;
82                 }
83
84                 lws_hdr_copy(wsi, buf, sizeof buf, n);
85                 buf[sizeof(buf) - 1] = '\0';
86
87                 fprintf(stderr, "    %s = %s\n", (char *)c, buf);
88                 n++;
89         } while (c);
90 }
91
92 const char * get_mimetype(const char *file)
93 {
94         int n = strlen(file);
95
96         if (n < 5)
97                 return NULL;
98
99         if (!strcmp(&file[n - 4], ".ico"))
100                 return "image/x-icon";
101
102         if (!strcmp(&file[n - 4], ".png"))
103                 return "image/png";
104
105         if (!strcmp(&file[n - 5], ".html"))
106                 return "text/html";
107
108         return NULL;
109 }
110
111 /* this protocol server (always the first one) handles HTTP,
112  *
113  * Some misc callbacks that aren't associated with a protocol also turn up only
114  * here on the first protocol server.
115  */
116
117 int callback_http(struct lws *wsi, enum lws_callback_reasons reason, void *user,
118                   void *in, size_t len)
119 {
120         struct per_session_data__http *pss =
121                         (struct per_session_data__http *)user;
122         unsigned char buffer[4096 + LWS_PRE];
123         unsigned long amount, file_len, sent;
124         char leaf_path[1024];
125         const char *mimetype;
126         char *other_headers;
127         unsigned char *end;
128         struct timeval tv;
129         unsigned char *p;
130         char buf[256];
131         char b64[64];
132         int n, m;
133
134 #ifdef EXTERNAL_POLL
135         struct lws_pollargs *pa = (struct lws_pollargs *)in;
136 #endif
137
138         switch (reason) {
139         case LWS_CALLBACK_HTTP:
140
141                 if (debug_level & LLL_INFO) {
142                         dump_handshake_info(wsi);
143
144                         /* dump the individual URI Arg parameters */
145                         n = 0;
146                         while (lws_hdr_copy_fragment(wsi, buf, sizeof(buf),
147                                                      WSI_TOKEN_HTTP_URI_ARGS, n) > 0) {
148                                 lwsl_info("URI Arg %d: %s\n", ++n, buf);
149                         }
150                 }
151                 if (len < 1) {
152                         lws_return_http_status(wsi,
153                                                 HTTP_STATUS_BAD_REQUEST, NULL);
154                         goto try_to_reuse;
155                 }
156
157                 /* this example server has no concept of directories */
158                 if (strchr((const char *)in + 1, '/')) {
159                         lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
160                         goto try_to_reuse;
161                 }
162
163                 /* if a legal POST URL, let it continue and accept data */
164                 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
165                         return 0;
166
167                 /* check for the "send a big file by hand" example case */
168
169                 if (!strcmp((const char *)in, "/leaf.jpg")) {
170                         if (strlen(resource_path) > sizeof(leaf_path) - 10)
171                                 return -1;
172                         sprintf(leaf_path, "%s/leaf.jpg", resource_path);
173
174                         /* well, let's demonstrate how to send the hard way */
175
176                         p = buffer + LWS_PRE;
177                         end = p + sizeof(buffer) - LWS_PRE;
178
179                         pss->fd = lws_plat_file_open(wsi, leaf_path, &file_len,
180                                                      LWS_O_RDONLY);
181
182                         if (pss->fd == LWS_INVALID_FILE) {
183                                 lwsl_err("faild to open file %s\n", leaf_path);
184                                 return -1;
185                         }
186
187                         /*
188                          * we will send a big jpeg file, but it could be
189                          * anything.  Set the Content-Type: appropriately
190                          * so the browser knows what to do with it.
191                          *
192                          * Notice we use the APIs to build the header, which
193                          * will do the right thing for HTTP 1/1.1 and HTTP2
194                          * depending on what connection it happens to be working
195                          * on
196                          */
197                         if (lws_add_http_header_status(wsi, 200, &p, end))
198                                 return 1;
199                         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
200                                         (unsigned char *)"libwebsockets",
201                                         13, &p, end))
202                                 return 1;
203                         if (lws_add_http_header_by_token(wsi,
204                                         WSI_TOKEN_HTTP_CONTENT_TYPE,
205                                         (unsigned char *)"image/jpeg",
206                                         10, &p, end))
207                                 return 1;
208                         if (lws_add_http_header_content_length(wsi,
209                                                                file_len, &p,
210                                                                end))
211                                 return 1;
212                         if (lws_finalize_http_header(wsi, &p, end))
213                                 return 1;
214
215                         /*
216                          * send the http headers...
217                          * this won't block since it's the first payload sent
218                          * on the connection since it was established
219                          * (too small for partial)
220                          *
221                          * Notice they are sent using LWS_WRITE_HTTP_HEADERS
222                          * which also means you can't send body too in one step,
223                          * this is mandated by changes in HTTP2
224                          */
225
226                         *p = '\0';
227                         lwsl_info("%s\n", buffer + LWS_PRE);
228
229                         n = lws_write(wsi, buffer + LWS_PRE, p - (buffer + LWS_PRE),
230                                       LWS_WRITE_HTTP_HEADERS);
231                         if (n < 0) {
232                                 lws_plat_file_close(wsi, pss->fd);
233                                 return -1;
234                         }
235                         /*
236                          * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
237                          */
238                         lws_callback_on_writable(wsi);
239                         break;
240                 }
241
242                 /* if not, send a file the easy way */
243                 strcpy(buf, resource_path);
244                 if (strcmp(in, "/")) {
245                         if (*((const char *)in) != '/')
246                                 strcat(buf, "/");
247                         strncat(buf, in, sizeof(buf) - strlen(resource_path));
248                 } else /* default file to serve */
249                         strcat(buf, "/test.html");
250                 buf[sizeof(buf) - 1] = '\0';
251
252                 /* refuse to serve files we don't understand */
253                 mimetype = get_mimetype(buf);
254                 if (!mimetype) {
255                         lwsl_err("Unknown mimetype for %s\n", buf);
256                         lws_return_http_status(wsi,
257                                       HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
258                         return -1;
259                 }
260
261                 /* demonstrates how to set a cookie on / */
262
263                 other_headers = NULL;
264                 n = 0;
265                 if (!strcmp((const char *)in, "/") &&
266                            !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
267                         /* this isn't very unguessable but it'll do for us */
268                         gettimeofday(&tv, NULL);
269                         n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
270                                 (unsigned int)tv.tv_sec,
271                                 (unsigned int)tv.tv_usec);
272
273                         p = (unsigned char *)leaf_path;
274
275                         if (lws_add_http_header_by_name(wsi,
276                                 (unsigned char *)"set-cookie:",
277                                 (unsigned char *)b64, n, &p,
278                                 (unsigned char *)leaf_path + sizeof(leaf_path)))
279                                 return 1;
280                         n = (char *)p - leaf_path;
281                         other_headers = leaf_path;
282                 }
283
284                 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
285                 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
286                         return -1; /* error or can't reuse connection: close the socket */
287
288                 /*
289                  * notice that the sending of the file completes asynchronously,
290                  * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
291                  * it's done
292                  */
293                 break;
294
295         case LWS_CALLBACK_HTTP_BODY:
296                 strncpy(buf, in, 20);
297                 buf[20] = '\0';
298                 if (len < 20)
299                         buf[len] = '\0';
300
301                 lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
302                                 (const char *)buf, (int)len);
303
304                 break;
305
306         case LWS_CALLBACK_HTTP_BODY_COMPLETION:
307                 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
308                 /* the whole of the sent body arrived, close or reuse the connection */
309                 lws_return_http_status(wsi, HTTP_STATUS_OK, NULL);
310                 goto try_to_reuse;
311
312         case LWS_CALLBACK_HTTP_FILE_COMPLETION:
313                 goto try_to_reuse;
314
315         case LWS_CALLBACK_HTTP_WRITEABLE:
316                 lwsl_info("LWS_CALLBACK_HTTP_WRITEABLE\n");
317
318                 if (pss->fd == LWS_INVALID_FILE)
319                         goto try_to_reuse;
320
321                 /*
322                  * we can send more of whatever it is we were sending
323                  */
324                 sent = 0;
325                 do {
326                         /* we'd like the send this much */
327                         n = sizeof(buffer) - LWS_PRE;
328
329                         /* but if the peer told us he wants less, we can adapt */
330                         m = lws_get_peer_write_allowance(wsi);
331
332                         /* -1 means not using a protocol that has this info */
333                         if (m == 0)
334                                 /* right now, peer can't handle anything */
335                                 goto later;
336
337                         if (m != -1 && m < n)
338                                 /* he couldn't handle that much */
339                                 n = m;
340
341                         n = lws_plat_file_read(wsi, pss->fd,
342                                                &amount, buffer + LWS_PRE, n);
343                         /* problem reading, close conn */
344                         if (n < 0) {
345                                 lwsl_err("problem reading file\n");
346                                 goto bail;
347                         }
348                         n = (int)amount;
349                         /* sent it all, close conn */
350                         if (n == 0)
351                                 goto penultimate;
352                         /*
353                          * To support HTTP2, must take care about preamble space
354                          *
355                          * identification of when we send the last payload frame
356                          * is handled by the library itself if you sent a
357                          * content-length header
358                          */
359                         m = lws_write(wsi, buffer + LWS_PRE, n, LWS_WRITE_HTTP);
360                         if (m < 0) {
361                                 lwsl_err("write failed\n");
362                                 /* write failed, close conn */
363                                 goto bail;
364                         }
365                         if (m) /* while still active, extend timeout */
366                                 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, 5);
367                         sent += m;
368
369                 } while (!lws_send_pipe_choked(wsi) && (sent < 1024 * 1024));
370 later:
371                 lws_callback_on_writable(wsi);
372                 break;
373 penultimate:
374                 lws_plat_file_close(wsi, pss->fd);
375                 pss->fd = LWS_INVALID_FILE;
376                 goto try_to_reuse;
377
378 bail:
379                 lws_plat_file_close(wsi, pss->fd);
380
381                 return -1;
382
383         /*
384          * callback for confirming to continue with client IP appear in
385          * protocol 0 callback since no websocket protocol has been agreed
386          * yet.  You can just ignore this if you won't filter on client IP
387          * since the default uhandled callback return is 0 meaning let the
388          * connection continue.
389          */
390         case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
391
392                 /* if we returned non-zero from here, we kill the connection */
393                 break;
394
395         /*
396          * callbacks for managing the external poll() array appear in
397          * protocol 0 callback
398          */
399
400         case LWS_CALLBACK_LOCK_POLL:
401                 /*
402                  * lock mutex to protect pollfd state
403                  * called before any other POLL related callback
404                  * if protecting wsi lifecycle change, len == 1
405                  */
406                 test_server_lock(len);
407                 break;
408
409         case LWS_CALLBACK_UNLOCK_POLL:
410                 /*
411                  * unlock mutex to protect pollfd state when
412                  * called after any other POLL related callback
413                  * if protecting wsi lifecycle change, len == 1
414                  */
415                 test_server_unlock(len);
416                 break;
417
418 #ifdef EXTERNAL_POLL
419         case LWS_CALLBACK_ADD_POLL_FD:
420
421                 if (count_pollfds >= max_poll_elements) {
422                         lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
423                         return 1;
424                 }
425
426                 fd_lookup[pa->fd] = count_pollfds;
427                 pollfds[count_pollfds].fd = pa->fd;
428                 pollfds[count_pollfds].events = pa->events;
429                 pollfds[count_pollfds++].revents = 0;
430                 break;
431
432         case LWS_CALLBACK_DEL_POLL_FD:
433                 if (!--count_pollfds)
434                         break;
435                 m = fd_lookup[pa->fd];
436                 /* have the last guy take up the vacant slot */
437                 pollfds[m] = pollfds[count_pollfds];
438                 fd_lookup[pollfds[count_pollfds].fd] = m;
439                 break;
440
441         case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
442                 pollfds[fd_lookup[pa->fd]].events = pa->events;
443                 break;
444 #endif
445
446         case LWS_CALLBACK_GET_THREAD_ID:
447                 /*
448                  * if you will call "lws_callback_on_writable"
449                  * from a different thread, return the caller thread ID
450                  * here so lws can use this information to work out if it
451                  * should signal the poll() loop to exit and restart early
452                  */
453
454                 /* return pthread_getthreadid_np(); */
455
456                 break;
457
458         default:
459                 break;
460         }
461
462         return 0;
463
464         /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
465 try_to_reuse:
466         if (lws_http_transaction_completed(wsi))
467                 return -1;
468
469         return 0;
470 }