sys_watch_directory.c 12 KB

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