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