sys_watch_directory.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. 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->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->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. ASSERT(!o->processing)
  161. ASSERT(!o->dir_handle)
  162. int res = read(o->inotify_fd, o->events, sizeof(o->events));
  163. if (res < 0) {
  164. ModuleLog(o->i, BLOG_ERROR, "read failed");
  165. instance_free(o, 1);
  166. return;
  167. }
  168. // stop waiting for inotify events
  169. BReactor_SetFileDescriptorEvents(o->i->params->reactor, &o->bfd, 0);
  170. ASSERT(res <= sizeof(o->events))
  171. ASSERT(res % sizeof(o->events[0]) == 0)
  172. // setup buffer state
  173. o->events_count = res / sizeof(o->events[0]);
  174. o->events_index = 0;
  175. // process inotify events
  176. next_inotify_event(o);
  177. }
  178. static void next_event (struct instance *o)
  179. {
  180. ASSERT(o->processing)
  181. // set not processing
  182. o->processing = 0;
  183. // signal down
  184. NCDModuleInst_Backend_Down(o->i);
  185. if (o->dir_handle) {
  186. next_dir_event(o);
  187. return;
  188. } else {
  189. next_inotify_event(o);
  190. return;
  191. }
  192. }
  193. static void func_new (NCDModuleInst *i)
  194. {
  195. // allocate instance
  196. struct instance *o = malloc(sizeof(*o));
  197. if (!o) {
  198. ModuleLog(i, BLOG_ERROR, "failed to allocate instance");
  199. goto fail0;
  200. }
  201. NCDModuleInst_Backend_SetUser(i, o);
  202. // init arguments
  203. o->i = i;
  204. // check arguments
  205. NCDValue *dir_arg;
  206. if (!NCDValue_ListRead(o->i->args, 1, &dir_arg)) {
  207. ModuleLog(o->i, BLOG_ERROR, "wrong arity");
  208. goto fail1;
  209. }
  210. if (!NCDValue_IsStringNoNulls(dir_arg)) {
  211. ModuleLog(o->i, BLOG_ERROR, "wrong type");
  212. goto fail1;
  213. }
  214. o->dir = NCDValue_StringValue(dir_arg);
  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, 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->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))) {
  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. // free BFileDescriptor
  248. BReactor_RemoveFileDescriptor(o->i->params->reactor, &o->bfd);
  249. fail2:
  250. ASSERT_FORCE(close(o->inotify_fd) == 0)
  251. fail1:
  252. free(o);
  253. fail0:
  254. NCDModuleInst_Backend_SetError(i);
  255. NCDModuleInst_Backend_Dead(i);
  256. }
  257. void instance_free (struct instance *o, int is_error)
  258. {
  259. NCDModuleInst *i = o->i;
  260. // close directory
  261. if (o->dir_handle) {
  262. if (closedir(o->dir_handle) < 0) {
  263. ModuleLog(o->i, BLOG_ERROR, "closedir failed");
  264. }
  265. }
  266. // free BFileDescriptor
  267. BReactor_RemoveFileDescriptor(o->i->params->reactor, &o->bfd);
  268. // close inotify
  269. ASSERT_FORCE(close(o->inotify_fd) == 0)
  270. // free instance
  271. free(o);
  272. if (is_error) {
  273. NCDModuleInst_Backend_SetError(i);
  274. }
  275. NCDModuleInst_Backend_Dead(i);
  276. }
  277. static void func_die (void *vo)
  278. {
  279. struct instance *o = vo;
  280. instance_free(o, 0);
  281. }
  282. static int func_getvar (void *vo, const char *name, NCDValue *out)
  283. {
  284. struct instance *o = vo;
  285. ASSERT(o->processing)
  286. if (!strcmp(name, "event_type")) {
  287. if (!NCDValue_InitString(out, o->processing_type)) {
  288. ModuleLog(o->i, BLOG_ERROR, "NCDValue_InitString failed");
  289. return 0;
  290. }
  291. return 1;
  292. }
  293. if (!strcmp(name, "filename")) {
  294. if (!NCDValue_InitString(out, o->processing_file)) {
  295. ModuleLog(o->i, BLOG_ERROR, "NCDValue_InitString failed");
  296. return 0;
  297. }
  298. return 1;
  299. }
  300. if (!strcmp(name, "filepath")) {
  301. char *str = concat_strings(3, o->dir, "/", o->processing_file);
  302. if (!str) {
  303. ModuleLog(o->i, BLOG_ERROR, "concat_strings failed");
  304. return 0;
  305. }
  306. if (!NCDValue_InitString(out, str)) {
  307. ModuleLog(o->i, BLOG_ERROR, "NCDValue_InitString failed");
  308. free(str);
  309. return 0;
  310. }
  311. free(str);
  312. return 1;
  313. }
  314. return 0;
  315. }
  316. static void nextevent_func_new (NCDModuleInst *i)
  317. {
  318. // check arguments
  319. if (!NCDValue_ListRead(i->args, 0)) {
  320. ModuleLog(i, BLOG_ERROR, "wrong arity");
  321. goto fail0;
  322. }
  323. // get method object
  324. struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)i->method_user);
  325. // make sure we are currently reporting an event
  326. if (!mo->processing) {
  327. ModuleLog(i, BLOG_ERROR, "not reporting an event");
  328. goto fail0;
  329. }
  330. // signal up.
  331. // Do it before finishing the event so our process does not advance any further if
  332. // we would be killed the event provider going down.
  333. NCDModuleInst_Backend_Up(i);
  334. // wait for next event
  335. next_event(mo);
  336. return;
  337. fail0:
  338. NCDModuleInst_Backend_SetError(i);
  339. NCDModuleInst_Backend_Dead(i);
  340. }
  341. static const struct NCDModule modules[] = {
  342. {
  343. .type = "sys.watch_directory",
  344. .func_new = func_new,
  345. .func_die = func_die,
  346. .func_getvar = func_getvar
  347. }, {
  348. .type = "sys.watch_directory::nextevent",
  349. .func_new = nextevent_func_new
  350. }, {
  351. .type = NULL
  352. }
  353. };
  354. const struct NCDModuleGroup ncdmodule_sys_watch_directory = {
  355. .modules = modules
  356. };