Improves documentation and directory management
[src/app-framework-binder.git] / src / main.c
1 /*
2  * Copyright (C) 2015, 2016, 2017 "IoT.bzh"
3  * Author "Fulup Ar Foll"
4  * Author José Bollo <jose.bollo@iot.bzh>
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18
19 #define _GNU_SOURCE
20 #define NO_BINDING_VERBOSE_MACRO
21
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <sys/stat.h>
28 #include <sys/wait.h>
29
30 #include <systemd/sd-event.h>
31
32 #include "afb-config.h"
33 #include "afb-hswitch.h"
34 #include "afb-apis.h"
35 #include "afb-api-so.h"
36 #include "afb-api-dbus.h"
37 #include "afb-api-ws.h"
38 #include "afb-hsrv.h"
39 #include "afb-context.h"
40 #include "afb-hreq.h"
41 #include "afb-sig-handler.h"
42 #include "afb-thread.h"
43 #include "afb-session.h"
44 #include "verbose.h"
45 #include "afb-common.h"
46 #include "afb-hook.h"
47
48 #include <afb/afb-binding.h>
49
50 /*
51    if SELF_PGROUP == 0 the launched command is the group leader
52    if SELF_PGROUP != 0 afb-daemon is the group leader
53 */
54 #define SELF_PGROUP 1
55
56 static struct afb_config *config;
57 static pid_t childpid;
58
59 /*----------------------------------------------------------
60  |   helpers for handling list of arguments
61  +--------------------------------------------------------- */
62
63 /*
64  * Calls the callback 'run' for each value of the 'list'
65  * until the callback returns 0 or the end of the list is reached.
66  * Returns either NULL if the end of the list is reached or a pointer
67  * to the item whose value made 'run' return 0.
68  * 'closure' is used for passing user data.
69  */
70 static struct afb_config_list *run_for_list(struct afb_config_list *list,
71                                             int (*run) (void *closure, char *value),
72                                             void *closure)
73 {
74         while (list && run(closure, list->value))
75                 list = list->next;
76         return list;
77 }
78
79 static int run_start(void *closure, char *value)
80 {
81         int (*starter) (const char *value) = closure;
82         return starter(value) >= 0;
83 }
84
85 static void start_list(struct afb_config_list *list,
86                        int (*starter) (const char *value), const char *message)
87 {
88         list = run_for_list(list, run_start, starter);
89         if (list) {
90                 ERROR("can't start %s %s", message, list->value);
91                 exit(1);
92         }
93 }
94
95 /*----------------------------------------------------------
96  | exit_handler
97  |   Handles on exit specific actions
98  +--------------------------------------------------------- */
99 static void exit_handler()
100 {
101         /* TODO: check whether using SIGHUP isn't better */
102         if (SELF_PGROUP)
103                 killpg(0, SIGKILL);
104         else if (childpid > 0)
105                 killpg(childpid, SIGKILL);
106 }
107
108 /*----------------------------------------------------------
109  | daemonize
110  |   set the process in background
111  +--------------------------------------------------------- */
112 static void daemonize()
113 {
114         int consoleFD;
115         int pid;
116
117         // open /dev/console to redirect output messAFBes
118         consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT, 0640);
119         if (consoleFD < 0) {
120                 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
121                 exit(1);
122         }
123         // fork process when running background mode
124         pid = fork();
125
126         // if fail nothing much to do
127         if (pid == -1) {
128                 ERROR("AFB-daemon Failed to fork son process");
129                 exit(1);
130         }
131         // if in father process, just leave
132         if (pid != 0)
133                 _exit(0);
134
135         // son process get all data in standalone mode
136         NOTICE("background mode [pid:%d console:%s]", getpid(),
137                config->console);
138
139         // redirect default I/O on console
140         close(2);
141         dup(consoleFD);         // redirect stderr
142         close(1);
143         dup(consoleFD);         // redirect stdout
144         close(0);               // no need for stdin
145         close(consoleFD);
146
147 #if 0
148         setsid();               // allow father process to fully exit
149         sleep(2);               // allow main to leave and release port
150 #endif
151 }
152
153 /*---------------------------------------------------------
154  | http server
155  |   Handles the HTTP server
156  +--------------------------------------------------------- */
157 static int init_alias(void *closure, char *spec)
158 {
159         struct afb_hsrv *hsrv = closure;
160         char *path = strchr(spec, ':');
161
162         if (path == NULL) {
163                 ERROR("Missing ':' in alias %s. Alias ignored", spec);
164                 return 1;
165         }
166         *path++ = 0;
167         INFO("Alias for url=%s to path=%s", spec, path);
168         return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
169                                   0, 0);
170 }
171
172 static int init_http_server(struct afb_hsrv *hsrv)
173 {
174         if (!afb_hsrv_add_handler
175             (hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
176                 return 0;
177
178         if (!afb_hsrv_add_handler
179             (hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
180                 return 0;
181
182         if (run_for_list(config->aliases, init_alias, hsrv))
183                 return 0;
184
185         if (config->roothttp != NULL) {
186                 if (!afb_hsrv_add_alias
187                     (hsrv, "", afb_common_rootdir_get_fd(), config->roothttp,
188                      -10, 1))
189                         return 0;
190         }
191
192         if (!afb_hsrv_add_handler
193             (hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL,
194              -20))
195                 return 0;
196
197         return 1;
198 }
199
200 static struct afb_hsrv *start_http_server()
201 {
202         int rc;
203         struct afb_hsrv *hsrv;
204
205         if (afb_hreq_init_download_path(config->uploaddir)) {
206                 ERROR("unable to set the upload directory %s", config->uploaddir);
207                 return NULL;
208         }
209
210         hsrv = afb_hsrv_create();
211         if (hsrv == NULL) {
212                 ERROR("memory allocation failure");
213                 return NULL;
214         }
215
216         if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
217             || !init_http_server(hsrv)) {
218                 ERROR("initialisation of httpd failed");
219                 afb_hsrv_put(hsrv);
220                 return NULL;
221         }
222
223         NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
224         NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
225
226         rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
227         if (!rc) {
228                 ERROR("starting of httpd failed");
229                 afb_hsrv_put(hsrv);
230                 return NULL;
231         }
232
233         return hsrv;
234 }
235
236 /*---------------------------------------------------------
237  | execute_command
238  |   
239  +--------------------------------------------------------- */
240
241 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
242 {
243         if (info->si_pid == childpid) {
244                 switch (info->si_code) {
245                 case CLD_EXITED:
246                 case CLD_KILLED:
247                 case CLD_DUMPED:
248                         childpid = 0;
249                         if (!SELF_PGROUP)
250                                 killpg(info->si_pid, SIGKILL);
251                         waitpid(info->si_pid, NULL, 0);
252                         exit(0);
253                 }
254         }
255 }
256
257 /*
258 # @@ @
259 # @p port
260 # @t token
261 */
262
263 #define SUBST_CHAR  '@'
264 #define SUBST_STR   "@"
265
266 static int instanciate_command_args()
267 {
268         char *orig, *repl, *sub, *val, port[20];
269         int i, rc, r;
270         size_t s, l;
271
272         rc = snprintf(port, sizeof port, "%d", config->httpdPort);
273         if (rc < 0 || rc >= (int)(sizeof port))
274                 return -1;
275
276         for (i = 0 ; (orig = config->exec[i]) ; i++) {
277                 repl = 0;
278                 s = 0;
279                 for(;;) {
280                         sub = strchrnul(orig, SUBST_CHAR);
281                         l = sub - orig;
282                         if (repl)
283                                 repl = mempcpy(repl, orig, l);
284                         else
285                                 s += l;
286                         if (!*sub) {
287                                 /* at end */
288                                 if (repl || orig == config->exec[i])
289                                         break;
290                                 repl = malloc(1 + s);
291                                 if (!repl)
292                                         return -1;
293                                 orig = config->exec[i];
294                                 config->exec[i] = repl;
295                                 repl[s] = 0;
296                         } else {
297                                 r = 2;
298                                 switch(sub[1]) {
299                                 case 'p': val = port;  break;
300                                 case 't': val = config->token ? : ""; break;
301                                 default: r = 1;
302                                 case SUBST_CHAR: val = SUBST_STR; break;
303                                 }
304                                 orig = &sub[r];
305                                 l = strlen(val);
306                                 if (repl)
307                                         repl = mempcpy(repl, val, l);
308                                 else
309                                         s += l;
310                         }
311                 }
312         }
313         return 0;
314 }
315
316 static int execute_command()
317 {
318         struct sigaction siga;
319
320         /* check whether a command is to execute or not */
321         if (!config->exec || !config->exec[0])
322                 return 0;
323
324         if (SELF_PGROUP)
325                 setpgid(0, 0);
326
327         /* install signal handler */
328         memset(&siga, 0, sizeof siga);
329         siga.sa_sigaction = on_sigchld;
330         siga.sa_flags = SA_SIGINFO;
331         sigaction(SIGCHLD, &siga, NULL);
332
333         /* fork now */
334         childpid = fork();
335         if (childpid)
336                 return 0;
337
338         /* makes arguments */
339         if (instanciate_command_args() >= 0) {
340                 if (!SELF_PGROUP)
341                         setpgid(0, 0);
342                 execv(config->exec[0], config->exec);
343                 ERROR("can't launch %s: %m", config->exec[0]);
344         }
345         exit(1);
346         return -1;
347 }
348
349 /*---------------------------------------------------------
350  | main
351  |   Parse option and launch action
352  +--------------------------------------------------------- */
353
354 int main(int argc, char *argv[])
355 {
356         struct afb_hsrv *hsrv;
357         struct sd_event *eventloop;
358
359         LOGAUTH("afb-daemon");
360
361         // ------------- Build session handler & init config -------
362         config = afb_config_parse_arguments(argc, argv);
363         atexit(exit_handler);
364
365         // ------------------ sanity check ----------------------------------------
366         if (config->httpdPort <= 0) {
367                 ERROR("no port is defined");
368                 exit(1);
369         }
370
371         mkdir(config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
372         if (chdir(config->workdir) < 0) {
373                 ERROR("Can't enter working dir %s", config->workdir);
374                 exit(1);
375         }
376
377         afb_session_init(config->nbSessionMax, config->cntxTimeout, config->token, afb_apis_count());
378
379         afb_api_so_set_timeout(config->apiTimeout);
380         start_list(config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
381         start_list(config->ws_clients, afb_api_ws_add_client, "the afb-websocket client");
382         start_list(config->ldpaths, afb_api_so_add_pathset, "the binding path set");
383         start_list(config->so_bindings, afb_api_so_add_binding, "the binding");
384         start_list(config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
385         start_list(config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
386
387         if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, config->cntxTimeout)) {
388                 ERROR("initialisation of cookies failed");
389                 exit(1);
390         }
391
392         if (afb_sig_handler_init() < 0) {
393                 ERROR("failed to initialise signal handlers");
394                 return 1;
395         }
396
397         // set the root dir
398         if (afb_common_rootdir_set(config->rootdir) < 0) {
399                 ERROR("failed to set common root directory");
400                 return 1;
401         }
402
403         if (afb_thread_init(3, 1, 20) < 0) {
404                 ERROR("failed to initialise threading");
405                 return 1;
406         }
407         // let's run this program with a low priority
408         nice(20);
409
410         // ------------------ Finaly Process Commands -----------------------------
411         // let's not take the risk to run as ROOT
412         //if (getuid() == 0)  goto errorNoRoot;
413
414         DEBUG("Init config done");
415
416         // --------- run -----------
417         if (config->background) {
418                 // --------- in background mode -----------
419                 INFO("entering background mode");
420                 daemonize();
421         } else {
422                 // ---- in foreground mode --------------------
423                 INFO("entering foreground mode");
424         }
425
426         /* ignore any SIGPIPE */
427         signal(SIGPIPE, SIG_IGN);
428
429         /* install trace of requests */
430         if (config->tracereq)
431                 afb_hook_req_create(NULL, NULL, NULL, config->tracereq, NULL, NULL);
432
433         /* start the services */
434         if (afb_apis_start_all_services(1) < 0)
435                 exit(1);
436
437         /* start the HTTP server */
438         if (!config->noHttpd) {
439                 hsrv = start_http_server();
440                 if (hsrv == NULL)
441                         exit(1);
442         }
443
444         /* run the command */
445         if (execute_command() < 0)
446                 exit(1);
447
448         /* signal that ready */
449         if (config->readyfd != 0) {
450                 static const char readystr[] = "READY=1";
451                 write(config->readyfd, readystr, sizeof(readystr) - 1);
452                 close(config->readyfd);
453         }
454
455         // infinite loop
456         eventloop = afb_common_get_event_loop();
457         for (;;)
458                 sd_event_run(eventloop, 30000000);
459
460         WARNING("hoops returned from infinite loop [report bug]");
461
462         return 0;
463 }