000b90ca3852b77a0a8a77321eab43ba704ca05e
[platform/upstream/libwebsockets.git] / lwsws / http.c
1 /*
2  * libwebsockets web server application
3  *
4  * Copyright (C) 2010-2016 Andy Green <andy@warmcat.com>
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU 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  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU 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 "lwsws.h"
22
23 /* http server gets files from this path */
24 #define LOCAL_RESOURCE_PATH INSTALL_DATADIR"/libwebsockets-test-server"
25 char *resource_path = LOCAL_RESOURCE_PATH;
26
27
28
29 /*
30  * We take a strict whitelist approach to stop ../ attacks
31  */
32 struct serveable {
33         const char *urlpath;
34         const char *mimetype;
35 };
36
37 const char * get_mimetype(const char *file)
38 {
39         int n = strlen(file);
40
41         if (n < 5)
42                 return NULL;
43
44         if (!strcmp(&file[n - 4], ".ico"))
45                 return "image/x-icon";
46
47         if (!strcmp(&file[n - 4], ".png"))
48                 return "image/png";
49
50         if (!strcmp(&file[n - 4], ".jpg"))
51                 return "image/jpeg";
52
53         if (!strcmp(&file[n - 5], ".html"))
54                 return "text/html";
55
56         if (!strcmp(&file[n - 4], ".css"))
57                 return "text/css";
58
59         return NULL;
60 }
61
62 /* this protocol server (always the first one) handles HTTP,
63  *
64  * Some misc callbacks that aren't associated with a protocol also turn up only
65  * here on the first protocol server.
66  */
67
68 int callback_http(struct lws *wsi, enum lws_callback_reasons reason, void *user,
69                   void *in, size_t len)
70 {
71         struct per_session_data__http *pss =
72                         (struct per_session_data__http *)user;
73         unsigned char buffer[4096 + LWS_PRE];
74         char leaf_path[1024];
75         const char *mimetype;
76         char *other_headers;
77         unsigned char *end;
78         struct timeval tv;
79         unsigned char *p;
80 #ifndef LWS_NO_CLIENT
81         struct per_session_data__http *pss1;
82         struct lws *wsi1;
83 #endif
84         char buf[256];
85         char b64[64];
86         int n, m;
87 #ifdef EXTERNAL_POLL
88         struct lws_pollargs *pa = (struct lws_pollargs *)in;
89 #endif
90
91 //      lwsl_err("%s: reason %d\n", __func__, reason);
92
93         switch (reason) {
94         case LWS_CALLBACK_HTTP:
95
96                 {
97                         char name[100], rip[50];
98                         lws_get_peer_addresses(wsi, lws_get_socket_fd(wsi), name,
99                                                sizeof(name), rip, sizeof(rip));
100                         sprintf(buf, "%s (%s)", name, rip);
101                         lwsl_notice("HTTP connect from %s\n", buf);
102                 }
103
104                 if (len < 1) {
105                         lws_return_http_status(wsi,
106                                                 HTTP_STATUS_BAD_REQUEST, NULL);
107                         goto try_to_reuse;
108                 }
109
110 #ifndef LWS_NO_CLIENT
111                 if (!strncmp(in, "/proxytest", 10)) {
112                         struct lws_client_connect_info i;
113                         char *rootpath = "/";
114                         const char *p = (const char *)in;
115
116                         if (lws_get_child(wsi))
117                                 break;
118
119                         pss->client_finished = 0;
120                         memset(&i,0, sizeof(i));
121                         i.context = lws_get_context(wsi);
122                         i.address = "git.libwebsockets.org";
123                         i.port = 80;
124                         i.ssl_connection = 0;
125                         if (p[10])
126                                 i.path = (char *)in + 10;
127                         else
128                                 i.path = rootpath;
129                         i.host = "git.libwebsockets.org";
130                         i.origin = NULL;
131                         i.method = "GET";
132                         i.parent_wsi = wsi;
133                         i.uri_replace_from = "git.libwebsockets.org/";
134                         i.uri_replace_to = "/proxytest/";
135                         if (!lws_client_connect_via_info(&i)) {
136                                 lwsl_err("proxy connect fail\n");
137                                 break;
138                         }
139                         break;
140                 }
141 #endif
142
143 #if 1
144                 /* this example server has no concept of directories */
145                 if (strchr((const char *)in + 1, '/')) {
146                         lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
147                         goto try_to_reuse;
148                 }
149 #endif
150
151                 /* if a legal POST URL, let it continue and accept data */
152                 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
153                         return 0;
154
155                 strncpy(buf, resource_path, sizeof(buf) - 1);
156                 buf[sizeof(buf) - 1] = '\0';
157                 if (strcmp(in, "/")) {
158                         if (*((const char *)in) != '/')
159                                 strcat(buf, "/");
160                         strncat(buf, in, sizeof(buf) - strlen(buf) - 1);
161                 } else /* default file to serve */
162                         strcat(buf, "/test.html");
163                 buf[sizeof(buf) - 1] = '\0';
164
165                 /* refuse to serve files we don't understand */
166                 mimetype = get_mimetype(buf);
167                 if (!mimetype) {
168                         lwsl_err("Unknown mimetype for %s\n", buf);
169                         lws_return_http_status(wsi,
170                                       HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
171                         return -1;
172                 }
173
174                 /* demonstrates how to set a cookie on / */
175
176                 other_headers = leaf_path;
177                 p = (unsigned char *)leaf_path;
178                 if (!strcmp((const char *)in, "/") &&
179                            !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
180                         /* this isn't very unguessable but it'll do for us */
181                         gettimeofday(&tv, NULL);
182                         n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
183                                 (unsigned int)tv.tv_sec,
184                                 (unsigned int)tv.tv_usec);
185
186                         if (lws_add_http_header_by_name(wsi,
187                                 (unsigned char *)"set-cookie:",
188                                 (unsigned char *)b64, n, &p,
189                                 (unsigned char *)leaf_path + sizeof(leaf_path)))
190                                 return 1;
191                 }
192                 if (lws_is_ssl(wsi) && lws_add_http_header_by_name(wsi,
193                                                 (unsigned char *)
194                                                 "Strict-Transport-Security:",
195                                                 (unsigned char *)
196                                                 "max-age=15768000 ; "
197                                                 "includeSubDomains", 36, &p,
198                                                 (unsigned char *)leaf_path +
199                                                         sizeof(leaf_path)))
200                         return 1;
201                 n = (char *)p - leaf_path;
202
203                 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
204                 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
205                         return -1; /* error or can't reuse connection: close the socket */
206
207                 /*
208                  * notice that the sending of the file completes asynchronously,
209                  * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
210                  * it's done
211                  */
212                 break;
213
214         case LWS_CALLBACK_HTTP_BODY:
215                 strncpy(buf, in, 20);
216                 buf[20] = '\0';
217                 if (len < 20)
218                         buf[len] = '\0';
219
220                 lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
221                                 (const char *)buf, (int)len);
222
223                 break;
224
225         case LWS_CALLBACK_HTTP_BODY_COMPLETION:
226                 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
227                 /* the whole of the sent body arrived, close or reuse the connection */
228                 lws_return_http_status(wsi, HTTP_STATUS_OK, NULL);
229                 goto try_to_reuse;
230
231         case LWS_CALLBACK_HTTP_FILE_COMPLETION:
232                 goto try_to_reuse;
233
234         case LWS_CALLBACK_HTTP_WRITEABLE:
235                 // lwsl_notice("LWS_CALLBACK_HTTP_WRITEABLE\n");
236
237 #ifdef LWS_WITH_CGI
238                 if (pss->reason_bf & 1) {
239                         if (lws_cgi_write_split_stdout_headers(wsi) < 0) {
240                                 lwsl_debug("lws_cgi_write_split_stdout_headers says close\n");
241                                 return -1;
242                         }
243
244                         pss->reason_bf &= ~1;
245                         break;
246                 }
247
248
249 #endif
250 #ifndef LWS_NO_CLIENT
251                 if (pss->reason_bf & 2) {
252                         char *px = buf + LWS_PRE;
253                         int lenx = sizeof(buf) - LWS_PRE;
254                         /*
255                          * our sink is writeable and our source has something
256                          * to read.  So read a lump of source material of
257                          * suitable size to send or what's available, whichever
258                          * is the smaller.
259                          */
260                         pss->reason_bf &= ~2;
261                         wsi1 = lws_get_child(wsi);
262                         if (!wsi1)
263                                 break;
264                         if (lws_http_client_read(wsi1, &px, &lenx) < 0)
265                                 return -1;
266
267                         if (pss->client_finished)
268                                 return -1;
269                         break;
270                 }
271 #endif
272                 break;
273
274 #ifndef LWS_NO_CLIENT
275
276         case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP: {
277                 char ctype[64], ctlen = 0;
278                 lwsl_err("LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP\n");
279                 p = buffer + LWS_PRE;
280                 end = p + sizeof(buffer) - LWS_PRE;
281                 if (lws_add_http_header_status(lws_get_parent(wsi), 200, &p, end))
282                         return 1;
283                 if (lws_add_http_header_by_token(lws_get_parent(wsi),
284                                 WSI_TOKEN_HTTP_SERVER,
285                                 (unsigned char *)"libwebsockets",
286                                 13, &p, end))
287                         return 1;
288
289                 ctlen = lws_hdr_copy(wsi, ctype, sizeof(ctype), WSI_TOKEN_HTTP_CONTENT_TYPE);
290                 if (ctlen > 0) {
291                         if (lws_add_http_header_by_token(lws_get_parent(wsi),
292                                 WSI_TOKEN_HTTP_CONTENT_TYPE,
293                                 (unsigned char *)ctype, ctlen, &p, end))
294                                 return 1;
295                 }
296 #if 0
297                 if (lws_add_http_header_content_length(lws_get_parent(wsi),
298                                                        file_len, &p, end))
299                         return 1;
300 #endif
301                 if (lws_finalize_http_header(lws_get_parent(wsi), &p, end))
302                         return 1;
303
304                 *p = '\0';
305                 lwsl_info("%s\n", buffer + LWS_PRE);
306
307                 n = lws_write(lws_get_parent(wsi), buffer + LWS_PRE,
308                               p - (buffer + LWS_PRE),
309                               LWS_WRITE_HTTP_HEADERS);
310                 if (n < 0)
311                         return -1;
312
313                 break; }
314         case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
315                 //lwsl_err("LWS_CALLBACK_CLOSED_CLIENT_HTTP\n");
316                 return -1;
317                 break;
318         case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
319                 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p\n", wsi);
320                 assert(lws_get_parent(wsi));
321                 if (!lws_get_parent(wsi))
322                         break;
323                 // lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p: sock: %d, parent_wsi: %p, parent_sock:%d,  len %d\n",
324                 //              wsi, lws_get_socket_fd(wsi),
325                 //              lws_get_parent(wsi),
326                 //              lws_get_socket_fd(lws_get_parent(wsi)), len);
327                 pss1 = lws_wsi_user(lws_get_parent(wsi));
328                 pss1->reason_bf |= 2;
329                 lws_callback_on_writable(lws_get_parent(wsi));
330                 break;
331         case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:
332                 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ len %d\n", len);
333                 assert(lws_get_parent(wsi));
334                 m = lws_write(lws_get_parent(wsi), (unsigned char *)in,
335                                 len, LWS_WRITE_HTTP);
336                 if (m < 0)
337                         return -1;
338                 break;
339         case LWS_CALLBACK_COMPLETED_CLIENT_HTTP:
340                 //lwsl_err("LWS_CALLBACK_COMPLETED_CLIENT_HTTP\n");
341                 assert(lws_get_parent(wsi));
342                 if (!lws_get_parent(wsi))
343                         break;
344                 pss1 = lws_wsi_user(lws_get_parent(wsi));
345                 pss1->client_finished = 1;
346                 break;
347 #endif
348
349 #ifdef LWS_WITH_CGI
350         /* CGI IO events (POLLIN/OUT) appear here our demo user code policy is
351          *
352          *  - POST data goes on subprocess stdin
353          *  - subprocess stdout goes on http via writeable callback
354          *  - subprocess stderr goes to the logs
355          */
356         case LWS_CALLBACK_CGI:
357                 pss->args = *((struct lws_cgi_args *)in);
358                 //lwsl_notice("LWS_CALLBACK_CGI: ch %d\n", pss->args.ch);
359                 switch (pss->args.ch) { /* which of stdin/out/err ? */
360                 case LWS_STDIN:
361                         /* TBD stdin rx flow control */
362                         break;
363                 case LWS_STDOUT:;
364                         pss->reason_bf |= 1;
365                         /* when writing to MASTER would not block */
366                         lws_callback_on_writable(wsi);
367                         break;
368                 case LWS_STDERR:
369                         n = read(lws_get_socket_fd(pss->args.stdwsi[LWS_STDERR]),
370                                         buf, 127);
371                         //lwsl_notice("stderr reads %d\n", n);
372                         if (n > 0) {
373                                 if (buf[n - 1] != '\n')
374                                         buf[n++] = '\n';
375                                 buf[n] = '\0';
376                                 lwsl_notice("CGI-stderr: %s\n", buf);
377                         }
378                         break;
379                 }
380                 break;
381
382         case LWS_CALLBACK_CGI_TERMINATED:
383                 //lwsl_notice("LWS_CALLBACK_CGI_TERMINATED\n");
384                 /* because we sent on openended http, close the connection */
385                 return -1;
386
387         case LWS_CALLBACK_CGI_STDIN_DATA:  /* POST body for stdin */
388                 lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA\n");
389                 pss->args = *((struct lws_cgi_args *)in);
390                 pss->args.data[pss->args.len] = '\0';
391                 //lwsl_err("(stdin fd = %d) %s\n", lws_get_socket_fd(pss->args.stdwsi[LWS_STDIN]), pss->args.data);
392                 n = write(lws_get_socket_fd(pss->args.stdwsi[LWS_STDIN]),
393                           pss->args.data, pss->args.len);
394                 //lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: write says %d", n);
395                 if (n < pss->args.len)
396                         lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: sent %d only %d went",
397                                         n, pss->args.len);
398                 return n;
399 #endif
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                 test_server_lock(len);
408                 break;
409
410         case LWS_CALLBACK_UNLOCK_POLL:
411                 test_server_unlock(len);
412                 break;
413
414         case LWS_CALLBACK_GET_THREAD_ID:
415                 /* return pthread_getthreadid_np(); */
416
417                 break;
418
419         default:
420                 break;
421         }
422
423         return 0;
424
425         /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
426 try_to_reuse:
427         if (lws_http_transaction_completed(wsi))
428                 return -1;
429
430         return 0;
431 }