instance: avoid dumping invalid service instances - prevents a potential crash
[project/procd.git] / upgraded / upgraded.c
1 /*
2  * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3  * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU Lesser General Public License version 2.1
7  * as published by the Free Software Foundation
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include <sys/reboot.h>
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <unistd.h>
21 #include <errno.h>
22
23 #include <libubox/uloop.h>
24
25 #include "../watchdog.h"
26
27 static struct uloop_process upgrade_proc;
28 unsigned int debug = 2;
29
30 static void upgrade_proc_cb(struct uloop_process *proc, int ret)
31 {
32         if (ret)
33                 fprintf(stderr, "sysupgrade aborted with return code: %d\n", ret);
34         uloop_end();
35 }
36
37 static void sysupgarde(char *folder)
38 {
39         char *args[] = { "/sbin/sysupgrade", "nand", NULL, NULL };
40
41         args[2] = folder;
42         upgrade_proc.cb = upgrade_proc_cb;
43         upgrade_proc.pid = fork();
44         if (!upgrade_proc.pid) {
45                 execvp(args[0], args);
46                 fprintf(stderr, "Failed to fork sysupgrade\n");
47                 exit(-1);
48         }
49         if (upgrade_proc.pid <= 0) {
50                 fprintf(stderr, "Failed to start sysupgarde\n");
51                 uloop_end();
52         }
53 }
54
55 int main(int argc, char **argv)
56 {
57         pid_t p = getpid();
58
59         if (p != 1) {
60                 fprintf(stderr, "this tool needs to run as pid 1\n");
61                 return -1;
62         }
63         if (chdir("/tmp") == -1) {
64                 fprintf(stderr, "failed to chdir to /tmp: %s\n", strerror(errno));
65                 return -1;
66         }
67         if (argc != 2) {
68                 fprintf(stderr, "sysupgrade stage 2 failed, no folder specified\n");
69                 return -1;
70         }
71
72         uloop_init();
73         watchdog_init(0);
74         sysupgarde(argv[1]);
75         uloop_run();
76
77         reboot(RB_AUTOBOOT);
78
79         return 0;
80 }