file_monitor_linux.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /*
  2. * Copyright (c) 2012-2023 Daniele Bartolini et al.
  3. * SPDX-License-Identifier: MIT
  4. */
  5. #include "core/platform.h"
  6. #if CROWN_PLATFORM_LINUX
  7. #include "core/containers/hash_map.inl"
  8. #include "core/filesystem/file_monitor.h"
  9. #include "core/filesystem/path.h"
  10. #include "core/memory/temp_allocator.inl"
  11. #include "core/strings/dynamic_string.inl"
  12. #include "core/thread/thread.h"
  13. #include <dirent.h> // opendir, readdir
  14. #include <errno.h>
  15. #include <limits.h> // NAME_MAX
  16. #include <sys/inotify.h>
  17. #include <sys/select.h>
  18. #include <unistd.h> // read
  19. namespace crown
  20. {
  21. struct FileMonitorImpl
  22. {
  23. Allocator *_allocator;
  24. int _fd;
  25. HashMap<int, DynamicString> _watches;
  26. HashMap<DynamicString, int> _watches_reverse;
  27. Thread _thread;
  28. bool _exit;
  29. bool _recursive;
  30. FileMonitorFunction _function;
  31. void *_user_data;
  32. explicit FileMonitorImpl(Allocator &a)
  33. : _allocator(&a)
  34. , _fd(0)
  35. , _watches(a)
  36. , _watches_reverse(a)
  37. , _exit(false)
  38. , _recursive(false)
  39. , _function(NULL)
  40. , _user_data(NULL)
  41. {
  42. }
  43. void add_watch(const char *path, bool recursive, bool generate_create_event = false)
  44. {
  45. CE_ENSURE(path != NULL);
  46. CE_ASSERT(!path::has_trailing_separator(path), "Malformed path");
  47. int wd = inotify_add_watch(_fd
  48. , path
  49. , IN_CREATE
  50. | IN_DELETE // File/directory deleted from watched directory.
  51. | IN_MODIFY
  52. | IN_ATTRIB
  53. | IN_MOVE
  54. | IN_DELETE_SELF // Watched file/directory was itself deleted.
  55. | IN_DONT_FOLLOW // Don't dereference pathname if it is a symbolic link.
  56. | IN_ONLYDIR // Only watch pathname if it is a directory.
  57. );
  58. if (wd == -1)
  59. return;
  60. TempAllocator512 ta;
  61. DynamicString str(ta);
  62. str = path;
  63. hash_map::set(_watches, wd, str);
  64. hash_map::set(_watches_reverse, str, wd);
  65. // Add all sub-dirs recursively
  66. if (recursive)
  67. add_subdirectories(path, generate_create_event);
  68. }
  69. void add_subdirectories(const char *path, bool generate_create_event)
  70. {
  71. struct dirent *entry;
  72. DIR *dir = opendir(path);
  73. if (dir != NULL) {
  74. while ((entry = readdir(dir))) {
  75. const char *dname = entry->d_name;
  76. if (!strcmp(dname, ".") || !strcmp(dname, ".."))
  77. continue;
  78. TempAllocator512 ta;
  79. DynamicString str(ta);
  80. path::join(str, path, dname);
  81. if (generate_create_event) {
  82. _function(_user_data
  83. , FileMonitorEvent::CREATED
  84. , entry->d_type == DT_DIR // FIXME: some filesystems do not support DT_DIR.
  85. , str.c_str()
  86. , NULL
  87. );
  88. }
  89. if (entry->d_type == DT_DIR)
  90. add_watch(str.c_str(), _recursive, generate_create_event);
  91. }
  92. closedir(dir);
  93. }
  94. }
  95. void start(u32 num, const char **paths, bool recursive, FileMonitorFunction fmf, void *user_data)
  96. {
  97. CE_ENSURE(NULL != fmf);
  98. _recursive = recursive;
  99. _function = fmf;
  100. _user_data = user_data;
  101. _fd = inotify_init();
  102. if (_fd == -1)
  103. return;
  104. for (u32 i = 0; i < num; ++i)
  105. add_watch(paths[i], recursive);
  106. _thread.start([](void *thiz) { return static_cast<FileMonitorImpl *>(thiz)->watch(); }, this);
  107. }
  108. void stop()
  109. {
  110. _exit = true;
  111. _thread.stop();
  112. close(_fd);
  113. }
  114. int watch()
  115. {
  116. while (!_exit) {
  117. TempAllocator512 ta;
  118. fd_set set;
  119. struct timeval timeout;
  120. u32 cookie = 0;
  121. u32 cookie_mask = 0;
  122. DynamicString cookie_path(ta);
  123. FD_ZERO(&set);
  124. FD_SET(_fd, &set);
  125. timeout.tv_sec = 0;
  126. timeout.tv_usec = 32*1000;
  127. // select returns 0 if timeout, 1 if input available, -1 if error.
  128. if (select(FD_SETSIZE, &set, NULL, NULL, &timeout) == 0)
  129. continue;
  130. #define BUF_LEN sizeof(struct inotify_event) + NAME_MAX + 1
  131. char buf[BUF_LEN*16];
  132. #undef BUF_LEN
  133. ssize_t len = read(_fd, buf, sizeof(buf));
  134. if (len == 0)
  135. return 0;
  136. if (len == -1)
  137. return -1;
  138. for (char *p = buf; p < buf + len;) {
  139. inotify_event *ev = (inotify_event *)p;
  140. if (ev->mask & IN_IGNORED) {
  141. // Watch was removed explicitly (inotify_rm_watch(2)) or
  142. // automatically (file was deleted, or filesystem was
  143. // unmounted).
  144. hash_map::remove(_watches, ev->wd);
  145. }
  146. if (ev->mask & IN_CREATE) {
  147. DynamicString path(ta);
  148. full_path(path, ev->wd, ev->name);
  149. _function(_user_data
  150. , FileMonitorEvent::CREATED
  151. , ev->mask & IN_ISDIR
  152. , path.c_str()
  153. , NULL
  154. );
  155. // From INOTIFY(7), Limitations and caveats:
  156. // If monitoring an entire directory subtree, and a new subdirectory
  157. // is created in that tree or an existing directory is renamed into
  158. // that tree, be aware that by the time you create a watch for the
  159. // new subdirectory, new files (and subdirectories) may already exist
  160. // inside the subdirectory. Therefore, you may want to scan the
  161. // contents of the subdirectory immediately after adding the watch
  162. // (and, if desired, recursively add watches for any subdirectories
  163. // that it contains).
  164. if (ev->mask & IN_ISDIR)
  165. add_watch(path.c_str(), _recursive, true);
  166. }
  167. if (ev->mask & IN_DELETE) {
  168. DynamicString path(ta);
  169. full_path(path, ev->wd, ev->name);
  170. _function(_user_data
  171. , FileMonitorEvent::DELETED
  172. , ev->mask & IN_ISDIR
  173. , path.c_str()
  174. , NULL
  175. );
  176. }
  177. if (ev->mask & IN_MODIFY || ev->mask & IN_ATTRIB) {
  178. DynamicString path(ta);
  179. full_path(path, ev->wd, ev->name);
  180. _function(_user_data
  181. , FileMonitorEvent::CHANGED
  182. , ev->mask & IN_ISDIR
  183. , path.c_str()
  184. , NULL
  185. );
  186. }
  187. if (ev->mask & IN_MOVED_FROM) {
  188. // Two consecutive IN_MOVED_FROM
  189. if (cookie != 0) {
  190. _function(_user_data
  191. , FileMonitorEvent::DELETED
  192. , cookie_mask & IN_ISDIR
  193. , cookie_path.c_str()
  194. , NULL
  195. );
  196. u32 wd = hash_map::get(_watches_reverse, cookie_path, INT32_MAX);
  197. hash_map::remove(_watches_reverse, cookie_path);
  198. inotify_rm_watch(_fd, wd);
  199. cookie = 0;
  200. cookie_mask = 0;
  201. } else {
  202. DynamicString path(ta);
  203. full_path(path, ev->wd, ev->name);
  204. cookie = ev->cookie;
  205. cookie_mask = ev->mask;
  206. cookie_path = path;
  207. }
  208. }
  209. if (ev->mask & IN_MOVED_TO) {
  210. if (cookie == ev->cookie) {
  211. // File or directory has been renamed
  212. DynamicString path(ta);
  213. full_path(path, ev->wd, ev->name);
  214. _function(_user_data
  215. , FileMonitorEvent::RENAMED
  216. , ev->mask & IN_ISDIR
  217. , cookie_path.c_str()
  218. , path.c_str()
  219. );
  220. cookie = 0;
  221. cookie_mask = 0;
  222. if (ev->mask & IN_ISDIR) {
  223. u32 wd = hash_map::get(_watches_reverse, cookie_path, INT32_MAX);
  224. hash_map::remove(_watches_reverse, cookie_path);
  225. inotify_rm_watch(_fd, wd);
  226. add_watch(path.c_str(), _recursive, true);
  227. }
  228. } else {
  229. // File or directory was moved to this folder
  230. DynamicString path(ta);
  231. full_path(path, ev->wd, ev->name);
  232. _function(_user_data
  233. , FileMonitorEvent::CREATED
  234. , ev->mask & IN_ISDIR
  235. , path.c_str()
  236. , NULL
  237. );
  238. cookie = 0;
  239. cookie_mask = 0;
  240. if (ev->mask & IN_ISDIR)
  241. add_watch(path.c_str(), _recursive, true);
  242. }
  243. }
  244. p += sizeof(inotify_event) + ev->len;
  245. }
  246. // Unpaired IN_MOVED_TO or IN_MOVE_FROM with missing IN_MOVED_TO (rename from outside
  247. // watched directory).
  248. if (cookie != 0) {
  249. if (cookie_mask & IN_MOVED_TO || cookie_mask & IN_MOVED_FROM) {
  250. _function(_user_data
  251. , FileMonitorEvent::DELETED
  252. , cookie_mask & IN_ISDIR
  253. , cookie_path.c_str()
  254. , NULL
  255. );
  256. u32 wd = hash_map::get(_watches_reverse, cookie_path, INT32_MAX);
  257. hash_map::remove(_watches_reverse, cookie_path);
  258. inotify_rm_watch(_fd, wd);
  259. }
  260. cookie = 0;
  261. cookie_mask = 0;
  262. }
  263. }
  264. return 0;
  265. }
  266. void full_path(DynamicString &path, int wd, const char *name)
  267. {
  268. TempAllocator512 ta;
  269. DynamicString path_base(ta);
  270. path_base = hash_map::get(_watches, wd, path_base);
  271. path::join(path, path_base.c_str(), name);
  272. }
  273. };
  274. FileMonitor::FileMonitor(Allocator &a)
  275. {
  276. _impl = CE_NEW(a, FileMonitorImpl)(a);
  277. }
  278. FileMonitor::~FileMonitor()
  279. {
  280. CE_DELETE(*_impl->_allocator, _impl);
  281. }
  282. void FileMonitor::start(u32 num, const char **paths, bool recursive, FileMonitorFunction fmf, void *user_data)
  283. {
  284. _impl->start(num, paths, recursive, fmf, user_data);
  285. }
  286. void FileMonitor::stop()
  287. {
  288. _impl->stop();
  289. }
  290. } // namespace crown
  291. #endif // if CROWN_PLATFORM_LINUX