moves helpers from config to helper-api
[src/app-framework-binder.git] / src / helper-api.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  */
19
20 #include "../include/local-def.h"
21 #include <dirent.h>
22 #include <sys/stat.h>
23 #include <sys/types.h>
24
25
26 // handle to hold queryAll values
27 typedef struct {
28      char    *msg;
29      int     idx;
30      size_t  len;
31 } queryHandleT;
32
33 static AFB_errorT   AFBerr [AFB_SUCCESS+1];
34 static json_object *jTypeStatic;
35 PUBLIC int verbose;
36
37 /* ------------------------------------------------------------------------------
38  * Get localtime and return in a string
39  * ------------------------------------------------------------------------------ */
40
41 PUBLIC char * configTime (void) {
42   static char reqTime [26];
43   time_t tt;
44   struct tm *rt;
45
46   /* Get actual Date and Time */
47   time (&tt);
48   rt = localtime (&tt);
49
50   strftime (reqTime, sizeof (reqTime), "(%d-%b %H:%M)",rt);
51
52   // return pointer on static data
53   return (reqTime);
54 }
55
56
57 // Sample Generic Ping Debug API
58 json_object* getPingTest(AFB_request *request) {
59     static int pingcount = 0;
60     json_object *response;
61     char query  [256];
62     char session[256];
63     int len;
64     
65     // request all query key/value
66     len = getQueryAll (request, query, sizeof(query));
67     if (len == 0) strncpy (query, "NoSearchQueryList", sizeof(query));
68     
69     // check if we have some post data
70     if (request->post == NULL)  request->post->data="NoData"; 
71           
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);
75     return (response);
76 }
77
78
79 // Helper to retrieve argument from  connection
80 const char* getQueryValue(const AFB_request * request, const char *name) {
81     const char *value;
82
83     value = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, name);
84     return (value);
85 }
86
87 static int getQueryCB (void*handle, enum MHD_ValueKind kind, const char *key, const char *value) {
88     queryHandleT *query = (queryHandleT*)handle;
89         
90     query->idx += snprintf (&query->msg[query->idx],query->len," %s: \'%s\',", key, value);
91     return MHD_YES; /* continue to iterate */
92 }
93
94 // Helper to retrieve argument from  connection
95 int getQueryAll(AFB_request * request, char *buffer, size_t len) {
96     queryHandleT query;
97     buffer[0] = '\0'; // start with an empty string
98     query.msg = buffer;
99     query.len = len;
100     query.idx = 0;
101
102     MHD_get_connection_values (request->connection, MHD_GET_ARGUMENT_KIND, getQueryCB, &query);
103     return (len);
104 }
105
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);
110 }
111
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);
116     
117     postHandle = (AFB_PostHandle*) request->post->data;
118     if (postHandle == NULL) return NULL;
119        
120     return ((AFB_PostCtx*) postHandle->ctx);
121 }
122
123 char* getPostPath (AFB_request *request) {
124     AFB_PostHandle *postHandle = getPostHandle(request);
125     AFB_PostCtx *postFileCtx;
126     
127     if (postHandle == NULL) return NULL;
128     
129     postFileCtx = (AFB_PostCtx*) postHandle->ctx;
130     if (postFileCtx == NULL) return NULL;
131   
132     return (postFileCtx->path);
133 }
134
135 json_object* getPostFile (AFB_request *request, AFB_PostItem *item, char* destination) {
136
137     AFB_PostHandle *postHandle = getPostHandle(request);
138     AFB_PostCtx *postFileCtx;
139     char filepath[512];
140     ssize_t len;
141             
142     // This is called after PostForm and then after DonePostForm
143     if (item == NULL) {
144         json_object* jresp;
145         postFileCtx = (AFB_PostCtx*) postHandle->ctx;
146         
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"));          
151         }
152         
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");
157         
158         // Error or not let's free all resources
159         close(postFileCtx->fd);
160         free (postFileCtx->path);
161         free (postFileCtx);
162         return (jresp);  
163     }
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");
168         goto ExitOnError;
169     } 
170     
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);
174         goto ExitOnError;
175     }
176     
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);
180         goto ExitOnError;
181     }
182 #endif
183     // Extract Application Context from posthandle [NULL == 1st iteration]    
184     postFileCtx = (AFB_PostCtx*) postHandle->ctx;
185
186     // This is the 1st Item iteration let's open output file and allocate necessary resources
187     if (postFileCtx == NULL)  {
188         DIR* destDir;
189         
190         // Create an application specific context
191         postFileCtx = calloc (1, sizeof(AFB_PostCtx)); // May place anything here until post->completeCB handle resources liberation
192         
193         // attach application to postHandle
194         postHandle->ctx = (void*) postFileCtx;   // May place anything here until post->completeCB handle resources liberation  
195         
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));
202
203         
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));
209             goto ExitOnError;
210           }
211         } else closedir (destDir);
212         
213         strncat (filepath, "/", sizeof(filepath));
214         strncat (filepath, item->filename, sizeof(filepath));  
215
216         postFileCtx->path = strdup (filepath);       
217         if (verbose) fprintf(stderr, "getPostFile path=%s\n", filepath);
218        
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));
221             goto ExitOnError;
222         } 
223     } else {     
224         // reuse existing application context
225         postFileCtx = (AFB_PostCtx*) postHandle->ctx;  
226     } 
227
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));
232         goto ExitOnError;
233     }
234   
235     // every intermediary iteration should return Success & NULL
236     request->errcode = MHD_HTTP_OK;
237     return NULL;
238     
239 ExitOnError:    
240     request->errcode = MHD_HTTP_EXPECTATION_FAILED;
241     return NULL;
242 }
243
244
245
246 static void jsoninit()
247 {
248   int idx, verbosesav;
249
250   if (jTypeStatic)
251         return;
252
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);
261   }
262   verbose = verbosesav;
263 }
264
265
266
267 // get JSON object from error level and increase its reference count
268 struct json_object *jsonNewStatus (AFB_error level)
269 {
270   jsoninit();
271   json_object *target =  AFBerr[level].json;
272   json_object_get (target);
273
274   return (target);
275 }
276
277 // get AFB object type with adequate usage count
278 struct json_object *jsonNewjtype (void)
279 {
280   jsoninit();
281   json_object_get (jTypeStatic); // increase reference count
282   return (jTypeStatic);
283 }
284
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;
289    va_list args;
290    char message [512];
291
292   jsoninit();
293
294    // format message
295    if (format != NULL) {
296        va_start(args, format);
297        vsnprintf (message, sizeof (message), format, args);
298        va_end(args);
299    }
300
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));
306    }
307    if (verbose) {
308         fprintf (stderr, "AFB:%-6s [%3d]: ", AFBerr [level].label, count++);
309         if (format != NULL) {
310             fprintf (stderr, "%s", message);
311         } else {
312             fprintf (stderr, "No Message");
313         }
314         fprintf (stderr, "\n");
315    }
316
317    return (AFBResponse);
318 }
319
320 // Dump a message on stderr
321 void jsonDumpObject (struct json_object * jObject) {
322
323    if (verbose) {
324         fprintf (stderr, "AFB:dump [%s]\n", json_object_to_json_string(jObject));
325    }
326 }
327