file_monitor_linux.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /*
  2. * Copyright (c) 2012-2018 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/dbartolini/crown/blob/master/LICENSE
  4. */
  5. #include "core/platform.h"
  6. #if CROWN_PLATFORM_LINUX
  7. #include "core/containers/hash_map.h"
  8. #include "core/filesystem/file_monitor.h"
  9. #include "core/filesystem/path.h"
  10. #include "core/memory/temp_allocator.h"
  11. #include "core/strings/dynamic_string.h"
  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. 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)
  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. CE_ASSERT(wd != -1, "inotify_add_watch: errno: %d", errno);
  59. TempAllocator512 ta;
  60. DynamicString str(ta);
  61. str = path;
  62. hash_map::set(_watches, wd, str);
  63. hash_map::set(_watches_reverse, str, wd);
  64. // Add all sub-dirs recursively
  65. DIR *dir;
  66. struct dirent *entry;
  67. if (!(dir = opendir(path)))
  68. return;
  69. while ((entry = readdir(dir)))
  70. {
  71. const char* dname = entry->d_name;
  72. if (!strcmp(dname, ".") || !strcmp(dname, ".."))
  73. continue;
  74. // FIXME: some filesystems do not support DT_DIR.
  75. if (entry->d_type != DT_DIR)
  76. continue;
  77. TempAllocator512 ta;
  78. DynamicString str(ta);
  79. path::join(str, path, dname);
  80. add_watch(str.c_str(), recursive);
  81. }
  82. closedir(dir);
  83. }
  84. void start(u32 num, const char** paths, bool recursive, FileMonitorFunction fmf, void* user_data)
  85. {
  86. CE_ENSURE(NULL != fmf);
  87. _recursive = recursive;
  88. _function = fmf;
  89. _user_data = user_data;
  90. _fd = inotify_init();
  91. CE_ASSERT(_fd != -1, "inotify_init: errno: %d", errno);
  92. for (u32 i = 0; i < num; ++i)
  93. add_watch(paths[i], recursive);
  94. _thread.start([](void* thiz) { return ((FileMonitorImpl*)thiz)->watch(); }, this);
  95. }
  96. void stop()
  97. {
  98. _exit = true;
  99. close(_fd);
  100. }
  101. int watch()
  102. {
  103. while (!_exit)
  104. {
  105. TempAllocator512 ta;
  106. fd_set set;
  107. struct timeval timeout;
  108. u32 cookie = 0;
  109. u32 cookie_mask = 0;
  110. DynamicString cookie_path(ta);
  111. FD_ZERO(&set);
  112. FD_SET(_fd, &set);
  113. timeout.tv_sec = 0;
  114. timeout.tv_usec = 32*1000;
  115. // select returns 0 if timeout, 1 if input available, -1 if error.
  116. if (select(FD_SETSIZE, &set, NULL, NULL, &timeout) == 0)
  117. continue;
  118. #define BUF_LEN sizeof(struct inotify_event) + NAME_MAX + 1
  119. char buf[BUF_LEN*16];
  120. #undef BUF_LEN
  121. ssize_t len = read(_fd, buf, sizeof(buf));
  122. if (len == 0)
  123. return 0;
  124. if (len == -1)
  125. return -1;
  126. for (char* p = buf; p < buf + len;)
  127. {
  128. inotify_event* ev = (inotify_event*)p;
  129. if (ev->mask & IN_IGNORED)
  130. {
  131. // Watch was removed explicitly (inotify_rm_watch(2)) or
  132. // automatically (file was deleted, or filesystem was
  133. // unmounted).
  134. hash_map::remove(_watches, ev->wd);
  135. }
  136. if (ev->mask & IN_CREATE)
  137. {
  138. DynamicString path(ta);
  139. full_path(path, ev->wd, ev->name);
  140. _function(_user_data
  141. , FileMonitorEvent::CREATED
  142. , ev->mask & IN_ISDIR
  143. , path.c_str()
  144. , NULL
  145. );
  146. // From INOTIFY(7), Limitations and caveats:
  147. // If monitoring an entire directory subtree, and a new subdirectory
  148. // is created in that tree or an existing directory is renamed into
  149. // that tree, be aware that by the time you create a watch for the
  150. // new subdirectory, new files (and subdirectories) may already exist
  151. // inside the subdirectory. Therefore, you may want to scan the
  152. // contents of the subdirectory immediately after adding the watch
  153. // (and, if desired, recursively add watches for any subdirectories
  154. // that it contains).
  155. if (ev->mask & IN_ISDIR)
  156. add_watch(path.c_str(), _recursive);
  157. }
  158. if (ev->mask & IN_DELETE)
  159. {
  160. DynamicString path(ta);
  161. full_path(path, ev->wd, ev->name);
  162. _function(_user_data
  163. , FileMonitorEvent::DELETED
  164. , ev->mask & IN_ISDIR
  165. , path.c_str()
  166. , NULL
  167. );
  168. }
  169. if (ev->mask & IN_MODIFY || ev->mask & IN_ATTRIB)
  170. {
  171. DynamicString path(ta);
  172. full_path(path, ev->wd, ev->name);
  173. _function(_user_data
  174. , FileMonitorEvent::CHANGED
  175. , ev->mask & IN_ISDIR
  176. , path.c_str()
  177. , NULL
  178. );
  179. }
  180. if (ev->mask & IN_MOVED_FROM)
  181. {
  182. // Two consecutive IN_MOVED_FROM
  183. if (cookie != 0)
  184. {
  185. _function(_user_data
  186. , FileMonitorEvent::DELETED
  187. , cookie_mask & IN_ISDIR
  188. , cookie_path.c_str()
  189. , NULL
  190. );
  191. u32 wd = hash_map::get(_watches_reverse, cookie_path, INT32_MAX);
  192. hash_map::remove(_watches_reverse, cookie_path);
  193. inotify_rm_watch(_fd, wd);
  194. cookie = 0;
  195. cookie_mask = 0;
  196. }
  197. else
  198. {
  199. DynamicString path(ta);
  200. full_path(path, ev->wd, ev->name);
  201. cookie = ev->cookie;
  202. cookie_mask = ev->mask;
  203. cookie_path = path;
  204. }
  205. }
  206. if (ev->mask & IN_MOVED_TO)
  207. {
  208. if (cookie == ev->cookie)
  209. {
  210. // File or directory has been renamed
  211. DynamicString path(ta);
  212. full_path(path, ev->wd, ev->name);
  213. _function(_user_data
  214. , FileMonitorEvent::RENAMED
  215. , ev->mask & IN_ISDIR
  216. , cookie_path.c_str()
  217. , path.c_str()
  218. );
  219. cookie = 0;
  220. cookie_mask = 0;
  221. if (ev->mask & IN_ISDIR)
  222. {
  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);
  227. }
  228. }
  229. else
  230. {
  231. // File or directory was moved to this folder
  232. DynamicString path(ta);
  233. full_path(path, ev->wd, ev->name);
  234. _function(_user_data
  235. , FileMonitorEvent::CREATED
  236. , ev->mask & IN_ISDIR
  237. , path.c_str()
  238. , NULL
  239. );
  240. cookie = 0;
  241. cookie_mask = 0;
  242. if (ev->mask & IN_ISDIR)
  243. add_watch(path.c_str(), _recursive);
  244. }
  245. }
  246. p += sizeof(inotify_event) + ev->len;
  247. }
  248. // Unpaired IN_MOVE_TO
  249. if (cookie != 0)
  250. {
  251. _function(_user_data
  252. , FileMonitorEvent::DELETED
  253. , cookie_mask & IN_ISDIR
  254. , cookie_path.c_str()
  255. , NULL
  256. );
  257. u32 wd = hash_map::get(_watches_reverse, cookie_path, INT32_MAX);
  258. hash_map::remove(_watches_reverse, cookie_path);
  259. inotify_rm_watch(_fd, wd);
  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 // CROWN_PLATFORM_LINUX