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, apiidx);
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);
92 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);
96 case AFB_SESSION_CREATE:
97 if (clientCtx->token[0] != '\0' && request->config->token[0] != '\0') {
98 request->errcode = MHD_HTTP_UNAUTHORIZED;
99 json_object_object_add(jcall, "status", json_object_new_string("exist"));
100 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CREATE Session already exist"));
101 json_object_object_add(jreqt, "request", jcall);
105 if (AFB_SUCCESS != ctxTokenCreate(clientCtx, request)) {
106 request->errcode = MHD_HTTP_UNAUTHORIZED;
107 json_object_object_add(jcall, "status", json_object_new_string("fail"));
108 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CREATE Invalid Initial Token"));
109 json_object_object_add(jreqt, "request", jcall);
112 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
113 json_object_object_add(jcall, "token", json_object_new_string(clientCtx->token));
114 json_object_object_add(jcall, "timeout", json_object_new_int(request->config->cntxTimeout));
118 case AFB_SESSION_RENEW:
119 if (AFB_SUCCESS != ctxTokenRefresh(clientCtx, request)) {
120 request->errcode = MHD_HTTP_UNAUTHORIZED;
121 json_object_object_add(jcall, "status", json_object_new_string("fail"));
122 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_REFRESH Broken Exchange Token Chain"));
123 json_object_object_add(jreqt, "request", jcall);
126 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
127 json_object_object_add(jcall, "token", json_object_new_string(clientCtx->token));
128 json_object_object_add(jcall, "timeout", json_object_new_int(request->config->cntxTimeout));
132 case AFB_SESSION_CLOSE:
133 if (AFB_SUCCESS != ctxTokenCheck(clientCtx, request)) {
134 request->errcode = MHD_HTTP_UNAUTHORIZED;
135 json_object_object_add(jcall, "status", json_object_new_string("empty"));
136 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CLOSE Not a Valid Access Token"));
137 json_object_object_add(jreqt, "request", jcall);
140 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
144 case AFB_SESSION_CHECK:
146 // default action is check
147 if (AFB_SUCCESS != ctxTokenCheck(clientCtx, request)) {
148 request->errcode = MHD_HTTP_UNAUTHORIZED;
149 json_object_object_add(jcall, "status", json_object_new_string("fail"));
150 json_object_object_add(jcall, "info", json_object_new_string("AFB_SESSION_CHECK Invalid Active Token"));
151 json_object_object_add(jreqt, "request", jcall);
157 // Effectively CALL PLUGIN API with a subset of the context
158 jresp = afb_apis_get(apiidx, verbidx)->callback(request, context);
160 // Store context in case it was updated by plugins
161 if (request->context != NULL)
162 clientCtx->contexts[apiidx] = request->context;
164 // handle intermediary Post Iterates out of band
165 if ((jresp == NULL) && (request->errcode == MHD_HTTP_OK))
168 // Session close is done after the API call so API can still use session in closing API
169 if (AFB_SESSION_CLOSE == session)
170 ctxTokenReset(clientCtx, request);
172 // API should return NULL of a valid Json Object
174 json_object_object_add(jcall, "status", json_object_new_string("null"));
175 json_object_object_add(jreqt, "request", jcall);
176 request->errcode = MHD_HTTP_NO_RESPONSE;
179 json_object_object_add(jcall, "status", json_object_new_string("processed"));
180 json_object_object_add(jreqt, "request", jcall);
181 json_object_object_add(jreqt, "response", jresp);
185 request->jresp = jreqt;
189 // Check of apiurl is declare in this plugin and call it
190 extern __thread sigjmp_buf *error_handler;
191 static AFB_error callPluginApi(AFB_request * request, int apiidx, int verbidx, void *context)
195 json_object *jcall, *jreqt;
198 // save context before calling the API
199 status = setjmp(jmpbuf);
202 // Request was found and at least partially executed
203 jreqt = json_object_new_object();
204 json_object_get(afbJsonType); // increate jsontype reference count
205 json_object_object_add(jreqt, "jtype", afbJsonType);
207 // prepare an object to store calling values
208 jcall = json_object_new_object();
209 json_object_object_add(jcall, "prefix", json_object_new_string(request->prefix));
210 json_object_object_add(jcall, "api", json_object_new_string(request->api));
212 // Plugin aborted somewhere during its execution
213 json_object_object_add(jcall, "status", json_object_new_string("abort"));
214 json_object_object_add(jcall, "info", json_object_new_string("Plugin broke during execution"));
215 json_object_object_add(jreqt, "request", jcall);
216 request->jresp = jreqt;
221 // Trigger a timer to protect from unacceptable long time execution
222 if (request->config->apiTimeout > 0)
223 alarm((unsigned)request->config->apiTimeout);
225 error_handler = &jmpbuf;
226 doCallPluginApi(request, apiidx, verbidx, context);
227 error_handler = NULL;
229 // cancel timeout and plugin signal handle before next call
237 STATIC AFB_error findAndCallApi(AFB_request * request, void *context)
242 if (!request->api || !request->prefix)
245 /* get the plugin if any */
246 apiidx = afb_apis_get_apiidx(request->prefix, 0);
248 request->jresp = jsonNewMessage(AFB_FATAL, "No Plugin=[%s] Url=%s", request->prefix, request->url);
249 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
253 /* get the verb if any */
254 verbidx = afb_apis_get_verbidx(apiidx, request->api);
256 request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s] url=[%s]", request->api, request->prefix, request->url);
257 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
261 /* Search for a plugin with this urlpath */
262 status = callPluginApi(request, apiidx, verbidx, context);
264 /* plugin callback did not return a valid Json Object */
265 if (status == AFB_FAIL) {
266 request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s] url=[%s]", request->api, request->prefix, request->url);
267 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
270 // Everything look OK
274 // This CB is call for every item with a form post it reformat iterator values
275 // and callback Plugin API for each Item within PostForm.
276 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)
282 // retrieve API request from Post iterator handle
283 AFB_PostHandle *postHandle = (AFB_PostHandle *) cls;
284 AFB_request *request = (AFB_request *) postHandle->privatebuf;
285 AFB_PostRequest postRequest;
288 fprintf(stderr, "postHandle key=%s filename=%s len=%zu mime=%s\n", key, filename, size, mimetype);
290 // Create and Item value for Plugin API
293 item.filename = filename;
294 item.mimetype = mimetype;
295 item.encoding = encoding;
298 item.offset = offset;
300 // Reformat Request to make it somehow similar to GET/PostJson case
301 postRequest.data = (char *)postHandle;
302 postRequest.len = size;
303 postRequest.type = AFB_POST_FORM;;
304 request->post = &postRequest;
306 // effectively call plugin API
307 status = findAndCallApi(request, &item);
308 // when returning no processing of postform stop
309 if (status != AFB_SUCCESS)
312 // let's allow iterator to move to next item
316 STATIC void freeRequest(AFB_request * request)
319 free(request->prefix);
324 STATIC AFB_request *createRequest(struct MHD_Connection *connection, AFB_session * session, const char *url)
327 AFB_request *request;
329 // Start with a clean request
330 request = calloc(1, sizeof(AFB_request));
331 char *urlcpy1, *urlcpy2;
332 char *baseapi, *baseurl;
334 // Extract plugin urlpath from request and make two copy because strsep overload copy
335 urlcpy1 = urlcpy2 = strdup(url);
336 baseurl = strsep(&urlcpy2, "/");
337 if (baseurl == NULL) {
338 request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call url=[%s]", url);
339 request->errcode = MHD_HTTP_BAD_REQUEST;
342 // let's compute URL and call API
343 baseapi = strsep(&urlcpy2, "/");
344 if (baseapi == NULL) {
345 request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call plugin=[%s] url=[%s]", baseurl, url);
346 request->errcode = MHD_HTTP_BAD_REQUEST;
349 // build request structure
350 request->connection = connection;
351 request->config = session->config;
353 request->prefix = strdup(baseurl);
354 request->api = strdup(baseapi);
375 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)
378 static int postcount = 0; // static counter to debug POST protocol
379 json_object *errMessage;
381 struct MHD_Response *webResponse;
382 const char *serialized;
383 AFB_request *request = NULL;
384 AFB_PostHandle *postHandle;
385 AFB_PostRequest postRequest;
388 // fprintf (stderr, "doRestAPI method=%s posthandle=%p\n", method, con_cls);
390 // if post data may come in multiple calls
391 const char *encoding, *param;
393 postHandle = *con_cls;
395 // This is the initial post event let's create form post structure POST data come in multiple events
396 if (postHandle == NULL) {
398 // allocate application POST processor handle to zero
399 postHandle = calloc(1, sizeof(AFB_PostHandle));
400 postHandle->uid = postcount++; // build a UID for DEBUG
401 *con_cls = postHandle; // update context with posthandle
403 // Let make sure we have the right encoding and a valid length
404 encoding = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_TYPE);
406 // We are facing an empty post let's process it as a get
407 if (encoding == NULL) {
408 postHandle->type = AFB_POST_EMPTY;
411 // Form post is handle through a PostProcessor and call API once per form key
412 if (strcasestr(encoding, FORM_CONTENT) != NULL) {
414 fprintf(stderr, "Create doPostIterate[uid=%d posthandle=%p]\n", postHandle->uid, postHandle);
416 request = createRequest(connection, session, url);
417 if (request->jresp != NULL)
419 postHandle->type = AFB_POST_FORM;
420 postHandle->privatebuf = (void *)request;
421 postHandle->pp = MHD_create_post_processor(connection, MAX_POST_SIZE, &doPostIterate, postHandle);
423 if (NULL == postHandle->pp) {
424 fprintf(stderr, "OOPS: Internal error fail to allocate MHD_create_post_processor\n");
430 // POST json is store into a buffer and present in one piece to API
431 if (strcasestr(encoding, JSON_CONTENT) != NULL) {
433 param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
435 sscanf(param, "%i", &contentlen);
437 // Because PostJson are build in RAM size is constrained
438 if (contentlen > MAX_POST_SIZE) {
439 errMessage = jsonNewMessage(AFB_FATAL, "Post Date to big %d > %d", contentlen, MAX_POST_SIZE);
442 // Size is OK, let's allocate a buffer to hold post data
443 postHandle->type = AFB_POST_JSON;
444 postHandle->privatebuf = malloc((unsigned)contentlen + 1); // allocate memory for full POST data + 1 for '\0' enf of string
446 // if (verbose) fprintf(stderr, "Create PostJson[uid=%d] Size=%d\n", postHandle->uid, contentlen);
450 // We only support Json and Form Post format
451 errMessage = jsonNewMessage(AFB_FATAL, "Post Date wrong type encoding=%s != %s", encoding, JSON_CONTENT);
456 // This time we receive partial/all Post data. Note that even if we get all POST data. We should nevertheless
457 // return MHD_YES and not process the request directly. Otherwise Libmicrohttpd is unhappy and fails with
458 // 'Internal application error, closing connection'.
459 if (*upload_data_size) {
461 if (postHandle->type == AFB_POST_FORM) {
462 // if (verbose) fprintf(stderr, "Processing PostForm[uid=%d]\n", postHandle->uid);
463 MHD_post_process(postHandle->pp, upload_data, *upload_data_size);
465 // Process JsonPost request when buffer is completed let's call API
466 if (postHandle->type == AFB_POST_JSON) {
467 // if (verbose) fprintf(stderr, "Updating PostJson[uid=%d]\n", postHandle->uid);
468 memcpy(&postHandle->privatebuf[postHandle->len], upload_data, *upload_data_size);
469 postHandle->len = postHandle->len + *upload_data_size;
472 *upload_data_size = 0;
475 } else { // we have finish with Post reception let's finish the work
477 // Create a request structure to finalise the request
478 request = createRequest(connection, session, url);
479 if (request->jresp != NULL) {
480 errMessage = request->jresp;
483 postRequest.type = postHandle->type;
485 // Postform add application context handle to request
486 if (postHandle->type == AFB_POST_FORM) {
487 postRequest.data = (char *)postHandle;
488 request->post = &postRequest;
491 if (postHandle->type == AFB_POST_JSON) {
492 // if (verbose) fprintf(stderr, "Processing PostJson[uid=%d]\n", postHandle->uid);
494 param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
496 sscanf(param, "%i", &contentlen);
498 // At this level we're may verify that we got everything and process DATA
499 if (postHandle->len != contentlen) {
500 errMessage = jsonNewMessage(AFB_FATAL, "Post Data Incomplete UID=%d Len %d != %d", postHandle->uid, contentlen, postHandle->len);
503 // Before processing data, make sure buffer string is properly ended
504 postHandle->privatebuf[postHandle->len] = '\0';
505 postRequest.data = postHandle->privatebuf;
506 request->post = &postRequest;
508 // if (verbose) fprintf(stderr, "Close Post[%d] Buffer=%s\n", postHandle->uid, request->post->data);
513 // Request is ready let's call API without any extra handle
514 status = findAndCallApi(request, NULL);
516 serialized = json_object_to_json_string(request->jresp);
517 webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
519 // client did not pass token on URI let's use cookies
520 if ((!request->restfull) && (request->context != NULL)) {
522 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);
523 MHD_add_response_header(webResponse, MHD_HTTP_HEADER_SET_COOKIE, cookie);
525 // if requested add an error status
526 if (request->errcode != 0)
527 ret = MHD_queue_response(connection, request->errcode, webResponse);
529 MHD_queue_response(connection, MHD_HTTP_OK, webResponse);
531 MHD_destroy_response(webResponse);
532 json_object_put(request->jresp); // decrease reference rqtcount to free the json object
533 freeRequest(request);
537 freeRequest(request);
538 serialized = json_object_to_json_string(errMessage);
539 webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
540 MHD_queue_response(connection, MHD_HTTP_BAD_REQUEST, webResponse);
541 MHD_destroy_response(webResponse);
542 json_object_put(errMessage); // decrease reference rqtcount to free the json object
565 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)
568 struct MHD_Response *webResponse;
569 const char *serialized;
570 AFB_request *request = NULL;
573 // fprintf (stderr, "doRestAPI method=%s posthandle=%p\n", method, con_cls);
575 // if post data may come in multiple calls
576 // this is a get we only need a request
577 request = createRequest(connection, session, url);
579 // Request is ready let's call API without any extra handle
580 status = findAndCallApi(request, NULL);
582 serialized = json_object_to_json_string(request->jresp);
583 webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
585 // client did not pass token on URI let's use cookies
586 if ((!request->restfull) && (request->context != NULL)) {
588 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);
589 MHD_add_response_header(webResponse, MHD_HTTP_HEADER_SET_COOKIE, cookie);
591 // if requested add an error status
592 if (request->errcode != 0)
593 ret = MHD_queue_response(connection, request->errcode, webResponse);
595 MHD_queue_response(connection, MHD_HTTP_OK, webResponse);
597 MHD_destroy_response(webResponse);
598 json_object_put(request->jresp); // decrease reference rqtcount to free the json object
599 freeRequest(request);
603 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)
607 if (afbJsonType == NULL)
608 afbJsonType = json_object_new_string (AFB_MSG_JTYPE);
610 if (0 == strcmp(method, MHD_HTTP_METHOD_POST)) {
611 rc = doRestApiPost(connection, session, url, method, upload_data, upload_data_size, con_cls);
613 rc = doRestApiGet(connection, session, url, method, upload_data, upload_data_size, con_cls);