upgraded.c 2.2 KB

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