executes scripts upon file system events (using inotify)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

699 lines
14 KiB

  1. /*
  2. * Copyright (c) 2014-2017 Albert S. <adhocify@quitesimple.org>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #define _GNU_SOURCE
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <sys/inotify.h>
  20. #include <sys/types.h>
  21. #include <sys/wait.h>
  22. #include <sys/stat.h>
  23. #include <fcntl.h>
  24. #include <unistd.h>
  25. #include <string.h>
  26. #include <signal.h>
  27. #include <libgen.h>
  28. #include <inttypes.h>
  29. #include <time.h>
  30. #include <stdbool.h>
  31. #include <stdarg.h>
  32. #include <errno.h>
  33. #include <fnmatch.h>
  34. #include <getopt.h>
  35. #include <ftw.h>
  36. #include <linux/limits.h>
  37. #define BUF_SIZE (sizeof(struct inotify_event) + NAME_MAX + 1) * 1024
  38. #define STREQ(s1,s2) ( strcmp(s1,s2) == 0 )
  39. #define SCRIPT_PLACE_SPECIFIER "{}" //TODO: think of a better name...
  40. struct watchlistentry
  41. {
  42. int ifd;
  43. char *path;
  44. bool isdir;
  45. struct watchlistentry *next;
  46. };
  47. struct watchlistentry *watchlist_head = NULL;
  48. struct watchlistentry **watchlist = &watchlist_head;
  49. struct ignorelist
  50. {
  51. char *ignore;
  52. struct ignorelist *next;
  53. };
  54. struct ignorelist *ignorelist_head = NULL;
  55. struct ignorelist **ignorelist_current = &ignorelist_head;
  56. /* Write-once globals. Set from process_arguments*/
  57. bool silent = false;
  58. bool noenv = false;
  59. bool fromstdin = false;
  60. bool forkbombcheck = true;
  61. bool daemonize = false;
  62. bool exit_with_child = false;
  63. int awaited_child_exit_code = -1;
  64. uint32_t mask = 0;
  65. char *prog = NULL;
  66. char *path_logfile = NULL;
  67. char **script_arguments = NULL; //options to be passed to script we are calling
  68. size_t n_script_arguments = 0;
  69. void *xmalloc(size_t size)
  70. {
  71. void *m = malloc(size);
  72. if(m == NULL)
  73. {
  74. perror("malloc");
  75. exit(EXIT_FAILURE);
  76. }
  77. return m;
  78. }
  79. char *xstrdup(const char *s)
  80. {
  81. char *tmp = strdup(s);
  82. if(tmp == NULL)
  83. {
  84. perror("strdup");
  85. exit(EXIT_FAILURE);
  86. }
  87. return tmp;
  88. }
  89. char *xrealpath(const char *path, char *resolved_path)
  90. {
  91. char *tmp = realpath(path, resolved_path);
  92. if(tmp == NULL)
  93. {
  94. perror("realpath");
  95. exit(EXIT_FAILURE);
  96. }
  97. return tmp;
  98. }
  99. char *ndirname(const char *path)
  100. {
  101. if(path == NULL)
  102. {
  103. return xstrdup(".");
  104. }
  105. char *c = strdupa(path);
  106. return xstrdup(dirname(c));
  107. }
  108. char *find_ifd_path(int ifd)
  109. {
  110. for(struct watchlistentry *lkp = watchlist_head; lkp != NULL; lkp = lkp->next)
  111. {
  112. if(lkp->ifd == ifd)
  113. {
  114. return lkp->path;
  115. }
  116. }
  117. return NULL;
  118. }
  119. bool is_ignored(const char *filename)
  120. {
  121. for(struct ignorelist *l = ignorelist_head; l != NULL; l = l->next)
  122. {
  123. if(fnmatch(l->ignore, filename, 0) == 0)
  124. {
  125. return true;
  126. }
  127. }
  128. return false;
  129. }
  130. bool path_is_directory(const char *path)
  131. {
  132. struct stat sb;
  133. int r = stat(path, &sb);
  134. if(r == -1)
  135. {
  136. perror("stat");
  137. return false;
  138. }
  139. return S_ISDIR(sb.st_mode);
  140. }
  141. static inline bool file_exists(const char *path)
  142. {
  143. return access(path, F_OK) == 0;
  144. }
  145. void add_to_ignore_list(const char *str)
  146. {
  147. *ignorelist_current = xmalloc(sizeof(struct ignorelist));
  148. (*ignorelist_current)->ignore = xstrdup(str);
  149. ignorelist_current = &(*ignorelist_current)->next;
  150. }
  151. void logwrite(const char *format, ...)
  152. {
  153. if(silent)
  154. {
  155. return;
  156. }
  157. va_list args;
  158. va_start(args, format);
  159. vfprintf(stdout, format, args);
  160. fflush(stdout);
  161. va_end(args);
  162. }
  163. void logerror(const char *format, ...)
  164. {
  165. va_list args;
  166. va_start(args, format);
  167. char *prefix = "Error: ";
  168. char *tmp = alloca(strlen(format) + strlen(prefix) + 1);
  169. strcpy(tmp, prefix);
  170. strcat(tmp, format);
  171. vfprintf(stderr, tmp, args);
  172. fflush(stderr);
  173. va_end(args);
  174. }
  175. void watchqueue_add_path(const char *pathname)
  176. {
  177. *watchlist = xmalloc(sizeof(struct watchlistentry));
  178. struct watchlistentry *e = *watchlist;
  179. char *path = xrealpath(pathname, NULL);
  180. e->ifd = 0;
  181. e->path = path;
  182. e->isdir = path_is_directory(pathname);
  183. e->next = NULL;
  184. watchlist= &e->next;
  185. }
  186. void create_watches(int fd, uint32_t mask)
  187. {
  188. for(struct watchlistentry *lkp = watchlist_head; lkp != NULL; lkp = lkp->next)
  189. {
  190. int ret = inotify_add_watch(fd, lkp->path, mask);
  191. if(ret == -1)
  192. {
  193. perror("inotify_add_watch");
  194. exit(EXIT_FAILURE);
  195. }
  196. lkp->ifd = ret;
  197. }
  198. }
  199. bool redirect_stdout(const char *outfile)
  200. {
  201. int fd = open(outfile, O_CREAT | O_WRONLY | O_APPEND, S_IRUSR | S_IWUSR);
  202. if(fd == -1)
  203. {
  204. perror("open");
  205. return false;
  206. }
  207. if(dup2(fd, 1) == -1 || dup2(fd, 2) == -1)
  208. {
  209. perror("dup2");
  210. return false;
  211. }
  212. return true;
  213. }
  214. bool run_prog(const char *eventfile, uint32_t eventmask)
  215. {
  216. pid_t pid = fork();
  217. if(pid == 0)
  218. {
  219. if(path_logfile)
  220. {
  221. if(! redirect_stdout(path_logfile))
  222. {
  223. return false;
  224. }
  225. }
  226. if(! noenv)
  227. {
  228. char envvar[30];
  229. snprintf(envvar, sizeof(envvar), "adhocifyevent=%"PRIu32, eventmask);
  230. putenv(envvar);
  231. }
  232. //This can be thrown away, if in create_script_args we create pointer to the pointer pointing to the SCRIPT_PLACE_SPECIFIER string.
  233. //Then all what we have to do here is to set the pointer to eventfile. However, we can have multiple of those, probably not worth it as we shouldn't have tons of arguments
  234. for(unsigned int i = 0; i < n_script_arguments; i++)
  235. {
  236. char *argument = script_arguments[i];
  237. if(argument && STREQ(argument, SCRIPT_PLACE_SPECIFIER))
  238. script_arguments[i] = eventfile;
  239. }
  240. execv(prog, script_arguments);
  241. perror("execv");
  242. return false;
  243. }
  244. if(pid == -1)
  245. {
  246. perror("fork");
  247. return false;
  248. }
  249. return true;
  250. }
  251. uint32_t nameToMask(const char *name)
  252. {
  253. if(STREQ(name, "IN_CLOSE_WRITE"))
  254. return IN_CLOSE_WRITE;
  255. else if(STREQ(name, "IN_OPEN"))
  256. return IN_OPEN;
  257. else if(STREQ(name, "IN_MODIFY"))
  258. return IN_MODIFY;
  259. else if(STREQ(name, "IN_DELETE"))
  260. return IN_DELETE;
  261. else if(STREQ(name, "IN_ATTRIB"))
  262. return IN_ATTRIB;
  263. else if(STREQ(name, "IN_CLOSE_NOWRITE"))
  264. return IN_CLOSE_NOWRITE;
  265. else if(STREQ(name, "IN_MOVED_FROM"))
  266. return IN_MOVED_FROM;
  267. else if(STREQ(name, "IN_MOVED_TO"))
  268. return IN_MOVED_TO;
  269. else if(STREQ(name, "IN_CREATE"))
  270. return IN_CREATE;
  271. else if(STREQ(name, "IN_DELETE_SELF"))
  272. return IN_DELETE_SELF;
  273. else if(STREQ(name, "IN_MOVE_SELF"))
  274. return IN_MOVE_SELF;
  275. else if(STREQ(name, "IN_ALL_EVENTS"))
  276. return IN_ALL_EVENTS;
  277. else if(STREQ(name, "IN_CLOSE"))
  278. return IN_CLOSE;
  279. else if(STREQ(name, "IN_MOVE"))
  280. return IN_MOVE;
  281. else
  282. return 0;
  283. }
  284. void check_forkbomb(const char *path_logfile, const char *path_prog)
  285. {
  286. char *dir_log = ndirname(path_logfile);
  287. char *dir_prog = ndirname(path_prog);
  288. struct watchlistentry *lkp = watchlist_head;
  289. while(lkp)
  290. {
  291. if(lkp->isdir)
  292. {
  293. char *dir_lkpPath = lkp->path;
  294. if( STREQ(dir_lkpPath, dir_log) || STREQ(dir_lkpPath, dir_prog) )
  295. {
  296. logerror("Don't place your logfiles or script in a directory you are watching for events. Pass -b to bypass this check.\n");
  297. exit(EXIT_FAILURE);
  298. }
  299. }
  300. lkp = lkp->next;
  301. }
  302. free(dir_log);
  303. free(dir_prog);
  304. }
  305. void queue_watches_from_stdin()
  306. {
  307. char *line = NULL;
  308. size_t n = 0;
  309. ssize_t r;
  310. while((r = getline(&line, &n, stdin)) != -1)
  311. {
  312. if(line[r-1] == '\n')
  313. line[r-1] = 0;
  314. watchqueue_add_path(line);
  315. }
  316. }
  317. char *get_eventfile_abspath(struct inotify_event *event)
  318. {
  319. char *wdpath = find_ifd_path(event->wd);
  320. if(wdpath == NULL)
  321. {
  322. return NULL;
  323. }
  324. char *result = NULL;
  325. if((event->len) > 0 )
  326. {
  327. if(asprintf(&result, "%s/%s", wdpath, event->name) == -1)
  328. {
  329. return NULL;
  330. }
  331. }
  332. else
  333. {
  334. result = strdup(wdpath);
  335. }
  336. return result;
  337. }
  338. void handle_event(struct inotify_event *event)
  339. {
  340. if(event->mask & mask)
  341. {
  342. char *eventfile_abspath = get_eventfile_abspath(event);
  343. if(eventfile_abspath == NULL)
  344. {
  345. logerror("Could not get absolute path for event. Watch descriptor %i\n", event->wd);
  346. exit(EXIT_FAILURE);
  347. }
  348. if(is_ignored(eventfile_abspath))
  349. {
  350. free(eventfile_abspath);
  351. return;
  352. }
  353. logwrite("Starting execution of child %s\n", prog);
  354. bool r = run_prog(eventfile_abspath, event->mask);
  355. if(!r)
  356. {
  357. logerror("Execution of child %s failed\n", prog);
  358. exit(EXIT_FAILURE);
  359. }
  360. fflush(stdout);
  361. fflush(stderr);
  362. free (eventfile_abspath);
  363. }
  364. }
  365. static inline char *get_cwd()
  366. {
  367. return getcwd(NULL,0);
  368. }
  369. void print_usage()
  370. {
  371. printf("adhocify [OPTIONS] script [arguments for script]\n");
  372. printf("--daemon, -d\t\t\tdaemonize\n");
  373. printf("--path, -w\t\t\tpath -- adds the specified path to the watchlist\n");
  374. printf("--logfile, -o\t\t\tlogfile -- output goes here\n");
  375. printf("--mask, -m\t\t\tmaskval -- inotify mask value. Can be specified multiple times, will be ORed.\n");
  376. printf("--no-env, -a\t\t\tif specified, the inotify event which occured won't be passed to the script as an environment variable.\n");
  377. printf("--silent, -q\t\t\tsilent\n");
  378. printf("--stdin, -s\t\t\tRead the paths which must be added to the watchlist from stdin. Each path in a seperate line\n");
  379. printf("--no-forkbomb-check, -b\t\tDisable fork bomb detection\n");
  380. printf("--ignore, -i\t\t\tpattern -- Ignore events on files for which the pattern matches\n");
  381. printf("--exit-with-child, -e\t\tExit when the script exits. You can also specify a return code (e. g. -e 1 = exit on error)\n");
  382. printf("\n\nIf your script should know the file the event occured on, use {} when you specify the script arguments (like xargs)\n");
  383. }
  384. static struct option long_options[] =
  385. {
  386. { "daemon", no_argument, 0, 'd' },
  387. { "logfile", required_argument, 0, 'o' },
  388. { "mask", required_argument, 0, 'm' },
  389. { "path", required_argument, 0, 'w' },
  390. { "no-env", no_argument, 0, 'a' },
  391. { "stdin", no_argument, 0, 's' },
  392. { "no-forkbomb-check", no_argument, 0, 'b' },
  393. { "ignore", required_argument, 0, 'i' },
  394. { "silent", no_argument, 0, 'q' },
  395. { "help", no_argument, 0, 'h' },
  396. { "exit-with-child", optional_argument, 0, 'e' }
  397. };
  398. //fills global n_script_arguments and script_arguments var
  399. void fill_script_arguments(size_t n_args, char *args[])
  400. {
  401. n_script_arguments = n_args + 2; //2 = argv0 and terminating NULL
  402. char **arguments = xmalloc( n_script_arguments * sizeof(char *) );
  403. const char *argv0 = memrchr(prog, '/', strlen(prog));
  404. argv0 = ( argv0 == NULL ) ? prog : argv0+1;
  405. arguments[0] = argv0;
  406. const int begin_offset = 1;
  407. for(unsigned int i = 0; i < n_args; i++)
  408. {
  409. char *argument = args[i];
  410. arguments[i+begin_offset] = strdup(argument);
  411. }
  412. arguments[n_args+begin_offset] = NULL;
  413. script_arguments = arguments;
  414. }
  415. void parse_options(int argc, char **argv)
  416. {
  417. char *watchpath = NULL;
  418. int option;
  419. int option_index;
  420. uint32_t optmask = 0;
  421. while((option = getopt_long(argc, argv, "absdo:w:m:l:i:e::", long_options, &option_index)) != -1)
  422. {
  423. switch(option)
  424. {
  425. case 'd':
  426. daemonize = true;
  427. break;
  428. case 'o':
  429. path_logfile = optarg;
  430. break;
  431. case 'm':
  432. optmask = nameToMask(optarg);
  433. if(optmask == 0) {
  434. logerror("Not supported inotify event: %s\n", optmask);
  435. exit(EXIT_FAILURE);
  436. }
  437. mask |= optmask;
  438. break;
  439. case 'w':
  440. watchpath = optarg;
  441. watchqueue_add_path(watchpath);
  442. break;
  443. case 'a':
  444. noenv=true;
  445. break;
  446. case 's':
  447. fromstdin=true;
  448. break;
  449. case 'b':
  450. forkbombcheck=false;
  451. break;
  452. case 'i':
  453. add_to_ignore_list(optarg);
  454. break;
  455. case 'q':
  456. silent=true;
  457. break;
  458. case 'h':
  459. print_usage();
  460. exit(EXIT_SUCCESS);
  461. case 'e':
  462. exit_with_child = true;
  463. if(optarg)
  464. {
  465. awaited_child_exit_code = atoi(optarg);
  466. }
  467. break;
  468. }
  469. }
  470. if(optind == argc)
  471. {
  472. print_usage();
  473. logerror("missing prog/script path\n");
  474. exit(EXIT_FAILURE);
  475. }
  476. prog = argv[optind++];
  477. if(optind <= argc)
  478. {
  479. fill_script_arguments(argc - optind, &argv[optind]);
  480. }
  481. }
  482. void process_options()
  483. {
  484. if(fromstdin)
  485. {
  486. queue_watches_from_stdin();
  487. }
  488. if(daemonize)
  489. {
  490. if(daemon(0,0) == -1)
  491. {
  492. perror("daemon");
  493. exit(EXIT_FAILURE);
  494. }
  495. }
  496. if(watchlist_head == NULL)
  497. {
  498. watchqueue_add_path(get_cwd());
  499. }
  500. if(mask == 0)
  501. {
  502. mask |= IN_CLOSE_WRITE;
  503. }
  504. if(! file_exists(prog))
  505. {
  506. fprintf(stderr, "File %s does not exist\n", prog);
  507. exit(EXIT_FAILURE);
  508. }
  509. if(path_logfile)
  510. {
  511. path_logfile = xrealpath(path_logfile, NULL);
  512. }
  513. if(forkbombcheck)
  514. {
  515. char *path_prog = xrealpath(prog, NULL);
  516. check_forkbomb(path_logfile, path_prog);
  517. }
  518. }
  519. void start_monitoring(int ifd)
  520. {
  521. while(1)
  522. {
  523. int len;
  524. int offset =0;
  525. char buf[BUF_SIZE];
  526. len = read(ifd, buf, BUF_SIZE);
  527. if(len == -1)
  528. {
  529. if(errno == EINTR)
  530. continue;
  531. perror("read");
  532. exit(EXIT_FAILURE);
  533. }
  534. while(offset < len)
  535. {
  536. struct inotify_event *event = (struct inotify_event *)&buf[offset];
  537. handle_event(event);
  538. offset+=sizeof(struct inotify_event) + event->len;
  539. }
  540. }
  541. }
  542. void child_handler(int signum, siginfo_t *info, void *context)
  543. {
  544. if(signum != SIGCHLD)
  545. {
  546. return;
  547. }
  548. int status;
  549. pid_t p = waitpid(-1, &status, WNOHANG);
  550. if(p == -1)
  551. {
  552. logerror("waitpid failed when handling child exit\n");
  553. exit(EXIT_FAILURE);
  554. }
  555. if(exit_with_child)
  556. {
  557. int adhocify_exit_code = 0;
  558. if(WIFEXITED(status))
  559. {
  560. adhocify_exit_code = WEXITSTATUS(status);
  561. if(awaited_child_exit_code > -1)
  562. {
  563. if(adhocify_exit_code == awaited_child_exit_code)
  564. {
  565. logwrite("child exited with specified exit code, exiting too\n");
  566. exit(adhocify_exit_code);
  567. }
  568. return; //not the exit code we wanted, keep running
  569. }
  570. }
  571. if(WIFSIGNALED(status))
  572. {
  573. adhocify_exit_code = 128 + WTERMSIG(status); //copy bash's behaviour
  574. }
  575. //TODO: coredump?
  576. exit(adhocify_exit_code);
  577. }
  578. }
  579. void set_signals()
  580. {
  581. struct sigaction action;
  582. action.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
  583. action.sa_sigaction = &child_handler;
  584. if(sigaction(SIGCHLD, &action, NULL) == -1)
  585. {
  586. logerror("Error when setting up the signal handler\n");
  587. exit(EXIT_FAILURE);
  588. }
  589. }
  590. int main(int argc, char **argv)
  591. {
  592. if(argc < 2)
  593. {
  594. print_usage();
  595. exit(EXIT_FAILURE);
  596. }
  597. //signal(SIGCHLD, SIG_IGN);
  598. set_signals();
  599. parse_options(argc, argv);
  600. process_options();
  601. int ifd = inotify_init();
  602. if(ifd == -1)
  603. {
  604. perror("inotify_init");
  605. exit(EXIT_FAILURE);
  606. }
  607. create_watches(ifd, mask);
  608. start_monitoring(ifd);
  609. }