lwsws cgi integration
[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         unsigned long amount, file_len, sent;
75         char leaf_path[1024];
76         const char *mimetype;
77         char *other_headers;
78         unsigned char *end;
79         struct timeval tv;
80         unsigned char *p;
81 #ifndef LWS_NO_CLIENT
82         struct per_session_data__http *pss1;
83         struct lws *wsi1;
84 #endif
85         char buf[256];
86         char b64[64];
87         int n, m;
88 #ifdef EXTERNAL_POLL
89         struct lws_pollargs *pa = (struct lws_pollargs *)in;
90 #endif
91
92 //      lwsl_err("%s: reason %d\n", __func__, reason);
93
94         switch (reason) {
95         case LWS_CALLBACK_HTTP:
96
97                 {
98                         char name[100], rip[50];
99                         lws_get_peer_addresses(wsi, lws_get_socket_fd(wsi), name,
100                                                sizeof(name), rip, sizeof(rip));
101                         sprintf(buf, "%s (%s)", name, rip);
102                         lwsl_notice("HTTP connect from %s\n", buf);
103                 }
104
105                 if (len < 1) {
106                         lws_return_http_status(wsi,
107                                                 HTTP_STATUS_BAD_REQUEST, NULL);
108                         goto try_to_reuse;
109                 }
110
111 #ifndef LWS_NO_CLIENT
112                 if (!strncmp(in, "/proxytest", 10)) {
113                         struct lws_client_connect_info i;
114                         char *rootpath = "/";
115                         const char *p = (const char *)in;
116
117                         if (lws_get_child(wsi))
118                                 break;
119
120                         pss->client_finished = 0;
121                         memset(&i,0, sizeof(i));
122                         i.context = lws_get_context(wsi);
123                         i.address = "git.libwebsockets.org";
124                         i.port = 80;
125                         i.ssl_connection = 0;
126                         if (p[10])
127                                 i.path = (char *)in + 10;
128                         else
129                                 i.path = rootpath;
130                         i.host = "git.libwebsockets.org";
131                         i.origin = NULL;
132                         i.method = "GET";
133                         i.parent_wsi = wsi;
134                         i.uri_replace_from = "git.libwebsockets.org/";
135                         i.uri_replace_to = "/proxytest/";
136                         if (!lws_client_connect_via_info(&i)) {
137                                 lwsl_err("proxy connect fail\n");
138                                 break;
139                         }
140
141
142
143                         break;
144                 }
145 #endif
146
147 #if 1
148                 /* this example server has no concept of directories */
149                 if (strchr((const char *)in + 1, '/')) {
150                         lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
151                         goto try_to_reuse;
152                 }
153 #endif
154
155                 /* if a legal POST URL, let it continue and accept data */
156                 if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI))
157                         return 0;
158
159                 /* check for the "send a big file by hand" example case */
160                 lwsl_notice("%s\n", in);
161                 if (!strcmp((const char *)in, "/leaf.jpg")) {
162                         if (strlen(resource_path) > sizeof(leaf_path) - 10)
163                                 return -1;
164                         sprintf(leaf_path, "%s/leaf.jpg", resource_path);
165
166                         /* well, let's demonstrate how to send the hard way */
167
168                         p = buffer + LWS_PRE;
169                         end = p + sizeof(buffer) - LWS_PRE;
170
171                         pss->fd = lws_plat_file_open(wsi, leaf_path, &file_len,
172                                                      LWS_O_RDONLY);
173
174                         if (pss->fd == LWS_INVALID_FILE) {
175                                 lwsl_err("faild to open file %s\n", leaf_path);
176                                 return -1;
177                         }
178
179                         /*
180                          * we will send a big jpeg file, but it could be
181                          * anything.  Set the Content-Type: appropriately
182                          * so the browser knows what to do with it.
183                          *
184                          * Notice we use the APIs to build the header, which
185                          * will do the right thing for HTTP 1/1.1 and HTTP2
186                          * depending on what connection it happens to be working
187                          * on
188                          */
189                         if (lws_add_http_header_status(wsi, 200, &p, end))
190                                 return 1;
191                         if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_SERVER,
192                                         (unsigned char *)"libwebsockets",
193                                         13, &p, end))
194                                 return 1;
195                         if (lws_add_http_header_by_token(wsi,
196                                         WSI_TOKEN_HTTP_CONTENT_TYPE,
197                                         (unsigned char *)"image/jpeg",
198                                         10, &p, end))
199                                 return 1;
200                         if (lws_add_http_header_content_length(wsi,
201                                                                file_len, &p,
202                                                                end))
203                                 return 1;
204                         if (lws_finalize_http_header(wsi, &p, end))
205                                 return 1;
206
207                         /*
208                          * send the http headers...
209                          * this won't block since it's the first payload sent
210                          * on the connection since it was established
211                          * (too small for partial)
212                          *
213                          * Notice they are sent using LWS_WRITE_HTTP_HEADERS
214                          * which also means you can't send body too in one step,
215                          * this is mandated by changes in HTTP2
216                          */
217
218                         *p = '\0';
219                         lwsl_info("%s\n", buffer + LWS_PRE);
220
221                         n = lws_write(wsi, buffer + LWS_PRE,
222                                       p - (buffer + LWS_PRE),
223                                       LWS_WRITE_HTTP_HEADERS);
224                         if (n < 0) {
225                                 lws_plat_file_close(wsi, pss->fd);
226                                 return -1;
227                         }
228                         /*
229                          * book us a LWS_CALLBACK_HTTP_WRITEABLE callback
230                          */
231                         lws_callback_on_writable(wsi);
232                         break;
233                 }
234
235                 /* if not, send a file the easy way */
236                 if (!strncmp(in, "/cgit-data/", 11)) {
237                         in = (char *)in + 11;
238                         strcpy(buf, "/usr/share/cgit");
239                 } else
240                         strcpy(buf, resource_path);
241
242                 if (strcmp(in, "/")) {
243                         if (*((const char *)in) != '/')
244                                 strcat(buf, "/");
245                         strncat(buf, in, sizeof(buf) - strlen(buf) - 1);
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 = leaf_path;
262                 p = (unsigned char *)leaf_path;
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                         if (lws_add_http_header_by_name(wsi,
272                                 (unsigned char *)"set-cookie:",
273                                 (unsigned char *)b64, n, &p,
274                                 (unsigned char *)leaf_path + sizeof(leaf_path)))
275                                 return 1;
276                 }
277                 if (lws_is_ssl(wsi) && lws_add_http_header_by_name(wsi,
278                                                 (unsigned char *)
279                                                 "Strict-Transport-Security:",
280                                                 (unsigned char *)
281                                                 "max-age=15768000 ; "
282                                                 "includeSubDomains", 36, &p,
283                                                 (unsigned char *)leaf_path +
284                                                         sizeof(leaf_path)))
285                         return 1;
286                 n = (char *)p - leaf_path;
287
288                 n = lws_serve_http_file(wsi, buf, mimetype, other_headers, n);
289                 if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
290                         return -1; /* error or can't reuse connection: close the socket */
291
292                 /*
293                  * notice that the sending of the file completes asynchronously,
294                  * we'll get a LWS_CALLBACK_HTTP_FILE_COMPLETION callback when
295                  * it's done
296                  */
297                 break;
298
299         case LWS_CALLBACK_HTTP_BODY:
300                 strncpy(buf, in, 20);
301                 buf[20] = '\0';
302                 if (len < 20)
303                         buf[len] = '\0';
304
305                 lwsl_notice("LWS_CALLBACK_HTTP_BODY: %s... len %d\n",
306                                 (const char *)buf, (int)len);
307
308                 break;
309
310         case LWS_CALLBACK_HTTP_BODY_COMPLETION:
311                 lwsl_notice("LWS_CALLBACK_HTTP_BODY_COMPLETION\n");
312                 /* the whole of the sent body arrived, close or reuse the connection */
313                 lws_return_http_status(wsi, HTTP_STATUS_OK, NULL);
314                 goto try_to_reuse;
315
316         case LWS_CALLBACK_HTTP_FILE_COMPLETION:
317                 goto try_to_reuse;
318
319         case LWS_CALLBACK_HTTP_WRITEABLE:
320                 lwsl_info("LWS_CALLBACK_HTTP_WRITEABLE\n");
321
322                 if (pss->client_finished)
323                         return -1;
324
325                 if (pss->fd == LWS_INVALID_FILE)
326                         goto try_to_reuse;
327 #ifdef LWS_WITH_CGI
328                 if (pss->reason_bf & 1) {
329                         if (lws_cgi_write_split_stdout_headers(wsi) < 0)
330                                 goto bail;
331
332                         pss->reason_bf &= ~1;
333                         break;
334                 }
335 #endif
336 #ifndef LWS_NO_CLIENT
337                 if (pss->reason_bf & 2) {
338                         char *px = buf + LWS_PRE;
339                         int lenx = sizeof(buf) - LWS_PRE;
340                         /*
341                          * our sink is writeable and our source has something
342                          * to read.  So read a lump of source material of
343                          * suitable size to send or what's available, whichever
344                          * is the smaller.
345                          */
346                         pss->reason_bf &= ~2;
347                         wsi1 = lws_get_child(wsi);
348                         if (!wsi1)
349                                 break;
350                         if (lws_http_client_read(wsi1, &px, &lenx) < 0)
351                                 goto bail;
352
353                         if (pss->client_finished)
354                                 return -1;
355                         break;
356                 }
357 #endif
358                 /*
359                  * we can send more of whatever it is we were sending
360                  */
361                 sent = 0;
362                 do {
363                         /* we'd like the send this much */
364                         n = sizeof(buffer) - LWS_PRE;
365
366                         /* but if the peer told us he wants less, we can adapt */
367                         m = lws_get_peer_write_allowance(wsi);
368
369                         /* -1 means not using a protocol that has this info */
370                         if (m == 0)
371                                 /* right now, peer can't handle anything */
372                                 goto later;
373
374                         if (m != -1 && m < n)
375                                 /* he couldn't handle that much */
376                                 n = m;
377
378                         n = lws_plat_file_read(wsi, pss->fd,
379                                                &amount, buffer + LWS_PRE, n);
380                         /* problem reading, close conn */
381                         if (n < 0) {
382                                 lwsl_err("problem reading file\n");
383                                 goto bail;
384                         }
385                         n = (int)amount;
386                         /* sent it all, close conn */
387                         if (n == 0)
388                                 goto penultimate;
389                         /*
390                          * To support HTTP2, must take care about preamble space
391                          *
392                          * identification of when we send the last payload frame
393                          * is handled by the library itself if you sent a
394                          * content-length header
395                          */
396                         m = lws_write(wsi, buffer + LWS_PRE, n, LWS_WRITE_HTTP);
397                         if (m < 0) {
398                                 lwsl_err("write failed\n");
399                                 /* write failed, close conn */
400                                 goto bail;
401                         }
402                         if (m) /* while still active, extend timeout */
403                                 lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT, 5);
404                         sent += m;
405
406                 } while (!lws_send_pipe_choked(wsi) && (sent < 1024 * 1024));
407 later:
408                 lws_callback_on_writable(wsi);
409                 break;
410 penultimate:
411                 lws_plat_file_close(wsi, pss->fd);
412                 pss->fd = LWS_INVALID_FILE;
413                 goto try_to_reuse;
414
415 bail:
416                 lws_plat_file_close(wsi, pss->fd);
417
418                 return -1;
419
420         /*
421          * callback for confirming to continue with client IP appear in
422          * protocol 0 callback since no websocket protocol has been agreed
423          * yet.  You can just ignore this if you won't filter on client IP
424          * since the default unhandled callback return is 0 meaning let the
425          * connection continue.
426          */
427         case LWS_CALLBACK_FILTER_NETWORK_CONNECTION:
428                 /* if we returned non-zero from here, we kill the connection */
429                 break;
430
431 #ifndef LWS_NO_CLIENT
432         case LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP: {
433                 char ctype[64], ctlen = 0;
434                 lwsl_err("LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP\n");
435                 p = buffer + LWS_PRE;
436                 end = p + sizeof(buffer) - LWS_PRE;
437                 if (lws_add_http_header_status(lws_get_parent(wsi), 200, &p, end))
438                         return 1;
439                 if (lws_add_http_header_by_token(lws_get_parent(wsi),
440                                 WSI_TOKEN_HTTP_SERVER,
441                                 (unsigned char *)"libwebsockets",
442                                 13, &p, end))
443                         return 1;
444
445                 ctlen = lws_hdr_copy(wsi, ctype, sizeof(ctype), WSI_TOKEN_HTTP_CONTENT_TYPE);
446                 if (ctlen > 0) {
447                         if (lws_add_http_header_by_token(lws_get_parent(wsi),
448                                 WSI_TOKEN_HTTP_CONTENT_TYPE,
449                                 (unsigned char *)ctype, ctlen, &p, end))
450                                 return 1;
451                 }
452 #if 0
453                 if (lws_add_http_header_content_length(lws_get_parent(wsi),
454                                                        file_len, &p, end))
455                         return 1;
456 #endif
457                 if (lws_finalize_http_header(lws_get_parent(wsi), &p, end))
458                         return 1;
459
460                 *p = '\0';
461                 lwsl_info("%s\n", buffer + LWS_PRE);
462
463                 n = lws_write(lws_get_parent(wsi), buffer + LWS_PRE,
464                               p - (buffer + LWS_PRE),
465                               LWS_WRITE_HTTP_HEADERS);
466                 if (n < 0)
467                         return -1;
468
469                 break; }
470         case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
471                 //lwsl_err("LWS_CALLBACK_CLOSED_CLIENT_HTTP\n");
472                 return -1;
473                 break;
474         case LWS_CALLBACK_RECEIVE_CLIENT_HTTP:
475                 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p\n", wsi);
476                 assert(lws_get_parent(wsi));
477                 if (!lws_get_parent(wsi))
478                         break;
479                 // lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP: wsi %p: sock: %d, parent_wsi: %p, parent_sock:%d,  len %d\n",
480                 //              wsi, lws_get_socket_fd(wsi),
481                 //              lws_get_parent(wsi),
482                 //              lws_get_socket_fd(lws_get_parent(wsi)), len);
483                 pss1 = lws_wsi_user(lws_get_parent(wsi));
484                 pss1->reason_bf |= 2;
485                 lws_callback_on_writable(lws_get_parent(wsi));
486                 break;
487         case LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ:
488                 //lwsl_err("LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ len %d\n", len);
489                 assert(lws_get_parent(wsi));
490                 m = lws_write(lws_get_parent(wsi), (unsigned char *)in,
491                                 len, LWS_WRITE_HTTP);
492                 if (m < 0)
493                         return -1;
494                 break;
495         case LWS_CALLBACK_COMPLETED_CLIENT_HTTP:
496                 //lwsl_err("LWS_CALLBACK_COMPLETED_CLIENT_HTTP\n");
497                 assert(lws_get_parent(wsi));
498                 if (!lws_get_parent(wsi))
499                         break;
500                 pss1 = lws_wsi_user(lws_get_parent(wsi));
501                 pss1->client_finished = 1;
502                 break;
503 #endif
504
505 #ifdef LWS_WITH_CGI
506         /* CGI IO events (POLLIN/OUT) appear here our demo user code policy is
507          *
508          *  - POST data goes on subprocess stdin
509          *  - subprocess stdout goes on http via writeable callback
510          *  - subprocess stderr goes to the logs
511          */
512         case LWS_CALLBACK_CGI:
513                 pss->args = *((struct lws_cgi_args *)in);
514                 //lwsl_notice("LWS_CALLBACK_CGI: ch %d\n", pss->args.ch);
515                 switch (pss->args.ch) { /* which of stdin/out/err ? */
516                 case LWS_STDIN:
517                         /* TBD stdin rx flow control */
518                         break;
519                 case LWS_STDOUT:
520                         pss->reason_bf |= 1;
521                         /* when writing to MASTER would not block */
522                         lws_callback_on_writable(wsi);
523                         break;
524                 case LWS_STDERR:
525                         n = read(lws_get_socket_fd(pss->args.stdwsi[LWS_STDERR]),
526                                         buf, 127);
527                         //lwsl_notice("stderr reads %d\n", n);
528                         if (n > 0) {
529                                 if (buf[n - 1] != '\n')
530                                         buf[n++] = '\n';
531                                 buf[n] = '\0';
532                                 lwsl_notice("CGI-stderr: %s\n", buf);
533                         }
534                         break;
535                 }
536                 break;
537
538         case LWS_CALLBACK_CGI_TERMINATED:
539                 //lwsl_notice("LWS_CALLBACK_CGI_TERMINATED\n");
540                 /* because we sent on openended http, close the connection */
541                 return -1;
542
543         case LWS_CALLBACK_CGI_STDIN_DATA:  /* POST body for stdin */
544                 //lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA\n");
545                 pss->args = *((struct lws_cgi_args *)in);
546                 n = write(lws_get_socket_fd(pss->args.stdwsi[LWS_STDIN]),
547                           pss->args.data, pss->args.len);
548                 //lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: write says %d", n);
549                 if (n < pss->args.len)
550                         lwsl_notice("LWS_CALLBACK_CGI_STDIN_DATA: sent %d only %d went",
551                                         n, pss->args.len);
552                 return n;
553 #endif
554
555         /*
556          * callbacks for managing the external poll() array appear in
557          * protocol 0 callback
558          */
559
560         case LWS_CALLBACK_LOCK_POLL:
561                 /*
562                  * lock mutex to protect pollfd state
563                  * called before any other POLL related callback
564                  * if protecting wsi lifecycle change, len == 1
565                  */
566                 test_server_lock(len);
567                 break;
568
569         case LWS_CALLBACK_UNLOCK_POLL:
570                 /*
571                  * unlock mutex to protect pollfd state when
572                  * called after any other POLL related callback
573                  * if protecting wsi lifecycle change, len == 1
574                  */
575                 test_server_unlock(len);
576                 break;
577
578 #ifdef EXTERNAL_POLL
579         case LWS_CALLBACK_ADD_POLL_FD:
580
581                 if (count_pollfds >= max_poll_elements) {
582                         lwsl_err("LWS_CALLBACK_ADD_POLL_FD: too many sockets to track\n");
583                         return 1;
584                 }
585
586                 fd_lookup[pa->fd] = count_pollfds;
587                 pollfds[count_pollfds].fd = pa->fd;
588                 pollfds[count_pollfds].events = pa->events;
589                 pollfds[count_pollfds++].revents = 0;
590                 break;
591
592         case LWS_CALLBACK_DEL_POLL_FD:
593                 if (!--count_pollfds)
594                         break;
595                 m = fd_lookup[pa->fd];
596                 /* have the last guy take up the vacant slot */
597                 pollfds[m] = pollfds[count_pollfds];
598                 fd_lookup[pollfds[count_pollfds].fd] = m;
599                 break;
600
601         case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
602                 pollfds[fd_lookup[pa->fd]].events = pa->events;
603                 break;
604 #endif
605
606         case LWS_CALLBACK_GET_THREAD_ID:
607                 /*
608                  * if you will call "lws_callback_on_writable"
609                  * from a different thread, return the caller thread ID
610                  * here so lws can use this information to work out if it
611                  * should signal the poll() loop to exit and restart early
612                  */
613
614                 /* return pthread_getthreadid_np(); */
615
616                 break;
617
618         default:
619                 break;
620         }
621
622         return 0;
623
624         /* if we're on HTTP1.1 or 2.0, will keep the idle connection alive */
625 try_to_reuse:
626         if (lws_http_transaction_completed(wsi))
627                 return -1;
628
629         return 0;
630 }