executes commands 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.

792 lines
16 KiB

  1. /*
  2. * Copyright (c) 2014-2020 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 "{}" //same as EVENTFILE_PLACEHOLDER for backwards compatibility
  40. #define EVENTFILE_PLACEHOLDER "%eventfilepath%"
  41. #define EVENTSTR_PLACEHOLDER "%eventmaskstr%"
  42. struct watchlistentry
  43. {
  44. int ifd;
  45. char *path;
  46. bool isdir;
  47. struct watchlistentry *next;
  48. };
  49. struct watchlistentry *watchlist_head = NULL;
  50. struct watchlistentry **watchlist = &watchlist_head;
  51. struct ignorelist
  52. {
  53. char *ignore;
  54. struct ignorelist *next;
  55. };
  56. struct ignorelist *ignorelist_head = NULL;
  57. struct ignorelist **ignorelist_current = &ignorelist_head;
  58. /* Write-once globals. Set from process_arguments*/
  59. bool silent = false;
  60. bool noenv = false;
  61. bool fromstdin = false;
  62. bool forkbombcheck = true;
  63. bool daemonize = false;
  64. bool exit_with_child = false;
  65. int awaited_child_exit_code = -1;
  66. bool negate_child_exit_code = false;
  67. uint32_t mask = 0;
  68. char *prog = NULL;
  69. char *path_logfile = NULL;
  70. char **script_arguments = NULL; //options to be passed to script we are calling
  71. size_t n_script_arguments = 0;
  72. void *xmalloc(size_t size)
  73. {
  74. void *m = malloc(size);
  75. if(m == NULL)
  76. {
  77. perror("malloc");
  78. exit(EXIT_FAILURE);
  79. }
  80. return m;
  81. }
  82. char *xstrdup(const char *s)
  83. {
  84. char *tmp = strdup(s);
  85. if(tmp == NULL)
  86. {
  87. perror("strdup");
  88. exit(EXIT_FAILURE);
  89. }
  90. return tmp;
  91. }
  92. char *xrealpath(const char *path, char *resolved_path)
  93. {
  94. char *tmp = realpath(path, resolved_path);
  95. if(tmp == NULL)
  96. {
  97. char *errorstr = strerror(errno);
  98. fprintf(stderr, "realpath on %s failed: %s\n", path, errorstr);
  99. exit(EXIT_FAILURE);
  100. }
  101. return tmp;
  102. }
  103. char *ndirname(const char *path)
  104. {
  105. if(path == NULL)
  106. {
  107. return xstrdup(".");
  108. }
  109. char *c = strdupa(path);
  110. return xstrdup(dirname(c));
  111. }
  112. char *find_ifd_path(int ifd)
  113. {
  114. for(struct watchlistentry *lkp = watchlist_head; lkp != NULL; lkp = lkp->next)
  115. {
  116. if(lkp->ifd == ifd)
  117. {
  118. return lkp->path;
  119. }
  120. }
  121. return NULL;
  122. }
  123. bool is_ignored(const char *filename)
  124. {
  125. for(struct ignorelist *l = ignorelist_head; l != NULL; l = l->next)
  126. {
  127. if(fnmatch(l->ignore, filename, 0) == 0)
  128. {
  129. return true;
  130. }
  131. }
  132. return false;
  133. }
  134. bool path_is_directory(const char *path)
  135. {
  136. struct stat sb;
  137. int r = stat(path, &sb);
  138. if(r == -1)
  139. {
  140. perror("stat");
  141. return false;
  142. }
  143. return S_ISDIR(sb.st_mode);
  144. }
  145. static inline bool file_exists(const char *path)
  146. {
  147. return access(path, F_OK) == 0;
  148. }
  149. void add_to_ignore_list(const char *str)
  150. {
  151. *ignorelist_current = xmalloc(sizeof(struct ignorelist));
  152. (*ignorelist_current)->ignore = xstrdup(str);
  153. ignorelist_current = &(*ignorelist_current)->next;
  154. }
  155. void logwrite(const char *format, ...)
  156. {
  157. if(silent)
  158. {
  159. return;
  160. }
  161. va_list args;
  162. va_start(args, format);
  163. vfprintf(stdout, format, args);
  164. fflush(stdout);
  165. va_end(args);
  166. }
  167. void logerror(const char *format, ...)
  168. {
  169. va_list args;
  170. va_start(args, format);
  171. char *prefix = "Error: ";
  172. char *tmp = alloca(strlen(format) + strlen(prefix) + 1);
  173. strcpy(tmp, prefix);
  174. strcat(tmp, format);
  175. vfprintf(stderr, tmp, args);
  176. fflush(stderr);
  177. va_end(args);
  178. }
  179. void watchqueue_add_path(const char *pathname)
  180. {
  181. *watchlist = xmalloc(sizeof(struct watchlistentry));
  182. struct watchlistentry *e = *watchlist;
  183. char *path = xrealpath(pathname, NULL);
  184. e->ifd = 0;
  185. e->path = path;
  186. e->isdir = path_is_directory(pathname);
  187. e->next = NULL;
  188. watchlist= &e->next;
  189. }
  190. void create_watches(int fd, uint32_t mask)
  191. {
  192. for(struct watchlistentry *lkp = watchlist_head; lkp != NULL; lkp = lkp->next)
  193. {
  194. int ret = inotify_add_watch(fd, lkp->path, mask);
  195. if(ret == -1)
  196. {
  197. perror("inotify_add_watch");
  198. exit(EXIT_FAILURE);
  199. }
  200. lkp->ifd = ret;
  201. }
  202. }
  203. bool redirect_stdout(const char *outfile)
  204. {
  205. int fd = open(outfile, O_CREAT | O_WRONLY | O_APPEND, S_IRUSR | S_IWUSR);
  206. if(fd == -1)
  207. {
  208. perror("open");
  209. return false;
  210. }
  211. if(dup2(fd, 1) == -1 || dup2(fd, 2) == -1)
  212. {
  213. perror("dup2");
  214. return false;
  215. }
  216. return true;
  217. }
  218. const char *mask_to_names(int mask)
  219. {
  220. static char ret[1024];
  221. size_t n = sizeof(ret) - 1;
  222. if(mask & IN_ATTRIB)
  223. {
  224. strncat(ret, "IN_ATTRIB,",n);
  225. }
  226. if(mask & IN_OPEN)
  227. {
  228. strncat(ret, "IN_OPEN,", n);
  229. }
  230. if(mask & IN_CLOSE)
  231. {
  232. strncat(ret, "IN_CLOSE,", n);
  233. }
  234. if(mask & IN_CLOSE_NOWRITE)
  235. {
  236. strncat(ret, "IN_CLOSE,", n);
  237. }
  238. if(mask & IN_CLOSE_WRITE)
  239. {
  240. strncat(ret, "IN_CLOSE_WRITE,", n);
  241. }
  242. if(mask & IN_CREATE)
  243. {
  244. strncat(ret, "IN_CREATE,", n);
  245. }
  246. if(mask & IN_DELETE)
  247. {
  248. strncat(ret, "IN_DELETE,", n);
  249. }
  250. if(mask & IN_DELETE_SELF)
  251. {
  252. strncat(ret, "IN_DELETE_SELF,", n);
  253. }
  254. if(mask & IN_MODIFY)
  255. {
  256. strncat(ret, "IN_MODIFY,", n);
  257. }
  258. if(mask & IN_MOVE)
  259. {
  260. strncat(ret, "IN_MOVE,", n);
  261. }
  262. if(mask & IN_MOVE_SELF)
  263. {
  264. strncat(ret, "IN_MOVE_SELF,", n);
  265. }
  266. if(mask & IN_MOVED_FROM)
  267. {
  268. strncat(ret, "IN_MOVED_FROM,", n);
  269. }
  270. if(mask & IN_MOVED_TO)
  271. {
  272. strncat(ret, "IN_MOVED_TO,", n);
  273. }
  274. for(int i = n; i >= 0; --i)
  275. {
  276. if(ret[i] == ',')
  277. {
  278. ret[i] = 0;
  279. break;
  280. }
  281. }
  282. ret[1023] = 0;
  283. return ret;
  284. }
  285. bool run_prog(const char *eventfile, uint32_t eventmask)
  286. {
  287. pid_t pid = fork();
  288. if(pid == 0)
  289. {
  290. if(path_logfile)
  291. {
  292. if(! redirect_stdout(path_logfile))
  293. {
  294. return false;
  295. }
  296. }
  297. if(! noenv)
  298. {
  299. char envvar[30];
  300. snprintf(envvar, sizeof(envvar), "ADHOCIFYEVENT=%"PRIu32, eventmask);
  301. putenv(envvar);
  302. }
  303. for(unsigned int i = 0; i < n_script_arguments; i++)
  304. {
  305. char *argument = script_arguments[i];
  306. if(argument != NULL)
  307. {
  308. if(STREQ(argument, SCRIPT_PLACE_SPECIFIER) || STREQ(argument, EVENTFILE_PLACEHOLDER))
  309. {
  310. script_arguments[i] = eventfile;
  311. }
  312. if(STREQ(argument, EVENTSTR_PLACEHOLDER))
  313. {
  314. script_arguments[i] = mask_to_names(eventmask);
  315. }
  316. }
  317. }
  318. execvp(prog, script_arguments);
  319. logerror("Exec of %s failed: %s\n", prog, strerror(errno));
  320. int exitcode = (errno == ENOENT) ? 127 : EXIT_FAILURE;
  321. exit(exitcode);
  322. }
  323. if(pid == -1)
  324. {
  325. perror("fork");
  326. return false;
  327. }
  328. return true;
  329. }
  330. uint32_t name_to_mask(const char *name)
  331. {
  332. if(STREQ(name, "IN_CLOSE_WRITE"))
  333. return IN_CLOSE_WRITE;
  334. else if(STREQ(name, "IN_OPEN"))
  335. return IN_OPEN;
  336. else if(STREQ(name, "IN_MODIFY"))
  337. return IN_MODIFY;
  338. else if(STREQ(name, "IN_DELETE"))
  339. return IN_DELETE;
  340. else if(STREQ(name, "IN_ATTRIB"))
  341. return IN_ATTRIB;
  342. else if(STREQ(name, "IN_CLOSE_NOWRITE"))
  343. return IN_CLOSE_NOWRITE;
  344. else if(STREQ(name, "IN_MOVED_FROM"))
  345. return IN_MOVED_FROM;
  346. else if(STREQ(name, "IN_MOVED_TO"))
  347. return IN_MOVED_TO;
  348. else if(STREQ(name, "IN_CREATE"))
  349. return IN_CREATE;
  350. else if(STREQ(name, "IN_DELETE_SELF"))
  351. return IN_DELETE_SELF;
  352. else if(STREQ(name, "IN_MOVE_SELF"))
  353. return IN_MOVE_SELF;
  354. else if(STREQ(name, "IN_ALL_EVENTS"))
  355. return IN_ALL_EVENTS;
  356. else if(STREQ(name, "IN_CLOSE"))
  357. return IN_CLOSE;
  358. else if(STREQ(name, "IN_MOVE"))
  359. return IN_MOVE;
  360. else
  361. return 0;
  362. }
  363. void check_forkbomb(const char *path_logfile, const char *path_prog)
  364. {
  365. char *dir_log = ndirname(path_logfile);
  366. char *dir_prog = ndirname(path_prog);
  367. struct watchlistentry *lkp = watchlist_head;
  368. while(lkp)
  369. {
  370. if(lkp->isdir)
  371. {
  372. char *dir_lkpPath = lkp->path;
  373. if( STREQ(dir_lkpPath, dir_log) || STREQ(dir_lkpPath, dir_prog) )
  374. {
  375. logerror("Don't place your logfiles or command in a directory you are watching for events. Pass -b to bypass this check.\n");
  376. exit(EXIT_FAILURE);
  377. }
  378. }
  379. lkp = lkp->next;
  380. }
  381. free(dir_log);
  382. free(dir_prog);
  383. }
  384. void queue_watches_from_stdin()
  385. {
  386. char *line = NULL;
  387. size_t n = 0;
  388. ssize_t r;
  389. while((r = getline(&line, &n, stdin)) != -1)
  390. {
  391. if(line[r-1] == '\n')
  392. line[r-1] = 0;
  393. watchqueue_add_path(line);
  394. }
  395. }
  396. char *get_eventfile_abspath(struct inotify_event *event)
  397. {
  398. char *wdpath = find_ifd_path(event->wd);
  399. if(wdpath == NULL)
  400. {
  401. return NULL;
  402. }
  403. char *result = NULL;
  404. if((event->len) > 0 )
  405. {
  406. if(asprintf(&result, "%s/%s", wdpath, event->name) == -1)
  407. {
  408. return NULL;
  409. }
  410. }
  411. else
  412. {
  413. result = strdup(wdpath);
  414. }
  415. return result;
  416. }
  417. void handle_event(struct inotify_event *event)
  418. {
  419. if(event->mask & mask)
  420. {
  421. char *eventfile_abspath = get_eventfile_abspath(event);
  422. if(eventfile_abspath == NULL)
  423. {
  424. logerror("Could not get absolute path for event. Watch descriptor %i\n", event->wd);
  425. exit(EXIT_FAILURE);
  426. }
  427. if(is_ignored(eventfile_abspath))
  428. {
  429. free(eventfile_abspath);
  430. return;
  431. }
  432. logwrite("Starting execution of command %s\n", prog);
  433. bool r = run_prog(eventfile_abspath, event->mask);
  434. if(!r)
  435. {
  436. logerror("Execution of command %s failed\n", prog);
  437. exit(EXIT_FAILURE);
  438. }
  439. fflush(stdout);
  440. fflush(stderr);
  441. free (eventfile_abspath);
  442. }
  443. }
  444. static inline char *get_cwd()
  445. {
  446. return getcwd(NULL,0);
  447. }
  448. void print_usage()
  449. {
  450. printf("adhocify [OPTIONS] command [arguments for command] - Monitor for inotify events and launch commands\n\n");
  451. printf("--daemon, -d run as a daemon\n");
  452. printf("--path, -w adds the specified path to the watchlist\n");
  453. printf("--logfile, -o path to write output of adhocify and stdout/stderr of launched commands to\n");
  454. printf("--mask, -m inotify event to watch for (see inotify(7)). Can be specified multiple times to watch for several events\n");
  455. printf("--no-env, -a if specified, the inotify event which occured won't be passed to the command as an environment variable\n");
  456. printf("--silent, -q surpress any output created by adhocify itself\n");
  457. printf("--stdin, -s Read the paths which must be added to the watchlist from stdin. Each path must be in a seperate line\n");
  458. printf("--no-forkbomb-check, -b Disable fork bomb detection\n");
  459. printf("--ignore, -i Shell wildcard pattern (see glob(7)) to ignore events on files for which the pattern matches\n");
  460. printf("--exit-with-child, -e Exit when the commands exits. You can also specify a return code (e. g. -e=1 to exit only on errors)\n"); printf("\nIf your command should know the file the event occured on, use the {} placeholder when you specify the arguments (like xargs)\n");
  461. }
  462. static struct option long_options[] =
  463. {
  464. { "daemon", no_argument, 0, 'd' },
  465. { "logfile", required_argument, 0, 'o' },
  466. { "mask", required_argument, 0, 'm' },
  467. { "path", required_argument, 0, 'w' },
  468. { "no-env", no_argument, 0, 'a' },
  469. { "stdin", no_argument, 0, 's' },
  470. { "no-forkbomb-check", no_argument, 0, 'b' },
  471. { "ignore", required_argument, 0, 'i' },
  472. { "silent", no_argument, 0, 'q' },
  473. { "help", no_argument, 0, 'h' },
  474. { "exit-with-child", optional_argument, 0, 'e' }
  475. };
  476. //fills global n_script_arguments and script_arguments var
  477. void fill_script_arguments(size_t n_args, char *args[])
  478. {
  479. n_script_arguments = n_args + 2; //2 = argv0 and terminating NULL
  480. char **arguments = xmalloc( n_script_arguments * sizeof(char *) );
  481. const char *argv0 = memrchr(prog, '/', strlen(prog));
  482. argv0 = ( argv0 == NULL ) ? prog : argv0+1;
  483. arguments[0] = argv0;
  484. const int begin_offset = 1;
  485. for(unsigned int i = 0; i < n_args; i++)
  486. {
  487. char *argument = args[i];
  488. arguments[i+begin_offset] = strdup(argument);
  489. }
  490. arguments[n_args+begin_offset] = NULL;
  491. script_arguments = arguments;
  492. }
  493. void parse_options(int argc, char **argv)
  494. {
  495. char *watchpath = NULL;
  496. int option;
  497. int option_index;
  498. uint32_t optmask = 0;
  499. while((option = getopt_long(argc, argv, "absdo:w:m:l:i:e::", long_options, &option_index)) != -1)
  500. {
  501. switch(option)
  502. {
  503. case 'd':
  504. daemonize = true;
  505. break;
  506. case 'o':
  507. path_logfile = optarg;
  508. break;
  509. case 'm':
  510. optmask = name_to_mask(optarg);
  511. if(optmask == 0) {
  512. logerror("Not supported inotify event: %s\n", optarg);
  513. exit(EXIT_FAILURE);
  514. }
  515. mask |= optmask;
  516. break;
  517. case 'w':
  518. watchpath = optarg;
  519. watchqueue_add_path(watchpath);
  520. break;
  521. case 'a':
  522. noenv=true;
  523. break;
  524. case 's':
  525. fromstdin=true;
  526. break;
  527. case 'b':
  528. forkbombcheck=false;
  529. break;
  530. case 'i':
  531. add_to_ignore_list(optarg);
  532. break;
  533. case 'q':
  534. silent=true;
  535. break;
  536. case 'h':
  537. print_usage();
  538. exit(EXIT_SUCCESS);
  539. case 'e':
  540. exit_with_child = true;
  541. if(optarg)
  542. {
  543. if(*optarg == '!')
  544. {
  545. negate_child_exit_code = true;
  546. ++optarg;
  547. }
  548. if(*optarg == '\0')
  549. {
  550. logerror("Please specify the exit code\n");
  551. exit(EXIT_FAILURE);
  552. }
  553. awaited_child_exit_code = atoi(optarg);
  554. }
  555. break;
  556. }
  557. }
  558. if(optind == argc)
  559. {
  560. print_usage();
  561. logerror("missing command path\n");
  562. exit(EXIT_FAILURE);
  563. }
  564. prog = argv[optind++];
  565. if(optind <= argc)
  566. {
  567. fill_script_arguments(argc - optind, &argv[optind]);
  568. }
  569. }
  570. void process_options()
  571. {
  572. if(fromstdin)
  573. {
  574. queue_watches_from_stdin();
  575. }
  576. if(watchlist_head == NULL)
  577. {
  578. watchqueue_add_path(get_cwd());
  579. }
  580. if(mask == 0)
  581. {
  582. mask |= IN_CLOSE_WRITE;
  583. }
  584. if(path_logfile)
  585. {
  586. path_logfile = xrealpath(path_logfile, NULL);
  587. }
  588. if(forkbombcheck)
  589. {
  590. char *path_prog = realpath(prog, NULL);
  591. if(path_prog != NULL)
  592. {
  593. check_forkbomb(path_logfile, path_prog);
  594. }
  595. free(path_prog);
  596. }
  597. if(daemonize)
  598. {
  599. if(daemon(0,0) == -1)
  600. {
  601. perror("daemon");
  602. exit(EXIT_FAILURE);
  603. }
  604. }
  605. }
  606. void start_monitoring(int ifd)
  607. {
  608. while(1)
  609. {
  610. int len;
  611. int offset =0;
  612. char buf[BUF_SIZE];
  613. len = read(ifd, buf, BUF_SIZE);
  614. if(len == -1)
  615. {
  616. if(errno == EINTR)
  617. continue;
  618. perror("read");
  619. exit(EXIT_FAILURE);
  620. }
  621. while(offset < len)
  622. {
  623. struct inotify_event *event = (struct inotify_event *)&buf[offset];
  624. handle_event(event);
  625. offset+=sizeof(struct inotify_event) + event->len;
  626. }
  627. }
  628. }
  629. void child_handler(int signum, siginfo_t *info, void *context)
  630. {
  631. if(signum != SIGCHLD)
  632. {
  633. return;
  634. }
  635. int status;
  636. pid_t p = waitpid(-1, &status, WNOHANG);
  637. if(p == -1)
  638. {
  639. logerror("waitpid failed when handling child exit\n");
  640. exit(EXIT_FAILURE);
  641. }
  642. int adhocify_exit_code = 0;
  643. if(WIFEXITED(status))
  644. {
  645. adhocify_exit_code = WEXITSTATUS(status);
  646. if(adhocify_exit_code == 127)
  647. {
  648. logwrite("command not found, exiting\n");
  649. exit(adhocify_exit_code);
  650. }
  651. if(exit_with_child && awaited_child_exit_code > -1)
  652. {
  653. bool must_exit = adhocify_exit_code == awaited_child_exit_code;
  654. if(negate_child_exit_code)
  655. {
  656. must_exit = !must_exit;
  657. }
  658. if(must_exit)
  659. {
  660. logwrite("command exited with specified exit code, exiting too\n");
  661. exit(adhocify_exit_code);
  662. }
  663. }
  664. }
  665. if(exit_with_child && WIFSIGNALED(status))
  666. {
  667. adhocify_exit_code = 128 + WTERMSIG(status); //copy bash's behaviour
  668. exit(adhocify_exit_code);
  669. }
  670. }
  671. void set_signals()
  672. {
  673. struct sigaction action;
  674. action.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
  675. action.sa_sigaction = &child_handler;
  676. if(sigaction(SIGCHLD, &action, NULL) == -1)
  677. {
  678. logerror("Error when setting up the signal handler\n");
  679. exit(EXIT_FAILURE);
  680. }
  681. }
  682. int main(int argc, char **argv)
  683. {
  684. if(argc < 2)
  685. {
  686. print_usage();
  687. exit(EXIT_FAILURE);
  688. }
  689. //signal(SIGCHLD, SIG_IGN);
  690. set_signals();
  691. parse_options(argc, argv);
  692. process_options();
  693. int ifd = inotify_init();
  694. if(ifd == -1)
  695. {
  696. perror("inotify_init");
  697. exit(EXIT_FAILURE);
  698. }
  699. create_watches(ifd, mask);
  700. start_monitoring(ifd);
  701. }