My initial commit message
[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  AFB_Error [AFB_SUCCESS+1];
37 STATIC json_object *AFBJsonType;
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    // fix config redirect message
65    session->config->html5.msg = "Angular/HTML5 redirect";
66    session->config->html5.len = strlen(session->config->html5.msg);
67
68    // default HTTP port
69    if (cliconfig->httpdPort == 0) session->config->httpdPort=1234;
70    else session->config->httpdPort=cliconfig->httpdPort;
71
72    // cache timeout default one hour
73    if (cliconfig->cacheTimeout == 0) session->config->cacheTimeout=3600;
74    else session->config->cacheTimeout=cliconfig->cacheTimeout;
75
76    if (cliconfig->rootdir == NULL) {
77        session->config->rootdir = getenv("AFBDIR");
78        if (session->config->rootdir == NULL) {
79            session->config->rootdir = malloc (512);
80            strncpy  (session->config->rootdir, getenv("HOME"),512);
81            strncat (session->config->rootdir, "/.AFB",512);
82        }
83        // if directory does not exist createit
84        mkdir (session->config->rootdir,  O_RDWR | S_IRWXU | S_IRGRP);
85    } else {
86        session->config->rootdir =  cliconfig->rootdir;
87    }
88    
89    // if no Angular/HTML5 rootbase let's try '/' as default
90    if  (cliconfig->rootbase == NULL) {
91        session->config->rootbase = "/";
92    } else {
93        session->config->console= cliconfig->console;
94    }
95    
96    // if no rootapi use '/api'
97    if  (cliconfig->rootbase == NULL) {
98        session->config->rootbase = "/api";
99    } else {
100        session->config->console= cliconfig->console;
101    }
102
103
104
105    // if no session dir create a default path from rootdir
106    if  (cliconfig->sessiondir == NULL) {
107        session->config->sessiondir = malloc (512);
108        strncpy (session->config->sessiondir, session->config->rootdir, 512);
109        strncat (session->config->sessiondir, "/sessions",512);
110    } else {
111        session->config->sessiondir = cliconfig->sessiondir;
112    }
113
114    // if no config dir create a default path from sessiondir
115    if  (cliconfig->configfile == NULL) {
116        session->config->configfile = malloc (512);
117        strncpy (session->config->configfile, session->config->sessiondir, 512);
118        strncat (session->config->configfile, "/AFB-config.json",512);
119    } else {
120        session->config->configfile = cliconfig->configfile;
121    }
122
123    // if no config dir create a default path from sessiondir
124    if  (cliconfig->pidfile == NULL) {
125        session->config->pidfile = malloc (512);
126        strncpy (session->config->pidfile, session->config->sessiondir, 512);
127        strncat (session->config->pidfile, "/AFB-process.pid",512);
128    } else {
129        session->config->pidfile= cliconfig->pidfile;
130    }
131
132    // if no config dir create a default path from sessiondir
133    if  (cliconfig->console == NULL) {
134        session->config->console = malloc (512);
135        strncpy (session->config->console, session->config->sessiondir, 512);
136        strncat (session->config->console, "/AFB-console.out",512);
137    } else {
138        session->config->console= cliconfig->console;
139    }
140    
141    // just upload json object and return without any further processing
142    if((fd = open(session->config->configfile, O_RDONLY)) < 0) {
143       if (verbose) fprintf (stderr, "AFB:notice: config at %s: %s\n", session->config->configfile, strerror(errno));
144       return AFB_EMPTY;
145    }
146
147    // openjson from FD is not public API we need to reopen it !!!
148    close(fd);
149    AFBConfig = json_object_from_file (session->config->configfile);
150
151    // check it is an AFB_config
152    if (json_object_object_get_ex (AFBConfig, "jtype", &value)) {
153       if (strcmp (AFB_CONFIG_JTYPE, json_object_get_string (value))) {
154          fprintf (stderr,"AFB: Error file [%s] is not a valid [%s] type\n ", session->config->configfile, AFB_CONFIG_JTYPE);
155          return AFB_FAIL;
156       }
157    }
158
159    if (!cliconfig->rootdir && json_object_object_get_ex (AFBConfig, "rootdir", &value)) {
160       session->config->rootdir =  strdup (json_object_get_string (value));
161    }
162    
163    if (!cliconfig->rootbase && json_object_object_get_ex (AFBConfig, "rootbase", &value)) {
164       session->config->rootbase =  strdup (json_object_get_string (value));
165    }
166    
167    if (!cliconfig->rootapi && json_object_object_get_ex (AFBConfig, "rootapi", &value)) {
168       session->config->rootapi =  strdup (json_object_get_string (value));
169    }
170    
171    if (!cliconfig->smack && json_object_object_get_ex (AFBConfig, "smack", &value)) {
172       session->config->smack =  strdup (json_object_get_string (value));
173    }
174    
175    if (!cliconfig->plugins && json_object_object_get_ex (AFBConfig, "plugins", &value)) {
176       session->config->plugins =  strdup (json_object_get_string (value));
177    }
178
179    if (!cliconfig->sessiondir && json_object_object_get_ex (AFBConfig, "sessiondir", &value)) {
180       session->config->sessiondir = strdup (json_object_get_string (value));
181    }
182    
183    if (!cliconfig->pidfile && json_object_object_get_ex (AFBConfig, "pidfile", &value)) {
184       session->config->pidfile = strdup (json_object_get_string (value));
185    }
186
187    if (!cliconfig->httpdPort && json_object_object_get_ex (AFBConfig, "httpdPort", &value)) {
188       session->config->httpdPort = json_object_get_int (value);
189    }
190    
191    if (!cliconfig->setuid && json_object_object_get_ex (AFBConfig, "setuid", &value)) {
192       session->config->setuid = json_object_get_int (value);
193    }
194
195    if (!cliconfig->localhostOnly && json_object_object_get_ex (AFBConfig, "localhostonly", &value)) {
196       session->config->localhostOnly = json_object_get_int (value);
197    }
198    
199    if (!cliconfig->cacheTimeout && json_object_object_get_ex (AFBConfig, "cachetimeout", &value)) {
200       session->config->cacheTimeout = json_object_get_int (value);
201    }
202    // cacheTimeout is an interger but HTTPd wants it as a string
203    snprintf (cacheTimeout, sizeof (cacheTimeout),"%d", session->config->cacheTimeout);
204    session->cacheTimeout = cacheTimeout; // httpd uses cacheTimeout string version
205    json_object_put   (AFBConfig);    // decrease reference count to free the json object
206
207    return AFB_SUCCESS;
208 }
209
210 // Save the config on disk
211 PUBLIC void configStoreFile (AFB_session * session) {
212    json_object * AFBConfig;
213    time_t rawtime;
214    struct tm * timeinfo;
215    int err;
216
217    AFBConfig =  json_object_new_object();
218
219    // add a timestamp and store session on disk
220    time ( &rawtime );  timeinfo = localtime ( &rawtime );
221    // A copy of the string is made and the memory is managed by the json_object
222    json_object_object_add (AFBConfig, "jtype"         , json_object_new_string (AFB_CONFIG_JTYPE));
223    json_object_object_add (AFBConfig, "timestamp"     , json_object_new_string (asctime (timeinfo)));
224    json_object_object_add (AFBConfig, "rootdir"       , json_object_new_string (session->config->rootdir));
225    json_object_object_add (AFBConfig, "rootapi"       , json_object_new_string (session->config->rootapi));
226    json_object_object_add (AFBConfig, "rootbase"      , json_object_new_string (session->config->rootbase));
227    json_object_object_add (AFBConfig, "smack"         , json_object_new_string (session->config->smack));
228    json_object_object_add (AFBConfig, "plugins"       , json_object_new_string (session->config->plugins));
229    json_object_object_add (AFBConfig, "sessiondir"    , json_object_new_string (session->config->sessiondir));
230    json_object_object_add (AFBConfig, "pidfile"       , json_object_new_string (session->config->pidfile));
231    json_object_object_add (AFBConfig, "httpdPort"     , json_object_new_int (session->config->httpdPort));
232    json_object_object_add (AFBConfig, "setuid"        , json_object_new_int (session->config->setuid));
233    json_object_object_add (AFBConfig, "localhostonly" , json_object_new_int (session->config->localhostOnly));
234    json_object_object_add (AFBConfig, "cachetimeout"  , json_object_new_int (session->config->cacheTimeout));
235
236    err = json_object_to_file (session->config->configfile, AFBConfig);
237    json_object_put   (AFBConfig);    // decrease reference count to free the json object
238    if (err < 0) {
239       fprintf(stderr, "AFB: Fail to save config on disk [%s]\n ", session->config->configfile);
240    }
241 }
242
243
244 PUBLIC AFB_session *configInit () {
245
246   AFB_session *session;
247   AFB_config  *config;
248   int idx, verbosesav;
249
250
251   session = malloc (sizeof (AFB_session));
252   memset (session,0, sizeof (AFB_session));
253
254   // create config handle
255   config = malloc (sizeof (AFB_config));
256   memset (config,0, sizeof (AFB_config));
257
258   // stack config handle into session
259   session->config = config;
260
261   AFBJsonType = json_object_new_string ("AFB_message");
262
263   // initialise JSON constant messages and increase reference count to make them permanent
264   verbosesav = verbose;
265   verbose = 0;  // run initialisation in silent mode
266
267
268
269   for (idx = 0; idx <= AFB_SUCCESS; idx++) {
270      AFB_Error[idx].level = idx;
271      AFB_Error[idx].label = ERROR_LABEL [idx];
272      AFB_Error[idx].json  = jsonNewMessage (idx, NULL);
273   }
274   verbose = verbosesav;
275   
276   return (session);
277 }
278
279
280 // get JSON object from error level and increase its reference count
281 PUBLIC json_object *jsonNewStatus (AFB_ERROR level) {
282
283   json_object *target =  AFB_Error[level].json;
284   json_object_get (target);
285
286   return (target);
287 }
288
289 // get AFB object type with adequate usage count
290 PUBLIC json_object *jsonNewjtype (void) {
291   json_object_get (AFBJsonType); // increase reference count
292   return (AFBJsonType);
293 }
294
295 // build an ERROR message and return it as a valid json object
296 PUBLIC  json_object *jsonNewMessage (AFB_ERROR level, char* format, ...) {
297    static int count = 0;
298    json_object * AFBResponse;
299    va_list args;
300    char message [512];
301
302    // format message
303    if (format != NULL) {
304        va_start(args, format);
305        vsnprintf (message, sizeof (message), format, args);
306        va_end(args);
307    }
308
309    AFBResponse = json_object_new_object();
310    json_object_object_add (AFBResponse, "jtype", jsonNewjtype ());
311    json_object_object_add (AFBResponse, "status" , json_object_new_string (ERROR_LABEL[level]));
312    if (format != NULL) {
313         json_object_object_add (AFBResponse, "info"   , json_object_new_string (message));
314    }
315    if (verbose) {
316         fprintf (stderr, "AFB:%-6s [%3d]: ", AFB_Error [level].label, count++);
317         if (format != NULL) {
318             fprintf (stderr, "%s", message);
319         } else {
320             fprintf (stderr, "No Message");
321         }
322         fprintf (stderr, "\n");
323    }
324
325    return (AFBResponse);
326 }
327
328 // Dump a message on stderr
329 PUBLIC void jsonDumpObject (json_object * jObject) {
330
331    if (verbose) {
332         fprintf (stderr, "AFB:dump [%s]\n", json_object_to_json_string(jObject));
333    }
334 }
335