public api remove superfluous context params API BREAK
[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;
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                 if (!lws_hdr_total_length(wsi, n)) {
77                         n++;
78                         continue;
79                 }
80
81                 lws_hdr_copy(wsi, buf, sizeof buf, n);
82
83                 fprintf(stderr, "    %s = %s\n", (char *)c, buf);
84                 n++;
85         } while (c);
86 }
87
88 const char * get_mimetype(const char *file)
89 {
90         int n = strlen(file);
91
92         if (n < 5)
93                 return NULL;
94
95         if (!strcmp(&file[n - 4], ".ico"))
96                 return "image/x-icon";
97
98         if (!strcmp(&file[n - 4], ".png"))
99                 return "image/png";
100
101         if (!strcmp(&file[n - 5], ".html"))
102                 return "text/html";
103
104         return NULL;
105 }
106
107 /* this protocol server (always the first one) handles HTTP,
108  *
109  * Some misc callbacks that aren't associated with a protocol also turn up only
110  * here on the first protocol server.
111  */
112
113 int callback_http(struct lws_context *context, struct lws *wsi,
114                   enum lws_callback_reasons reason, void *user,
115                   void *in, size_t len)
116 {
117         struct per_session_data__http *pss =
118                         (struct per_session_data__http *)user;
119         static unsigned char buffer[4096];
120         unsigned long amount, file_len;
121         char leaf_path[1024];
122         const char *mimetype;
123         char *other_headers;
124         unsigned char *end;
125         struct timeval tv;
126         unsigned char *p;
127         char buf[256];
128         char b64[64];
129         int n, m;
130
131 #ifdef EXTERNAL_POLL
132         struct lws_pollargs *pa = (struct lws_pollargs *)in;
133 #endif
134
135         switch (reason) {
136         case LWS_CALLBACK_HTTP:
137
138                 dump_handshake_info(wsi);
139
140                 /* dump the individual URI Arg parameters */
141                 m = 1;
142                 n = 0;
143                 while (m > 0) {
144                         m = lws_hdr_copy_fragment(wsi, buf, sizeof(buf),
145                                                   WSI_TOKEN_HTTP_URI_ARGS, n);
146                         if (m < 0)
147                                 continue;
148                         n++;
149                         lwsl_info("URI Arg %d: %s\n", n, buf);
150                 }
151
152                 if (len < 1) {
153                         lws_return_http_status(wsi,
154                                                 HTTP_STATUS_BAD_REQUEST, NULL);
155                         goto try_to_reuse;
156                 }
157
158                 /* this example server has no concept of directories */
159                 if (strchr((const char *)in + 1, '/')) {
160                         lws_return_http_status(wsi,
161                                                HTTP_STATUS_FORBIDDEN, NULL);
162                         goto try_to_reuse;
163                 }
164
165                 /* if a legal POST URL, let it continue and accept data */
166                 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
167                         return 0;
168
169                 /* check for the "send a big file by hand" example case */
170
171                 if (!strcmp((const char *)in, "/leaf.jpg")) {
172                         if (strlen(resource_path) > sizeof(leaf_path) - 10)
173                                 return -1;
174                         sprintf(leaf_path, "%s/leaf.jpg", resource_path);
175
176                         /* well, let's demonstrate how to send the hard way */
177
178                         p = buffer + LWS_SEND_BUFFER_PRE_PADDING;
179                         end = p + sizeof(buffer) - LWS_SEND_BUFFER_PRE_PADDING;
180
181                         pss->fd = lws_plat_file_open(wsi, leaf_path, &file_len,
182                                                      LWS_O_RDONLY);
183
184                         if (pss->fd == LWS_INVALID_FILE)
185                                 return -1;
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                         n = lws_write(wsi, buffer + LWS_SEND_BUFFER_PRE_PADDING,
227                                       p - (buffer + LWS_SEND_BUFFER_PRE_PADDING),
228                                       LWS_WRITE_HTTP_HEADERS);
229
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
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                 /*
317                  * we can send more of whatever it is we were sending
318                  */
319                 do {
320                         /* we'd like the send this much */
321                         n = sizeof(buffer) - LWS_SEND_BUFFER_PRE_PADDING;
322
323                         /* but if the peer told us he wants less, we can adapt */
324                         m = lws_get_peer_write_allowance(wsi);
325
326                         /* -1 means not using a protocol that has this info */
327                         if (m == 0)
328                                 /* right now, peer can't handle anything */
329                                 goto later;
330
331                         if (m != -1 && m < n)
332                                 /* he couldn't handle that much */
333                                 n = m;
334
335                         n = lws_plat_file_read(wsi, pss->fd,
336                                                &amount, buffer +
337                                                 LWS_SEND_BUFFER_PRE_PADDING, n);
338                         /* problem reading, close conn */
339                         if (n < 0)
340                                 goto bail;
341                         n = (int)amount;
342                         /* sent it all, close conn */
343                         if (n == 0)
344                                 goto flush_bail;
345                         /*
346                          * To support HTTP2, must take care about preamble space
347                          *
348                          * identification of when we send the last payload frame
349                          * is handled by the library itself if you sent a
350                          * content-length header
351                          */
352                         m = lws_write(wsi, buffer + LWS_SEND_BUFFER_PRE_PADDING,
353                                       n, LWS_WRITE_HTTP);
354                         if (m < 0)
355                                 /* write failed, close conn */
356                                 goto bail;
357
358                         /*
359                          * http2 won't do this
360                          */
361                         if (m != n)
362                                 /* partial write, adjust */
363                                 if (lws_plat_file_seek_cur(wsi, pss->fd, m - n) ==
364                                                              (unsigned long)-1)
365                                         goto bail;
366
367                         if (m) /* while still active, extend timeout */
368                                 lws_set_timeout(wsi,
369                                                 PENDING_TIMEOUT_HTTP_CONTENT, 5);
370
371                         /* if we have indigestion, let him clear it
372                          * before eating more */
373                         if (lws_partial_buffered(wsi))
374                                 break;
375
376                 } while (!lws_send_pipe_choked(wsi));
377
378 later:
379                 lws_callback_on_writable(wsi);
380                 break;
381 flush_bail:
382                 /* true if still partial pending */
383                 if (lws_partial_buffered(wsi)) {
384                         lws_callback_on_writable(wsi);
385                         break;
386                 }
387                 lws_plat_file_close(wsi, pss->fd);
388                 goto try_to_reuse;
389
390 bail:
391                 lws_plat_file_close(wsi, pss->fd);
392                 return -1;
393
394         /*
395          * callback for confirming to continue with client IP appear in
396          * protocol 0 callback since no websocket protocol has been agreed
397          * yet.  You can just ignore this if you won't filter on client IP
398          * since the default uhandled callback return is 0 meaning let the
399          * connection continue.
400          */
401         case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
402
403                 /* if we returned non-zero from here, we kill the connection */
404                 break;
405
406         /*
407          * callbacks for managing the external poll() array appear in
408          * protocol 0 callback
409          */
410
411         case LWS_CALLBACK_LOCK_POLL:
412                 /*
413                  * lock mutex to protect pollfd state
414                  * called before any other POLL related callback
415                  * if protecting wsi lifecycle change, len == 1
416                  */
417                 test_server_lock(len);
418                 break;
419
420         case LWS_CALLBACK_UNLOCK_POLL:
421                 /*
422                  * unlock mutex to protect pollfd state when
423                  * called after any other POLL related callback
424                  * if protecting wsi lifecycle change, len == 1
425                  */
426                 test_server_unlock(len);
427                 break;
428
429 #ifdef EXTERNAL_POLL
430         case LWS_CALLBACK_ADD_POLL_FD:
431
432                 if (count_pollfds >= max_poll_elements) {
433                         lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
434                         return 1;
435                 }
436
437                 fd_lookup[pa->fd] = count_pollfds;
438                 pollfds[count_pollfds].fd = pa->fd;
439                 pollfds[count_pollfds].events = pa->events;
440                 pollfds[count_pollfds++].revents = 0;
441                 break;
442
443         case LWS_CALLBACK_DEL_POLL_FD:
444                 if (!--count_pollfds)
445                         break;
446                 m = fd_lookup[pa->fd];
447                 /* have the last guy take up the vacant slot */
448                 pollfds[m] = pollfds[count_pollfds];
449                 fd_lookup[pollfds[count_pollfds].fd] = m;
450                 break;
451
452         case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
453                 pollfds[fd_lookup[pa->fd]].events = pa->events;
454                 break;
455 #endif
456
457         case LWS_CALLBACK_GET_THREAD_ID:
458                 /*
459                  * if you will call "lws_callback_on_writable"
460                  * from a different thread, return the caller thread ID
461                  * here so lws can use this information to work out if it
462                  * should signal the poll() loop to exit and restart early
463                  */
464
465                 /* return pthread_getthreadid_np(); */
466
467                 break;
468
469         default:
470                 break;
471         }
472
473         return 0;
474
475         /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
476 try_to_reuse:
477         if (lws_http_transaction_completed(wsi))
478                 return -1;
479
480         return 0;
481 }