sys_watch_directory.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. const 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. 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->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->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->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 (NCDModuleInst *i)
  198. {
  199. // allocate instance
  200. struct instance *o = malloc(sizeof(*o));
  201. if (!o) {
  202. ModuleLog(i, BLOG_ERROR, "failed to allocate instance");
  203. goto fail0;
  204. }
  205. NCDModuleInst_Backend_SetUser(i, o);
  206. // init arguments
  207. o->i = i;
  208. // check arguments
  209. NCDValRef dir_arg;
  210. if (!NCDVal_ListRead(o->i->args, 1, &dir_arg)) {
  211. ModuleLog(o->i, BLOG_ERROR, "wrong arity");
  212. goto fail1;
  213. }
  214. if (!NCDVal_IsStringNoNulls(dir_arg)) {
  215. ModuleLog(o->i, BLOG_ERROR, "wrong type");
  216. goto fail1;
  217. }
  218. o->dir = NCDVal_StringValue(dir_arg);
  219. // open inotify
  220. if ((o->inotify_fd = inotify_init()) < 0) {
  221. ModuleLog(o->i, BLOG_ERROR, "inotify_init failed");
  222. goto fail1;
  223. }
  224. // add watch
  225. if (inotify_add_watch(o->inotify_fd, o->dir, IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_FROM | IN_MOVED_TO) < 0) {
  226. ModuleLog(o->i, BLOG_ERROR, "inotify_add_watch failed");
  227. goto fail2;
  228. }
  229. // set non-blocking
  230. if (!badvpn_set_nonblocking(o->inotify_fd)) {
  231. ModuleLog(o->i, BLOG_ERROR, "badvpn_set_nonblocking failed");
  232. goto fail2;
  233. }
  234. // init BFileDescriptor
  235. BFileDescriptor_Init(&o->bfd, o->inotify_fd, (BFileDescriptor_handler)inotify_fd_handler, o);
  236. if (!BReactor_AddFileDescriptor(o->i->iparams->reactor, &o->bfd)) {
  237. ModuleLog(o->i, BLOG_ERROR, "BReactor_AddFileDescriptor failed");
  238. goto fail2;
  239. }
  240. // open directory
  241. if (!(o->dir_handle = opendir(o->dir))) {
  242. ModuleLog(o->i, BLOG_ERROR, "opendir failed");
  243. goto fail3;
  244. }
  245. // set not processing
  246. o->processing = 0;
  247. // read first directory entry
  248. next_dir_event(o);
  249. return;
  250. fail3:
  251. // free BFileDescriptor
  252. BReactor_RemoveFileDescriptor(o->i->iparams->reactor, &o->bfd);
  253. fail2:
  254. ASSERT_FORCE(close(o->inotify_fd) == 0)
  255. fail1:
  256. free(o);
  257. fail0:
  258. NCDModuleInst_Backend_SetError(i);
  259. NCDModuleInst_Backend_Dead(i);
  260. }
  261. void instance_free (struct instance *o, int is_error)
  262. {
  263. NCDModuleInst *i = o->i;
  264. // close directory
  265. if (o->dir_handle) {
  266. if (closedir(o->dir_handle) < 0) {
  267. ModuleLog(o->i, BLOG_ERROR, "closedir failed");
  268. }
  269. }
  270. // free BFileDescriptor
  271. BReactor_RemoveFileDescriptor(o->i->iparams->reactor, &o->bfd);
  272. // close inotify
  273. if (close(o->inotify_fd) < 0) {
  274. ModuleLog(o->i, BLOG_ERROR, "close failed");
  275. }
  276. // free instance
  277. free(o);
  278. if (is_error) {
  279. NCDModuleInst_Backend_SetError(i);
  280. }
  281. NCDModuleInst_Backend_Dead(i);
  282. }
  283. static void func_die (void *vo)
  284. {
  285. struct instance *o = vo;
  286. instance_free(o, 0);
  287. }
  288. static int func_getvar (void *vo, const char *name, NCDValMem *mem, NCDValRef *out)
  289. {
  290. struct instance *o = vo;
  291. ASSERT(o->processing)
  292. if (!strcmp(name, "event_type")) {
  293. *out = NCDVal_NewString(mem, o->processing_type);
  294. if (NCDVal_IsInvalid(*out)) {
  295. ModuleLog(o->i, BLOG_ERROR, "NCDVal_NewString failed");
  296. }
  297. return 1;
  298. }
  299. if (!strcmp(name, "filename")) {
  300. *out = NCDVal_NewString(mem, o->processing_file);
  301. if (NCDVal_IsInvalid(*out)) {
  302. ModuleLog(o->i, BLOG_ERROR, "NCDVal_NewString failed");
  303. }
  304. return 1;
  305. }
  306. if (!strcmp(name, "filepath")) {
  307. char *str = concat_strings(3, o->dir, "/", o->processing_file);
  308. if (!str) {
  309. ModuleLog(o->i, BLOG_ERROR, "concat_strings failed");
  310. goto fail;
  311. }
  312. *out = NCDVal_NewString(mem, str);
  313. if (NCDVal_IsInvalid(*out)) {
  314. ModuleLog(o->i, BLOG_ERROR, "NCDVal_NewString failed");
  315. }
  316. free(str);
  317. return 1;
  318. }
  319. return 0;
  320. fail:
  321. *out = NCDVal_NewInvalid();
  322. return 1;
  323. }
  324. static void nextevent_func_new (NCDModuleInst *i)
  325. {
  326. // check arguments
  327. if (!NCDVal_ListRead(i->args, 0)) {
  328. ModuleLog(i, BLOG_ERROR, "wrong arity");
  329. goto fail0;
  330. }
  331. // get method object
  332. struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)i->method_user);
  333. // make sure we are currently reporting an event
  334. if (!mo->processing) {
  335. ModuleLog(i, BLOG_ERROR, "not reporting an event");
  336. goto fail0;
  337. }
  338. // signal up.
  339. // Do it before finishing the event so our process does not advance any further if
  340. // we would be killed the event provider going down.
  341. NCDModuleInst_Backend_Up(i);
  342. // wait for next event
  343. next_event(mo);
  344. return;
  345. fail0:
  346. NCDModuleInst_Backend_SetError(i);
  347. NCDModuleInst_Backend_Dead(i);
  348. }
  349. static const struct NCDModule modules[] = {
  350. {
  351. .type = "sys.watch_directory",
  352. .func_new = func_new,
  353. .func_die = func_die,
  354. .func_getvar = func_getvar
  355. }, {
  356. .type = "sys.watch_directory::nextevent",
  357. .func_new = nextevent_func_new
  358. }, {
  359. .type = NULL
  360. }
  361. };
  362. const struct NCDModuleGroup ncdmodule_sys_watch_directory = {
  363. .modules = modules
  364. };