sys_watch_directory.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. /**
  2. * @file sys_watch_directory.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the author nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *
  29. * @section DESCRIPTION
  30. *
  31. * Directory watcher.
  32. *
  33. * Synopsis: sys.watch_directory(string dir)
  34. * Description: reports directory entry events. Transitions up when an event is detected, and
  35. * goes down waiting for the next event when sys.watch_directory::nextevent() is called.
  36. * The directory is first scanned and "added" events are reported for all files.
  37. * Variables:
  38. * string event_type - what happened with the file: "added", "removed" or "changed"
  39. * string filename - name of the file in the directory the event refers to
  40. * string filepath - "dir/filename"
  41. *
  42. * Synopsis: sys.watch_directory::nextevent()
  43. * Description: makes the watch_directory module transition down in order to report the next event.
  44. */
  45. #include <stdlib.h>
  46. #include <string.h>
  47. #include <unistd.h>
  48. #include <sys/inotify.h>
  49. #include <sys/types.h>
  50. #include <dirent.h>
  51. #include <errno.h>
  52. #include <misc/nonblocking.h>
  53. #include <misc/concat_strings.h>
  54. #include <ncd/NCDModule.h>
  55. #include <generated/blog_channel_ncd_sys_watch_directory.h>
  56. #define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__)
  57. #define MAX_INOTIFY_EVENTS 128
  58. struct instance {
  59. NCDModuleInst *i;
  60. char *dir;
  61. DIR *dir_handle;
  62. int inotify_fd;
  63. BFileDescriptor bfd;
  64. struct inotify_event events[MAX_INOTIFY_EVENTS];
  65. int events_count;
  66. int events_index;
  67. int processing;
  68. const char *processing_file;
  69. const char *processing_type;
  70. };
  71. struct nextevent_instance {
  72. NCDModuleInst *i;
  73. };
  74. static void instance_free (struct instance *o, int is_error);
  75. static void next_dir_event (struct instance *o)
  76. {
  77. ASSERT(!o->processing)
  78. ASSERT(o->dir_handle)
  79. struct dirent *entry;
  80. do {
  81. // get next entry
  82. errno = 0;
  83. if (!(entry = readdir(o->dir_handle))) {
  84. if (errno != 0) {
  85. ModuleLog(o->i, BLOG_ERROR, "readdir failed");
  86. instance_free(o, 1);
  87. return;
  88. }
  89. // close directory
  90. if (closedir(o->dir_handle) < 0) {
  91. ModuleLog(o->i, BLOG_ERROR, "closedir failed");
  92. o->dir_handle = NULL;
  93. instance_free(o, 1);
  94. return;
  95. }
  96. // set no dir handle
  97. o->dir_handle = NULL;
  98. // start receiving inotify events
  99. BReactor_SetFileDescriptorEvents(o->i->params->reactor, &o->bfd, BREACTOR_READ);
  100. return;
  101. }
  102. } while (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."));
  103. // set event
  104. o->processing_file = entry->d_name;
  105. o->processing_type = "added";
  106. o->processing = 1;
  107. // signal up
  108. NCDModuleInst_Backend_Up(o->i);
  109. }
  110. static void assert_inotify_event (struct instance *o)
  111. {
  112. ASSERT(o->events_index < o->events_count)
  113. ASSERT(o->events[o->events_index].len % sizeof(o->events[0]) == 0)
  114. ASSERT(o->events[o->events_index].len / sizeof(o->events[0]) <= o->events_count - (o->events_index + 1))
  115. }
  116. static const char * translate_inotify_event (struct instance *o)
  117. {
  118. assert_inotify_event(o);
  119. struct inotify_event *event = &o->events[o->events_index];
  120. if (strlen(event->name) > 0) {
  121. if ((event->mask & (IN_CREATE | IN_MOVED_TO))) {
  122. return "added";
  123. }
  124. if ((event->mask & (IN_DELETE | IN_MOVED_FROM))) {
  125. return "removed";
  126. }
  127. if ((event->mask & IN_MODIFY)) {
  128. return "changed";
  129. }
  130. }
  131. return NULL;
  132. }
  133. static void skip_inotify_event (struct instance *o)
  134. {
  135. assert_inotify_event(o);
  136. o->events_index += 1 + o->events[o->events_index].len / sizeof(o->events[0]);
  137. }
  138. static void next_inotify_event (struct instance *o)
  139. {
  140. ASSERT(!o->processing)
  141. ASSERT(!o->dir_handle)
  142. // skip any bad events
  143. while (o->events_index < o->events_count && !translate_inotify_event(o)) {
  144. ModuleLog(o->i, BLOG_ERROR, "unknown inotify event");
  145. skip_inotify_event(o);
  146. }
  147. if (o->events_index == o->events_count) {
  148. // wait for more events
  149. BReactor_SetFileDescriptorEvents(o->i->params->reactor, &o->bfd, BREACTOR_READ);
  150. return;
  151. }
  152. // set event
  153. o->processing_file = o->events[o->events_index].name;
  154. o->processing_type = translate_inotify_event(o);
  155. o->processing = 1;
  156. // consume this event
  157. skip_inotify_event(o);
  158. // signal up
  159. NCDModuleInst_Backend_Up(o->i);
  160. }
  161. static void inotify_fd_handler (struct instance *o, int events)
  162. {
  163. ASSERT(!o->processing)
  164. ASSERT(!o->dir_handle)
  165. int res = read(o->inotify_fd, o->events, sizeof(o->events));
  166. if (res < 0) {
  167. ModuleLog(o->i, BLOG_ERROR, "read failed");
  168. instance_free(o, 1);
  169. return;
  170. }
  171. // stop waiting for inotify events
  172. BReactor_SetFileDescriptorEvents(o->i->params->reactor, &o->bfd, 0);
  173. ASSERT(res <= sizeof(o->events))
  174. ASSERT(res % sizeof(o->events[0]) == 0)
  175. // setup buffer state
  176. o->events_count = res / sizeof(o->events[0]);
  177. o->events_index = 0;
  178. // process inotify events
  179. next_inotify_event(o);
  180. }
  181. static void next_event (struct instance *o)
  182. {
  183. ASSERT(o->processing)
  184. // set not processing
  185. o->processing = 0;
  186. // signal down
  187. NCDModuleInst_Backend_Down(o->i);
  188. if (o->dir_handle) {
  189. next_dir_event(o);
  190. return;
  191. } else {
  192. next_inotify_event(o);
  193. return;
  194. }
  195. }
  196. static void func_new (NCDModuleInst *i)
  197. {
  198. // allocate instance
  199. struct instance *o = malloc(sizeof(*o));
  200. if (!o) {
  201. ModuleLog(i, BLOG_ERROR, "failed to allocate instance");
  202. goto fail0;
  203. }
  204. NCDModuleInst_Backend_SetUser(i, o);
  205. // init arguments
  206. o->i = i;
  207. // check arguments
  208. NCDValue *dir_arg;
  209. if (!NCDValue_ListRead(o->i->args, 1, &dir_arg)) {
  210. ModuleLog(o->i, BLOG_ERROR, "wrong arity");
  211. goto fail1;
  212. }
  213. if (!NCDValue_IsStringNoNulls(dir_arg)) {
  214. ModuleLog(o->i, BLOG_ERROR, "wrong type");
  215. goto fail1;
  216. }
  217. o->dir = NCDValue_StringValue(dir_arg);
  218. // open inotify
  219. if ((o->inotify_fd = inotify_init()) < 0) {
  220. ModuleLog(o->i, BLOG_ERROR, "inotify_init failed");
  221. goto fail1;
  222. }
  223. // add watch
  224. if (inotify_add_watch(o->inotify_fd, o->dir, IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_FROM | IN_MOVED_TO) < 0) {
  225. ModuleLog(o->i, BLOG_ERROR, "inotify_add_watch failed");
  226. goto fail2;
  227. }
  228. // set non-blocking
  229. if (!badvpn_set_nonblocking(o->inotify_fd)) {
  230. ModuleLog(o->i, BLOG_ERROR, "badvpn_set_nonblocking failed");
  231. goto fail2;
  232. }
  233. // init BFileDescriptor
  234. BFileDescriptor_Init(&o->bfd, o->inotify_fd, (BFileDescriptor_handler)inotify_fd_handler, o);
  235. if (!BReactor_AddFileDescriptor(o->i->params->reactor, &o->bfd)) {
  236. ModuleLog(o->i, BLOG_ERROR, "BReactor_AddFileDescriptor failed");
  237. goto fail2;
  238. }
  239. // open directory
  240. if (!(o->dir_handle = opendir(o->dir))) {
  241. ModuleLog(o->i, BLOG_ERROR, "opendir failed");
  242. goto fail3;
  243. }
  244. // set not processing
  245. o->processing = 0;
  246. // read first directory entry
  247. next_dir_event(o);
  248. return;
  249. fail3:
  250. // free BFileDescriptor
  251. BReactor_RemoveFileDescriptor(o->i->params->reactor, &o->bfd);
  252. fail2:
  253. ASSERT_FORCE(close(o->inotify_fd) == 0)
  254. fail1:
  255. free(o);
  256. fail0:
  257. NCDModuleInst_Backend_SetError(i);
  258. NCDModuleInst_Backend_Dead(i);
  259. }
  260. void instance_free (struct instance *o, int is_error)
  261. {
  262. NCDModuleInst *i = o->i;
  263. // close directory
  264. if (o->dir_handle) {
  265. if (closedir(o->dir_handle) < 0) {
  266. ModuleLog(o->i, BLOG_ERROR, "closedir failed");
  267. }
  268. }
  269. // free BFileDescriptor
  270. BReactor_RemoveFileDescriptor(o->i->params->reactor, &o->bfd);
  271. // close inotify
  272. ASSERT_FORCE(close(o->inotify_fd) == 0)
  273. // free instance
  274. free(o);
  275. if (is_error) {
  276. NCDModuleInst_Backend_SetError(i);
  277. }
  278. NCDModuleInst_Backend_Dead(i);
  279. }
  280. static void func_die (void *vo)
  281. {
  282. struct instance *o = vo;
  283. instance_free(o, 0);
  284. }
  285. static int func_getvar (void *vo, const char *name, NCDValue *out)
  286. {
  287. struct instance *o = vo;
  288. ASSERT(o->processing)
  289. if (!strcmp(name, "event_type")) {
  290. if (!NCDValue_InitString(out, o->processing_type)) {
  291. ModuleLog(o->i, BLOG_ERROR, "NCDValue_InitString failed");
  292. return 0;
  293. }
  294. return 1;
  295. }
  296. if (!strcmp(name, "filename")) {
  297. if (!NCDValue_InitString(out, o->processing_file)) {
  298. ModuleLog(o->i, BLOG_ERROR, "NCDValue_InitString failed");
  299. return 0;
  300. }
  301. return 1;
  302. }
  303. if (!strcmp(name, "filepath")) {
  304. char *str = concat_strings(3, o->dir, "/", o->processing_file);
  305. if (!str) {
  306. ModuleLog(o->i, BLOG_ERROR, "concat_strings failed");
  307. return 0;
  308. }
  309. if (!NCDValue_InitString(out, str)) {
  310. ModuleLog(o->i, BLOG_ERROR, "NCDValue_InitString failed");
  311. free(str);
  312. return 0;
  313. }
  314. free(str);
  315. return 1;
  316. }
  317. return 0;
  318. }
  319. static void nextevent_func_new (NCDModuleInst *i)
  320. {
  321. // allocate instance
  322. struct nextevent_instance *o = malloc(sizeof(*o));
  323. if (!o) {
  324. ModuleLog(i, BLOG_ERROR, "failed to allocate instance");
  325. goto fail0;
  326. }
  327. NCDModuleInst_Backend_SetUser(i, o);
  328. // init arguments
  329. o->i = i;
  330. // check arguments
  331. if (!NCDValue_ListRead(o->i->args, 0)) {
  332. ModuleLog(o->i, BLOG_ERROR, "wrong arity");
  333. goto fail1;
  334. }
  335. // get method object
  336. struct instance *mo = ((NCDModuleInst *)i->method_user)->inst_user;
  337. // make sure we are currently reporting an event
  338. if (!mo->processing) {
  339. ModuleLog(o->i, BLOG_ERROR, "not reporting an event");
  340. goto fail1;
  341. }
  342. // signal up.
  343. // Do it before finishing the event so our process does not advance any further if
  344. // we would be killed the event provider going down.
  345. NCDModuleInst_Backend_Up(o->i);
  346. // wait for next event
  347. next_event(mo);
  348. return;
  349. fail1:
  350. free(o);
  351. fail0:
  352. NCDModuleInst_Backend_SetError(i);
  353. NCDModuleInst_Backend_Dead(i);
  354. }
  355. static void nextevent_func_die (void *vo)
  356. {
  357. struct nextevent_instance *o = vo;
  358. NCDModuleInst *i = o->i;
  359. // free instance
  360. free(o);
  361. NCDModuleInst_Backend_Dead(i);
  362. }
  363. static const struct NCDModule modules[] = {
  364. {
  365. .type = "sys.watch_directory",
  366. .func_new = func_new,
  367. .func_die = func_die,
  368. .func_getvar = func_getvar
  369. }, {
  370. .type = "sys.watch_directory::nextevent",
  371. .func_new = nextevent_func_new,
  372. .func_die = nextevent_func_die
  373. }, {
  374. .type = NULL
  375. }
  376. };
  377. const struct NCDModuleGroup ncdmodule_sys_watch_directory = {
  378. .modules = modules
  379. };