Add hooking of daemon interface
[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 #include <systemd/sd-daemon.h>
32
33 #include <afb/afb-binding.h>
34
35 #include "afb-config.h"
36 #include "afb-hswitch.h"
37 #include "afb-apis.h"
38 #include "afb-api-so.h"
39 #include "afb-api-dbus.h"
40 #include "afb-api-ws.h"
41 #include "afb-hsrv.h"
42 #include "afb-context.h"
43 #include "afb-hreq.h"
44 #include "jobs.h"
45 #include "afb-session.h"
46 #include "verbose.h"
47 #include "afb-common.h"
48 #include "afb-hook.h"
49 #include "sd-fds.h"
50
51 /*
52    if SELF_PGROUP == 0 the launched command is the group leader
53    if SELF_PGROUP != 0 afb-daemon is the group leader
54 */
55 #define SELF_PGROUP 1
56
57 static struct afb_config *config;
58 static pid_t childpid;
59
60 /*----------------------------------------------------------
61  |   helpers for handling list of arguments
62  +--------------------------------------------------------- */
63
64 /*
65  * Calls the callback 'run' for each value of the 'list'
66  * until the callback returns 0 or the end of the list is reached.
67  * Returns either NULL if the end of the list is reached or a pointer
68  * to the item whose value made 'run' return 0.
69  * 'closure' is used for passing user data.
70  */
71 static struct afb_config_list *run_for_list(struct afb_config_list *list,
72                                             int (*run) (void *closure, char *value),
73                                             void *closure)
74 {
75         while (list && run(closure, list->value))
76                 list = list->next;
77         return list;
78 }
79
80 static int run_start(void *closure, char *value)
81 {
82         int (*starter) (const char *value) = closure;
83         return starter(value) >= 0;
84 }
85
86 static void start_list(struct afb_config_list *list,
87                        int (*starter) (const char *value), const char *message)
88 {
89         list = run_for_list(list, run_start, starter);
90         if (list) {
91                 ERROR("can't start %s %s", message, list->value);
92                 exit(1);
93         }
94 }
95
96 /*----------------------------------------------------------
97  | exit_handler
98  |   Handles on exit specific actions
99  +--------------------------------------------------------- */
100 static void exit_handler()
101 {
102         if (SELF_PGROUP)
103                 killpg(0, SIGHUP);
104         else if (childpid > 0)
105                 killpg(childpid, SIGHUP);
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 char *instanciate_string(char *arg, const char *port, const char *token)
267 {
268         char *resu, *it, *wr;
269         int chg, dif;
270
271         /* get the changes */
272         chg = 0;
273         dif = 0;
274         it = strchrnul(arg, SUBST_CHAR);
275         while (*it) {
276                 switch(*++it) {
277                 case 'p': chg++; dif += (int)strlen(port) - 2; break;
278                 case 't': chg++; dif += (int)strlen(token) - 2; break;
279                 case SUBST_CHAR: it++; chg++; dif--; break;
280                 default: break;
281                 }
282                 it = strchrnul(it, SUBST_CHAR);
283         }
284
285         /* return arg when no change */
286         if (!chg)
287                 return arg;
288
289         /* allocates the result */
290         resu = malloc((it - arg) + dif + 1);
291         if (!resu) {
292                 ERROR("out of memory");
293                 return NULL;
294         }
295
296         /* instanciate the arguments */
297         wr = resu;
298         for (;;) {
299                 it = strchrnul(arg, SUBST_CHAR);
300                 wr = mempcpy(wr, arg, it - arg);
301                 if (!*it)
302                         break;
303                 switch(*++it) {
304                 case 'p': wr = stpcpy(wr, port); break;
305                 case 't': wr = stpcpy(wr, token); break;
306                 default: *wr++ = SUBST_CHAR;
307                 case SUBST_CHAR: *wr++ = *it;
308                 }
309                 arg = ++it;
310         }
311
312         *wr = 0;
313         return resu;
314 }
315
316 static int instanciate_environ(const char *port, const char *token)
317 {
318         extern char **environ;
319         char *repl;
320         int i;
321
322         /* instanciate the environment */
323         for (i = 0 ; environ[i] ; i++) {
324                 repl = instanciate_string(environ[i], port, token);
325                 if (!repl)
326                         return -1;
327                 environ[i] = repl;
328         }
329         return 0;
330 }
331
332 static int instanciate_command_args(const char *port, const char *token)
333 {
334         char *repl;
335         int i;
336
337         /* instanciate the arguments */
338         for (i = 0 ; config->exec[i] ; i++) {
339                 repl = instanciate_string(config->exec[i], port, token);
340                 if (!repl)
341                         return -1;
342                 config->exec[i] = repl;
343         }
344         return 0;
345 }
346
347 static int execute_command()
348 {
349         struct sigaction siga;
350         char port[20];
351         int rc;
352
353         /* check whether a command is to execute or not */
354         if (!config->exec || !config->exec[0])
355                 return 0;
356
357         if (SELF_PGROUP)
358                 setpgid(0, 0);
359
360         /* install signal handler */
361         memset(&siga, 0, sizeof siga);
362         siga.sa_sigaction = on_sigchld;
363         siga.sa_flags = SA_SIGINFO;
364         sigaction(SIGCHLD, &siga, NULL);
365
366         /* fork now */
367         childpid = fork();
368         if (childpid)
369                 return 0;
370
371         /* compute the string for port */
372         if (config->httpdPort)
373                 rc = snprintf(port, sizeof port, "%d", config->httpdPort);
374         else
375                 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
376         if (rc < 0 || rc >= (int)(sizeof port)) {
377                 ERROR("port->txt failed");
378         }
379         else {
380                 /* instanciate arguments and environment */
381                 if (instanciate_command_args(port, config->token) >= 0
382                  && instanciate_environ(port, config->token) >= 0) {
383                         /* run */
384                         if (!SELF_PGROUP)
385                                 setpgid(0, 0);
386                         execv(config->exec[0], config->exec);
387                         ERROR("can't launch %s: %m", config->exec[0]);
388                 }
389         }
390         exit(1);
391         return -1;
392 }
393
394 /*---------------------------------------------------------
395  | job for starting the daemon
396  +--------------------------------------------------------- */
397
398 static void start()
399 {
400         struct afb_hsrv *hsrv;
401
402         // ------------------ sanity check ----------------------------------------
403         if (config->httpdPort <= 0) {
404                 ERROR("no port is defined");
405                 goto error;
406         }
407
408         mkdir(config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
409         if (chdir(config->workdir) < 0) {
410                 ERROR("Can't enter working dir %s", config->workdir);
411                 goto error;
412         }
413
414         /* install hooks */
415         if (config->tracereq)
416                 afb_hook_create_xreq(NULL, NULL, NULL, config->tracereq, NULL, NULL);
417         if (config->traceditf)
418                 afb_hook_create_ditf(NULL, config->traceditf, NULL, NULL);
419
420         afb_apis_set_timeout(config->apiTimeout);
421         start_list(config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
422         start_list(config->ws_clients, afb_api_ws_add_client, "the afb-websocket client");
423         start_list(config->ldpaths, afb_api_so_add_pathset, "the binding path set");
424         start_list(config->so_bindings, afb_api_so_add_binding, "the binding");
425
426         afb_session_init(config->nbSessionMax, config->cntxTimeout, config->token);
427
428         start_list(config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
429         start_list(config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
430
431         if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, config->cntxTimeout)) {
432                 ERROR("initialisation of cookies failed");
433                 goto error;
434         }
435
436         // set the root dir
437         if (afb_common_rootdir_set(config->rootdir) < 0) {
438                 ERROR("failed to set common root directory");
439                 goto error;
440         }
441
442         DEBUG("Init config done");
443
444         /* start the services */
445         if (afb_apis_start_all_services(1) < 0)
446                 goto error;
447
448         /* start the HTTP server */
449         if (!config->noHttpd) {
450                 hsrv = start_http_server();
451                 if (hsrv == NULL)
452                         goto error;
453         }
454
455         /* run the command */
456         if (execute_command() < 0)
457                 goto error;
458
459         /* ready */
460         sd_notify(1, "READY=1");
461         return;
462 error:
463         exit(1);
464 }
465 /*---------------------------------------------------------
466  | main
467  |   Parse option and launch action
468  +--------------------------------------------------------- */
469
470 int main(int argc, char *argv[])
471 {
472         // let's run this program with a low priority
473         nice(20);
474
475         sd_fds_init();
476
477         // ------------- Build session handler & init config -------
478         config = afb_config_parse_arguments(argc, argv);
479         INFO("running with pid %d", getpid());
480
481         // --------- run -----------
482         if (config->background) {
483                 // --------- in background mode -----------
484                 INFO("entering background mode");
485                 daemonize();
486         } else {
487                 // ---- in foreground mode --------------------
488                 INFO("entering foreground mode");
489         }
490
491         /* handle groups */
492         atexit(exit_handler);
493
494         /* ignore any SIGPIPE */
495         signal(SIGPIPE, SIG_IGN);
496
497         /* enter job processing */
498         jobs_start(3, 0, 50, start);
499         WARNING("hoops returned from jobs_enter! [report bug]");
500         return 1;
501 }
502