sys_watch_directory.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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/module_common.h>
  55. #include <generated/blog_channel_ncd_sys_watch_directory.h>
  56. #define MAX_INOTIFY_EVENTS 128
  57. struct instance {
  58. NCDModuleInst *i;
  59. NCDValNullTermString dir_nts;
  60. DIR *dir_handle;
  61. int inotify_fd;
  62. BFileDescriptor bfd;
  63. struct inotify_event events[MAX_INOTIFY_EVENTS];
  64. int events_count;
  65. int events_index;
  66. int processing;
  67. const char *processing_file;
  68. const char *processing_type;
  69. };
  70. static void instance_free (struct instance *o, int is_error);
  71. static void next_dir_event (struct instance *o)
  72. {
  73. ASSERT(!o->processing)
  74. ASSERT(o->dir_handle)
  75. struct dirent *entry;
  76. do {
  77. // get next entry
  78. errno = 0;
  79. if (!(entry = readdir(o->dir_handle))) {
  80. if (errno != 0) {
  81. ModuleLog(o->i, BLOG_ERROR, "readdir failed");
  82. instance_free(o, 1);
  83. return;
  84. }
  85. // close directory
  86. if (closedir(o->dir_handle) < 0) {
  87. ModuleLog(o->i, BLOG_ERROR, "closedir failed");
  88. o->dir_handle = NULL;
  89. instance_free(o, 1);
  90. return;
  91. }
  92. // set no dir handle
  93. o->dir_handle = NULL;
  94. // start receiving inotify events
  95. BReactor_SetFileDescriptorEvents(o->i->params->iparams->reactor, &o->bfd, BREACTOR_READ);
  96. return;
  97. }
  98. } while (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."));
  99. // set event
  100. o->processing_file = entry->d_name;
  101. o->processing_type = "added";
  102. o->processing = 1;
  103. // signal up
  104. NCDModuleInst_Backend_Up(o->i);
  105. }
  106. static void assert_inotify_event (struct instance *o)
  107. {
  108. ASSERT(o->events_index < o->events_count)
  109. ASSERT(o->events[o->events_index].len % sizeof(o->events[0]) == 0)
  110. ASSERT(o->events[o->events_index].len / sizeof(o->events[0]) <= o->events_count - (o->events_index + 1))
  111. }
  112. static const char * translate_inotify_event (struct instance *o)
  113. {
  114. assert_inotify_event(o);
  115. struct inotify_event *event = &o->events[o->events_index];
  116. if (strlen(event->name) > 0) {
  117. if ((event->mask & (IN_CREATE | IN_MOVED_TO))) {
  118. return "added";
  119. }
  120. if ((event->mask & (IN_DELETE | IN_MOVED_FROM))) {
  121. return "removed";
  122. }
  123. if ((event->mask & IN_MODIFY)) {
  124. return "changed";
  125. }
  126. }
  127. return NULL;
  128. }
  129. static void skip_inotify_event (struct instance *o)
  130. {
  131. assert_inotify_event(o);
  132. o->events_index += 1 + o->events[o->events_index].len / sizeof(o->events[0]);
  133. }
  134. static void next_inotify_event (struct instance *o)
  135. {
  136. ASSERT(!o->processing)
  137. ASSERT(!o->dir_handle)
  138. // skip any bad events
  139. while (o->events_index < o->events_count && !translate_inotify_event(o)) {
  140. ModuleLog(o->i, BLOG_ERROR, "unknown inotify event");
  141. skip_inotify_event(o);
  142. }
  143. if (o->events_index == o->events_count) {
  144. // wait for more events
  145. BReactor_SetFileDescriptorEvents(o->i->params->iparams->reactor, &o->bfd, BREACTOR_READ);
  146. return;
  147. }
  148. // set event
  149. o->processing_file = o->events[o->events_index].name;
  150. o->processing_type = translate_inotify_event(o);
  151. o->processing = 1;
  152. // consume this event
  153. skip_inotify_event(o);
  154. // signal up
  155. NCDModuleInst_Backend_Up(o->i);
  156. }
  157. static void inotify_fd_handler (struct instance *o, int events)
  158. {
  159. if (o->processing) {
  160. ModuleLog(o->i, BLOG_ERROR, "file descriptor error");
  161. instance_free(o, 1);
  162. return;
  163. }
  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->iparams->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 (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  197. {
  198. struct instance *o = vo;
  199. o->i = i;
  200. // check arguments
  201. NCDValRef dir_arg;
  202. if (!NCDVal_ListRead(params->args, 1, &dir_arg)) {
  203. ModuleLog(o->i, BLOG_ERROR, "wrong arity");
  204. goto fail0;
  205. }
  206. if (!NCDVal_IsStringNoNulls(dir_arg)) {
  207. ModuleLog(o->i, BLOG_ERROR, "wrong type");
  208. goto fail0;
  209. }
  210. // null terminate dir
  211. if (!NCDVal_StringNullTerminate(dir_arg, &o->dir_nts)) {
  212. ModuleLog(o->i, BLOG_ERROR, "NCDVal_StringNullTerminate failed");
  213. goto fail0;
  214. }
  215. // open inotify
  216. if ((o->inotify_fd = inotify_init()) < 0) {
  217. ModuleLog(o->i, BLOG_ERROR, "inotify_init failed");
  218. goto fail1;
  219. }
  220. // add watch
  221. if (inotify_add_watch(o->inotify_fd, o->dir_nts.data, IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_FROM | IN_MOVED_TO) < 0) {
  222. ModuleLog(o->i, BLOG_ERROR, "inotify_add_watch failed");
  223. goto fail2;
  224. }
  225. // set non-blocking
  226. if (!badvpn_set_nonblocking(o->inotify_fd)) {
  227. ModuleLog(o->i, BLOG_ERROR, "badvpn_set_nonblocking failed");
  228. goto fail2;
  229. }
  230. // init BFileDescriptor
  231. BFileDescriptor_Init(&o->bfd, o->inotify_fd, (BFileDescriptor_handler)inotify_fd_handler, o);
  232. if (!BReactor_AddFileDescriptor(o->i->params->iparams->reactor, &o->bfd)) {
  233. ModuleLog(o->i, BLOG_ERROR, "BReactor_AddFileDescriptor failed");
  234. goto fail2;
  235. }
  236. // open directory
  237. if (!(o->dir_handle = opendir(o->dir_nts.data))) {
  238. ModuleLog(o->i, BLOG_ERROR, "opendir failed");
  239. goto fail3;
  240. }
  241. // set not processing
  242. o->processing = 0;
  243. // read first directory entry
  244. next_dir_event(o);
  245. return;
  246. fail3:
  247. BReactor_RemoveFileDescriptor(o->i->params->iparams->reactor, &o->bfd);
  248. fail2:
  249. if (close(o->inotify_fd) < 0) {
  250. ModuleLog(o->i, BLOG_ERROR, "close failed");
  251. }
  252. fail1:
  253. NCDValNullTermString_Free(&o->dir_nts);
  254. fail0:
  255. NCDModuleInst_Backend_DeadError(i);
  256. }
  257. void instance_free (struct instance *o, int is_error)
  258. {
  259. // close directory
  260. if (o->dir_handle) {
  261. if (closedir(o->dir_handle) < 0) {
  262. ModuleLog(o->i, BLOG_ERROR, "closedir failed");
  263. }
  264. }
  265. // free BFileDescriptor
  266. BReactor_RemoveFileDescriptor(o->i->params->iparams->reactor, &o->bfd);
  267. // close inotify
  268. if (close(o->inotify_fd) < 0) {
  269. ModuleLog(o->i, BLOG_ERROR, "close failed");
  270. }
  271. // free dir nts
  272. NCDValNullTermString_Free(&o->dir_nts);
  273. if (is_error) {
  274. NCDModuleInst_Backend_DeadError(o->i);
  275. } else {
  276. NCDModuleInst_Backend_Dead(o->i);
  277. }
  278. }
  279. static void func_die (void *vo)
  280. {
  281. struct instance *o = vo;
  282. instance_free(o, 0);
  283. }
  284. static int func_getvar (void *vo, const char *name, NCDValMem *mem, NCDValRef *out)
  285. {
  286. struct instance *o = vo;
  287. ASSERT(o->processing)
  288. if (!strcmp(name, "event_type")) {
  289. *out = NCDVal_NewString(mem, o->processing_type);
  290. return 1;
  291. }
  292. if (!strcmp(name, "filename")) {
  293. *out = NCDVal_NewString(mem, o->processing_file);
  294. return 1;
  295. }
  296. if (!strcmp(name, "filepath")) {
  297. char *str = concat_strings(3, o->dir_nts.data, "/", o->processing_file);
  298. if (!str) {
  299. ModuleLog(o->i, BLOG_ERROR, "concat_strings failed");
  300. goto fail;
  301. }
  302. *out = NCDVal_NewString(mem, str);
  303. free(str);
  304. return 1;
  305. }
  306. return 0;
  307. fail:
  308. *out = NCDVal_NewInvalid();
  309. return 1;
  310. }
  311. static void nextevent_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
  312. {
  313. // check arguments
  314. if (!NCDVal_ListRead(params->args, 0)) {
  315. ModuleLog(i, BLOG_ERROR, "wrong arity");
  316. goto fail0;
  317. }
  318. // get method object
  319. struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user);
  320. // make sure we are currently reporting an event
  321. if (!mo->processing) {
  322. ModuleLog(i, BLOG_ERROR, "not reporting an event");
  323. goto fail0;
  324. }
  325. // signal up.
  326. // Do it before finishing the event so our process does not advance any further if
  327. // we would be killed the event provider going down.
  328. NCDModuleInst_Backend_Up(i);
  329. // wait for next event
  330. next_event(mo);
  331. return;
  332. fail0:
  333. NCDModuleInst_Backend_DeadError(i);
  334. }
  335. static struct NCDModule modules[] = {
  336. {
  337. .type = "sys.watch_directory",
  338. .func_new2 = func_new,
  339. .func_die = func_die,
  340. .func_getvar = func_getvar,
  341. .alloc_size = sizeof(struct instance)
  342. }, {
  343. .type = "sys.watch_directory::nextevent",
  344. .func_new2 = nextevent_func_new
  345. }, {
  346. .type = NULL
  347. }
  348. };
  349. const struct NCDModuleGroup ncdmodule_sys_watch_directory = {
  350. .modules = modules
  351. };