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"
36 #define AFB_MSG_JTYPE "AJB_reply"
38 #define JSON_CONTENT "application/json"
39 #define FORM_CONTENT MHD_HTTP_POST_ENCODING_MULTIPART_FORMDATA
41 static json_object *afbJsonType;
43 // Because of POST call multiple time requestApi we need to free POST handle here
44 // Note this method is called from http-svc just before closing session
45 PUBLIC void endPostRequest(AFB_PostHandle * postHandle)
48 if (postHandle->type == AFB_POST_JSON) {
49 // if (verbose) fprintf(stderr, "End PostJson Request UID=%d\n", postHandle->uid);
52 if (postHandle->type == AFB_POST_FORM) {
54 fprintf(stderr, "End PostForm Request UID=%d\n", postHandle->uid);
56 if (postHandle->privatebuf)
57 free(postHandle->privatebuf);
61 // Check of apiurl is declare in this plugin and call it
62 static AFB_error doCallPluginApi(AFB_request * request, int apiidx, int verbidx, void *context)
64 enum AFB_sessionE session;
65 json_object *jresp, *jcall, *jreqt;
66 AFB_clientCtx *clientCtx = NULL;
68 // Request was found and at least partially executed
69 jreqt = json_object_new_object();
70 json_object_object_add(jreqt, "jtype", json_object_get(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->method));
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_add_status(jcall, "fail", "Client Session Context Full !!!");
86 json_object_object_add(jreqt, "request", jcall);
89 request->context = clientCtx->contexts[apiidx];
90 request->uuid = clientCtx->uuid;
93 fprintf(stderr, "Plugin=[%s] Api=[%s] Middleware=[%d] Client=[%p] Uuid=[%s] Token=[%s]\n", request->prefix, request->method, session, clientCtx, clientCtx->uuid, clientCtx->token);
97 case AFB_SESSION_CREATE:
98 if (clientCtx->token[0] != '\0' && request->config->token[0] != '\0') {
99 request->errcode = MHD_HTTP_UNAUTHORIZED;
100 json_add_status(jcall, "exist", "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_add_status(jcall, "fail", "AFB_SESSION_CREATE Invalid Initial Token");
108 json_object_object_add(jreqt, "request", jcall);
111 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
112 json_object_object_add(jcall, "token", json_object_new_string(clientCtx->token));
113 json_object_object_add(jcall, "timeout", json_object_new_int(request->config->cntxTimeout));
117 case AFB_SESSION_RENEW:
118 if (AFB_SUCCESS != ctxTokenRefresh(clientCtx, request)) {
119 request->errcode = MHD_HTTP_UNAUTHORIZED;
120 json_add_status(jcall, "fail", "AFB_SESSION_REFRESH Broken Exchange Token Chain");
121 json_object_object_add(jreqt, "request", jcall);
124 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
125 json_object_object_add(jcall, "token", json_object_new_string(clientCtx->token));
126 json_object_object_add(jcall, "timeout", json_object_new_int(request->config->cntxTimeout));
130 case AFB_SESSION_CLOSE:
131 if (AFB_SUCCESS != ctxTokenCheck(clientCtx, request)) {
132 request->errcode = MHD_HTTP_UNAUTHORIZED;
133 json_add_status(jcall, "fail", "AFB_SESSION_CLOSE Not a Valid Access Token"));
134 json_object_object_add(jreqt, "request", jcall);
137 json_object_object_add(jcall, "uuid", json_object_new_string(clientCtx->uuid));
141 case AFB_SESSION_CHECK:
143 // default action is check
144 if (AFB_SUCCESS != ctxTokenCheck(clientCtx, request)) {
145 request->errcode = MHD_HTTP_UNAUTHORIZED;
146 json_add_status(jcall, "fail", "AFB_SESSION_CHECK Invalid Active Token"));
147 json_object_object_add(jreqt, "request", jcall);
154 // Effectively CALL PLUGIN API with a subset of the context
155 jresp = afb_apis_get(apiidx, verbidx)->callback(request, context);
157 // Store context in case it was updated by plugins
158 if (request->context != NULL)
159 clientCtx->contexts[apiidx] = request->context;
161 // handle intermediary Post Iterates out of band
162 if ((jresp == NULL) && (request->errcode == MHD_HTTP_OK))
165 // Session close is done after the API call so API can still use session in closing API
166 if (AFB_SESSION_CLOSE == session)
167 ctxTokenReset(clientCtx, request);
169 // API should return NULL of a valid Json Object
171 json_object_object_add(jcall, "status", json_object_new_string("null"));
172 json_object_object_add(jreqt, "request", jcall);
173 request->errcode = MHD_HTTP_NO_RESPONSE;
176 json_object_object_add(jcall, "status", json_object_new_string("processed"));
177 json_object_object_add(jreqt, "request", jcall);
178 json_object_object_add(jreqt, "response", jresp);
182 request->jresp = jreqt;
186 // Check of apiurl is declare in this plugin and call it
187 extern __thread sigjmp_buf *error_handler;
188 static AFB_error callPluginApi(AFB_request * request, int apiidx, int verbidx, void *context)
190 sigjmp_buf jmpbuf, *older;
192 json_object *jcall, *jreqt;
195 // save context before calling the API
196 status = setjmp(jmpbuf);
199 // Request was found and at least partially executed
200 jreqt = json_object_new_object();
201 json_object_object_add(jreqt, "jtype", json_object_get(afbJsonType));
203 // prepare an object to store calling values
204 jcall = json_object_new_object();
205 json_object_object_add(jcall, "prefix", json_object_new_string(request->prefix));
206 json_object_object_add(jcall, "api", json_object_new_string(request->method));
208 // Plugin aborted somewhere during its execution
209 json_object_object_add(jcall, "status", json_object_new_string("abort"));
210 json_object_object_add(jcall, "info", json_object_new_string("Plugin broke during execution"));
211 json_object_object_add(jreqt, "request", jcall);
212 request->jresp = jreqt;
215 // Trigger a timer to protect from unacceptable long time execution
216 if (request->config->apiTimeout > 0)
217 alarm((unsigned)request->config->apiTimeout);
219 older = error_handler;
220 error_handler = &jmpbuf;
221 doCallPluginApi(request, apiidx, verbidx, context);
222 error_handler = older;
224 // cancel timeout and plugin signal handle before next call
230 STATIC AFB_error findAndCallApi(AFB_request * request, void *context)
235 if (!request->method || !request->prefix)
238 /* get the plugin if any */
239 apiidx = afb_apis_get_apiidx(request->prefix, 0);
241 request->jresp = jsonNewMessage(AFB_FATAL, "No Plugin=[%s] Url=%s", request->prefix, request->url);
242 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
246 /* get the verb if any */
247 verbidx = afb_apis_get_verbidx(apiidx, request->method);
249 request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s] url=[%s]", request->method, request->prefix, request->url);
250 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
254 /* Search for a plugin with this urlpath */
255 status = callPluginApi(request, apiidx, verbidx, context);
257 /* plugin callback did not return a valid Json Object */
258 if (status == AFB_FAIL) {
259 request->jresp = jsonNewMessage(AFB_FATAL, "No API=[%s] for Plugin=[%s] url=[%s]", request->method, request->prefix, request->url);
260 request->errcode = MHD_HTTP_UNPROCESSABLE_ENTITY;
263 // Everything look OK
267 // This CB is call for every item with a form post it reformat iterator values
268 // and callback Plugin API for each Item within PostForm.
269 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)
275 // retrieve API request from Post iterator handle
276 AFB_PostHandle *postHandle = (AFB_PostHandle *) cls;
277 AFB_request *request = (AFB_request *) postHandle->privatebuf;
278 AFB_PostRequest postRequest;
281 fprintf(stderr, "postHandle key=%s filename=%s len=%zu mime=%s\n", key, filename, size, mimetype);
283 // Create and Item value for Plugin API
286 item.filename = filename;
287 item.mimetype = mimetype;
288 item.encoding = encoding;
291 item.offset = offset;
293 // Reformat Request to make it somehow similar to GET/PostJson case
294 postRequest.data = (char *)postHandle;
295 postRequest.len = size;
296 postRequest.type = AFB_POST_FORM;;
297 request->post = &postRequest;
299 // effectively call plugin API
300 status = findAndCallApi(request, &item);
301 // when returning no processing of postform stop
302 if (status != AFB_SUCCESS)
305 // let's allow iterator to move to next item
309 STATIC void freeRequest(AFB_request * request)
312 free((void*)request->prefix);
313 free((void*)request->method);
317 STATIC AFB_request *createRequest(struct MHD_Connection *connection, AFB_session * session, const char *url)
320 AFB_request *request;
322 // Start with a clean request
323 request = calloc(1, sizeof(AFB_request));
324 char *urlcpy1, *urlcpy2;
325 char *baseapi, *baseurl;
327 // Extract plugin urlpath from request and make two copy because strsep overload copy
328 urlcpy1 = urlcpy2 = strdup(url);
329 baseurl = strsep(&urlcpy2, "/");
330 if (baseurl == NULL) {
331 request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call url=[%s]", url);
332 request->errcode = MHD_HTTP_BAD_REQUEST;
335 // let's compute URL and call API
336 baseapi = strsep(&urlcpy2, "/");
337 if (baseapi == NULL) {
338 request->jresp = jsonNewMessage(AFB_FATAL, "Invalid API call plugin=[%s] url=[%s]", baseurl, url);
339 request->errcode = MHD_HTTP_BAD_REQUEST;
342 // build request structure
343 // request->connection = connection;
344 request->config = session->config;
346 request->prefix = strdup(baseurl);
347 request->method = strdup(baseapi);
368 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)
371 static int postcount = 0; // static counter to debug POST protocol
372 json_object *errMessage;
374 struct MHD_Response *webResponse;
375 const char *serialized;
376 AFB_request *request = NULL;
377 AFB_PostHandle *postHandle;
378 AFB_PostRequest postRequest;
381 // fprintf (stderr, "doRestAPI method=%s posthandle=%p\n", method, con_cls);
383 // if post data may come in multiple calls
384 const char *encoding, *param;
386 postHandle = *con_cls;
388 // This is the initial post event let's create form post structure POST data come in multiple events
389 if (postHandle == NULL) {
391 // allocate application POST processor handle to zero
392 postHandle = calloc(1, sizeof(AFB_PostHandle));
393 postHandle->uid = postcount++; // build a UID for DEBUG
394 *con_cls = postHandle; // update context with posthandle
396 // Let make sure we have the right encoding and a valid length
397 encoding = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_TYPE);
399 // We are facing an empty post let's process it as a get
400 if (encoding == NULL) {
401 postHandle->type = AFB_POST_EMPTY;
405 // Form post is handle through a PostProcessor and call API once per form key
406 if (strcasestr(encoding, FORM_CONTENT) != NULL) {
408 fprintf(stderr, "Create doPostIterate[uid=%d posthandle=%p]\n", postHandle->uid, postHandle);
410 request = createRequest(connection, session, url);
411 if (request->jresp != NULL)
413 postHandle->type = AFB_POST_FORM;
414 postHandle->privatebuf = (void *)request;
415 postHandle->pp = MHD_create_post_processor(connection, MAX_POST_SIZE, &doPostIterate, postHandle);
417 if (NULL == postHandle->pp) {
418 fprintf(stderr, "OOPS: Internal error fail to allocate MHD_create_post_processor\n");
424 // POST json is store into a buffer and present in one piece to API
425 if (strcasestr(encoding, JSON_CONTENT) != NULL) {
427 param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
429 sscanf(param, "%i", &contentlen);
431 // Because PostJson are build in RAM size is constrained
432 if (contentlen > MAX_POST_SIZE) {
433 errMessage = jsonNewMessage(AFB_FATAL, "Post Date to big %d > %d", contentlen, MAX_POST_SIZE);
436 // Size is OK, let's allocate a buffer to hold post data
437 postHandle->type = AFB_POST_JSON;
438 postHandle->privatebuf = malloc((unsigned)contentlen + 1); // allocate memory for full POST data + 1 for '\0' enf of string
440 // if (verbose) fprintf(stderr, "Create PostJson[uid=%d] Size=%d\n", postHandle->uid, contentlen);
444 // We only support Json and Form Post format
445 errMessage = jsonNewMessage(AFB_FATAL, "Post Date wrong type encoding=%s != %s", encoding, JSON_CONTENT);
449 // This time we receive partial/all Post data. Note that even if we get all POST data. We should nevertheless
450 // return MHD_YES and not process the request directly. Otherwise Libmicrohttpd is unhappy and fails with
451 // 'Internal application error, closing connection'.
452 if (*upload_data_size) {
454 if (postHandle->type == AFB_POST_FORM) {
455 // if (verbose) fprintf(stderr, "Processing PostForm[uid=%d]\n", postHandle->uid);
456 MHD_post_process(postHandle->pp, upload_data, *upload_data_size);
458 // Process JsonPost request when buffer is completed let's call API
459 if (postHandle->type == AFB_POST_JSON) {
460 // if (verbose) fprintf(stderr, "Updating PostJson[uid=%d]\n", postHandle->uid);
461 memcpy(&postHandle->privatebuf[postHandle->len], upload_data, *upload_data_size);
462 postHandle->len = postHandle->len + *upload_data_size;
465 *upload_data_size = 0;
470 if (postHandle->type == AFB_POST_FORM)
471 request = postHandle->privatebuf;
473 // Create a request structure to finalise the request
474 request = createRequest(connection, session, url);
476 if (request->jresp != NULL) {
477 errMessage = request->jresp;
480 postRequest.type = postHandle->type;
482 // Postform add application context handle to request
483 if (postHandle->type == AFB_POST_FORM) {
484 postRequest.data = (char *)postHandle;
485 request->post = &postRequest;
488 if (postHandle->type == AFB_POST_JSON) {
489 // if (verbose) fprintf(stderr, "Processing PostJson[uid=%d]\n", postHandle->uid);
491 param = MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_CONTENT_LENGTH);
493 sscanf(param, "%i", &contentlen);
495 // At this level we're may verify that we got everything and process DATA
496 if (postHandle->len != contentlen) {
497 errMessage = jsonNewMessage(AFB_FATAL, "Post Data Incomplete UID=%d Len %d != %d", postHandle->uid, contentlen, postHandle->len);
500 // Before processing data, make sure buffer string is properly ended
501 postHandle->privatebuf[postHandle->len] = '\0';
502 postRequest.data = postHandle->privatebuf;
503 request->post = &postRequest;
505 // if (verbose) fprintf(stderr, "Close Post[%d] Buffer=%s\n", postHandle->uid, request->post->data);
509 // Request is ready let's call API without any extra handle
510 status = findAndCallApi(request, NULL);
512 serialized = json_object_to_json_string(request->jresp);
513 webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
515 // client did not pass token on URI let's use cookies
516 if ((!request->restfull) && (request->context != NULL)) {
518 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);
519 MHD_add_response_header(webResponse, MHD_HTTP_HEADER_SET_COOKIE, cookie);
521 // if requested add an error status
522 if (request->errcode != 0)
523 ret = MHD_queue_response(connection, request->errcode, webResponse);
525 MHD_queue_response(connection, MHD_HTTP_OK, webResponse);
527 MHD_destroy_response(webResponse);
528 json_object_put(request->jresp); // decrease reference rqtcount to free the json object
529 freeRequest(request);
533 freeRequest(request);
534 serialized = json_object_to_json_string(errMessage);
535 webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
536 MHD_queue_response(connection, MHD_HTTP_BAD_REQUEST, webResponse);
537 MHD_destroy_response(webResponse);
538 json_object_put(errMessage); // decrease reference rqtcount to free the json object
561 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)
564 struct MHD_Response *webResponse;
565 const char *serialized;
566 AFB_request *request = NULL;
569 // fprintf (stderr, "doRestAPI method=%s posthandle=%p\n", method, con_cls);
571 // if post data may come in multiple calls
572 // this is a get we only need a request
573 request = createRequest(connection, session, url);
575 // Request is ready let's call API without any extra handle
576 status = findAndCallApi(request, NULL);
578 serialized = json_object_to_json_string(request->jresp);
579 webResponse = MHD_create_response_from_buffer(strlen(serialized), (void *)serialized, MHD_RESPMEM_MUST_COPY);
581 // client did not pass token on URI let's use cookies
582 if ((!request->restfull) && (request->context != NULL)) {
584 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);
585 MHD_add_response_header(webResponse, MHD_HTTP_HEADER_SET_COOKIE, cookie);
587 // if requested add an error status
588 if (request->errcode != 0)
589 ret = MHD_queue_response(connection, request->errcode, webResponse);
591 MHD_queue_response(connection, MHD_HTTP_OK, webResponse);
593 MHD_destroy_response(webResponse);
594 json_object_put(request->jresp); // decrease reference rqtcount to free the json object
595 freeRequest(request);
599 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)
603 if (afbJsonType == NULL)
604 afbJsonType = json_object_new_string (AFB_MSG_JTYPE);
606 if (0 == strcmp(method, MHD_HTTP_METHOD_POST)) {
607 rc = doRestApiPost(connection, session, url, method, upload_data, upload_data_size, con_cls);
609 rc = doRestApiGet(connection, session, url, method, upload_data, upload_data_size, con_cls);