acc12a88cf5f5f61ee435694368b400ec6766db0
[src/app-framework-binder.git] / src / http-svc.c
1 /*
2  * Copyright (C) 2015 "IoT.bzh"
3  * Author "Fulup Ar Foll"
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  * 
18  * Handle standard HTTP request
19  *    Features/Restriction:
20     - handle ETAG to limit upload to modified/new files [cache default 3600s]
21     - handles redirect to index.htlm when path is a directory [code 301]
22     - only support GET method
23     - does not follow link.
24
25    References: https://www.gnu.org/software/libmicrohttpd/manual/html_node/index.html#Top
26    http://libmicrohttpd.sourcearchive.com/documentation/0.4.2/microhttpd_8h.html
27    https://gnunet.org/svn/libmicrohttpd/src/examples/fileserver_example_external_select.c
28    https://github.com/json-c/json-c
29    POST https://www.gnu.org/software/libmicrohttpd/manual/html_node/microhttpd_002dpost.html#microhttpd_002dpost
30  */
31
32
33 #include <microhttpd.h>
34
35 #include <poll.h>
36 #include <sys/stat.h>
37 #include "../include/local-def.h"
38
39 // let's compute fixed URL length only once
40 static apiUrlLen=0;
41 static baseUrlLen=0;
42 static rootUrlLen=0;
43
44 // proto missing from GCC
45 char *strcasestr(const char *haystack, const char *needle);
46
47 static int rqtcount = 0;  // dummy request rqtcount to make each message be different
48 static int postcount = 0;
49
50 // try to open libmagic to handle mime types
51 static AFB_error initLibMagic (AFB_session *session) {
52   
53     /*MAGIC_MIME tells magic to return a mime of the file, but you can specify different things*/
54     if (verbose) printf("Loading mimetype default magic database\n");
55   
56     session->magic = magic_open(MAGIC_MIME_TYPE);
57     if (session->magic == NULL) {
58         fprintf(stderr,"ERROR: unable to initialize magic library\n");
59         return AFB_FAIL;
60     }
61     
62     // Warning: should not use NULL for DB [libmagic bug wont pass efence check]
63     if (magic_load(session->magic, MAGIC_DB) != 0) {
64         fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
65         magic_close(session->magic);
66         return AFB_FAIL;
67     }
68
69     return AFB_SUCCESS;
70 }
71
72 // Because of POST call multiple time requestApi we need to free POST handle here
73 static void endRequest (void *cls, struct MHD_Connection *connection, void **con_cls, enum MHD_RequestTerminationCode toe) {
74   AFB_PostHandle *posthandle = *con_cls;
75
76   // if post handle was used let's free everything
77   if (posthandle != NULL) endPostRequest (posthandle);
78 }
79
80
81 // Create check etag value
82 STATIC void computeEtag(char *etag, int maxlen, struct stat *sbuf) {
83     int time;
84     time = sbuf->st_mtim.tv_sec;
85     snprintf(etag, maxlen, "%d", time);
86 }
87
88 STATIC int servFile (struct MHD_Connection *connection, AFB_session *session, const char *url, AFB_staticfile *staticfile) {
89     const char *etagCache, *mimetype; 
90     char etagValue[15];
91     struct MHD_Response *response;
92     struct stat sbuf; 
93     int ret;
94
95     if (fstat (staticfile->fd, &sbuf) != 0) {
96         fprintf(stderr, "Fail to stat file: [%s] error:%s\n", staticfile->path, strerror(errno));
97         goto abortRequest;
98     }
99        
100     // if url is a directory let's add index.html and redirect client
101     if (S_ISDIR (sbuf.st_mode)) {
102         close (staticfile->fd); // close directory check for Index
103        
104         // No trailing '/'. Let's add one and redirect for relative paths to work
105         if (url [strlen (url) -1] != '/') {
106             response = MHD_create_response_from_buffer(0,"", MHD_RESPMEM_PERSISTENT);
107             strncpy(staticfile->path, url, sizeof (staticfile->path));
108             strncat(staticfile->path, "/", sizeof (staticfile->path));
109             MHD_add_response_header (response, "Location", staticfile->path);
110             MHD_queue_response (connection, MHD_HTTP_MOVED_PERMANENTLY, response);
111             if (verbose) fprintf (stderr,"Adding trailing '/' [%s]\n",staticfile->path);      
112             goto sendRequest;
113         }
114         
115         strncat (staticfile->path, OPA_INDEX, sizeof (staticfile->path));
116         if (-1 == (staticfile->fd = open(staticfile->path, O_RDONLY)) || (fstat (staticfile->fd, &sbuf) != 0)) {
117            fprintf(stderr, "No Index.html in direcory [%s]\n", staticfile->path);
118            goto abortRequest;  
119         } 
120     } else if (! S_ISREG (sbuf.st_mode)) { // only standard file any other one including symbolic links are refused.
121         close (staticfile->fd); // nothing useful to do with this file
122         fprintf (stderr, "Fail file: [%s] is not a regular file\n", staticfile->path);
123         const char *errorstr = "<html><body>Application Framework Binder Invalid file type</body></html>";
124         response = MHD_create_response_from_buffer (strlen (errorstr),
125                      (void *) errorstr,  MHD_RESPMEM_PERSISTENT);
126         MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response);
127         goto sendRequest;
128     } 
129     
130     // https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching?hl=fr
131     // ftp://ftp.heanet.ie/disk1/www.gnu.org/software/libmicrohttpd/doxygen/dc/d0c/microhttpd_8h.html
132
133     // Check etag value and load file only when modification date changes
134     etagCache = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
135     computeEtag(etagValue, sizeof (etagValue), &sbuf);
136
137     if (etagCache != NULL && strcmp(etagValue, etagCache) == 0) {
138         close(staticfile->fd); // file did not change since last upload
139         if (verbose) fprintf(stderr, "Not Modify: [%s]\n", staticfile->path);
140         response = MHD_create_response_from_buffer(0, "", MHD_RESPMEM_PERSISTENT);
141         MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, session->cacheTimeout); // default one hour cache
142         MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etagValue);
143         MHD_queue_response(connection, MHD_HTTP_NOT_MODIFIED, response);
144
145     } else { // it's a new file, we need to upload it to client
146         // if we have magic let's try to guest mime type
147         if (session->magic) {          
148            mimetype= magic_descriptor(session->magic, staticfile->fd);
149            if (mimetype != NULL)  MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
150         } else mimetype="application/unknown";
151         
152         if (verbose) fprintf(stderr, "Serving: [%s] mime=%s\n", staticfile->path, mimetype);
153         response = MHD_create_response_from_fd(sbuf.st_size, staticfile->fd);
154         MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, session->cacheTimeout); // default one hour cache
155         MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etagValue);
156         MHD_queue_response(connection, MHD_HTTP_OK, response);
157     }
158     
159 sendRequest:    
160     MHD_destroy_response(response);
161     return (MHD_YES);
162
163 abortRequest:
164     return (FAILED);
165 }
166
167
168 // this function return either Index.htlm or a redirect to /#!route to make angular happy
169 STATIC int redirectHTML5(struct MHD_Connection *connection, AFB_session *session, const char* url) {
170
171     int fd;
172     int ret;
173     struct MHD_Response *response;
174     AFB_staticfile staticfile;
175
176     // Url match /opa/xxxx should redirect to "/opa/#!page" to force index.html reload
177     strncpy(staticfile.path, session->config->rootbase, sizeof (staticfile.path));
178     strncat(staticfile.path, "/#!", sizeof (staticfile.path));
179     strncat(staticfile.path, &url[1], sizeof (staticfile.path));
180     response = MHD_create_response_from_buffer(0,"", MHD_RESPMEM_PERSISTENT);
181     MHD_add_response_header (response, "Location", staticfile.path);
182     MHD_queue_response (connection, MHD_HTTP_MOVED_PERMANENTLY, response);
183     if (verbose) fprintf (stderr,"checkHTML5 redirect to [%s]\n",staticfile.path);
184     return (MHD_YES);
185 }
186
187
188 // minimal httpd file server for static HTML,JS,CSS,etc...
189 STATIC int requestFile(struct MHD_Connection *connection, AFB_session *session, const char* url) {
190     int fd, ret, idx;
191     AFB_staticfile staticfile;
192     char *requestdir, *requesturl;
193    
194     // default search for file is rootdir base
195     requestdir= session->config->rootdir;
196     requesturl=(char*)url;
197     
198     // Check for optional aliases
199     for (idx=0; session->config->aliasdir[idx].url != NULL; idx++) {
200         if (0 == strncmp(url, session->config->aliasdir[idx].url, session->config->aliasdir[idx].len)) {
201              requestdir = session->config->aliasdir[idx].path;
202              requesturl=(char*)&url[session->config->aliasdir[idx].len];
203              break;
204         }
205     }
206     
207     // build full path from rootdir + url
208     strncpy(staticfile.path, requestdir, sizeof (staticfile.path));   
209     strncat(staticfile.path, requesturl, sizeof (staticfile.path));
210
211     // try to open file and get its size
212     if (-1 == (staticfile.fd = open(staticfile.path, O_RDONLY))) {
213         fprintf(stderr, "Fail to open file: [%s] error:%s\n", staticfile.path, strerror(errno));
214         return (FAILED);
215     }
216     // open file is OK let use it
217     ret = servFile (connection, session, url, &staticfile);
218     return ret;
219 }
220
221 // Check and Dispatch HTTP request
222 STATIC int newRequest(void *cls,
223         struct MHD_Connection *connection,
224         const char *url,
225         const char *method,
226         const char *version,
227         const char *upload_data, size_t *upload_data_size, void **con_cls) {
228
229     AFB_session *session = cls;
230     struct MHD_Response *response;
231     int ret;
232     
233     // this is a REST API let's check for plugins
234     if (0 == strncmp(url, session->config->rootapi, apiUrlLen)) {
235         ret = doRestApi(connection, session, &url[apiUrlLen+1], method, upload_data, upload_data_size, con_cls);
236         return ret;
237     }
238     
239     // From here only accept get request
240     if (0 != strcmp(method, MHD_HTTP_METHOD_GET)) return MHD_NO; /* unexpected method */
241    
242     // If a static file exist serve it now
243     ret = requestFile(connection, session, url);
244     if (ret != FAILED) return ret;
245     
246     // no static was served let's try HTML5 OPA redirect
247     if (0 == strncmp(url, session->config->rootbase, baseUrlLen)) {
248         ret = redirectHTML5(connection, session, &url[baseUrlLen]);
249         return ret;
250     }
251
252      // Nothing respond to this request Files, API, Angular Base
253     const char *errorstr = "<html><body>AFB-Daemon File Not Find file</body></html>";
254     response = MHD_create_response_from_buffer(strlen(errorstr), (void*)errorstr, MHD_RESPMEM_PERSISTENT);
255     ret = MHD_queue_response(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response);
256     return (MHD_YES);
257 }
258
259 STATIC int newClient(void *cls, const struct sockaddr * addr, socklen_t addrlen) {
260     // check if client is coming from an acceptable IP
261     return (MHD_YES); // MHD_NO
262 }
263
264
265 PUBLIC AFB_error httpdStart(AFB_session *session) {
266
267     // compute fixed URL length at startup time
268     apiUrlLen = strlen (session->config->rootapi);
269     baseUrlLen= strlen (session->config->rootbase);
270     rootUrlLen= strlen (session->config->rootdir);
271     
272     // Initialise Client Session Hash Table
273     ctxStoreInit (CTX_NBCLIENTS);
274      
275     //TBD open libmagic cache [fail to pass EFENCE check (allocating 0 bytes)]
276     //initLibMagic (session);
277     
278     
279     if (verbose) {
280         printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
281         printf("AFB:notice Browser URL= http://localhost:%d\n", session->config->httpdPort);
282     }
283
284     session->httpd = (void*) MHD_start_daemon(
285                 MHD_USE_EPOLL_LINUX_ONLY
286                 | MHD_USE_TCP_FASTOPEN
287                 | MHD_USE_DEBUG
288               ,
289             session->config->httpdPort, // port
290             &newClient, NULL, // Tcp Accept call back + extra attribute
291             &newRequest, session, // Http Request Call back + extra attribute
292             MHD_OPTION_NOTIFY_COMPLETED, &endRequest, NULL,
293             MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 15, // 15 seconds
294             MHD_OPTION_END); // options-end
295     // TBD: MHD_OPTION_SOCK_ADDR
296
297     if (session->httpd == NULL) {
298         printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
299         return AFB_FATAL;
300     }
301     return AFB_SUCCESS;
302 }
303
304 // infinite loop
305 PUBLIC AFB_error httpdLoop(AFB_session *session) {
306     int count = 0;
307     const union MHD_DaemonInfo *info;
308     struct pollfd pfd;
309
310     info = MHD_get_daemon_info(session->httpd,
311                                MHD_DAEMON_INFO_EPOLL_FD_LINUX_ONLY);
312     if (info == NULL) {
313         printf("Error: httpLoop no pollfd");
314         goto error;
315     }
316     pfd.fd = info->listen_fd;
317     pfd.events = POLLIN;
318
319     if (verbose) fprintf(stderr, "AFB:notice entering httpd waiting loop\n");
320     while (TRUE) {
321         if (verbose) fprintf(stderr, "AFB:notice httpd alive [%d]\n", count++);
322         poll(&pfd, 1, 15000); // 15 seconds (as above timeout when starting)
323         MHD_run(session->httpd);
324     }
325
326 error:
327     // should never return from here
328     return AFB_FATAL;
329 }
330
331 PUBLIC int httpdStatus(AFB_session *session) {
332     return (MHD_run(session->httpd));
333 }
334
335 PUBLIC void httpdStop(AFB_session *session) {
336     MHD_stop_daemon(session->httpd);
337 }