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