post example in test server
[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, *start;
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 0
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 (strlen(in) >= 12 &&
152                     !strncmp(in + strlen(in) - 12, "/postresults", 12)) {
153                         m = sprintf(buf, "<html><body>Form results: '%s'<br>"
154                                         "</body></html>", pss->post_string);
155
156                         p = buffer + LWS_PRE;
157                         start = p;
158                         end = p + sizeof(buffer) - LWS_PRE;
159
160                         if (lws_add_http_header_status(wsi, 200, &p, end))
161                                 return 1;
162                         if (lws_add_http_header_by_token(wsi,
163                                         WSI_TOKEN_HTTP_CONTENT_TYPE,
164                                         (unsigned char *)"text/html",
165                                         9, &p, end))
166                                 return 1;
167                         if (lws_add_http_header_content_length(wsi, m, &p,
168                                                                end))
169                                 return 1;
170                         if (lws_finalize_http_header(wsi, &p, end))
171                                 return 1;
172
173                         n = lws_write(wsi, start, p - start,
174                                       LWS_WRITE_HTTP_HEADERS);
175                         if (n < 0)
176                                 return 1;
177
178                         n = lws_write(wsi, (unsigned char *)buf, m, LWS_WRITE_HTTP);
179                         if (n < 0)
180                                 return 1;
181
182                         goto try_to_reuse;
183                 }
184
185                 /* if a legal POST URL, let it continue and accept data */
186                 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
187                         return 0;
188
189                 strncpy(buf, resource_path, sizeof(buf) - 1);
190                 buf[sizeof(buf) - 1] = '\0';
191                 if (strcmp(in, "/")) {
192                         if (*((const char *)in) != '/')
193                                 strcat(buf, "/");
194                         strncat(buf, in, sizeof(buf) - strlen(buf) - 1);
195                 } else /* default file to serve */
196                         strcat(buf, "/test.html");
197                 buf[sizeof(buf) - 1] = '\0';
198
199                 /* refuse to serve files we don't understand */
200                 mimetype = get_mimetype(buf);
201                 if (!mimetype) {
202                         lwsl_err("Unknown mimetype for %s\n", buf);
203                         lws_return_http_status(wsi,
204                                       HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, NULL);
205                         return -1;
206                 }
207
208                 /* demonstrates how to set a cookie on / */
209
210                 other_headers = leaf_path;
211                 p = (unsigned char *)leaf_path;
212                 if (!strcmp((const char *)in, "/") &&
213                            !lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_COOKIE)) {
214                         /* this isn't very unguessable but it'll do for us */
215                         gettimeofday(&tv, NULL);
216                         n = sprintf(b64, "test=LWS_%u_%u_COOKIE;Max-Age=360000",
217                                 (unsigned int)tv.tv_sec,
218                                 (unsigned int)tv.tv_usec);
219
220                         if (lws_add_http_header_by_name(wsi,
221                                 (unsigned char *)"set-cookie:",
222                                 (unsigned char *)b64, n, &p,
223                                 (unsigned char *)leaf_path + sizeof(leaf_path)))
224                                 return 1;
225                 }
226                 if (lws_is_ssl(wsi) && lws_add_http_header_by_name(wsi,
227                                                 (unsigned char *)
228                                                 "Strict-Transport-Security:",
229                                                 (unsigned char *)
230                                                 "max-age=15768000 ; "
231                                                 "includeSubDomains", 36, &p,
232                                                 (unsigned char *)leaf_path +
233                                                         sizeof(leaf_path)))
234                         return 1;
235                 n = (char *)p - leaf_path;
236
237                 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
238                 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
239                         return -1; /* error or can't reuse connection: close the socket */
240
241                 /*
242                  * notice that the sending of the file completes asynchronously,
243                  * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
244                  * it's done
245                  */
246                 break;
247
248         case LWS_CALLBACK_HTTP_BODY:
249                 lwsl_notice("LWS_CALLBACK_HTTP_BODY: len %d\n", (int)len);
250                 strncpy(pss->post_string, in, sizeof (pss->post_string) -1);
251                 pss->post_string[sizeof(pss->post_string) - 1] = '\0';
252                 break;
253
254         case LWS_CALLBACK_HTTP_BODY_COMPLETION:
255                 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
256                 /*
257                  * the whole of the sent body arrived,
258                  * respond to the client with a redirect to show the
259                  * results
260                  */
261                 p = (unsigned char *)buf + LWS_PRE;
262                 n = lws_http_redirect(wsi,
263                                       HTTP_STATUS_SEE_OTHER, /* 303 */
264                                       (unsigned char *)"postresults", 12, /* location + len */
265                                       &p, /* temp buffer to use */
266                                       p + sizeof(buf) - 1 - LWS_PRE /* buffer len */
267                         );
268                 goto try_to_reuse;
269
270         case LWS_CALLBACK_HTTP_FILE_COMPLETION:
271                 goto try_to_reuse;
272
273         case LWS_CALLBACK_HTTP_WRITEABLE:
274                 // lwsl_notice("LWS_CALLBACK_HTTP_WRITEABLE\n");
275
276 #ifdef LWS_WITH_CGI
277                 if (pss->reason_bf & 1) {
278                         if (lws_cgi_write_split_stdout_headers(wsi) < 0) {
279                                 lwsl_debug("lws_cgi_write_split_stdout_headers says close\n");
280                                 return -1;
281                         }
282
283                         pss->reason_bf &= ~1;
284                         break;
285                 }
286
287
288 #endif
289 #ifndef LWS_NO_CLIENT
290                 if (pss->reason_bf & 2) {
291                         char *px = buf + LWS_PRE;
292                         int lenx = sizeof(buf) - LWS_PRE;
293                         /*
294                          * our sink is writeable and our source has something
295                          * to read.  So read a lump of source material of
296                          * suitable size to send or what's available, whichever
297                          * is the smaller.
298                          */
299                         pss->reason_bf &= ~2;
300                         wsi1 = lws_get_child(wsi);
301                         if (!wsi1)
302                                 break;
303                         if (lws_http_client_read(wsi1, &px, &lenx) < 0)
304                                 return -1;
305
306                         if (pss->client_finished)
307                                 return -1;
308                         break;
309                 }
310 #endif
311                 break;
312
313 #ifndef LWS_NO_CLIENT
314
315         case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP: {
316                 char ctype[64], ctlen = 0;
317                 lwsl_err("LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP\n");
318                 p = buffer + LWS_PRE;
319                 end = p + sizeof(buffer) - LWS_PRE;
320                 if (lws_add_http_header_status(lws_get_parent(wsi), 200, &p, end))
321                         return 1;
322                 if (lws_add_http_header_by_token(lws_get_parent(wsi),
323                                 WSI_TOKEN_HTTP_SERVER,
324                                 (unsigned char *)"libwebsockets",
325                                 13, &p, end))
326                         return 1;
327
328                 ctlen = lws_hdr_copy(wsi, ctype, sizeof(ctype), WSI_TOKEN_HTTP_CONTENT_TYPE);
329                 if (ctlen > 0) {
330                         if (lws_add_http_header_by_token(lws_get_parent(wsi),
331                                 WSI_TOKEN_HTTP_CONTENT_TYPE,
332                                 (unsigned char *)ctype, ctlen, &p, end))
333                                 return 1;
334                 }
335 #if 0
336                 if (lws_add_http_header_content_length(lws_get_parent(wsi),
337                                                        file_len, &p, end))
338                         return 1;
339 #endif
340                 if (lws_finalize_http_header(lws_get_parent(wsi), &p, end))
341                         return 1;
342
343                 *p = '\0';
344                 lwsl_info("%s\n", buffer + LWS_PRE);
345
346                 n = lws_write(lws_get_parent(wsi), buffer + LWS_PRE,
347                               p - (buffer + LWS_PRE),
348                               LWS_WRITE_HTTP_HEADERS);
349                 if (n < 0)
350                         return -1;
351
352                 break; }
353         case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
354                 //lwsl_err("LWS_CALLBACK_CLOSED_CLIENT_HTTP\n");
355                 return -1;
356                 break;
357         case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
358                 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p\n", wsi);
359                 assert(lws_get_parent(wsi));
360                 if (!lws_get_parent(wsi))
361                         break;
362                 // lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p: sock: %d, parent_wsi: %p, parent_sock:%d,  len %d\n",
363                 //              wsi, lws_get_socket_fd(wsi),
364                 //              lws_get_parent(wsi),
365                 //              lws_get_socket_fd(lws_get_parent(wsi)), len);
366                 pss1 = lws_wsi_user(lws_get_parent(wsi));
367                 pss1->reason_bf |= 2;
368                 lws_callback_on_writable(lws_get_parent(wsi));
369                 break;
370         case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:
371                 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ len %d\n", len);
372                 assert(lws_get_parent(wsi));
373                 m = lws_write(lws_get_parent(wsi), (unsigned char *)in,
374                                 len, LWS_WRITE_HTTP);
375                 if (m < 0)
376                         return -1;
377                 break;
378         case LWS_CALLBACK_COMPLETED_CLIENT_HTTP:
379                 //lwsl_err("LWS_CALLBACK_COMPLETED_CLIENT_HTTP\n");
380                 assert(lws_get_parent(wsi));
381                 if (!lws_get_parent(wsi))
382                         break;
383                 pss1 = lws_wsi_user(lws_get_parent(wsi));
384                 pss1->client_finished = 1;
385                 break;
386 #endif
387
388 #ifdef LWS_WITH_CGI
389         /* CGI IO events (POLLIN/OUT) appear here our demo user code policy is
390          *
391          *  - POST data goes on subprocess stdin
392          *  - subprocess stdout goes on http via writeable callback
393          *  - subprocess stderr goes to the logs
394          */
395         case LWS_CALLBACK_CGI:
396                 pss->args = *((struct lws_cgi_args *)in);
397                 //lwsl_notice("LWS_CALLBACK_CGI: ch %d\n", pss->args.ch);
398                 switch (pss->args.ch) { /* which of stdin/out/err ? */
399                 case LWS_STDIN:
400                         /* TBD stdin rx flow control */
401                         break;
402                 case LWS_STDOUT:;
403                         pss->reason_bf |= 1;
404                         /* when writing to MASTER would not block */
405                         lws_callback_on_writable(wsi);
406                         break;
407                 case LWS_STDERR:
408                         n = read(lws_get_socket_fd(pss->args.stdwsi[LWS_STDERR]),
409                                         buf, 127);
410                         //lwsl_notice("stderr reads %d\n", n);
411                         if (n > 0) {
412                                 if (buf[n - 1] != '\n')
413                                         buf[n++] = '\n';
414                                 buf[n] = '\0';
415                                 lwsl_notice("CGI-stderr: %s\n", buf);
416                         }
417                         break;
418                 }
419                 break;
420
421         case LWS_CALLBACK_CGI_TERMINATED:
422                 //lwsl_notice("LWS_CALLBACK_CGI_TERMINATED\n");
423                 /* because we sent on openended http, close the connection */
424                 return -1;
425
426         case LWS_CALLBACK_CGI_STDIN_DATA:  /* POST body for stdin */
427                 lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA\n");
428                 pss->args = *((struct lws_cgi_args *)in);
429                 pss->args.data[pss->args.len] = '\0';
430                 //lwsl_err("(stdin fd = %d) %s\n", lws_get_socket_fd(pss->args.stdwsi[LWS_STDIN]), pss->args.data);
431                 n = write(lws_get_socket_fd(pss->args.stdwsi[LWS_STDIN]),
432                           pss->args.data, pss->args.len);
433                 //lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: write says %d", n);
434                 if (n < pss->args.len)
435                         lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: sent %d only %d went",
436                                         n, pss->args.len);
437                 return n;
438 #endif
439
440         /*
441          * callbacks for managing the external poll() array appear in
442          * protocol 0 callback
443          */
444
445         case LWS_CALLBACK_LOCK_POLL:
446                 test_server_lock(len);
447                 break;
448
449         case LWS_CALLBACK_UNLOCK_POLL:
450                 test_server_unlock(len);
451                 break;
452
453         case LWS_CALLBACK_GET_THREAD_ID:
454                 /* return pthread_getthreadid_np(); */
455
456                 break;
457
458         default:
459                 break;
460         }
461
462         return 0;
463
464         /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
465 try_to_reuse:
466         if (lws_http_transaction_completed(wsi))
467                 return -1;
468
469         return 0;
470 }