upgraded: register stage2 process in uloop as intended
[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 #define _GNU_SOURCE
16
17 #include <sys/reboot.h>
18
19 #include <fcntl.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <errno.h>
25
26 #include <libubox/uloop.h>
27
28 #include "../watchdog.h"
29
30 #ifndef O_PATH
31 #define O_PATH          010000000
32 #endif
33
34 static struct uloop_process upgrade_proc;
35 unsigned int debug = 2;
36
37 static void upgrade_proc_cb(struct uloop_process *proc, int ret)
38 {
39         if (ret)
40                 fprintf(stderr, "sysupgrade aborted with return code: %d\n", ret);
41         uloop_end();
42 }
43
44 static void sysupgrade(char *path, char *command)
45 {
46         char *args[] = { "/lib/upgrade/stage2", NULL, NULL, NULL };
47
48         args[1] = path;
49         args[2] = command;
50         upgrade_proc.cb = upgrade_proc_cb;
51         upgrade_proc.pid = fork();
52         if (!upgrade_proc.pid) {
53                 execvp(args[0], args);
54                 fprintf(stderr, "Failed to fork sysupgrade\n");
55                 exit(-1);
56         }
57         if (upgrade_proc.pid <= 0) {
58                 fprintf(stderr, "Failed to start sysupgrade\n");
59                 uloop_end();
60         }
61
62         uloop_process_add(&upgrade_proc);
63 }
64
65 int main(int argc, char **argv)
66 {
67         pid_t p = getpid();
68
69         if (p != 1) {
70                 fprintf(stderr, "this tool needs to run as pid 1\n");
71                 return -1;
72         }
73
74         int fd = open("/", O_DIRECTORY|O_PATH);
75         if (fd < 0) {
76                 fprintf(stderr, "unable to open prefix directory: %s\n", strerror(errno));
77                 return -1;
78         }
79
80         chroot(".");
81
82         if (fchdir(fd) == -1) {
83                 fprintf(stderr, "failed to chdir to prefix directory: %s\n", strerror(errno));
84                 return -1;
85         }
86         close(fd);
87
88         if (argc != 3) {
89                 fprintf(stderr, "sysupgrade stage 2 failed, invalid command line\n");
90                 return -1;
91         }
92
93         uloop_init();
94         watchdog_init(0);
95         sysupgrade(argv[1], argv[2]);
96         uloop_run();
97
98         reboot(RB_AUTOBOOT);
99
100         return 0;
101 }