2 * Copyright (C) 2016 "IoT.bzh"
3 * Author "Fulup Ar Foll"
4 * Author José Bollo <jose.bollo@iot.bzh>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program 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
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 * Contain all generic part to handle REST/API
21 * https://www.gnu.org/software/libmicrohttpd/tutorial.html [search 'largepost.c']
26 #include "../include/local-def.h"
35 #define AFB_MSG_JTYPE "AJB_reply"
37 #define JSON_CONTENT "application/json"
38 #define FORM_CONTENT "multipart/form-data" /* TODO: replace with MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA */
40 static json_object *afbJsonType;
42 // Because of POST call multiple time requestApi we need to free POST handle here
43 // Note this method is called from http-svc just before closing session
44 PUBLIC void endPostRequest(AFB_PostHandle * postHandle)
47 if (postHandle->type == AFB_POST_JSON) {
48 // if (verbose) fprintf(stderr, "End PostJson Request UID=%d\n", postHandle->uid);
51 if (postHandle->type == AFB_POST_FORM) {
53 fprintf(stderr, "End PostForm Request UID=%d\n", postHandle->uid);
55 if (postHandle->privatebuf)
56 free(postHandle->privatebuf);
60 // Check of apiurl is declare in this plugin and call it
61 static AFB_error doCallPluginApi(AFB_request * request, int apiidx, int verbidx, void *context)
63 enum AFB_sessionE session;
64 json_object *jresp, *jcall, *jreqt;
65 AFB_clientCtx *clientCtx = NULL;
67 // Request was found and at least partially executed
68 jreqt = json_object_new_object();
69 json_object_get(afbJsonType); // increate jsontype reference count
70 json_object_object_add(jreqt, "jtype", afbJsonType);
72 // prepare an object to store calling values
73 jcall = json_object_new_object();
74 json_object_object_add(jcall, "prefix", json_object_new_string(request->prefix));
75 json_object_object_add(jcall, "api", json_object_new_string(request->api));
77 // Out of SessionNone every call get a client context session
78 session = afb_apis_get(apiidx, verbidx)->session;
79 if (AFB_SESSION_NONE != session) {
81 // add client context to request
82 clientCtx = ctxClientGet(request);
83 if (clientCtx == NULL) {
84 request->errcode = MHD_HTTP_INSUFFICIENT_STORAGE;
85 json_object_object_add(jcall, "status", json_object_new_string("fail"));
86 json_object_object_add(jcall, "info", json_object_new_string("Client Session Context Full !!!"));
87 json_object_object_add(jreqt, "request", jcall);
90 request->context = clientCtx->contexts[apiidx];
91 request->uuid = clientCtx->uuid;
94 fprintf(stderr, "Plugin=[%s] Api=[%s] Middleware=[%d] Client=[%p] Uuid=[%s] Token=[%s]\n", request->prefix, request->api, session, clientCtx, clientCtx->uuid, clientCtx->token);
98 case AFB_SESSION_CREATE:
99 if (clientCtx->token[0] != '\0' && request->config->token[0] != '\0') {
100 request->errcode = MHD_HTTP_UNAUTHORIZED;
101 json_object_object_add(jcall, "status", json_object_new_string("exist"));
102 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CREATE Session already exist"));
103 json_object_object_add(jreqt, "request", jcall);
107 if (AFB_SUCCESS != ctxTokenCreate(clientCtx, request)) {
108 request->errcode = MHD_HTTP_UNAUTHORIZED;
109 json_object_object_add(jcall, "status", json_object_new_string("fail"));
110 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CREATE Invalid Initial Token"));
111 json_object_object_add(jreqt, "request", jcall);
114 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
115 json_object_object_add(jcall, "token", json_object_new_string(clientCtx->token));
116 json_object_object_add(jcall, "timeout", json_object_new_int(request->config->cntxTimeout));
120 case AFB_SESSION_RENEW:
121 if (AFB_SUCCESS != ctxTokenRefresh(clientCtx, request)) {
122 request->errcode = MHD_HTTP_UNAUTHORIZED;
123 json_object_object_add(jcall, "status", json_object_new_string("fail"));
124 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_REFRESH Broken Exchange Token Chain"));
125 json_object_object_add(jreqt, "request", jcall);
128 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
129 json_object_object_add(jcall, "token", json_object_new_string(clientCtx->token));
130 json_object_object_add(jcall, "timeout", json_object_new_int(request->config->cntxTimeout));
134 case AFB_SESSION_CLOSE:
135 if (AFB_SUCCESS != ctxTokenCheck(clientCtx, request)) {
136 request->errcode = MHD_HTTP_UNAUTHORIZED;
137 json_object_object_add(jcall, "status", json_object_new_string("empty"));
138 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CLOSE Not a Valid Access Token"));
139 json_object_object_add(jreqt, "request", jcall);
142 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
146 case AFB_SESSION_CHECK:
148 // default action is check
149 if (AFB_SUCCESS != ctxTokenCheck(clientCtx, request)) {
150 request->errcode = MHD_HTTP_UNAUTHORIZED;
151 json_object_object_add(jcall, "status", json_object_new_string("fail"));
152 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CHECK Invalid Active Token"));
153 json_object_object_add(jreqt, "request", jcall);
159 // Effectively CALL PLUGIN API with a subset of the context
160 jresp = afb_apis_get(apiidx, verbidx)->callback(request, context);
162 // Store context in case it was updated by plugins
163 if (request->context != NULL)
164 clientCtx->contexts[apiidx] = request->context;
166 // handle intermediary Post Iterates out of band
167 if ((jresp == NULL) && (request->errcode == MHD_HTTP_OK))
170 // Session close is done after the API call so API can still use session in closing API
171 if (AFB_SESSION_CLOSE == session)
172 ctxTokenReset(clientCtx, request);
174 // API should return NULL of a valid Json Object
176 json_object_object_add(jcall, "status", json_object_new_string("null"));
177 json_object_object_add(jreqt, "request", jcall);
178 request->errcode = MHD_HTTP_NO_RESPONSE;
181 json_object_object_add(jcall, "status", json_object_new_string("processed"));
182 json_object_object_add(jreqt, "request", jcall);
183 json_object_object_add(jreqt, "response", jresp);
187 request->jresp = jreqt;
191 // Check of apiurl is declare in this plugin and call it
192 extern __thread sigjmp_buf *error_handler;
193 static AFB_error callPluginApi(AFB_request * request, int apiidx, int verbidx, void *context)
197 json_object *jcall, *jreqt;
200 // save context before calling the API
201 status = setjmp(jmpbuf);
204 // Request was found and at least partially executed
205 jreqt = json_object_new_object();
206 json_object_get(afbJsonType); // increate jsontype reference count
207 json_object_object_add(jreqt, "jtype", afbJsonType);
209 // prepare an object to store calling values
210 jcall = json_object_new_object();
211 json_object_object_add(jcall, "prefix", json_object_new_string(request->prefix));
212 json_object_object_add(jcall, "api", json_object_new_string(request->api));
214 // Plugin aborted somewhere during its execution
215 json_object_object_add(jcall, "status", json_object_new_string("abort"));
216 json_object_object_add(jcall, "info", json_object_new_string("Plugin broke during execution"));
217 json_object_object_add(jreqt, "request", jcall);
218 request->jresp = jreqt;
223 // Trigger a timer to protect from unacceptable long time execution
224 if (request->config->apiTimeout > 0)
225 alarm((unsigned)request->config->apiTimeout);
227 error_handler = &jmpbuf;
228 doCallPluginApi(request, apiidx, verbidx, context);
229 error_handler = NULL;
231 // cancel timeout and plugin signal handle before next call
239 STATIC AFB_error findAndCallApi(AFB_request * request, void *context)
244 if (!request->api || !request->prefix)
247 /* get the plugin if any */
248 apiidx = afb_apis_get_apiidx(request->prefix, 0);
250 request->jresp = jsonNewMessage(AFB_FATAL, "No Plugin=[%s] Url=%s", request->prefix, request->url);
251 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
255 /* get the verb if any */
256 verbidx = afb_apis_get_verbidx(apiidx, request->api);
258 request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s] url=[%s]", request->api, request->prefix, request->url);
259 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
263 /* Search for a plugin with this urlpath */
264 status = callPluginApi(request, apiidx, verbidx, context);
266 /* plugin callback did not return a valid Json Object */
267 if (status == AFB_FAIL) {
268 request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s] url=[%s]", request->api, request->prefix, request->url);
269 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
272 // Everything look OK
276 // This CB is call for every item with a form post it reformat iterator values
277 // and callback Plugin API for each Item within PostForm.
278 STATIC int doPostIterate(void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *mimetype, const char *encoding, const char *data, uint64_t offset, size_t size)
284 // retrieve API request from Post iterator handle
285 AFB_PostHandle *postHandle = (AFB_PostHandle *) cls;
286 AFB_request *request = (AFB_request *) postHandle->privatebuf;
287 AFB_PostRequest postRequest;
290 fprintf(stderr, "postHandle key=%s filename=%s len=%zu mime=%s\n", key, filename, size, mimetype);
292 // Create and Item value for Plugin API
295 item.filename = filename;
296 item.mimetype = mimetype;
297 item.encoding = encoding;
300 item.offset = offset;
302 // Reformat Request to make it somehow similar to GET/PostJson case
303 postRequest.data = (char *)postHandle;
304 postRequest.len = size;
305 postRequest.type = AFB_POST_FORM;;
306 request->post = &postRequest;
308 // effectively call plugin API
309 status = findAndCallApi(request, &item);
310 // when returning no processing of postform stop
311 if (status != AFB_SUCCESS)
314 // let's allow iterator to move to next item
318 STATIC void freeRequest(AFB_request * request)
321 free(request->prefix);
326 STATIC AFB_request *createRequest(struct MHD_Connection *connection, AFB_session * session, const char *url)
329 AFB_request *request;
331 // Start with a clean request
332 request = calloc(1, sizeof(AFB_request));
333 char *urlcpy1, *urlcpy2;
334 char *baseapi, *baseurl;
336 // Extract plugin urlpath from request and make two copy because strsep overload copy
337 urlcpy1 = urlcpy2 = strdup(url);
338 baseurl = strsep(&urlcpy2, "/");
339 if (baseurl == NULL) {
340 request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call url=[%s]", url);
341 request->errcode = MHD_HTTP_BAD_REQUEST;
344 // let's compute URL and call API
345 baseapi = strsep(&urlcpy2, "/");
346 if (baseapi == NULL) {
347 request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call plugin=[%s] url=[%s]", baseurl, url);
348 request->errcode = MHD_HTTP_BAD_REQUEST;
351 // build request structure
352 request->connection = connection;
353 request->config = session->config;
355 request->prefix = strdup(baseurl);
356 request->api = strdup(baseapi);
377 static int doRestApiPost(struct MHD_Connection *connection, AFB_session * session, const char *url, const char *method, const char *upload_data, size_t * upload_data_size, void **con_cls)
380 static int postcount = 0; // static counter to debug POST protocol
381 json_object *errMessage;
383 struct MHD_Response *webResponse;
384 const char *serialized;
385 AFB_request *request = NULL;
386 AFB_PostHandle *postHandle;
387 AFB_PostRequest postRequest;
390 // fprintf (stderr, "doRestAPI method=%s posthandle=%p\n", method, con_cls);
392 // if post data may come in multiple calls
393 const char *encoding, *param;
395 postHandle = *con_cls;
397 // This is the initial post event let's create form post structure POST data come in multiple events
398 if (postHandle == NULL) {
400 // allocate application POST processor handle to zero
401 postHandle = calloc(1, sizeof(AFB_PostHandle));
402 postHandle->uid = postcount++; // build a UID for DEBUG
403 *con_cls = postHandle; // update context with posthandle
405 // Let make sure we have the right encoding and a valid length
406 encoding = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_TYPE);
408 // We are facing an empty post let's process it as a get
409 if (encoding == NULL) {
410 postHandle->type = AFB_POST_EMPTY;
413 // Form post is handle through a PostProcessor and call API once per form key
414 if (strcasestr(encoding, FORM_CONTENT) != NULL) {
416 fprintf(stderr, "Create doPostIterate[uid=%d posthandle=%p]\n", postHandle->uid, postHandle);
418 request = createRequest(connection, session, url);
419 if (request->jresp != NULL)
421 postHandle->type = AFB_POST_FORM;
422 postHandle->privatebuf = (void *)request;
423 postHandle->pp = MHD_create_post_processor(connection, MAX_POST_SIZE, &doPostIterate, postHandle);
425 if (NULL == postHandle->pp) {
426 fprintf(stderr, "OOPS: Internal error fail to allocate MHD_create_post_processor\n");
432 // POST json is store into a buffer and present in one piece to API
433 if (strcasestr(encoding, JSON_CONTENT) != NULL) {
435 param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
437 sscanf(param, "%i", &contentlen);
439 // Because PostJson are build in RAM size is constrained
440 if (contentlen > MAX_POST_SIZE) {
441 errMessage = jsonNewMessage(AFB_FATAL, "Post Date to big %d > %d", contentlen, MAX_POST_SIZE);
444 // Size is OK, let's allocate a buffer to hold post data
445 postHandle->type = AFB_POST_JSON;
446 postHandle->privatebuf = malloc((unsigned)contentlen + 1); // allocate memory for full POST data + 1 for '\0' enf of string
448 // if (verbose) fprintf(stderr, "Create PostJson[uid=%d] Size=%d\n", postHandle->uid, contentlen);
452 // We only support Json and Form Post format
453 errMessage = jsonNewMessage(AFB_FATAL, "Post Date wrong type encoding=%s != %s", encoding, JSON_CONTENT);
458 // This time we receive partial/all Post data. Note that even if we get all POST data. We should nevertheless
459 // return MHD_YES and not process the request directly. Otherwise Libmicrohttpd is unhappy and fails with
460 // 'Internal application error, closing connection'.
461 if (*upload_data_size) {
463 if (postHandle->type == AFB_POST_FORM) {
464 // if (verbose) fprintf(stderr, "Processing PostForm[uid=%d]\n", postHandle->uid);
465 MHD_post_process(postHandle->pp, upload_data, *upload_data_size);
467 // Process JsonPost request when buffer is completed let's call API
468 if (postHandle->type == AFB_POST_JSON) {
469 // if (verbose) fprintf(stderr, "Updating PostJson[uid=%d]\n", postHandle->uid);
470 memcpy(&postHandle->privatebuf[postHandle->len], upload_data, *upload_data_size);
471 postHandle->len = postHandle->len + *upload_data_size;
474 *upload_data_size = 0;
477 } else { // we have finish with Post reception let's finish the work
479 // Create a request structure to finalise the request
480 request = createRequest(connection, session, url);
481 if (request->jresp != NULL) {
482 errMessage = request->jresp;
485 postRequest.type = postHandle->type;
487 // Postform add application context handle to request
488 if (postHandle->type == AFB_POST_FORM) {
489 postRequest.data = (char *)postHandle;
490 request->post = &postRequest;
493 if (postHandle->type == AFB_POST_JSON) {
494 // if (verbose) fprintf(stderr, "Processing PostJson[uid=%d]\n", postHandle->uid);
496 param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
498 sscanf(param, "%i", &contentlen);
500 // At this level we're may verify that we got everything and process DATA
501 if (postHandle->len != contentlen) {
502 errMessage = jsonNewMessage(AFB_FATAL, "Post Data Incomplete UID=%d Len %d != %d", postHandle->uid, contentlen, postHandle->len);
505 // Before processing data, make sure buffer string is properly ended
506 postHandle->privatebuf[postHandle->len] = '\0';
507 postRequest.data = postHandle->privatebuf;
508 request->post = &postRequest;
510 // if (verbose) fprintf(stderr, "Close Post[%d] Buffer=%s\n", postHandle->uid, request->post->data);
515 // Request is ready let's call API without any extra handle
516 status = findAndCallApi(request, NULL);
518 serialized = json_object_to_json_string(request->jresp);
519 webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
521 // client did not pass token on URI let's use cookies
522 if ((!request->restfull) && (request->context != NULL)) {
524 snprintf(cookie, sizeof(cookie), "%s-%d=%s; Path=%s; Max-Age=%d; HttpOnly", COOKIE_NAME, request->config->httpdPort, request->uuid, request->config->rootapi, request->config->cntxTimeout);
525 MHD_add_response_header(webResponse, MHD_HTTP_HEADER_SET_COOKIE, cookie);
527 // if requested add an error status
528 if (request->errcode != 0)
529 ret = MHD_queue_response(connection, request->errcode, webResponse);
531 MHD_queue_response(connection, MHD_HTTP_OK, webResponse);
533 MHD_destroy_response(webResponse);
534 json_object_put(request->jresp); // decrease reference rqtcount to free the json object
535 freeRequest(request);
539 freeRequest(request);
540 serialized = json_object_to_json_string(errMessage);
541 webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
542 MHD_queue_response(connection, MHD_HTTP_BAD_REQUEST, webResponse);
543 MHD_destroy_response(webResponse);
544 json_object_put(errMessage); // decrease reference rqtcount to free the json object
567 static int doRestApiGet(struct MHD_Connection *connection, AFB_session * session, const char *url, const char *method, const char *upload_data, size_t * upload_data_size, void **con_cls)
570 struct MHD_Response *webResponse;
571 const char *serialized;
572 AFB_request *request = NULL;
575 // fprintf (stderr, "doRestAPI method=%s posthandle=%p\n", method, con_cls);
577 // if post data may come in multiple calls
578 // this is a get we only need a request
579 request = createRequest(connection, session, url);
581 // Request is ready let's call API without any extra handle
582 status = findAndCallApi(request, NULL);
584 serialized = json_object_to_json_string(request->jresp);
585 webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
587 // client did not pass token on URI let's use cookies
588 if ((!request->restfull) && (request->context != NULL)) {
590 snprintf(cookie, sizeof(cookie), "%s-%d=%s; Path=%s; Max-Age=%d; HttpOnly", COOKIE_NAME, request->config->httpdPort, request->uuid, request->config->rootapi, request->config->cntxTimeout);
591 MHD_add_response_header(webResponse, MHD_HTTP_HEADER_SET_COOKIE, cookie);
593 // if requested add an error status
594 if (request->errcode != 0)
595 ret = MHD_queue_response(connection, request->errcode, webResponse);
597 MHD_queue_response(connection, MHD_HTTP_OK, webResponse);
599 MHD_destroy_response(webResponse);
600 json_object_put(request->jresp); // decrease reference rqtcount to free the json object
601 freeRequest(request);
605 int doRestApi(struct MHD_Connection *connection, AFB_session * session, const char *url, const char *method, const char *upload_data, size_t * upload_data_size, void **con_cls)
609 if (afbJsonType == NULL)
610 afbJsonType = json_object_new_string (AFB_MSG_JTYPE);
612 if (0 == strcmp(method, MHD_HTTP_METHOD_POST)) {
613 rc = doRestApiPost(connection, session, url, method, upload_data, upload_data_size, con_cls);
615 rc = doRestApiGet(connection, session, url, method, upload_data, upload_data_size, con_cls);