public api remove context from user callback 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 *wsi, enum lws_callback_reasons reason, void *user,
114                   void *in, size_t len)
115 {
116         struct per_session_data__http *pss =
117                         (struct per_session_data__http *)user;
118         static unsigned char buffer[4096];
119         unsigned long amount, file_len;
120         char leaf_path[1024];
121         const char *mimetype;
122         char *other_headers;
123         unsigned char *end;
124         struct timeval tv;
125         unsigned char *p;
126         char buf[256];
127         char b64[64];
128         int n, m;
129
130 #ifdef EXTERNAL_POLL
131         struct lws_pollargs *pa = (struct lws_pollargs *)in;
132 #endif
133
134         switch (reason) {
135         case LWS_CALLBACK_HTTP:
136
137                 dump_handshake_info(wsi);
138
139                 /* dump the individual URI Arg parameters */
140                 m = 1;
141                 n = 0;
142                 while (m > 0) {
143                         m = lws_hdr_copy_fragment(wsi, buf, sizeof(buf),
144                                                   WSI_TOKEN_HTTP_URI_ARGS, n);
145                         if (m < 0)
146                                 continue;
147                         n++;
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,
160                                                HTTP_STATUS_FORBIDDEN, NULL);
161                         goto try_to_reuse;
162                 }
163
164                 /* if a legal POST URL, let it continue and accept data */
165                 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
166                         return 0;
167
168                 /* check for the "send a big file by hand" example case */
169
170                 if (!strcmp((const char *)in, "/leaf.jpg")) {
171                         if (strlen(resource_path) > sizeof(leaf_path) - 10)
172                                 return -1;
173                         sprintf(leaf_path, "%s/leaf.jpg", resource_path);
174
175                         /* well, let's demonstrate how to send the hard way */
176
177                         p = buffer + LWS_SEND_BUFFER_PRE_PADDING;
178                         end = p + sizeof(buffer) - LWS_SEND_BUFFER_PRE_PADDING;
179
180                         pss->fd = lws_plat_file_open(wsi, leaf_path, &file_len,
181                                                      LWS_O_RDONLY);
182
183                         if (pss->fd == LWS_INVALID_FILE)
184                                 return -1;
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                         n = lws_write(wsi, buffer + LWS_SEND_BUFFER_PRE_PADDING,
226                                       p - (buffer + LWS_SEND_BUFFER_PRE_PADDING),
227                                       LWS_WRITE_HTTP_HEADERS);
228
229                         if (n < 0) {
230                                 lws_plat_file_close(wsi, pss->fd);
231                                 return -1;
232                         }
233                         /*
234                          * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
235                          */
236                         lws_callback_on_writable(wsi);
237                         break;
238                 }
239
240                 /* if not, send a file the easy way */
241                 strcpy(buf, resource_path);
242                 if (strcmp(in, "/")) {
243                         if (*((const char *)in) != '/')
244                                 strcat(buf, "/");
245                         strncat(buf, in, sizeof(buf) - strlen(resource_path));
246                 } else /* default file to serve */
247                         strcat(buf, "/test.html");
248                 buf[sizeof(buf) - 1] = '\0';
249
250                 /* refuse to serve files we don't understand */
251                 mimetype = get_mimetype(buf);
252                 if (!mimetype) {
253                         lwsl_err("Unknown mimetype for %s\n", buf);
254                         lws_return_http_status(wsi,
255                                       HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
256                         return -1;
257                 }
258
259                 /* demonstrates how to set a cookie on / */
260
261                 other_headers = NULL;
262                 n = 0;
263                 if (!strcmp((const char *)in, "/") &&
264                            !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
265                         /* this isn't very unguessable but it'll do for us */
266                         gettimeofday(&tv, NULL);
267                         n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
268                                 (unsigned int)tv.tv_sec,
269                                 (unsigned int)tv.tv_usec);
270
271                         p = (unsigned char *)leaf_path;
272
273                         if (lws_add_http_header_by_name(wsi,
274                                 (unsigned char *)"set-cookie:",
275                                 (unsigned char *)b64, n, &p,
276                                 (unsigned char *)leaf_path + sizeof(leaf_path)))
277                                 return 1;
278                         n = (char *)p - leaf_path;
279                         other_headers = leaf_path;
280                 }
281
282                 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
283                 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
284                         return -1; /* error or can't reuse connection: close the socket */
285
286                 /*
287                  * notice that the sending of the file completes asynchronously,
288                  * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
289                  * it's done
290                  */
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                 /*
316                  * we can send more of whatever it is we were sending
317                  */
318                 do {
319                         /* we'd like the send this much */
320                         n = sizeof(buffer) - LWS_SEND_BUFFER_PRE_PADDING;
321
322                         /* but if the peer told us he wants less, we can adapt */
323                         m = lws_get_peer_write_allowance(wsi);
324
325                         /* -1 means not using a protocol that has this info */
326                         if (m == 0)
327                                 /* right now, peer can't handle anything */
328                                 goto later;
329
330                         if (m != -1 && m < n)
331                                 /* he couldn't handle that much */
332                                 n = m;
333
334                         n = lws_plat_file_read(wsi, pss->fd,
335                                                &amount, buffer +
336                                                 LWS_SEND_BUFFER_PRE_PADDING, n);
337                         /* problem reading, close conn */
338                         if (n < 0)
339                                 goto bail;
340                         n = (int)amount;
341                         /* sent it all, close conn */
342                         if (n == 0)
343                                 goto flush_bail;
344                         /*
345                          * To support HTTP2, must take care about preamble space
346                          *
347                          * identification of when we send the last payload frame
348                          * is handled by the library itself if you sent a
349                          * content-length header
350                          */
351                         m = lws_write(wsi, buffer + LWS_SEND_BUFFER_PRE_PADDING,
352                                       n, LWS_WRITE_HTTP);
353                         if (m < 0)
354                                 /* write failed, close conn */
355                                 goto bail;
356
357                         /*
358                          * http2 won't do this
359                          */
360                         if (m != n)
361                                 /* partial write, adjust */
362                                 if (lws_plat_file_seek_cur(wsi, pss->fd, m - n) ==
363                                                              (unsigned long)-1)
364                                         goto bail;
365
366                         if (m) /* while still active, extend timeout */
367                                 lws_set_timeout(wsi,
368                                                 PENDING_TIMEOUT_HTTP_CONTENT, 5);
369
370                         /* if we have indigestion, let him clear it
371                          * before eating more */
372                         if (lws_partial_buffered(wsi))
373                                 break;
374
375                 } while (!lws_send_pipe_choked(wsi));
376
377 later:
378                 lws_callback_on_writable(wsi);
379                 break;
380 flush_bail:
381                 /* true if still partial pending */
382                 if (lws_partial_buffered(wsi)) {
383                         lws_callback_on_writable(wsi);
384                         break;
385                 }
386                 lws_plat_file_close(wsi, pss->fd);
387                 goto try_to_reuse;
388
389 bail:
390                 lws_plat_file_close(wsi, pss->fd);
391                 return -1;
392
393         /*
394          * callback for confirming to continue with client IP appear in
395          * protocol 0 callback since no websocket protocol has been agreed
396          * yet.  You can just ignore this if you won't filter on client IP
397          * since the default uhandled callback return is 0 meaning let the
398          * connection continue.
399          */
400         case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
401
402                 /* if we returned non-zero from here, we kill the connection */
403                 break;
404
405         /*
406          * callbacks for managing the external poll() array appear in
407          * protocol 0 callback
408          */
409
410         case LWS_CALLBACK_LOCK_POLL:
411                 /*
412                  * lock mutex to protect pollfd state
413                  * called before any other POLL related callback
414                  * if protecting wsi lifecycle change, len == 1
415                  */
416                 test_server_lock(len);
417                 break;
418
419         case LWS_CALLBACK_UNLOCK_POLL:
420                 /*
421                  * unlock mutex to protect pollfd state when
422                  * called after any other POLL related callback
423                  * if protecting wsi lifecycle change, len == 1
424                  */
425                 test_server_unlock(len);
426                 break;
427
428 #ifdef EXTERNAL_POLL
429         case LWS_CALLBACK_ADD_POLL_FD:
430
431                 if (count_pollfds >= max_poll_elements) {
432                         lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
433                         return 1;
434                 }
435
436                 fd_lookup[pa->fd] = count_pollfds;
437                 pollfds[count_pollfds].fd = pa->fd;
438                 pollfds[count_pollfds].events = pa->events;
439                 pollfds[count_pollfds++].revents = 0;
440                 break;
441
442         case LWS_CALLBACK_DEL_POLL_FD:
443                 if (!--count_pollfds)
444                         break;
445                 m = fd_lookup[pa->fd];
446                 /* have the last guy take up the vacant slot */
447                 pollfds[m] = pollfds[count_pollfds];
448                 fd_lookup[pollfds[count_pollfds].fd] = m;
449                 break;
450
451         case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
452                 pollfds[fd_lookup[pa->fd]].events = pa->events;
453                 break;
454 #endif
455
456         case LWS_CALLBACK_GET_THREAD_ID:
457                 /*
458                  * if you will call "lws_callback_on_writable"
459                  * from a different thread, return the caller thread ID
460                  * here so lws can use this information to work out if it
461                  * should signal the poll() loop to exit and restart early
462                  */
463
464                 /* return pthread_getthreadid_np(); */
465
466                 break;
467
468         default:
469                 break;
470         }
471
472         return 0;
473
474         /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
475 try_to_reuse:
476         if (lws_http_transaction_completed(wsi))
477                 return -1;
478
479         return 0;
480 }