Fixed Plugin.private bug, added "no session mode" fixed plugin API
[src/app-framework-binder.git] / src / config.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    References:
19      https://www.gnu.org/software/libmicrohttpd/manual/html_node/index.html#Top
20      http://www-01.ibm.com/support/knowledgecenter/SSB23S_1.1.0.9/com.ibm.ztpf-ztpfdf.doc_put.09/gtpc2/cpp_vsprintf.html?cp=SSB23S_1.1.0.9%2F0-3-8-1-0-16-8
21
22 */
23
24
25 #include "../include/local-def.h"
26 #include <stdarg.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29
30
31 #define AFB_CONFIG_JTYPE "AFB_config"
32
33 PUBLIC  char *ERROR_LABEL[]=ERROR_LABEL_DEF;
34
35 PUBLIC int verbose;
36 STATIC AFB_errorT   AFBerr [AFB_SUCCESS+1];
37 STATIC json_object *jTypeStatic;
38
39 /* ------------------------------------------------------------------------------
40  * Get localtime and return in a string
41  * ------------------------------------------------------------------------------ */
42
43 PUBLIC char * configTime (void) {
44   static char reqTime [26];
45   time_t tt;
46   struct tm *rt;
47
48   /* Get actual Date and Time */
49   time (&tt);
50   rt = localtime (&tt);
51
52   strftime (reqTime, sizeof (reqTime), "(%d-%b %H:%M)",rt);
53
54   // return pointer on static data
55   return (reqTime);
56 }
57
58 // load config from disk and merge with CLI option
59 PUBLIC AFB_error configLoadFile (AFB_session * session, AFB_config *cliconfig) {
60    static char cacheTimeout [10];
61    int fd;
62    json_object * AFBConfig, *value;
63    
64    // TBD integrate alias-dir array with config-file
65    session->config->aliasdir = cliconfig->aliasdir;
66    
67    // default HTTP port
68    if (cliconfig->httpdPort == 0) session->config->httpdPort=1234;
69    else session->config->httpdPort=cliconfig->httpdPort;
70    
71    // default Plugin API timeout
72    if (cliconfig->apiTimeout == 0) session->config->apiTimeout=DEFLT_API_TIMEOUT;
73    else session->config->apiTimeout=cliconfig->apiTimeout;
74    
75    // default AUTH_TOKEN
76    if (cliconfig->token == NULL) session->config->token= DEFLT_AUTH_TOKEN;
77    else session->config->token=cliconfig->token;
78
79    // cache timeout default one hour
80    if (cliconfig->cacheTimeout == 0) session->config->cacheTimeout=DEFLT_CACHE_TIMEOUT;
81    else session->config->cacheTimeout=cliconfig->cacheTimeout;
82
83    // cache timeout default one hour
84    if (cliconfig->cntxTimeout == 0) session->config->cntxTimeout=DEFLT_CNTX_TIMEOUT;
85    else session->config->cntxTimeout=cliconfig->cntxTimeout;
86
87    if (cliconfig->rootdir == NULL) {
88        session->config->rootdir = getenv("AFBDIR");
89        if (session->config->rootdir == NULL) {
90            session->config->rootdir = malloc (512);
91            strncpy  (session->config->rootdir, getenv("HOME"),512);
92            strncat (session->config->rootdir, "/.AFB",512);
93        }
94        // if directory does not exist createit
95        mkdir (session->config->rootdir,  O_RDWR | S_IRWXU | S_IRGRP);
96    } else {
97        session->config->rootdir =  cliconfig->rootdir;
98    }
99    
100    // if no Angular/HTML5 rootbase let's try '/' as default
101    if  (cliconfig->rootbase == NULL) {
102        session->config->rootbase = "/opa";
103    } else {
104        session->config->rootbase= cliconfig->rootbase;
105    }
106    
107    if  (cliconfig->rootapi == NULL) {
108        session->config->rootapi = "/api";
109    } else {
110        session->config->rootapi= cliconfig->rootapi;
111    }
112
113    if  (cliconfig->smack == NULL) {
114        session->config->smack = "demo";
115    } else {
116        session->config->smack= cliconfig->smack;
117    }
118
119    if  (cliconfig->smack == NULL) {
120        session->config->plugins = "all";
121    } else {
122        session->config->plugins= cliconfig->plugins;
123    }
124
125    // if no session dir create a default path from rootdir
126    if  (cliconfig->sessiondir == NULL) {
127        session->config->sessiondir = malloc (512);
128        strncpy (session->config->sessiondir, session->config->rootdir, 512);
129        strncat (session->config->sessiondir, "/sessions",512);
130    } else {
131        session->config->sessiondir = cliconfig->sessiondir;
132    }
133
134    // if no config dir create a default path from sessiondir
135    if  (cliconfig->configfile == NULL) {
136        session->config->configfile = malloc (512);
137        strncpy (session->config->configfile, session->config->sessiondir, 512);
138        strncat (session->config->configfile, "/AFB-config.json",512);
139    } else {
140        session->config->configfile = cliconfig->configfile;
141    }
142
143    // if no config dir create a default path from sessiondir
144    if  (cliconfig->pidfile == NULL) {
145        session->config->pidfile = malloc (512);
146        strncpy (session->config->pidfile, session->config->sessiondir, 512);
147        strncat (session->config->pidfile, "/AFB-process.pid",512);
148    } else {
149        session->config->pidfile= cliconfig->pidfile;
150    }
151
152    // if no config dir create a default path from sessiondir
153    if  (cliconfig->console == NULL) {
154        session->config->console = malloc (512);
155        strncpy (session->config->console, session->config->sessiondir, 512);
156        strncat (session->config->console, "/AFB-console.out",512);
157    } else {
158        session->config->console= cliconfig->console;
159    }
160    
161    // just upload json object and return without any further processing
162    if((fd = open(session->config->configfile, O_RDONLY)) < 0) {
163       if (verbose) fprintf (stderr, "AFB:notice: config at %s: %s\n", session->config->configfile, strerror(errno));
164       return AFB_EMPTY;
165    }
166
167    // openjson from FD is not public API we need to reopen it !!!
168    close(fd);
169    AFBConfig = json_object_from_file (session->config->configfile);
170
171    // check it is an AFB_config
172    if (json_object_object_get_ex (AFBConfig, "jtype", &value)) {
173       if (strcmp (AFB_CONFIG_JTYPE, json_object_get_string (value))) {
174          fprintf (stderr,"AFB: Error file [%s] is not a valid [%s] type\n ", session->config->configfile, AFB_CONFIG_JTYPE);
175          return AFB_FAIL;
176       }
177    }
178
179    if (!cliconfig->rootdir && json_object_object_get_ex (AFBConfig, "rootdir", &value)) {
180       session->config->rootdir =  strdup (json_object_get_string (value));
181    }
182    
183    if (!cliconfig->rootbase && json_object_object_get_ex (AFBConfig, "rootbase", &value)) {
184       session->config->rootbase =  strdup (json_object_get_string (value));
185    }
186    
187    if (!cliconfig->rootapi && json_object_object_get_ex (AFBConfig, "rootapi", &value)) {
188       session->config->rootapi =  strdup (json_object_get_string (value));
189    }
190    
191    if (!cliconfig->smack && json_object_object_get_ex (AFBConfig, "smack", &value)) {
192       session->config->smack =  strdup (json_object_get_string (value));
193    }
194    
195    if (!cliconfig->plugins && json_object_object_get_ex (AFBConfig, "plugins", &value)) {
196       session->config->plugins =  strdup (json_object_get_string (value));
197    }
198
199    if (!cliconfig->setuid && json_object_object_get_ex (AFBConfig, "setuid", &value)) {
200       session->config->setuid = strdup (json_object_get_string (value));
201    }
202    
203    if (!cliconfig->sessiondir && json_object_object_get_ex (AFBConfig, "sessiondir", &value)) {
204       session->config->sessiondir = strdup (json_object_get_string (value));
205    }
206    
207    if (!cliconfig->pidfile && json_object_object_get_ex (AFBConfig, "pidfile", &value)) {
208       session->config->pidfile = strdup (json_object_get_string (value));
209    }
210
211    if (!cliconfig->httpdPort && json_object_object_get_ex (AFBConfig, "httpdPort", &value)) {
212       session->config->httpdPort = json_object_get_int (value);
213    }
214    
215
216    if (!cliconfig->localhostOnly && json_object_object_get_ex (AFBConfig, "localhostonly", &value)) {
217       session->config->localhostOnly = json_object_get_int (value);
218    }
219    
220    if (!cliconfig->cacheTimeout && json_object_object_get_ex (AFBConfig, "cachetimeout", &value)) {
221       session->config->cacheTimeout = json_object_get_int (value);
222    }
223    
224    if (!cliconfig->apiTimeout && json_object_object_get_ex (AFBConfig, "apitimeout", &value)) {
225       session->config->apiTimeout = json_object_get_int (value);
226    }
227    
228    if (!cliconfig->cntxTimeout && json_object_object_get_ex (AFBConfig, "cntxtimeout", &value)) {
229       session->config->cntxTimeout = json_object_get_int (value);
230    }
231    
232    // cacheTimeout is an integer but HTTPd wants it as a string
233    snprintf (cacheTimeout, sizeof (cacheTimeout),"%d", session->config->cacheTimeout);
234    session->cacheTimeout = cacheTimeout; // httpd uses cacheTimeout string version
235    
236    json_object_put   (AFBConfig);    // decrease reference count to free the json object
237
238  
239    
240    return AFB_SUCCESS;
241 }
242
243 // Save the config on disk
244 PUBLIC void configStoreFile (AFB_session * session) {
245    json_object * AFBConfig;
246    time_t rawtime;
247    struct tm * timeinfo;
248    int err;
249
250    AFBConfig =  json_object_new_object();
251
252    // add a timestamp and store session on disk
253    time ( &rawtime );  timeinfo = localtime ( &rawtime );
254    // A copy of the string is made and the memory is managed by the json_object
255    json_object_object_add (AFBConfig, "jtype"         , json_object_new_string (AFB_CONFIG_JTYPE));
256    json_object_object_add (AFBConfig, "timestamp"     , json_object_new_string (asctime (timeinfo)));
257    json_object_object_add (AFBConfig, "rootdir"       , json_object_new_string (session->config->rootdir));
258    json_object_object_add (AFBConfig, "rootapi"       , json_object_new_string (session->config->rootapi));
259    json_object_object_add (AFBConfig, "rootbase"      , json_object_new_string (session->config->rootbase));
260    json_object_object_add (AFBConfig, "smack"         , json_object_new_string (session->config->smack));
261    json_object_object_add (AFBConfig, "plugins"       , json_object_new_string (session->config->plugins));
262    json_object_object_add (AFBConfig, "sessiondir"    , json_object_new_string (session->config->sessiondir));
263    json_object_object_add (AFBConfig, "pidfile"       , json_object_new_string (session->config->pidfile));
264    json_object_object_add (AFBConfig, "setuid"        , json_object_new_string (session->config->setuid));
265    json_object_object_add (AFBConfig, "httpdPort"     , json_object_new_int (session->config->httpdPort));
266    json_object_object_add (AFBConfig, "localhostonly" , json_object_new_int (session->config->localhostOnly));
267    json_object_object_add (AFBConfig, "cachetimeout"  , json_object_new_int (session->config->cacheTimeout));
268    json_object_object_add (AFBConfig, "apitimeout"    , json_object_new_int (session->config->apiTimeout));
269    json_object_object_add (AFBConfig, "cntxtimeout"   , json_object_new_int (session->config->cntxTimeout));
270
271    err = json_object_to_file (session->config->configfile, AFBConfig);
272    json_object_put   (AFBConfig);    // decrease reference count to free the json object
273    if (err < 0) {
274       fprintf(stderr, "AFB: Fail to save config on disk [%s]\n ", session->config->configfile);
275    }
276 }
277
278
279 PUBLIC AFB_session *configInit () {
280
281   AFB_session *session;
282   AFB_config  *config;
283   int idx, verbosesav;
284
285
286   session = malloc (sizeof (AFB_session));
287   memset (session,0, sizeof (AFB_session));
288
289   // create config handle
290   config = malloc (sizeof (AFB_config));
291   memset (config,0, sizeof (AFB_config));
292
293   // stack config handle into session
294   session->config = config;
295
296   jTypeStatic = json_object_new_string ("AFB_message");
297
298   // initialise JSON constant messages and increase reference count to make them permanent
299   verbosesav = verbose;
300   verbose = 0;  // run initialisation in silent mode
301
302
303   for (idx = 0; idx <= AFB_SUCCESS; idx++) {
304      AFBerr[idx].level = idx;
305      AFBerr[idx].label = ERROR_LABEL [idx];
306      AFBerr[idx].json  = jsonNewMessage (idx, NULL);
307   }
308   verbose = verbosesav;
309   
310   return (session);
311 }
312
313
314 // get JSON object from error level and increase its reference count
315 PUBLIC json_object *jsonNewStatus (AFB_error level) {
316
317   json_object *target =  AFBerr[level].json;
318   json_object_get (target);
319
320   return (target);
321 }
322
323 // get AFB object type with adequate usage count
324 PUBLIC json_object *jsonNewjtype (void) {
325   json_object_get (jTypeStatic); // increase reference count
326   return (jTypeStatic);
327 }
328
329 // build an ERROR message and return it as a valid json object
330 PUBLIC  json_object *jsonNewMessage (AFB_error level, char* format, ...) {
331    static int count = 0;
332    json_object * AFBResponse;
333    va_list args;
334    char message [512];
335
336    // format message
337    if (format != NULL) {
338        va_start(args, format);
339        vsnprintf (message, sizeof (message), format, args);
340        va_end(args);
341    }
342
343    AFBResponse = json_object_new_object();
344    json_object_object_add (AFBResponse, "jtype", jsonNewjtype ());
345    json_object_object_add (AFBResponse, "status" , json_object_new_string (ERROR_LABEL[level]));
346    if (format != NULL) {
347         json_object_object_add (AFBResponse, "info"   , json_object_new_string (message));
348    }
349    if (verbose) {
350         fprintf (stderr, "AFB:%-6s [%3d]: ", AFBerr [level].label, count++);
351         if (format != NULL) {
352             fprintf (stderr, "%s", message);
353         } else {
354             fprintf (stderr, "No Message");
355         }
356         fprintf (stderr, "\n");
357    }
358
359    return (AFBResponse);
360 }
361
362 // Dump a message on stderr
363 PUBLIC void jsonDumpObject (json_object * jObject) {
364
365    if (verbose) {
366         fprintf (stderr, "AFB:dump [%s]\n", json_object_to_json_string(jObject));
367    }
368 }
369