procd: replace exit(-1) with exit(EXIT_FAILURE)
[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", path, command, NULL };
47
48 upgrade_proc.cb = upgrade_proc_cb;
49 upgrade_proc.pid = fork();
50 if (upgrade_proc.pid < 0) {
51 fprintf(stderr, "Failed to fork sysupgrade\n");
52 return;
53 }
54
55 if (!upgrade_proc.pid) {
56 /* Child */
57 execvp(args[0], args);
58 fprintf(stderr, "Failed to exec sysupgrade\n");
59 _exit(EXIT_FAILURE);
60 }
61
62 uloop_process_add(&upgrade_proc);
63 uloop_run();
64 }
65
66 int main(int argc, char **argv)
67 {
68 pid_t p = getpid();
69
70 if (p != 1) {
71 fprintf(stderr, "this tool needs to run as pid 1\n");
72 return 1;
73 }
74
75 int fd = open("/", O_DIRECTORY|O_PATH);
76 if (fd < 0) {
77 fprintf(stderr, "unable to open prefix directory: %m\n");
78 return 1;
79 }
80
81 if (chroot(".") < 0) {
82 fprintf(stderr, "failed to chroot: %m\n");
83 return 1;
84 }
85
86 if (fchdir(fd) == -1) {
87 fprintf(stderr, "failed to chdir to prefix directory: %m\n");
88 return 1;
89 }
90 close(fd);
91
92 if (argc != 3) {
93 fprintf(stderr, "sysupgrade stage 2 failed, invalid command line\n");
94 return 1;
95 }
96
97 uloop_init();
98 watchdog_init(0);
99 sysupgrade(argv[1], argv[2]);
100
101 reboot(RB_AUTOBOOT);
102
103 return 0;
104 }