qubes_add_pendrive_script.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * The Qubes OS Project, http://www.qubes-os.org
  3. *
  4. * Copyright (C) 2010 Rafal Wojtczuk <rafal@invisiblethingslab.com>
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2
  9. * of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. *
  20. */
  21. #include <stdio.h>
  22. #include <unistd.h>
  23. #include <sys/inotify.h>
  24. #include <fcntl.h>
  25. #include <stdlib.h>
  26. int parse_events(char *buf, int len)
  27. {
  28. int i = 0;
  29. while (i < len) {
  30. struct inotify_event *ev = (struct inotify_event *)(buf + i);
  31. if ((ev->mask & IN_UNMOUNT) || (ev->mask & IN_IGNORED))
  32. return 1;
  33. i += sizeof(struct inotify_event) + ev->len;
  34. }
  35. return 0;
  36. }
  37. #define BUFLEN 1024
  38. void wait_for_umount(char *name)
  39. {
  40. char buf[BUFLEN];
  41. int fd = inotify_init();
  42. int len;
  43. int ret = inotify_add_watch(fd, name, IN_ATTRIB);
  44. if (ret < 0) {
  45. perror("inotify_add_watch");
  46. return;
  47. }
  48. for (;;) {
  49. len = read(fd, buf, BUFLEN - 1);
  50. if (len <= 0) {
  51. perror("read inotify");
  52. return;
  53. }
  54. if (parse_events(buf, len))
  55. return;
  56. }
  57. }
  58. void background()
  59. {
  60. int i, fd;
  61. for (i = 0; i < 256; i++)
  62. close(i);
  63. fd = open("/dev/null", O_RDWR);
  64. for (i = 0; i <= 2; i++)
  65. dup2(fd, i);
  66. switch (fork()) {
  67. case -1:
  68. exit(1);
  69. case 0: break;
  70. default:
  71. exit(0);
  72. }
  73. }
  74. #define MOUNTDIR "/mnt/incoming"
  75. int main()
  76. {
  77. background();
  78. if (!system("su - user -c 'mount " MOUNTDIR "'"))
  79. wait_for_umount(MOUNTDIR "/.");
  80. system("xenstore-write device/qpen umount");
  81. return 0;
  82. }