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