71b21388b168839fa59ffab7326e2a99e8113887
[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         /* TODO: check whether using SIGHUP isn't better */
103         if (SELF_PGROUP)
104                 killpg(0, SIGKILL);
105         else if (childpid > 0)
106                 killpg(childpid, SIGKILL);
107 }
108
109 /*----------------------------------------------------------
110  | daemonize
111  |   set the process in background
112  +--------------------------------------------------------- */
113 static void daemonize()
114 {
115         int consoleFD;
116         int pid;
117
118         // open /dev/console to redirect output messAFBes
119         consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT, 0640);
120         if (consoleFD < 0) {
121                 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
122                 exit(1);
123         }
124         // fork process when running background mode
125         pid = fork();
126
127         // if fail nothing much to do
128         if (pid == -1) {
129                 ERROR("AFB-daemon Failed to fork son process");
130                 exit(1);
131         }
132         // if in father process, just leave
133         if (pid != 0)
134                 _exit(0);
135
136         // son process get all data in standalone mode
137         NOTICE("background mode [pid:%d console:%s]", getpid(),
138                config->console);
139
140         // redirect default I/O on console
141         close(2);
142         dup(consoleFD);         // redirect stderr
143         close(1);
144         dup(consoleFD);         // redirect stdout
145         close(0);               // no need for stdin
146         close(consoleFD);
147
148 #if 0
149         setsid();               // allow father process to fully exit
150         sleep(2);               // allow main to leave and release port
151 #endif
152 }
153
154 /*---------------------------------------------------------
155  | http server
156  |   Handles the HTTP server
157  +--------------------------------------------------------- */
158 static int init_alias(void *closure, char *spec)
159 {
160         struct afb_hsrv *hsrv = closure;
161         char *path = strchr(spec, ':');
162
163         if (path == NULL) {
164                 ERROR("Missing ':' in alias %s. Alias ignored", spec);
165                 return 1;
166         }
167         *path++ = 0;
168         INFO("Alias for url=%s to path=%s", spec, path);
169         return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
170                                   0, 0);
171 }
172
173 static int init_http_server(struct afb_hsrv *hsrv)
174 {
175         if (!afb_hsrv_add_handler
176             (hsrv, config->rootapi, afb_hswitch_websocket_switch, NULL, 20))
177                 return 0;
178
179         if (!afb_hsrv_add_handler
180             (hsrv, config->rootapi, afb_hswitch_apis, NULL, 10))
181                 return 0;
182
183         if (run_for_list(config->aliases, init_alias, hsrv))
184                 return 0;
185
186         if (config->roothttp != NULL) {
187                 if (!afb_hsrv_add_alias
188                     (hsrv, "", afb_common_rootdir_get_fd(), config->roothttp,
189                      -10, 1))
190                         return 0;
191         }
192
193         if (!afb_hsrv_add_handler
194             (hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL,
195              -20))
196                 return 0;
197
198         return 1;
199 }
200
201 static struct afb_hsrv *start_http_server()
202 {
203         int rc;
204         struct afb_hsrv *hsrv;
205
206         if (afb_hreq_init_download_path(config->uploaddir)) {
207                 ERROR("unable to set the upload directory %s", config->uploaddir);
208                 return NULL;
209         }
210
211         hsrv = afb_hsrv_create();
212         if (hsrv == NULL) {
213                 ERROR("memory allocation failure");
214                 return NULL;
215         }
216
217         if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
218             || !init_http_server(hsrv)) {
219                 ERROR("initialisation of httpd failed");
220                 afb_hsrv_put(hsrv);
221                 return NULL;
222         }
223
224         NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
225         NOTICE("Browser URL= http:/*localhost:%d", config->httpdPort);
226
227         rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
228         if (!rc) {
229                 ERROR("starting of httpd failed");
230                 afb_hsrv_put(hsrv);
231                 return NULL;
232         }
233
234         return hsrv;
235 }
236
237 /*---------------------------------------------------------
238  | execute_command
239  |   
240  +--------------------------------------------------------- */
241
242 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
243 {
244         if (info->si_pid == childpid) {
245                 switch (info->si_code) {
246                 case CLD_EXITED:
247                 case CLD_KILLED:
248                 case CLD_DUMPED:
249                         childpid = 0;
250                         if (!SELF_PGROUP)
251                                 killpg(info->si_pid, SIGKILL);
252                         waitpid(info->si_pid, NULL, 0);
253                         exit(0);
254                 }
255         }
256 }
257
258 /*
259 # @@ @
260 # @p port
261 # @t token
262 */
263
264 #define SUBST_CHAR  '@'
265 #define SUBST_STR   "@"
266
267 static char *instanciate_string(char *arg, const char *port, const char *token)
268 {
269         char *resu, *it, *wr;
270         int chg, dif;
271
272         /* get the changes */
273         chg = 0;
274         dif = 0;
275         it = strchrnul(arg, SUBST_CHAR);
276         while (*it) {
277                 switch(*++it) {
278                 case 'p': chg++; dif += (int)strlen(port) - 2; break;
279                 case 't': chg++; dif += (int)strlen(token) - 2; break;
280                 case SUBST_CHAR: it++; chg++; dif--; break;
281                 default: break;
282                 }
283                 it = strchrnul(it, SUBST_CHAR);
284         }
285
286         /* return arg when no change */
287         if (!chg)
288                 return arg;
289
290         /* allocates the result */
291         resu = malloc((it - arg) + dif + 1);
292         if (!resu) {
293                 ERROR("out of memory");
294                 return NULL;
295         }
296
297         /* instanciate the arguments */
298         wr = resu;
299         for (;;) {
300                 it = strchrnul(arg, SUBST_CHAR);
301                 wr = mempcpy(wr, arg, it - arg);
302                 if (!*it)
303                         break;
304                 switch(*++it) {
305                 case 'p': wr = stpcpy(wr, port); break;
306                 case 't': wr = stpcpy(wr, token); break;
307                 default: *wr++ = SUBST_CHAR;
308                 case SUBST_CHAR: *wr++ = *it;
309                 }
310                 arg = ++it;
311         }
312
313         *wr = 0;
314         return resu;
315 }
316
317 static int instanciate_environ(const char *port, const char *token)
318 {
319         extern char **environ;
320         char *repl;
321         int i;
322
323         /* instanciate the environment */
324         for (i = 0 ; environ[i] ; i++) {
325                 repl = instanciate_string(environ[i], port, token);
326                 if (!repl)
327                         return -1;
328                 environ[i] = repl;
329         }
330         return 0;
331 }
332
333 static int instanciate_command_args(const char *port, const char *token)
334 {
335         char *repl;
336         int i;
337
338         /* instanciate the arguments */
339         for (i = 0 ; config->exec[i] ; i++) {
340                 repl = instanciate_string(config->exec[i], port, token);
341                 if (!repl)
342                         return -1;
343                 config->exec[i] = repl;
344         }
345         return 0;
346 }
347
348 static int execute_command()
349 {
350         struct sigaction siga;
351         char port[20];
352         int rc;
353
354         /* check whether a command is to execute or not */
355         if (!config->exec || !config->exec[0])
356                 return 0;
357
358         if (SELF_PGROUP)
359                 setpgid(0, 0);
360
361         /* install signal handler */
362         memset(&siga, 0, sizeof siga);
363         siga.sa_sigaction = on_sigchld;
364         siga.sa_flags = SA_SIGINFO;
365         sigaction(SIGCHLD, &siga, NULL);
366
367         /* fork now */
368         childpid = fork();
369         if (childpid)
370                 return 0;
371
372         /* compute the string for port */
373         if (config->httpdPort)
374                 rc = snprintf(port, sizeof port, "%d", config->httpdPort);
375         else
376                 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
377         if (rc < 0 || rc >= (int)(sizeof port)) {
378                 ERROR("port->txt failed");
379         }
380         else {
381                 /* instanciate arguments and environment */
382                 if (instanciate_command_args(port, config->token) >= 0
383                  && instanciate_environ(port, config->token) >= 0) {
384                         /* run */
385                         if (!SELF_PGROUP)
386                                 setpgid(0, 0);
387                         execv(config->exec[0], config->exec);
388                         ERROR("can't launch %s: %m", config->exec[0]);
389                 }
390         }
391         exit(1);
392         return -1;
393 }
394
395 /*---------------------------------------------------------
396  | job for starting the daemon
397  +--------------------------------------------------------- */
398
399 static void start()
400 {
401         struct afb_hsrv *hsrv;
402
403         // ------------------ sanity check ----------------------------------------
404         if (config->httpdPort <= 0) {
405                 ERROR("no port is defined");
406                 goto error;
407         }
408
409         mkdir(config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
410         if (chdir(config->workdir) < 0) {
411                 ERROR("Can't enter working dir %s", config->workdir);
412                 goto error;
413         }
414
415         afb_api_so_set_timeout(config->apiTimeout);
416         start_list(config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
417         start_list(config->ws_clients, afb_api_ws_add_client, "the afb-websocket client");
418         start_list(config->ldpaths, afb_api_so_add_pathset, "the binding path set");
419         start_list(config->so_bindings, afb_api_so_add_binding, "the binding");
420
421         afb_session_init(config->nbSessionMax, config->cntxTimeout, config->token);
422
423         start_list(config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
424         start_list(config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
425
426         if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, config->cntxTimeout)) {
427                 ERROR("initialisation of cookies failed");
428                 goto error;
429         }
430
431         // set the root dir
432         if (afb_common_rootdir_set(config->rootdir) < 0) {
433                 ERROR("failed to set common root directory");
434                 goto error;
435         }
436
437         DEBUG("Init config done");
438
439         /* install trace of requests */
440         if (config->tracereq)
441                 afb_hook_req_create(NULL, NULL, NULL, config->tracereq, NULL, NULL);
442
443         /* start the services */
444         if (afb_apis_start_all_services(1) < 0)
445                 goto error;
446
447         /* start the HTTP server */
448         if (!config->noHttpd) {
449                 hsrv = start_http_server();
450                 if (hsrv == NULL)
451                         goto error;
452         }
453
454         /* run the command */
455         if (execute_command() < 0)
456                 goto error;
457
458         /* ready */
459         sd_notify(1, "READY=1");
460         return;
461 error:
462         exit(1);
463 }
464 /*---------------------------------------------------------
465  | main
466  |   Parse option and launch action
467  +--------------------------------------------------------- */
468
469 int main(int argc, char *argv[])
470 {
471         // let's run this program with a low priority
472         nice(20);
473
474         LOGAUTH("afb-daemon");
475
476         sd_fds_init();
477
478         // ------------- Build session handler & init config -------
479         config = afb_config_parse_arguments(argc, argv);
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_enter(3, 1, 20, start);
499         WARNING("hoops returned from jobs_enter! [report bug]");
500         return 1;
501 }
502