Fix segmentation fault when random token
[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 AFB_BINDING_PRAGMA_NO_VERBOSE_MACRO
21
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <stdint.h>
25 #include <signal.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <sys/stat.h>
30 #include <sys/wait.h>
31
32 #if !defined(NO_CALL_PERSONALITY)
33 #include <sys/personality.h>
34 #endif
35
36 #include <json-c/json.h>
37
38 #include <systemd/sd-daemon.h>
39
40 #include "afb-config.h"
41 #include "afb-hswitch.h"
42 #include "afb-apiset.h"
43 #include "afb-api-so.h"
44 #include "afb-api-dbus.h"
45 #include "afb-api-ws.h"
46 #include "afb-hsrv.h"
47 #include "afb-hreq.h"
48 #include "afb-xreq.h"
49 #include "jobs.h"
50 #include "afb-session.h"
51 #include "verbose.h"
52 #include "afb-common.h"
53 #include "afb-monitor.h"
54 #include "afb-hook.h"
55 #include "sd-fds.h"
56 #include "afb-debug.h"
57 #include "process-name.h"
58
59 /*
60    if SELF_PGROUP == 0 the launched command is the group leader
61    if SELF_PGROUP != 0 afb-daemon is the group leader
62 */
63 #define SELF_PGROUP 1
64
65 struct afb_apiset *main_apiset;
66
67 static struct afb_config *config;
68 static pid_t childpid;
69
70 /*----------------------------------------------------------
71  |   helpers for handling list of arguments
72  +--------------------------------------------------------- */
73
74 /*
75  * Calls the callback 'run' for each value of the 'list'
76  * until the callback returns 0 or the end of the list is reached.
77  * Returns either NULL if the end of the list is reached or a pointer
78  * to the item whose value made 'run' return 0.
79  * 'closure' is used for passing user data.
80  */
81 static struct afb_config_list *run_for_list(struct afb_config_list *list,
82                                             int (*run) (void *closure, char *value),
83                                             void *closure)
84 {
85         while (list && run(closure, list->value))
86                 list = list->next;
87         return list;
88 }
89
90 static int run_start(void *closure, char *value)
91 {
92         int (*starter) (const char *value, struct afb_apiset *apiset) = closure;
93         return starter(value, main_apiset) >= 0;
94 }
95
96 static void apiset_start_list(struct afb_config_list *list,
97                        int (*starter) (const char *value, struct afb_apiset *apiset), const char *message)
98 {
99         list = run_for_list(list, run_start, starter);
100         if (list) {
101                 ERROR("can't start %s %s", message, list->value);
102                 exit(1);
103         }
104 }
105
106 /*----------------------------------------------------------
107  | exit_handler
108  |   Handles on exit specific actions
109  +--------------------------------------------------------- */
110 static void exit_handler()
111 {
112         struct sigaction siga;
113
114         memset(&siga, 0, sizeof siga);
115         siga.sa_handler = SIG_IGN;
116         sigaction(SIGTERM, &siga, NULL);
117
118         if (SELF_PGROUP)
119                 killpg(0, SIGTERM);
120         else if (childpid > 0)
121                 killpg(childpid, SIGTERM);
122 }
123
124 static void on_sigterm(int signum, siginfo_t *info, void *uctx)
125 {
126         NOTICE("Received SIGTERM");
127         exit(0);
128 }
129
130 static void on_sighup(int signum, siginfo_t *info, void *uctx)
131 {
132         NOTICE("Received SIGHUP");
133         /* TODO */
134 }
135
136 static void setup_daemon()
137 {
138         struct sigaction siga;
139
140         /* install signal handlers */
141         memset(&siga, 0, sizeof siga);
142         siga.sa_flags = SA_SIGINFO;
143
144         siga.sa_sigaction = on_sigterm;
145         sigaction(SIGTERM, &siga, NULL);
146
147         siga.sa_sigaction = on_sighup;
148         sigaction(SIGHUP, &siga, NULL);
149
150         /* handle groups */
151         atexit(exit_handler);
152
153         /* ignore any SIGPIPE */
154         signal(SIGPIPE, SIG_IGN);
155 }
156
157 /*----------------------------------------------------------
158  | daemonize
159  |   set the process in background
160  +--------------------------------------------------------- */
161 static void daemonize()
162 {
163         int consoleFD;
164         int pid;
165
166         // open /dev/console to redirect output messAFBes
167         consoleFD = open(config->console, O_WRONLY | O_APPEND | O_CREAT, 0640);
168         if (consoleFD < 0) {
169                 ERROR("AFB-daemon cannot open /dev/console (use --foreground)");
170                 exit(1);
171         }
172         // fork process when running background mode
173         pid = fork();
174
175         // if fail nothing much to do
176         if (pid == -1) {
177                 ERROR("AFB-daemon Failed to fork son process");
178                 exit(1);
179         }
180         // if in father process, just leave
181         if (pid != 0)
182                 _exit(0);
183
184         // son process get all data in standalone mode
185         NOTICE("background mode [pid:%d console:%s]", getpid(),
186                config->console);
187
188         // redirect default I/O on console
189         close(2);
190         dup(consoleFD);         // redirect stderr
191         close(1);
192         dup(consoleFD);         // redirect stdout
193         close(0);               // no need for stdin
194         close(consoleFD);
195
196 #if 0
197         setsid();               // allow father process to fully exit
198         sleep(2);               // allow main to leave and release port
199 #endif
200 }
201
202 /*---------------------------------------------------------
203  | http server
204  |   Handles the HTTP server
205  +--------------------------------------------------------- */
206 static int init_alias(void *closure, char *spec)
207 {
208         struct afb_hsrv *hsrv = closure;
209         char *path = strchr(spec, ':');
210
211         if (path == NULL) {
212                 ERROR("Missing ':' in alias %s. Alias ignored", spec);
213                 return 1;
214         }
215         *path++ = 0;
216         INFO("Alias for url=%s to path=%s", spec, path);
217         return afb_hsrv_add_alias(hsrv, spec, afb_common_rootdir_get_fd(), path,
218                                   0, 0);
219 }
220
221 static int init_http_server(struct afb_hsrv *hsrv)
222 {
223         if (!afb_hsrv_add_handler
224             (hsrv, config->rootapi, afb_hswitch_websocket_switch, main_apiset, 20))
225                 return 0;
226
227         if (!afb_hsrv_add_handler
228             (hsrv, config->rootapi, afb_hswitch_apis, main_apiset, 10))
229                 return 0;
230
231         if (run_for_list(config->aliases, init_alias, hsrv))
232                 return 0;
233
234         if (config->roothttp != NULL) {
235                 if (!afb_hsrv_add_alias
236                     (hsrv, "", afb_common_rootdir_get_fd(), config->roothttp,
237                      -10, 1))
238                         return 0;
239         }
240
241         if (!afb_hsrv_add_handler
242             (hsrv, config->rootbase, afb_hswitch_one_page_api_redirect, NULL,
243              -20))
244                 return 0;
245
246         return 1;
247 }
248
249 static struct afb_hsrv *start_http_server()
250 {
251         int rc;
252         struct afb_hsrv *hsrv;
253
254         if (afb_hreq_init_download_path(config->uploaddir)) {
255                 ERROR("unable to set the upload directory %s", config->uploaddir);
256                 return NULL;
257         }
258
259         hsrv = afb_hsrv_create();
260         if (hsrv == NULL) {
261                 ERROR("memory allocation failure");
262                 return NULL;
263         }
264
265         if (!afb_hsrv_set_cache_timeout(hsrv, config->cacheTimeout)
266             || !init_http_server(hsrv)) {
267                 ERROR("initialisation of httpd failed");
268                 afb_hsrv_put(hsrv);
269                 return NULL;
270         }
271
272         NOTICE("Waiting port=%d rootdir=%s", config->httpdPort, config->rootdir);
273         NOTICE("Browser URL= http://localhost:%d", config->httpdPort);
274
275         rc = afb_hsrv_start(hsrv, (uint16_t) config->httpdPort, 15);
276         if (!rc) {
277                 ERROR("starting of httpd failed");
278                 afb_hsrv_put(hsrv);
279                 return NULL;
280         }
281
282         return hsrv;
283 }
284
285 /*---------------------------------------------------------
286  | execute_command
287  |   
288  +--------------------------------------------------------- */
289
290 static void on_sigchld(int signum, siginfo_t *info, void *uctx)
291 {
292         if (info->si_pid == childpid) {
293                 switch (info->si_code) {
294                 case CLD_EXITED:
295                 case CLD_KILLED:
296                 case CLD_DUMPED:
297                         childpid = 0;
298                         if (!SELF_PGROUP)
299                                 killpg(info->si_pid, SIGKILL);
300                         waitpid(info->si_pid, NULL, 0);
301                         exit(0);
302                 }
303         }
304 }
305
306 /*
307 # @@ @
308 # @p port
309 # @t token
310 */
311
312 #define SUBST_CHAR  '@'
313 #define SUBST_STR   "@"
314
315 static char *instanciate_string(char *arg, const char *port, const char *token)
316 {
317         char *resu, *it, *wr;
318         int chg, dif;
319
320         /* get the changes */
321         chg = 0;
322         dif = 0;
323         it = strchrnul(arg, SUBST_CHAR);
324         while (*it) {
325                 switch(*++it) {
326                 case 'p': chg++; dif += (int)strlen(port) - 2; break;
327                 case 't': chg++; dif += (int)strlen(token) - 2; break;
328                 case SUBST_CHAR: it++; chg++; dif--; break;
329                 default: break;
330                 }
331                 it = strchrnul(it, SUBST_CHAR);
332         }
333
334         /* return arg when no change */
335         if (!chg)
336                 return arg;
337
338         /* allocates the result */
339         resu = malloc((it - arg) + dif + 1);
340         if (!resu) {
341                 ERROR("out of memory");
342                 return NULL;
343         }
344
345         /* instanciate the arguments */
346         wr = resu;
347         for (;;) {
348                 it = strchrnul(arg, SUBST_CHAR);
349                 wr = mempcpy(wr, arg, it - arg);
350                 if (!*it)
351                         break;
352                 switch(*++it) {
353                 case 'p': wr = stpcpy(wr, port); break;
354                 case 't': wr = stpcpy(wr, token); break;
355                 default: *wr++ = SUBST_CHAR; /*@fallthrough@*/
356                 case SUBST_CHAR: *wr++ = *it;
357                 }
358                 arg = ++it;
359         }
360
361         *wr = 0;
362         return resu;
363 }
364
365 static int instanciate_environ(const char *port, const char *token)
366 {
367         extern char **environ;
368         char *repl;
369         int i;
370
371         /* instanciate the environment */
372         for (i = 0 ; environ[i] ; i++) {
373                 repl = instanciate_string(environ[i], port, token);
374                 if (!repl)
375                         return -1;
376                 environ[i] = repl;
377         }
378         return 0;
379 }
380
381 static int instanciate_command_args(const char *port, const char *token)
382 {
383         char *repl;
384         int i;
385
386         /* instanciate the arguments */
387         for (i = 0 ; config->exec[i] ; i++) {
388                 repl = instanciate_string(config->exec[i], port, token);
389                 if (!repl)
390                         return -1;
391                 config->exec[i] = repl;
392         }
393         return 0;
394 }
395
396 static int execute_command()
397 {
398         struct sigaction siga;
399         char port[20];
400         const char *token;
401         int rc;
402
403         /* check whether a command is to execute or not */
404         if (!config->exec || !config->exec[0])
405                 return 0;
406
407         if (SELF_PGROUP)
408                 setpgid(0, 0);
409
410         /* install signal handler */
411         memset(&siga, 0, sizeof siga);
412         siga.sa_sigaction = on_sigchld;
413         siga.sa_flags = SA_SIGINFO;
414         sigaction(SIGCHLD, &siga, NULL);
415
416         /* fork now */
417         childpid = fork();
418         if (childpid)
419                 return 0;
420
421         /* compute the string for port */
422         if (config->httpdPort)
423                 rc = snprintf(port, sizeof port, "%d", config->httpdPort);
424         else
425                 rc = snprintf(port, sizeof port, "%cp", SUBST_CHAR);
426         if (rc < 0 || rc >= (int)(sizeof port)) {
427                 ERROR("port->txt failed");
428         }
429         else {
430                 /* instanciate arguments and environment */
431                 token = afb_session_initial_token();
432                 if (instanciate_command_args(port, token) >= 0
433                  && instanciate_environ(port, token) >= 0) {
434                         /* run */
435                         if (!SELF_PGROUP)
436                                 setpgid(0, 0);
437                         execv(config->exec[0], config->exec);
438                         ERROR("can't launch %s: %m", config->exec[0]);
439                 }
440         }
441         exit(1);
442         return -1;
443 }
444
445 /*---------------------------------------------------------
446  | startup calls
447  +--------------------------------------------------------- */
448
449 struct startup_req
450 {
451         struct afb_xreq xreq;
452         char *api;
453         char *verb;
454         struct afb_config_list *current;
455         struct afb_session *session;
456 };
457
458 static void startup_call_reply(struct afb_xreq *xreq, int status, struct json_object *obj)
459 {
460         struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
461
462         if (status >= 0)
463                 NOTICE("startup call %s returned %s", sreq->current->value, json_object_get_string(obj));
464         else {
465                 ERROR("startup call %s ERROR! %s", sreq->current->value, json_object_get_string(obj));
466                 exit(1);
467         }
468 }
469
470 static void startup_call_current(struct startup_req *sreq);
471
472 static void startup_call_unref(struct afb_xreq *xreq)
473 {
474         struct startup_req *sreq = CONTAINER_OF_XREQ(struct startup_req, xreq);
475
476         free(sreq->api);
477         free(sreq->verb);
478         json_object_put(sreq->xreq.json);
479         sreq->current = sreq->current->next;
480         if (sreq->current)
481                 startup_call_current(sreq);
482         else {
483                 afb_session_close(sreq->session);
484                 afb_session_unref(sreq->session);
485                 free(sreq);
486         }
487 }
488
489 static struct afb_xreq_query_itf startup_xreq_itf =
490 {
491         .reply = startup_call_reply,
492         .unref = startup_call_unref
493 };
494
495 static void startup_call_current(struct startup_req *sreq)
496 {
497         char *api, *verb, *json;
498
499         api = sreq->current->value;
500         verb = strchr(api, '/');
501         if (verb) {
502                 json = strchr(verb, ':');
503                 if (json) {
504                         afb_xreq_init(&sreq->xreq, &startup_xreq_itf);
505                         afb_context_init(&sreq->xreq.context, sreq->session, NULL);
506                         sreq->xreq.context.validated = 1;
507                         sreq->api = strndup(api, verb - api);
508                         sreq->verb = strndup(verb + 1, json - verb - 1);
509                         sreq->xreq.api = sreq->api;
510                         sreq->xreq.verb = sreq->verb;
511                         sreq->xreq.json = json_tokener_parse(json + 1);
512                         if (sreq->api && sreq->verb && sreq->xreq.json) {
513                                 afb_xreq_process(&sreq->xreq, main_apiset);
514                                 return;
515                         }
516                 }
517         }
518         ERROR("Bad call specification %s", sreq->current->value);
519         exit(1);
520 }
521
522 static void run_startup_calls()
523 {
524         struct afb_config_list *list;
525         struct startup_req *sreq;
526
527         list = config->calls;
528         if (list) {
529                 sreq = calloc(1, sizeof *sreq);
530                 sreq->session = afb_session_create("startup", 3600);
531                 sreq->current = list;
532                 startup_call_current(sreq);
533         }
534 }
535
536 /*---------------------------------------------------------
537  | job for starting the daemon
538  +--------------------------------------------------------- */
539
540 static void start(int signum)
541 {
542         struct afb_hsrv *hsrv;
543
544         afb_debug("start-entry");
545
546         if (signum) {
547                 ERROR("start aborted: received signal %s", strsignal(signum));
548                 exit(1);
549         }
550
551         // ------------------ sanity check ----------------------------------------
552         if (config->httpdPort <= 0) {
553                 ERROR("no port is defined");
554                 goto error;
555         }
556
557         /* set the directories */
558         mkdir(config->workdir, S_IRWXU | S_IRGRP | S_IXGRP);
559         if (chdir(config->workdir) < 0) {
560                 ERROR("Can't enter working dir %s", config->workdir);
561                 goto error;
562         }
563         if (afb_common_rootdir_set(config->rootdir) < 0) {
564                 ERROR("failed to set common root directory");
565                 goto error;
566         }
567
568         /* configure the daemon */
569         afb_session_init(config->nbSessionMax, config->cntxTimeout, config->token);
570         if (!afb_hreq_init_cookie(config->httpdPort, config->rootapi, config->cntxTimeout)) {
571                 ERROR("initialisation of cookies failed");
572                 goto error;
573         }
574         main_apiset = afb_apiset_create("main", config->apiTimeout);
575         if (!main_apiset) {
576                 ERROR("can't create main api set");
577                 goto error;
578         }
579         if (afb_monitor_init() < 0) {
580                 ERROR("failed to setup monitor");
581                 goto error;
582         }
583
584         /* install hooks */
585         if (config->tracereq)
586                 afb_hook_create_xreq(NULL, NULL, NULL, config->tracereq, NULL, NULL);
587         if (config->traceditf)
588                 afb_hook_create_ditf(NULL, config->traceditf, NULL, NULL);
589         if (config->tracesvc)
590                 afb_hook_create_svc(NULL, config->tracesvc, NULL, NULL);
591         if (config->traceevt)
592                 afb_hook_create_evt(NULL, config->traceevt, NULL, NULL);
593
594         /* load bindings */
595         afb_debug("start-load");
596         apiset_start_list(config->so_bindings, afb_api_so_add_binding, "the binding");
597         apiset_start_list(config->dbus_clients, afb_api_dbus_add_client, "the afb-dbus client");
598         apiset_start_list(config->ws_clients, afb_api_ws_add_client, "the afb-websocket client");
599         apiset_start_list(config->ldpaths, afb_api_so_add_pathset_fails, "the binding path set");
600         apiset_start_list(config->weak_ldpaths, afb_api_so_add_pathset_nofails, "the weak binding path set");
601
602         apiset_start_list(config->dbus_servers, afb_api_dbus_add_server, "the afb-dbus service");
603         apiset_start_list(config->ws_servers, afb_api_ws_add_server, "the afb-websocket service");
604
605         DEBUG("Init config done");
606
607         /* start the services */
608         afb_debug("start-start");
609 #if !defined(NO_CALL_PERSONALITY)
610         personality((unsigned long)-1L);
611 #endif
612         if (afb_apiset_start_all_services(main_apiset, 1) < 0)
613                 goto error;
614
615         /* start the HTTP server */
616         afb_debug("start-http");
617         if (!config->noHttpd) {
618                 hsrv = start_http_server();
619                 if (hsrv == NULL)
620                         goto error;
621         }
622
623         /* run the startup calls */
624         afb_debug("start-call");
625         run_startup_calls();
626
627         /* run the command */
628         afb_debug("start-exec");
629         if (execute_command() < 0)
630                 goto error;
631
632         /* ready */
633         sd_notify(1, "READY=1");
634         return;
635 error:
636         exit(1);
637 }
638
639 /*---------------------------------------------------------
640  | main
641  |   Parse option and launch action
642  +--------------------------------------------------------- */
643
644 int main(int argc, char *argv[])
645 {
646         afb_debug("main-entry");
647
648         // let's run this program with a low priority
649         nice(20);
650
651         sd_fds_init();
652
653         // ------------- Build session handler & init config -------
654         config = afb_config_parse_arguments(argc, argv);
655         if (config->name) {
656                 verbose_set_name(config->name, 0);
657                 process_name_set_name(config->name);
658                 process_name_replace_cmdline(argv, config->name);
659         }
660         afb_debug("main-args");
661
662         // --------- run -----------
663         if (config->background) {
664                 // --------- in background mode -----------
665                 INFO("entering background mode");
666                 daemonize();
667         } else {
668                 // ---- in foreground mode --------------------
669                 INFO("entering foreground mode");
670         }
671         INFO("running with pid %d", getpid());
672
673         /* set the daemon environment */
674         setup_daemon();
675
676         afb_debug("main-start");
677
678         /* enter job processing */
679         jobs_start(3, 0, 50, start);
680         WARNING("hoops returned from jobs_enter! [report bug]");
681         return 1;
682 }
683