Debian Codegraph @

modules/gcide/watcher.c

raw
1 /* This file is part of GNU Dico.
2 Copyright (C) 2024 Sergey Poznyakoff
3
4 GNU Dico is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 3, or (at your option)
7 any later version.
8
9 GNU Dico is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with GNU Dico. If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <poll.h>
21 #include <sys/inotify.h>
22 #include <sys/ioctl.h>
23
24 #include "gcide.h"
25 #include <errno.h>
26 #include <appi18n.h>
27
28 WATCHER
29 watcher_setup(char const *dbdir)
30 {
31 WATCHER w;
32 int wfd;
33
34 w = calloc(1, sizeof(*w));
35 if (!w) {
36 DICO_LOG_MEMERR();
37 return NULL;
38 }
39
40 if ((w->fd = inotify_init()) == -1) {
41 DICO_LOG_ERRNO();
42 free(w);
43 return NULL;
44 }
45
46 wfd = inotify_add_watch(w->fd, dbdir,
47 IN_DELETE | IN_CREATE | IN_CLOSE_WRITE |
48 IN_MOVED_FROM | IN_MOVED_TO);
49
50 if (wfd == -1) {
51 dico_log(L_ERR, errno, "inotify_add_watch");
52 close(w->fd);
53 free(w);
54 return NULL;
55 }
56
57 w->events = POLLIN;
58
59 return w;
60 }
61
62 void
63 watcher_close(WATCHER w)
64 {
65 if (w) {
66 close(w->fd);
67 free(w);
68 }
69 }
70
71 int
72 watcher_is_modified(WATCHER w)
73 {
74 int changed = 0;
75 int rc;
76
77 if (!w)
78 return 1;
79
80 while ((rc = poll(w, 1, 0)) != 0) {
81 if (rc == -1) {
82 if (errno != EINTR)
83 dico_log(L_ERR, errno, "watcher_is_modified: poll failed");
84 break;
85 }
86
87 if (w->revents & POLLIN) {
88 char buffer[4096];
89 int n;
90
91 n = read(w->fd, buffer, sizeof(buffer));
92 if (n == -1) {
93 dico_log(L_ERR, errno, "watcher_is_modified: read");
94 return 0;
95 }
96
97 if (!changed) {
98 struct inotify_event *ep = (struct inotify_event *) buffer;
99 while (n) {
100 int size;
101
102 if (ep->wd >= 0) {
103 if (ep->mask & IN_IGNORED)
104 /* nothing */ ;
105 else if (ep->mask & IN_Q_OVERFLOW)
106 dico_log(L_NOTICE, 0, "event queue overflow");
107 else if (ep->mask & IN_UNMOUNT)
108 /* FIXME: no special handling for now */;
109 else {
110 changed = 1;
111 break;
112 }
113 }
114 size = sizeof(*ep) + ep->len;
115 ep = (struct inotify_event *) ((char*) ep + size);
116 n -= size;
117 }
118 }
119 }
120 }
121 return changed;
122 }