2 * Copyright (C) 2015 "IoT.bzh"
3 * Author "Fulup Ar Foll"
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.
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.
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/>.
20 #include "../include/local-def.h"
23 #include <sys/types.h>
26 // handle to hold queryAll values
33 static AFB_errorT AFBerr [AFB_SUCCESS+1];
34 static json_object *jTypeStatic;
37 /* ------------------------------------------------------------------------------
38 * Get localtime and return in a string
39 * ------------------------------------------------------------------------------ */
41 PUBLIC char * configTime (void) {
42 static char reqTime [26];
46 /* Get actual Date and Time */
50 strftime (reqTime, sizeof (reqTime), "(%d-%b %H:%M)",rt);
52 // return pointer on static data
57 // Sample Generic Ping Debug API
58 json_object* getPingTest(AFB_request *request) {
59 static int pingcount = 0;
60 json_object *response;
65 // request all query key/value
66 len = getQueryAll (request, query, sizeof(query));
67 if (len == 0) strncpy (query, "NoSearchQueryList", sizeof(query));
69 // check if we have some post data
70 if (request->post == NULL) request->post->data="NoData";
72 // return response to caller
73 response = jsonNewMessage(AFB_SUCCESS, "Ping Binder Daemon count=%d uuid=%s query={%s} session={0x%x} PostData: [%s] "
74 , pingcount++, request->uuid, query, session, request->post->data);
79 // Helper to retrieve argument from connection
80 const char* getQueryValue(const AFB_request * request, const char *name) {
83 value = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, name);
87 static int getQueryCB (void*handle, enum MHD_ValueKind kind, const char *key, const char *value) {
88 queryHandleT *query = (queryHandleT*)handle;
90 query->idx += snprintf (&query->msg[query->idx],query->len," %s: \'%s\',", key, value);
91 return MHD_YES; /* continue to iterate */
94 // Helper to retrieve argument from connection
95 int getQueryAll(AFB_request * request, char *buffer, size_t len) {
97 buffer[0] = '\0'; // start with an empty string
102 MHD_get_connection_values (request->connection, MHD_GET_ARGUMENT_KIND, getQueryCB, &query);
106 // Helper to retrieve POST handle
107 AFB_PostHandle* getPostHandle (AFB_request *request) {
108 if (request->post == NULL) return (NULL);
109 return ((AFB_PostHandle*) request->post->data);
112 // Helper to retrieve POST file context
113 AFB_PostCtx* getPostContext (AFB_request *request) {
114 AFB_PostHandle* postHandle;
115 if (request->post == NULL) return (NULL);
117 postHandle = (AFB_PostHandle*) request->post->data;
118 if (postHandle == NULL) return NULL;
120 return ((AFB_PostCtx*) postHandle->ctx);
123 char* getPostPath (AFB_request *request) {
124 AFB_PostHandle *postHandle = getPostHandle(request);
125 AFB_PostCtx *postFileCtx;
127 if (postHandle == NULL) return NULL;
129 postFileCtx = (AFB_PostCtx*) postHandle->ctx;
130 if (postFileCtx == NULL) return NULL;
132 return (postFileCtx->path);
135 json_object* getPostFile (AFB_request *request, AFB_PostItem *item, char* destination) {
137 AFB_PostHandle *postHandle = getPostHandle(request);
138 AFB_PostCtx *postFileCtx;
142 // This is called after PostForm and then after DonePostForm
145 postFileCtx = (AFB_PostCtx*) postHandle->ctx;
147 // No Post Application Context [something really bad happen]
148 if (postFileCtx == NULL) {
149 request->errcode = MHD_HTTP_EXPECTATION_FAILED;
150 return(jsonNewMessage(AFB_FAIL,"Error: PostForm no PostContext to free\n"));
153 // We have a context but last Xform iteration fail or application set a message
154 if (request->jresp != NULL) {
155 jresp = request->jresp; // retrieve previous error from postCtx
156 } else jresp = jsonNewMessage(AFB_SUCCESS,"getPostFile Post Request done");
158 // Error or not let's free all resources
159 close(postFileCtx->fd);
160 free (postFileCtx->path);
164 #if defined(PLEASE_FIX_ME_THE_ERROR_IS_postFileCtx_NOT_INITIALIZED)
165 // Make sure it's a valid PostForm request
166 if (!request->post && request->post->type != AFB_POST_FORM) {
167 postFileCtx->jresp= jsonNewMessage(AFB_FAIL,"This is not a valid PostForm request\n");
171 // Check this is a file element
172 if (item->filename == NULL) {
173 postFileCtx->jresp= jsonNewMessage(AFB_FAIL,"No Filename attached to key=%s\n", item->key);
177 // Check we got something in buffer
178 if (item->len <= 0) {
179 postFileCtx->jresp= jsonNewMessage(AFB_FAIL,"Buffer size NULL key=%s]\n", item->key);
183 // Extract Application Context from posthandle [NULL == 1st iteration]
184 postFileCtx = (AFB_PostCtx*) postHandle->ctx;
186 // This is the 1st Item iteration let's open output file and allocate necessary resources
187 if (postFileCtx == NULL) {
190 // Create an application specific context
191 postFileCtx = calloc (1, sizeof(AFB_PostCtx)); // May place anything here until post->completeCB handle resources liberation
193 // attach application to postHandle
194 postHandle->ctx = (void*) postFileCtx; // May place anything here until post->completeCB handle resources liberation
196 // Build destination directory full path
197 if (destination[0] != '/') {
198 strncpy (filepath, request->config->sessiondir, sizeof(filepath));
199 strncat (filepath, "/", sizeof(filepath));
200 strncat (filepath, destination, sizeof(filepath));
201 } else strncpy (filepath, destination, sizeof(filepath));
204 // make sure destination directory exist
205 destDir = opendir (filepath);
206 if (destDir == NULL) {
207 if (mkdir(filepath,O_RDWR | S_IRWXU | S_IRGRP) < 0) {
208 postFileCtx->jresp= jsonNewMessage(AFB_FAIL,"Fail to Create destination directory=[%s] error=%s\n", filepath, strerror(errno));
211 } else closedir (destDir);
213 strncat (filepath, "/", sizeof(filepath));
214 strncat (filepath, item->filename, sizeof(filepath));
216 postFileCtx->path = strdup (filepath);
217 if (verbose) fprintf(stderr, "getPostFile path=%s\n", filepath);
219 if((postFileCtx->fd = open(filepath, O_RDWR |O_CREAT, S_IRWXU|S_IRGRP)) <= 0) {
220 postFileCtx->jresp= jsonNewMessage(AFB_FAIL,"Fail to Create destination File=[%s] error=%s\n", filepath, strerror(errno));
224 // reuse existing application context
225 postFileCtx = (AFB_PostCtx*) postHandle->ctx;
228 // Check we successfully wrote full buffer
229 len = write (postFileCtx->fd, item->data, item->len);
230 if ((ssize_t)item->len != len) {
231 postFileCtx->jresp= jsonNewMessage(AFB_FAIL,"Fail to write file [%s] at [%s] error=\n", item->filename, strerror(errno));
235 // every intermediary iteration should return Success & NULL
236 request->errcode = MHD_HTTP_OK;
240 request->errcode = MHD_HTTP_EXPECTATION_FAILED;
246 static void jsoninit()
253 // initialise JSON constant messages and increase reference count to make them permanent
254 verbosesav = verbose;
255 verbose = 0; // run initialisation in silent mode
256 jTypeStatic = json_object_new_string ("AFB_message");
257 for (idx = 0; idx <= AFB_SUCCESS; idx++) {
258 AFBerr[idx].level = idx;
259 AFBerr[idx].label = ERROR_LABEL [idx];
260 AFBerr[idx].json = jsonNewMessage (idx, NULL);
262 verbose = verbosesav;
267 // get JSON object from error level and increase its reference count
268 struct json_object *jsonNewStatus (AFB_error level)
271 json_object *target = AFBerr[level].json;
272 json_object_get (target);
277 // get AFB object type with adequate usage count
278 struct json_object *jsonNewjtype (void)
281 json_object_get (jTypeStatic); // increase reference count
282 return (jTypeStatic);
285 // build an ERROR message and return it as a valid json object
286 struct json_object *jsonNewMessage (AFB_error level, char* format, ...) {
287 static int count = 0;
288 json_object * AFBResponse;
295 if (format != NULL) {
296 va_start(args, format);
297 vsnprintf (message, sizeof (message), format, args);
301 AFBResponse = json_object_new_object();
302 json_object_object_add (AFBResponse, "jtype", jsonNewjtype ());
303 json_object_object_add (AFBResponse, "status" , json_object_new_string (ERROR_LABEL[level]));
304 if (format != NULL) {
305 json_object_object_add (AFBResponse, "info" , json_object_new_string (message));
308 fprintf (stderr, "AFB:%-6s [%3d]: ", AFBerr [level].label, count++);
309 if (format != NULL) {
310 fprintf (stderr, "%s", message);
312 fprintf (stderr, "No Message");
314 fprintf (stderr, "\n");
317 return (AFBResponse);
320 // Dump a message on stderr
321 void jsonDumpObject (struct json_object * jObject) {
324 fprintf (stderr, "AFB:dump [%s]\n", json_object_to_json_string(jObject));