54093e409204de6d3c082d335b67ee86c7d4aff3
[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
23
24 // handle to hold queryAll values
25 typedef struct {
26      char    *msg;
27      int     idx;
28      size_t  len;
29 } queryHandleT;
30
31 // Sample Generic Ping Debug API
32 PUBLIC json_object* getPingTest(AFB_request *request) {
33     static pingcount = 0;
34     json_object *response;
35     char query  [256];
36     char session[256];
37     int len;
38     
39     // request all query key/value
40     len = getQueryAll (request, query, sizeof(query));
41     if (len == 0) strncpy (query, "NoSearchQueryList", sizeof(query));
42     
43     // check if we have some post data
44     if (request->post == NULL)  request->post->data="NoData"; 
45           
46     // return response to caller
47     response = jsonNewMessage(AFB_SUCCESS, "Ping Binder Daemon count=%d uuid=%s query={%s} session={0x%x} PostData: [%s] "
48                , pingcount++, request->uuid, query, session, request->post->data);
49     return (response);
50 }
51
52
53 // Helper to retrieve argument from  connection
54 PUBLIC const char* getQueryValue(const AFB_request * request, const char *name) {
55     const char *value;
56
57     value = MHD_lookup_connection_value(request->connection, MHD_GET_ARGUMENT_KIND, name);
58     return (value);
59 }
60
61 STATIC int getQueryCB (void*handle, enum MHD_ValueKind kind, const char *key, const char *value) {
62     queryHandleT *query = (queryHandleT*)handle;
63         
64     query->idx += snprintf (&query->msg[query->idx],query->len," %s: \'%s\',", key, value);
65 }
66
67 // Helper to retrieve argument from  connection
68 PUBLIC int getQueryAll(AFB_request * request, char *buffer, size_t len) {
69     queryHandleT query;
70     buffer[0] = '\0'; // start with an empty string
71     query.msg= buffer;
72     query.len= len;
73     query.idx= 0;
74
75     MHD_get_connection_values (request->connection, MHD_GET_ARGUMENT_KIND, getQueryCB, &query);
76     return (len);
77 }
78
79 // Helper to retrieve POST handle
80 PUBLIC AFB_PostHandle* getPostHandle (AFB_request *request) {
81     if (request->post == NULL) return (NULL);
82     return ((AFB_PostHandle*) request->post->data);
83 }
84
85 // Helper to retrieve POST file context
86 PUBLIC AFB_PostCtx* getPostContext (AFB_request *request) {
87     AFB_PostHandle* postHandle;
88     if (request->post == NULL) return (NULL);
89     
90     postHandle = (AFB_PostHandle*) request->post->data;
91     if (postHandle == NULL) return NULL;
92        
93     return ((AFB_PostCtx*) postHandle->ctx);
94 }
95
96 PUBLIC char* getPostPath (AFB_request *request) {
97     AFB_PostHandle *postHandle = getPostHandle(request);
98     AFB_PostCtx *postFileCtx;
99     
100     if (postHandle == NULL) return NULL;
101     
102     postFileCtx = (AFB_PostCtx*) postHandle->ctx;
103     if (postFileCtx == NULL) return NULL;
104   
105     return (postFileCtx->path);
106 }
107
108 PUBLIC json_object* getPostFile (AFB_request *request, AFB_PostItem *item, char* destination) {
109
110     AFB_PostHandle *postHandle = getPostHandle(request);
111     AFB_PostCtx *postFileCtx;
112     char filepath[512];
113     int len;
114             
115     // This is called after PostForm and then after DonePostForm
116     if (item == NULL) {
117         json_object* jresp;
118         postFileCtx = (AFB_PostCtx*) postHandle->ctx;
119         
120         // No Post Application Context [something really bad happen]
121         if (postFileCtx == NULL) {
122             request->errcode = MHD_HTTP_EXPECTATION_FAILED;
123             return(jsonNewMessage(AFB_FAIL,"Error: PostForm no PostContext to free\n"));          
124         }
125         
126         // We have a context but last Xform iteration fail or application set a message
127         if (request->jresp != NULL) {
128             jresp = request->jresp;  // retrieve previous error from postCtx
129         } else jresp = jsonNewMessage(AFB_SUCCESS,"getPostFile Post Request done");
130         
131         // Error or not let's free all resources
132         close(postFileCtx->fd);
133         free (postFileCtx->path);
134         free (postFileCtx);
135         return (jresp);  
136     }
137     
138     // Make sure it's a valid PostForm request
139     if (!request->post && request->post->type != AFB_POST_FORM) {
140         postFileCtx->jresp= jsonNewMessage(AFB_FAIL,"This is not a valid PostForm request\n");
141         goto ExitOnError;
142     } 
143     
144     // Check this is a file element
145     if (item->filename == NULL) {
146         postFileCtx->jresp= jsonNewMessage(AFB_FAIL,"No Filename attached to key=%s\n", item->key);
147         goto ExitOnError;
148     }
149     
150     // Check we got something in buffer
151     if (item->len <= 0) {       
152         postFileCtx->jresp= jsonNewMessage(AFB_FAIL,"Buffer size NULL key=%s]\n", item->key);
153         goto ExitOnError;
154     }
155
156     // Extract Application Context from posthandle [NULL == 1st iteration]    
157     postFileCtx = (AFB_PostCtx*) postHandle->ctx;
158
159     // This is the 1st Item iteration let's open output file and allocate necessary resources
160     if (postFileCtx == NULL)  {
161         DIR* destDir;
162         
163         // Create an application specific context
164         postFileCtx = calloc (1, sizeof(AFB_PostCtx)); // May place anything here until post->completeCB handle resources liberation
165         
166         // attach application to postHandle
167         postHandle->ctx = (void*) postFileCtx;   // May place anything here until post->completeCB handle resources liberation  
168         
169         // Build destination directory full path
170         if (destination[0] != '/') {
171            strncpy (filepath, request->config->sessiondir, sizeof(filepath)); 
172            strncat (filepath, "/", sizeof(filepath));
173            strncat (filepath, destination, sizeof(filepath)); 
174         } else strncpy (filepath, destination, sizeof(filepath));
175
176         
177         // make sure destination directory exist
178         destDir = opendir (filepath);
179         if (destDir == NULL) {
180           if (mkdir(filepath,O_RDWR | S_IRWXU | S_IRGRP) < 0) {
181             postFileCtx->jresp= jsonNewMessage(AFB_FAIL,"Fail to Create destination directory=[%s] error=%s\n", filepath, strerror(errno));
182             goto ExitOnError;
183           }
184         } else closedir (destDir);
185         
186         strncat (filepath, "/", sizeof(filepath));
187         strncat (filepath, item->filename, sizeof(filepath));  
188
189         postFileCtx->path = strdup (filepath);       
190         if (verbose) fprintf(stderr, "getPostFile path=%s\n", filepath);
191        
192         if((postFileCtx->fd = open(filepath, O_RDWR |O_CREAT, S_IRWXU|S_IRGRP)) <= 0) {
193             postFileCtx->jresp= jsonNewMessage(AFB_FAIL,"Fail to Create destination File=[%s] error=%s\n", filepath, strerror(errno));
194             goto ExitOnError;
195         } 
196     } else {     
197         // reuse existing application context
198         postFileCtx = (AFB_PostCtx*) postHandle->ctx;  
199     } 
200
201     // Check we successfully wrote full buffer
202     len = write (postFileCtx->fd, item->data, item->len);
203     if (item->len != len) {
204         postFileCtx->jresp= jsonNewMessage(AFB_FAIL,"Fail to write file [%s] at [%s] error=\n", item->filename, strerror(errno));
205         goto ExitOnError;
206     }
207   
208     // every intermediary iteration should return Success & NULL
209     request->errcode = MHD_HTTP_OK;
210     return NULL;
211     
212 ExitOnError:    
213     request->errcode = MHD_HTTP_EXPECTATION_FAILED;
214     return NULL;
215 }