034753f461eeb962b34b76fbd206a4594029f310
[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 <sys/stat.h>
36 #include "../include/local-def.h"
37
38 // let's compute fixed URL length only once
39 static apiUrlLen=0;
40 static baseUrlLen=0;
41 static rootUrlLen=0;
42
43 // proto missing from GCC
44 char *strcasestr(const char *haystack, const char *needle);
45
46 static int rqtcount = 0;  // dummy request rqtcount to make each message be different
47 static int postcount = 0;
48
49 // try to open libmagic to handle mime types
50 static AFB_error initLibMagic (AFB_session *session) {
51   
52     /*MAGIC_MIME tells magic to return a mime of the file, but you can specify different things*/
53     if (verbose) printf("Loading mimetype default magic database\n");
54   
55     session->magic = magic_open(MAGIC_MIME_TYPE);
56     if (session->magic == NULL) {
57         fprintf(stderr,"ERROR: unable to initialize magic library\n");
58         return AFB_FAIL;
59     }
60     
61     // Warning: should not use NULL for DB [libmagic bug wont pass efence check]
62     if (magic_load(session->magic, MAGIC_DB) != 0) {
63         fprintf(stderr,"cannot load magic database - %s\n", magic_error(session->magic));
64         magic_close(session->magic);
65         return AFB_FAIL;
66     }
67
68     return AFB_SUCCESS;
69 }
70
71 // Because of POST call multiple time requestApi we need to free POST handle here
72 static void endRequest (void *cls, struct MHD_Connection *connection, void **con_cls, enum MHD_RequestTerminationCode toe) {
73   AFB_HttpPost *posthandle = *con_cls;
74
75   // if post handle was used let's free everything
76   if (posthandle) {
77      if (verbose) fprintf (stderr, "End Post Request UID=%d\n", posthandle->uid);
78      free (posthandle->data);
79      free (posthandle);
80   }
81 }
82
83
84 // Create check etag value
85 STATIC void computeEtag(char *etag, int maxlen, struct stat *sbuf) {
86     int time;
87     time = sbuf->st_mtim.tv_sec;
88     snprintf(etag, maxlen, "%d", time);
89 }
90
91 STATIC int servFile (struct MHD_Connection *connection, AFB_session *session, const char *url, AFB_staticfile *staticfile) {
92     const char *etagCache, *mimetype; 
93     char etagValue[15];
94     struct MHD_Response *response;
95     struct stat sbuf; 
96     int ret;
97
98     if (fstat (staticfile->fd, &sbuf) != 0) {
99         fprintf(stderr, "Fail to stat file: [%s] error:%s\n", staticfile->path, strerror(errno));
100         goto abortRequest;
101     }
102     
103     
104     
105
106     
107     // if url is a directory let's add index.html and redirect client
108     if (S_ISDIR (sbuf.st_mode)) {
109         close (staticfile->fd); // close directory check for Index
110        
111         // No trailing '/'. Let's add one and redirect for relative paths to work
112         if (url [strlen (url) -1] != '/') {
113             response = MHD_create_response_from_buffer(0,"", MHD_RESPMEM_PERSISTENT);
114             strncat(staticfile->path, "/", sizeof (staticfile->path));
115             MHD_add_response_header (response, "Location", staticfile->path);
116             MHD_queue_response (connection, MHD_HTTP_MOVED_PERMANENTLY, response);
117             if (verbose) fprintf (stderr,"Adding trailing '/' [%s]\n",staticfile->path);      
118             goto sendRequest;
119         }
120         
121         strncat (staticfile->path, OPA_INDEX, sizeof (staticfile->path));
122         if (-1 == (staticfile->fd = open(staticfile->path, O_RDONLY)) || (fstat (staticfile->fd, &sbuf) != 0)) {
123            fprintf(stderr, "No Index.html in direcory [%s]\n", staticfile->path);
124            goto abortRequest;  
125         }      
126     } else if (! S_ISREG (sbuf.st_mode)) { // only standard file any other one including symbolic links are refused.
127         close (staticfile->fd); // nothing useful to do with this file
128         fprintf (stderr, "Fail file: [%s] is not a regular file\n", staticfile->path);
129         const char *errorstr = "<html><body>Application Framework Binder Invalid file type</body></html>";
130         response = MHD_create_response_from_buffer (strlen (errorstr),
131                      (void *) errorstr,  MHD_RESPMEM_PERSISTENT);
132         MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response);
133         goto sendRequest;
134     } 
135     
136     // https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching?hl=fr
137     // ftp://ftp.heanet.ie/disk1/www.gnu.org/software/libmicrohttpd/doxygen/dc/d0c/microhttpd_8h.html
138
139     // Check etag value and load file only when modification date changes
140     etagCache = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_IF_NONE_MATCH);
141     computeEtag(etagValue, sizeof (etagValue), &sbuf);
142
143     if (etagCache != NULL && strcmp(etagValue, etagCache) == 0) {
144         close(staticfile->fd); // file did not change since last upload
145         if (verbose) fprintf(stderr, "Not Modify: [%s]\n", staticfile->path);
146         response = MHD_create_response_from_buffer(0, "", MHD_RESPMEM_PERSISTENT);
147         MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, session->cacheTimeout); // default one hour cache
148         MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etagValue);
149         MHD_queue_response(connection, MHD_HTTP_NOT_MODIFIED, response);
150
151     } else { // it's a new file, we need to upload it to client
152         // if we have magic let's try to guest mime type
153         if (session->magic) {          
154            mimetype= magic_descriptor(session->magic, staticfile->fd);
155            if (mimetype != NULL)  MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, mimetype);
156         } else mimetype="Unknown";
157         
158         if (verbose) fprintf(stderr, "Serving: [%s] mime=%s\n", staticfile->path, mimetype);
159         response = MHD_create_response_from_fd(sbuf.st_size, staticfile->fd);
160         MHD_add_response_header(response, MHD_HTTP_HEADER_CACHE_CONTROL, session->cacheTimeout); // default one hour cache
161         MHD_add_response_header(response, MHD_HTTP_HEADER_ETAG, etagValue);
162         MHD_queue_response(connection, MHD_HTTP_OK, response);
163     }
164     
165 sendRequest:    
166     MHD_destroy_response(response);
167     return (MHD_YES);
168
169 abortRequest:
170     return (FAILED);
171 }
172
173
174 // this function return either Index.htlm or a redirect to /#!route to make angular happy
175 STATIC int redirectHTML5(struct MHD_Connection *connection, AFB_session *session, const char* url) {
176
177     int fd;
178     int ret;
179     struct MHD_Response *response;
180     AFB_staticfile staticfile;
181
182     // Url match /opa/xxxx should redirect to "/opa/#!page" to force index.html reload
183     strncpy(staticfile.path, session->config->rootbase, sizeof (staticfile.path));
184     strncat(staticfile.path, "/#!", sizeof (staticfile.path));
185     strncat(staticfile.path, &url[1], sizeof (staticfile.path));
186     response = MHD_create_response_from_buffer(0,"", MHD_RESPMEM_PERSISTENT);
187     MHD_add_response_header (response, "Location", staticfile.path);
188     MHD_queue_response (connection, MHD_HTTP_MOVED_PERMANENTLY, response);
189     if (verbose) fprintf (stderr,"checkHTML5 redirect to [%s]\n",staticfile.path);
190     return (MHD_YES);
191 }
192
193
194 // minimal httpd file server for static HTML,JS,CSS,etc...
195 STATIC int requestFile(struct MHD_Connection *connection, AFB_session *session, const char* url) {
196     int fd, ret, idx;
197     AFB_staticfile staticfile;
198     char *requestdir, *requesturl;
199    
200     // default search for file is rootdir base
201     requestdir= session->config->rootdir;
202     requesturl=(char*)url;
203     
204     // Check for optional aliases
205     for (idx=0; session->config->aliasdir[idx].url != NULL; idx++) {
206         if (0 == strncmp(url, session->config->aliasdir[idx].url, session->config->aliasdir[idx].len)) {
207              requestdir = session->config->aliasdir[idx].path;
208              requesturl=(char*)&url[session->config->aliasdir[idx].len];
209              break;
210         }
211     }
212     
213     // build full path from rootdir + url
214     strncpy(staticfile.path, requestdir, sizeof (staticfile.path));   
215     strncat(staticfile.path, requesturl, sizeof (staticfile.path));
216
217     // try to open file and get its size
218     if (-1 == (staticfile.fd = open(staticfile.path, O_RDONLY))) {
219         fprintf(stderr, "Fail to open file: [%s] error:%s\n", staticfile.path, strerror(errno));
220         return (FAILED);
221     }
222     // open file is OK let use it
223     ret = servFile (connection, session, url, &staticfile);
224     return ret;
225 }
226
227 // Check and Dispatch HTTP request
228 STATIC int newRequest(void *cls,
229         struct MHD_Connection *connection,
230         const char *url,
231         const char *method,
232         const char *version,
233         const char *upload_data, size_t *upload_data_size, void **con_cls) {
234
235     AFB_session *session = cls;
236     struct MHD_Response *response;
237     int ret;
238     
239     // this is a REST API let's check for plugins
240     if (0 == strncmp(url, session->config->rootapi, apiUrlLen)) {
241         ret = doRestApi(connection, session, &url[apiUrlLen+1], method, upload_data, upload_data_size, con_cls);
242         return ret;
243     }
244     
245     // From here only accept get request
246     if (0 != strcmp(method, MHD_HTTP_METHOD_GET)) return MHD_NO; /* unexpected method */
247    
248     // If a static file exist serve it now
249     ret = requestFile(connection, session, url);
250     if (ret != FAILED) return ret;
251     
252     // no static was served let's try HTML5 OPA redirect
253     if (0 == strncmp(url, session->config->rootbase, baseUrlLen)) {
254         ret = redirectHTML5(connection, session, &url[baseUrlLen]);
255         return ret;
256     }
257
258      // Nothing respond to this request Files, API, Angular Base
259     const char *errorstr = "<html><body>Alsa-Json-Gateway Unknown or Not readable file</body></html>";
260     response = MHD_create_response_from_buffer(strlen(errorstr), (void*)errorstr, MHD_RESPMEM_PERSISTENT);
261     ret = MHD_queue_response(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response);
262     return (MHD_YES);
263 }
264
265 STATIC int newClient(void *cls, const struct sockaddr * addr, socklen_t addrlen) {
266     // check if client is coming from an acceptable IP
267     return (MHD_YES); // MHD_NO
268 }
269
270
271 PUBLIC AFB_error httpdStart(AFB_session *session) {
272     
273     // compute fixed URL length at startup time
274     apiUrlLen = strlen (session->config->rootapi);
275     baseUrlLen= strlen (session->config->rootbase);
276     rootUrlLen= strlen (session->config->rootdir);
277      
278     // TBD open libmagic cache [fail to pass EFENCE check]
279     // initLibMagic (session);
280     
281     
282     if (verbose) {
283         printf("AFB:notice Waiting port=%d rootdir=%s\n", session->config->httpdPort, session->config->rootdir);
284         printf("AFB:notice Browser URL= http://localhost:%d\n", session->config->httpdPort);
285     }
286
287     session->httpd = (void*) MHD_start_daemon(
288             MHD_USE_SELECT_INTERNALLY | MHD_USE_DEBUG, // use request and not threads
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, MHD_OPTION_END); // 15s + options-end
294     // TBD: MHD_OPTION_SOCK_ADDR
295
296     if (session->httpd == NULL) {
297         printf("Error: httpStart invalid httpd port: %d", session->config->httpdPort);
298         return AFB_FATAL;
299     }
300     return AFB_SUCCESS;
301 }
302
303 // infinite loop
304 PUBLIC AFB_error httpdLoop(AFB_session *session) {
305     static int  count = 0;
306
307     if (verbose) fprintf(stderr, "AFB:notice entering httpd waiting loop\n");
308     if (session->foreground) {
309
310         while (TRUE) {
311             fprintf(stderr, "AFB:notice Use Ctrl-C to quit\n");
312             (void) getc(stdin);
313         }
314     } else {
315         while (TRUE) {
316             sleep(3600);
317             if (verbose) fprintf(stderr, "AFB:notice httpd alive [%d]\n", count++);
318         }
319     }
320
321     // should never return from here
322     return AFB_FATAL;
323 }
324
325 PUBLIC int httpdStatus(AFB_session *session) {
326     return (MHD_run(session->httpd));
327 }
328
329 PUBLIC void httpdStop(AFB_session *session) {
330     MHD_stop_daemon(session->httpd);
331 }