View | Details | Raw Unified | Return to bug 214338 | Differences between
and this patch

Collapse All | Expand All

(-)devel/glib20/Makefile (-1 / +10 lines)
Lines 48-54 Link Here
48
		glib-compile-resources.1 gresource.1 gdbus-codegen.1
48
		glib-compile-resources.1 gresource.1 gdbus-codegen.1
49
gobject_MAN=	glib-genmarshal.1 glib-mkenums.1 gobject-query.1
49
gobject_MAN=	glib-genmarshal.1 glib-mkenums.1 gobject-query.1
50
50
51
OPTIONS_DEFINE=	COLLATION_FIX DEBUG NLS
51
OPTIONS_DEFINE=	COLLATION_FIX DEBUG FAM_ALTBACKEND NLS
52
OPTIONS_SUB=	yes
52
OPTIONS_SUB=	yes
53
# libc collation was fixed by https://svnweb.freebsd.org/changeset/base/290494
53
# libc collation was fixed by https://svnweb.freebsd.org/changeset/base/290494
54
COLLATION_FIX_DESC=	Use ICU for UTF-8 string collation (if libc is broken)
54
COLLATION_FIX_DESC=	Use ICU for UTF-8 string collation (if libc is broken)
Lines 65-70 Link Here
65
# http://www.freebsd.org/cgi/query-pr.cgi?pr=175930 see comment by ed@
65
# http://www.freebsd.org/cgi/query-pr.cgi?pr=175930 see comment by ed@
66
#COLLATION_FIX_CONFIGURE_ENV+=	CFLAGS="-D__STDC_ISO_10646__"
66
#COLLATION_FIX_CONFIGURE_ENV+=	CFLAGS="-D__STDC_ISO_10646__"
67
67
68
FAM_ALTBACKEND_DESC=		Alternate file monitor backend
69
68
.include <bsd.port.pre.mk>
70
.include <bsd.port.pre.mk>
69
71
70
# doesn't build yet
72
# doesn't build yet
Lines 98-103 Link Here
98
		s|-Werror|| ; \
100
		s|-Werror|| ; \
99
		s|#define HAVE_SYS_INOTIFY_H 1||' ${WRKSRC}/configure
101
		s|#define HAVE_SYS_INOTIFY_H 1||' ${WRKSRC}/configure
100
102
103
post-patch-FAM_ALTBACKEND-on:
104
	@${REINPLACE_CMD} -e '/^libkqueue_la_OBJECTS =/s|$$(am_libkqueue_la_OBJECTS)|libkqueue_la-gkqueuefilemonitor.lo libkqueue_la-kqueue-helper.lo|' \
105
		${WRKSRC}/gio/kqueue/Makefile.in
106
	@${CP} -f ${FILESDIR}/gkqueuefilemonitor.c ${WRKSRC}/gio/kqueue/gkqueuefilemonitor.c
107
	@${CP} -f ${FILESDIR}/kqueue_fnm.c ${WRKSRC}/gio/kqueue/kqueue-helper.c
108
	@${CP} ${FILESDIR}/kqueue_fnm.h ${WRKSRC}/gio/kqueue/kqueue_fnm.h
109
101
post-install:
110
post-install:
102
	@${MKDIR} ${STAGEDIR}${PREFIX}/share/GConf/gsettings
111
	@${MKDIR} ${STAGEDIR}${PREFIX}/share/GConf/gsettings
103
	@${MKDIR} ${STAGEDIR}${PREFIX}/lib/gio/modules
112
	@${MKDIR} ${STAGEDIR}${PREFIX}/lib/gio/modules
(-)devel/glib20/files/gkqueuefilemonitor.c (+217 lines)
Line 0 Link Here
1
/*-
2
 * Copyright (c) 2016 - 2018 Rozhuk Ivan <rozhuk.im@gmail.com>
3
 * All rights reserved.
4
 *
5
 * Redistribution and use in source and binary forms, with or without
6
 * modification, are permitted provided that the following conditions
7
 * are met:
8
 * 1. Redistributions of source code must retain the above copyright
9
 *    notice, this list of conditions and the following disclaimer.
10
 * 2. Redistributions in binary form must reproduce the above copyright
11
 *    notice, this list of conditions and the following disclaimer in the
12
 *    documentation and/or other materials provided with the distribution.
13
 *
14
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
15
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24
 * SUCH DAMAGE.
25
 *
26
 * Author: Rozhuk Ivan <rozhuk.im@gmail.com>
27
 *
28
 */
29
30
#include "config.h"
31
32
#include <glib-object.h>
33
#include <string.h>
34
#include <gio/gfilemonitor.h>
35
#include <gio/glocalfilemonitor.h>
36
#include <gio/giomodule.h>
37
#include "glib-private.h"
38
#include <glib-unix.h>
39
#include "kqueue_fnm.h"
40
41
/* Defaults. */
42
#ifndef KQUEUE_MON_RATE_LIMIT_TIME_INIT
43
#	define KQUEUE_MON_RATE_LIMIT_TIME_INIT		1000
44
#endif
45
#ifndef KQUEUE_MON_RATE_LIMIT_TIME_MAX
46
#	define KQUEUE_MON_RATE_LIMIT_TIME_MAX		8000
47
#endif
48
#ifndef KQUEUE_MON_RATE_LIMIT_TIME_MUL
49
#	define KQUEUE_MON_RATE_LIMIT_TIME_MUL		2
50
#endif
51
#ifndef KQUEUE_MON_MAX_DIR_FILES
52
#	define KQUEUE_MON_MAX_DIR_FILES			128
53
#endif
54
#ifndef KQUEUE_MON_LOCAL_SUBFILES
55
#	define KQUEUE_MON_LOCAL_SUBFILES		1
56
#endif
57
#ifndef KQUEUE_MON_LOCAL_SUBDIRS
58
#	define KQUEUE_MON_LOCAL_SUBDIRS			0
59
#endif
60
61
62
static GMutex			kqueue_lock;
63
static volatile kq_fnm_p	kqueue_fnm = NULL;
64
/* Exclude from file changes monitoring, watch only for dirs. */
65
static const char *non_local_fs[] = {
66
	"fusefs.sshfs",
67
	NULL
68
};
69
70
#define G_TYPE_KQUEUE_FILE_MONITOR      (g_kqueue_file_monitor_get_type())
71
#define G_KQUEUE_FILE_MONITOR(inst)     (G_TYPE_CHECK_INSTANCE_CAST((inst), \
72
					 G_TYPE_KQUEUE_FILE_MONITOR, GKqueueFileMonitor))
73
74
typedef GLocalFileMonitorClass	GKqueueFileMonitorClass;
75
76
typedef struct {
77
	GLocalFileMonitor	parent_instance;
78
	kq_fnmo_p		fnmo;
79
} GKqueueFileMonitor;
80
81
GType g_kqueue_file_monitor_get_type(void);
82
G_DEFINE_TYPE_WITH_CODE (GKqueueFileMonitor, g_kqueue_file_monitor, G_TYPE_LOCAL_FILE_MONITOR,
83
       g_io_extension_point_implement(G_LOCAL_FILE_MONITOR_EXTENSION_POINT_NAME,
84
               g_define_type_id,
85
               "kqueue",
86
               10))
87
88
89
static void
90
kqueue_event_handler(kq_fnm_p kfnm,
91
    kq_fnmo_p fnmo, void *udata, uint32_t event,
92
    const char *base, const char *filename, const char *new_filename) {
93
	static const uint32_t kfnm_to_glib_map[] = {
94
		0,				/* KF_EVENT_NOT_CHANGED */
95
		G_FILE_MONITOR_EVENT_CREATED,	/* KF_EVENT_CREATED */
96
		G_FILE_MONITOR_EVENT_DELETED,	/* KF_EVENT_DELETED */
97
		G_FILE_MONITOR_EVENT_RENAMED,	/* KF_EVENT_RENAMED */
98
		G_FILE_MONITOR_EVENT_CHANGED	/* KF_EVENT_CHANGED */
99
	};
100
101
	if (NULL == kfnm || NULL == filename ||
102
	    KF_EVENT_CREATED > event ||
103
	    KF_EVENT_CHANGED < event)
104
		return;
105
	g_file_monitor_source_handle_event(udata,
106
	    kfnm_to_glib_map[event],
107
	    filename, new_filename, NULL,
108
	    g_get_monotonic_time());
109
}
110
111
static gboolean
112
g_kqueue_file_monitor_is_supported(void) {
113
	kq_file_mon_settings_t kfms;
114
115
	if (NULL != kqueue_fnm)
116
		return (TRUE);
117
	/* Init only once. */
118
	g_mutex_lock(&kqueue_lock);
119
	if (NULL != kqueue_fnm) {
120
		g_mutex_unlock(&kqueue_lock);
121
		return (TRUE); /* Initialized while wait lock. */
122
	}
123
124
	memset(&kfms, 0x00, sizeof(kq_file_mon_settings_t));
125
	kfms.rate_limit_time_init = KQUEUE_MON_RATE_LIMIT_TIME_INIT;
126
	kfms.rate_limit_time_max = KQUEUE_MON_RATE_LIMIT_TIME_MAX;
127
	kfms.rate_limit_time_mul = KQUEUE_MON_RATE_LIMIT_TIME_MUL;
128
	kfms.max_dir_files = KQUEUE_MON_MAX_DIR_FILES;
129
	kfms.mon_local_subfiles = KQUEUE_MON_LOCAL_SUBFILES;
130
	kfms.mon_local_subdirs = KQUEUE_MON_LOCAL_SUBDIRS;
131
	kfms.local_fs = NULL;
132
	kfms.non_local_fs = non_local_fs;
133
134
	kqueue_fnm = kq_fnm_create(&kfms, kqueue_event_handler);
135
	if (NULL == kqueue_fnm) {
136
		g_mutex_unlock(&kqueue_lock);
137
		return (FALSE); /* Init fail. */
138
	}
139
	g_mutex_unlock(&kqueue_lock);
140
141
	return (TRUE);
142
}
143
144
static gboolean
145
g_kqueue_file_monitor_cancel(GFileMonitor *monitor) {
146
	GKqueueFileMonitor *gffm = G_KQUEUE_FILE_MONITOR(monitor);
147
148
	kq_fnm_del(kqueue_fnm, gffm->fnmo);
149
	gffm->fnmo = NULL;
150
151
	return (TRUE);
152
}
153
154
static void
155
g_kqueue_file_monitor_finalize(GObject *object) {
156
	//GKqueueFileMonitor *gffm = G_KQUEUE_FILE_MONITOR(object);
157
158
	//g_mutex_lock(&kqueue_lock);
159
	//kq_fnm_free(kqueue_fnm);
160
	//kqueue_fnm = NULL;
161
	//g_mutex_unlock(&kqueue_lock);
162
	//G_OBJECT_CLASS(g_kqueue_file_monitor_parent_class)->finalize(object);
163
}
164
165
static void
166
g_kqueue_file_monitor_start(GLocalFileMonitor *local_monitor,
167
    const gchar *dirname, const gchar *basename,
168
    const gchar *filename, GFileMonitorSource *source) {
169
	GKqueueFileMonitor *gffm = G_KQUEUE_FILE_MONITOR(local_monitor);
170
171
	g_assert(NULL != kqueue_fnm);
172
	//g_source_ref((GSource*)source);
173
174
	if (NULL == filename) {
175
		filename = dirname;
176
	}
177
	gffm->fnmo = kq_fnm_add(kqueue_fnm, filename, source);
178
}
179
180
static void
181
g_kqueue_file_monitor_init(GKqueueFileMonitor *monitor) {
182
183
}
184
185
static void
186
g_kqueue_file_monitor_class_init(GKqueueFileMonitorClass *class) {
187
	GObjectClass *gobject_class = G_OBJECT_CLASS(class);
188
	GFileMonitorClass *file_monitor_class = G_FILE_MONITOR_CLASS(class);
189
190
	class->is_supported = g_kqueue_file_monitor_is_supported;
191
	class->start = g_kqueue_file_monitor_start;
192
	class->mount_notify = TRUE; /* TODO: ??? */
193
	file_monitor_class->cancel = g_kqueue_file_monitor_cancel;
194
	gobject_class->finalize = g_kqueue_file_monitor_finalize;
195
}
196
197
static void
198
g_kqueue_file_monitor_class_finalize(GKqueueFileMonitorClass *class) {
199
200
}
201
202
void
203
g_io_module_load(GIOModule *module) {
204
205
	g_type_module_use(G_TYPE_MODULE(module));
206
207
	g_io_extension_point_implement(G_LOCAL_FILE_MONITOR_EXTENSION_POINT_NAME,
208
	    G_TYPE_KQUEUE_FILE_MONITOR, "kqueue", 10);
209
	g_io_extension_point_implement(G_NFS_FILE_MONITOR_EXTENSION_POINT_NAME,
210
	    G_TYPE_KQUEUE_FILE_MONITOR, "kqueue", 10);
211
}
212
213
void
214
g_io_module_unload(GIOModule *module) {
215
216
	g_assert_not_reached();
217
}
(-)devel/glib20/files/kqueue_fnm.c (+1086 lines)
Line 0 Link Here
1
/*-
2
 * Copyright (c) 2016 - 2018 Rozhuk Ivan <rozhuk.im@gmail.com>
3
 * All rights reserved.
4
 *
5
 * Redistribution and use in source and binary forms, with or without
6
 * modification, are permitted provided that the following conditions
7
 * are met:
8
 * 1. Redistributions of source code must retain the above copyright
9
 *    notice, this list of conditions and the following disclaimer.
10
 * 2. Redistributions in binary form must reproduce the above copyright
11
 *    notice, this list of conditions and the following disclaimer in the
12
 *    documentation and/or other materials provided with the distribution.
13
 *
14
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
15
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24
 * SUCH DAMAGE.
25
 *
26
 * Author: Rozhuk Ivan <rozhuk.im@gmail.com>
27
 *
28
 */
29
30
#include <sys/param.h>
31
#include <sys/types.h>
32
#include <sys/event.h>
33
#include <sys/time.h>
34
#include <sys/stat.h>
35
#include <sys/mount.h>
36
#include <sys/fcntl.h> /* open, fcntl */
37
38
#include <inttypes.h>
39
#include <stdlib.h> /* malloc, exit */
40
#include <unistd.h> /* close, write, sysconf */
41
#include <string.h> /* bcopy, bzero, memcpy, memmove, memset, strerror... */
42
#include <dirent.h> /* opendir, readdir */
43
#include <errno.h>
44
#include <pthread.h>
45
46
#include "kqueue_fnm.h"
47
48
49
/* Preallocate items count. */
50
#ifndef FILES_ALLOC_BLK_SIZE
51
#	define FILES_ALLOC_BLK_SIZE	32
52
#endif
53
54
55
typedef struct readdir_context_s {
56
	int		fd;
57
	uint8_t		*buf;
58
	size_t		buf_size;
59
	size_t		buf_used;
60
	size_t		buf_pos;
61
} readdir_ctx_t, *readdir_ctx_p;
62
63
64
typedef struct file_info_s { /* Directory file. */
65
	int		fd;		/* For notify kqueue(). */
66
	struct dirent 	de;		/* d_reclen used for action. */
67
	struct stat	sb;
68
} file_info_t, *file_info_p;
69
70
71
typedef struct kq_file_nmon_obj_s {
72
	int		fd;		/* For notify kqueue(). */
73
	int		is_dir;
74
	int		is_local;	/* Is file system local. */
75
	struct stat	sb;
76
	char		path[(PATH_MAX + 2)];
77
	size_t		path_size;
78
	size_t		name_offset;	/* Parent path size. */
79
	uint32_t	rate_lim_cur_interval;	/* From rate_limit_time_init to rate_limit_time_max. 0 disabled. */
80
	size_t		rate_lim_ev_cnt;	/* Events count then rate_lim_cur_interval != 0 since last report. */
81
	sbintime_t	rate_lim_ev_last;	/* Last event time. */
82
	void		*udata;
83
	kq_fnm_p	kfnm;
84
	/* For dir. */
85
	file_info_p	files;
86
	volatile size_t	files_count;
87
	size_t		files_allocated;
88
} kq_fnmo_t;
89
90
91
typedef struct kq_file_nonify_monitor_s {
92
	int		fd;		/* kqueue() fd. */
93
	int		pfd[2];		/* pipe queue specific. */
94
	kfnm_event_handler_cb cb_func;	/* Callback on dir/file change. */
95
	kq_file_mon_settings_t s;
96
	sbintime_t	rate_lim_time_init; /* rate_limit_time_init */
97
	pthread_t	tid;
98
} kq_fnm_t;
99
100
101
typedef void (*kq_msg_cb)(void *arg);
102
103
typedef struct kq_file_mon_msg_pkt_s {
104
	size_t		magic;
105
	kq_msg_cb	msg_cb;
106
	void		*arg;
107
	size_t		chk_sum;
108
} kq_fnm_msg_pkt_t, *kq_fnm_msg_pkt_p;
109
110
#define KF_MSG_PKT_MAGIC	0xffddaa00
111
112
113
#ifndef O_NOATIME
114
#	define O_NOATIME	0
115
#endif
116
#ifndef O_EVTONLY
117
#	define O_EVTONLY	O_RDONLY
118
#endif
119
#define OPEN_FILE_FLAGS		(O_EVTONLY | O_NONBLOCK | O_NOFOLLOW | O_NOATIME | O_CLOEXEC)
120
121
#define EVFILT_VNODE_SUB_FLAGS	(NOTE_WRITE |				\
122
				NOTE_EXTEND |				\
123
				NOTE_ATTRIB |				\
124
				NOTE_LINK |				\
125
				NOTE_CLOSE_WRITE)
126
127
#define EVFILT_VNODE_FLAGS_ALL	(NOTE_DELETE |				\
128
				EVFILT_VNODE_SUB_FLAGS |		\
129
				NOTE_RENAME |				\
130
				NOTE_REVOKE)
131
132
#ifndef _GENERIC_DIRSIZ
133
#	define _GENERIC_DIRSIZ(__de)	MIN((__de)->d_reclen, sizeof(struct dirent))
134
#endif
135
136
#define IS_NAME_DOTS(__name)	('.' == (__name)[0] &&			\
137
				 ('\0' == (__name)[1] || 		\
138
				  ('.' == (__name)[1] && '\0' == (__name)[2])))
139
#define IS_DE_NAME_EQ(__de1, __de2)  (0 == mem_cmpn((__de1)->d_name,	\
140
						    (__de1)->d_namlen,	\
141
						    (__de2)->d_name,	\
142
						    (__de2)->d_namlen))
143
#define zalloc(__size)		calloc(1, (__size))
144
145
#if (!defined(HAVE_REALLOCARRAY) && (!defined(__FreeBSD_version) || __FreeBSD_version < 1100000))
146
#	define reallocarray(__mem, __size, __count)	realloc((__mem), ((__size) * (__count)))
147
#endif
148
149
#ifndef CLOCK_MONOTONIC_FAST
150
#	define CLOCK_MONOTONIC_FAST	CLOCK_MONOTONIC
151
#endif
152
153
154
#if defined(__FreeBSD_version) && (__FreeBSD_version < 1200040)
155
/* https://svnweb.freebsd.org/base?view=revision&revision=321686
156
 * https://svnweb.freebsd.org/base/head/sys/sys/time.h?view=markup&pathrev=321686#l198
157
 * https://svnweb.freebsd.org/base/head/sys/sys/param.h?revision=321688&view=markup#l61
158
 */
159
static __inline sbintime_t
160
mstosbt(int64_t _ms)
161
{
162
	return ((_ms * (((uint64_t)1 << 63) / 500)) >> 32);
163
}
164
#endif
165
166
void 	*kq_fnm_proccess_events_proc(void *data);
167
168
static inline int
169
mem_cmpn(const void *buf1, const size_t buf1_size,
170
    const void *buf2, const size_t buf2_size) {
171
172
	if (buf1_size != buf2_size)
173
		return (((buf1_size > buf2_size) ? 127 : -127));
174
	if (0 == buf1_size || buf1 == buf2)
175
		return (0);
176
	if (NULL == buf1)
177
		return (-127);
178
	if (NULL == buf2)
179
		return (127);
180
	return (memcmp(buf1, buf2, buf1_size));
181
}
182
183
static int
184
realloc_items(void **items, const size_t item_size,
185
    size_t *allocated, const size_t alloc_blk_cnt, const size_t count) {
186
	size_t allocated_prev, allocated_new;
187
	uint8_t *items_new;
188
189
	if (NULL == items || 0 == item_size || NULL == allocated ||
190
	    0 == alloc_blk_cnt)
191
		return (EINVAL);
192
	allocated_prev = (*allocated);
193
	if (NULL != (*items) &&
194
	    allocated_prev > count &&
195
	    allocated_prev <= (count + alloc_blk_cnt))
196
		return (0);
197
	allocated_new = (((count / alloc_blk_cnt) + 1) * alloc_blk_cnt);
198
	items_new = (uint8_t*)reallocarray((*items), item_size, allocated_new);
199
	if (NULL == items_new) /* Realloc fail! */
200
		return (ENOMEM);
201
202
	if (allocated_new > allocated_prev) { /* Init new mem. */
203
		memset((items_new + (allocated_prev * item_size)), 0x00,
204
		    ((allocated_new - allocated_prev) * item_size));
205
	}
206
	(*items) = items_new;
207
	(*allocated) = allocated_new;
208
209
	return (0);
210
}
211
212
213
static int
214
readdir_start(int fd, struct stat *sb, size_t exp_count, readdir_ctx_p rdd) {
215
	size_t buf_size;
216
217
	if (-1 == fd || NULL == sb || NULL == rdd)
218
		return (EINVAL);
219
	if (-1 == lseek(fd, 0, SEEK_SET))
220
		return (errno);
221
	/* Calculate buf size for getdents(). */
222
	buf_size = MAX((size_t)sb->st_size, (exp_count * sizeof(struct dirent)));
223
	if (0 == buf_size) {
224
		buf_size = (16 * PAGE_SIZE);
225
	}
226
	/* Make buf size well aligned. */
227
	if (0 != sb->st_blksize) {
228
		if (powerof2(sb->st_blksize)) {
229
			buf_size = roundup2(buf_size, sb->st_blksize);
230
		} else {
231
			buf_size = roundup(buf_size, sb->st_blksize);
232
		}
233
	} else {
234
		buf_size = round_page(buf_size);
235
	}
236
	/* Init. */
237
	memset(rdd, 0x00, sizeof(readdir_ctx_t));
238
	rdd->buf = malloc(buf_size);
239
	if (NULL == rdd->buf)
240
		return (ENOMEM);
241
	rdd->buf_size = buf_size;
242
	rdd->fd = fd;
243
244
	return (0);
245
}
246
247
static void
248
readdir_free(readdir_ctx_p rdd) {
249
250
	if (NULL == rdd || NULL == rdd->buf)
251
		return;
252
	free(rdd->buf);
253
	memset(rdd, 0x00, sizeof(readdir_ctx_t));
254
}
255
256
static int
257
readdir_next(readdir_ctx_p rdd, struct dirent *de) {
258
	int error = 0, ios;
259
	uint8_t *ptr;
260
261
	if (NULL == rdd || NULL == rdd->buf || NULL == de)
262
		return (EINVAL);
263
264
	for (;;) {
265
		if (rdd->buf_used <= rdd->buf_pos) {
266
			/* Called once if buf size calculated ok. */
267
			ios = getdents(rdd->fd, (char*)rdd->buf, (int)rdd->buf_size);
268
			if (-1 == ios) {
269
				error = errno;
270
				break;
271
			}
272
			if (0 == ios) {
273
				error = ESPIPE; /* EOF. */
274
				break;
275
			}
276
			rdd->buf_used = (size_t)ios;
277
			rdd->buf_pos = 0;
278
		}
279
		/* Keep data aligned. */
280
		ptr = (rdd->buf + rdd->buf_pos);
281
		memcpy(de, ptr, (sizeof(struct dirent) - sizeof(de->d_name)));
282
		if (0 == de->d_reclen) {
283
			error = ESPIPE; /* EOF. */
284
			break;
285
		}
286
		rdd->buf_pos += de->d_reclen;
287
#ifdef DT_WHT
288
		if (DT_WHT == de->d_type)
289
			continue;
290
#endif
291
		memcpy(de, ptr, _GENERIC_DIRSIZ(de));
292
		if (!IS_NAME_DOTS(de->d_name))
293
			return (0); /* OK. */
294
	}
295
296
	/* Err or no more files. */
297
	readdir_free(rdd);
298
299
	return (error);
300
}
301
302
303
static int
304
file_info_find_ni(file_info_p files, size_t files_count,
305
    file_info_p fi, size_t *idx) {
306
	size_t i;
307
	mode_t st_ftype;
308
309
	if (NULL == files || NULL == fi || NULL == idx)
310
		return (0);
311
	st_ftype = (S_IFMT & fi->sb.st_mode);
312
	for (i = 0; i < files_count; i ++) {
313
		if ((S_IFMT & files[i].sb.st_mode) != st_ftype)
314
			continue;
315
		if ((fi->sb.st_ino != files[i].sb.st_ino ||
316
		     fi->de.d_fileno != files[i].de.d_fileno) &&
317
		    0 == IS_DE_NAME_EQ(&fi->de, &files[i].de))
318
			continue;
319
		(*idx) = i;
320
		return (1);
321
	}
322
	(*idx) = files_count;
323
	return (0);
324
}
325
326
static int
327
file_info_find_ino(file_info_p files, size_t files_count,
328
    file_info_p fi, size_t *idx) {
329
	size_t i;
330
	mode_t st_ftype;
331
332
	if (NULL == files || NULL == fi || NULL == idx)
333
		return (0);
334
	st_ftype = (S_IFMT & fi->sb.st_mode);
335
	for (i = 0; i < files_count; i ++) {
336
		if ((S_IFMT & files[i].sb.st_mode) != st_ftype ||
337
		    fi->sb.st_ino != files[i].sb.st_ino ||
338
		    fi->de.d_fileno != files[i].de.d_fileno)
339
			continue;
340
		(*idx) = i;
341
		return (1);
342
	}
343
	(*idx) = files_count;
344
	return (0);
345
}
346
347
static int
348
file_info_find_name(file_info_p files, size_t files_count,
349
    file_info_p fi, size_t *idx) {
350
	size_t i;
351
	mode_t st_ftype;
352
353
	if (NULL == files || NULL == fi || NULL == idx)
354
		return (0);
355
	st_ftype = (S_IFMT & fi->sb.st_mode);
356
	for (i = 0; i < files_count; i ++) {
357
		if ((S_IFMT & files[i].sb.st_mode) != st_ftype ||
358
		    0 == IS_DE_NAME_EQ(&fi->de, &files[i].de))
359
			continue;
360
		(*idx) = i;
361
		return (1);
362
	}
363
	(*idx) = files_count;
364
	return (0);
365
}
366
367
static void
368
file_info_fd_close(file_info_p files, size_t files_count) {
369
	size_t i;
370
371
	if (NULL == files || 0 == files_count)
372
		return;
373
	for (i = 0; i < files_count; i ++) {
374
		if (-1 == files[i].fd)
375
			continue;
376
		close(files[i].fd);
377
		files[i].fd = -1;
378
	}
379
}
380
381
382
static int
383
is_fs_local(struct statfs *stfs, const char **local_fs, const char **non_local_fs) {
384
	size_t i;
385
386
	if (NULL == stfs)
387
		return (0);
388
	if (NULL != local_fs) {
389
		for (i = 0; NULL != local_fs[i]; i ++) {
390
			if (0 == strncmp(stfs->f_fstypename, local_fs[i],
391
			    sizeof(stfs->f_fstypename)))
392
				return (1);
393
		}
394
	}
395
	if (0 == (MNT_LOCAL & stfs->f_flags))
396
		return (0);
397
	if (NULL != non_local_fs) {
398
		for (i = 0; NULL != non_local_fs[i]; i ++) {
399
			if (0 == strncmp(stfs->f_fstypename, non_local_fs[i],
400
			    sizeof(stfs->f_fstypename)))
401
				return (0);
402
		}
403
	}
404
	return (1);
405
}
406
407
408
static void
409
kq_fnmo_rate_lim_stop(kq_fnmo_p fnmo) {
410
	struct kevent kev;
411
412
	if (NULL == fnmo || -1 == fnmo->fd || 0 == fnmo->rate_lim_cur_interval)
413
		return;
414
	fnmo->rate_lim_cur_interval = 0;
415
	fnmo->rate_lim_ev_cnt = 0;
416
	EV_SET(&kev, fnmo->fd, EVFILT_TIMER, EV_DELETE, 0, 0, NULL);
417
	kevent(fnmo->kfnm->fd, &kev, 1, NULL, 0, NULL);
418
}
419
420
static int
421
kq_fnmo_rate_lim_shedule_next(kq_fnmo_p fnmo) {
422
	u_short flags = (EV_ADD | EV_CLEAR | EV_ONESHOT);
423
	struct kevent kev;
424
425
	if (NULL == fnmo || -1 == fnmo->fd || 0 == fnmo->kfnm->s.rate_limit_time_init)
426
		return (EINVAL);
427
	if (0 == fnmo->rate_lim_cur_interval) { /* First call. */
428
		fnmo->rate_lim_cur_interval = fnmo->kfnm->s.rate_limit_time_init;
429
	} else {
430
		if (fnmo->rate_lim_cur_interval == fnmo->kfnm->s.rate_limit_time_max)
431
			return (0); /* No need to modify timer. */
432
		/* Increase rate limit interval. */
433
		fnmo->rate_lim_cur_interval *= fnmo->kfnm->s.rate_limit_time_mul;
434
	}
435
	if (fnmo->rate_lim_cur_interval >= fnmo->kfnm->s.rate_limit_time_max) {
436
		/* Check upper limit and shedule periodic timer with upper rate limit time. */
437
		flags &= ~EV_ONESHOT;
438
		fnmo->rate_lim_cur_interval = fnmo->kfnm->s.rate_limit_time_max;
439
	}
440
	EV_SET(&kev, fnmo->fd, EVFILT_TIMER, flags,
441
	    NOTE_MSECONDS, fnmo->rate_lim_cur_interval, fnmo);
442
	if (-1 == kevent(fnmo->kfnm->fd, &kev, 1, NULL, 0, NULL)) {
443
		fnmo->rate_lim_cur_interval = 0;
444
		return (errno);
445
	}
446
	return (0);
447
}
448
449
/* Return:
450
 * 0 for events that not handled
451
 * 1 for handled = rate limited
452
 * -1 on error.
453
 */
454
static int
455
kq_fnmo_rate_lim_check(kq_fnmo_p fnmo) {
456
	sbintime_t sbt, sbt_now;
457
	struct timespec ts;
458
459
	if (NULL == fnmo)
460
		return (-1);
461
	if (-1 == fnmo->fd ||
462
	    0 == fnmo->kfnm->s.rate_limit_time_init)
463
		return (0);
464
	if (0 != fnmo->rate_lim_cur_interval) {
465
		fnmo->rate_lim_ev_cnt ++; /* Count event, timer is active. */
466
		return (1);
467
	}
468
469
	/* Do we need to enable rate limit? */
470
	if (0 != clock_gettime(CLOCK_MONOTONIC_FAST, &ts))
471
		return (-1);
472
	sbt_now = tstosbt(ts);
473
	sbt = (fnmo->rate_lim_ev_last + fnmo->kfnm->rate_lim_time_init);
474
	fnmo->rate_lim_ev_last = sbt_now;
475
	if (sbt < sbt_now) /* Events rate to low. */
476
		return (0);
477
	/* Try to enable rate limit. */
478
	if (0 != kq_fnmo_rate_lim_shedule_next(fnmo))
479
		return (-1);
480
	/* Ok. */
481
	fnmo->rate_lim_ev_cnt ++;
482
483
	return (1);
484
}
485
486
static void
487
kq_fnmo_clean(kq_fnmo_p fnmo) {
488
489
	if (NULL == fnmo)
490
		return;
491
	if (-1 != fnmo->fd) {
492
		kq_fnmo_rate_lim_stop(fnmo);
493
		close(fnmo->fd);
494
		fnmo->fd = -1;
495
	}
496
	if (0 != fnmo->is_local) { /* Stop monitoring files/dirs. */
497
		file_info_fd_close(fnmo->files, fnmo->files_count);
498
	}
499
	free(fnmo->files);
500
	fnmo->files = NULL;
501
	fnmo->files_count = 0;
502
	fnmo->files_allocated = 0;
503
}
504
505
static void
506
kq_fnmo_free(void *arg) {
507
	kq_fnmo_p fnmo = arg;
508
509
	if (NULL == fnmo)
510
		return;
511
	kq_fnmo_clean(fnmo);
512
	free(fnmo);
513
}
514
515
static kq_fnmo_p
516
kq_fnmo_alloc(kq_fnm_p kfnm, const char *path, void *udata) {
517
	kq_fnmo_p fnmo;
518
519
	if (NULL == kfnm || NULL == path)
520
		return (NULL);
521
	fnmo = zalloc(sizeof(kq_fnmo_t));
522
	if (NULL == fnmo)
523
		return (NULL);
524
	/* Remember args. */
525
	fnmo->path_size = strlcpy(fnmo->path, path, PATH_MAX);
526
	fnmo->name_offset = fnmo->path_size;
527
	fnmo->udata = udata;
528
	fnmo->kfnm = kfnm;
529
530
	return (fnmo);
531
}
532
533
static int
534
kq_fnmo_readdir(kq_fnmo_p fnmo, size_t exp_count) {
535
	int error;
536
	struct dirent *de;
537
	file_info_p tmfi;
538
	readdir_ctx_t rdd;
539
540
	if (NULL == fnmo || 0 == fnmo->is_dir)
541
		return (EINVAL);
542
543
	free(fnmo->files);
544
	fnmo->files = NULL;
545
	fnmo->files_count = 0;
546
	fnmo->files_allocated = 0;
547
	/* Pre allocate. */
548
	if (0 != realloc_items((void**)&fnmo->files,
549
	    sizeof(file_info_t), &fnmo->files_allocated,
550
	    FILES_ALLOC_BLK_SIZE, (exp_count + 1)))
551
		return (ENOMEM);
552
553
	error = readdir_start(fnmo->fd, &fnmo->sb, exp_count, &rdd);
554
	if (0 != error)
555
		return (error);
556
	for (;;) {
557
		if (0 != realloc_items((void**)&fnmo->files,
558
		    sizeof(file_info_t), &fnmo->files_allocated,
559
		    FILES_ALLOC_BLK_SIZE, fnmo->files_count)) {
560
			free(fnmo->files);
561
			fnmo->files = NULL;
562
			fnmo->files_count = 0;
563
			fnmo->files_allocated = 0;
564
			readdir_free(&rdd);
565
			return (ENOMEM);
566
		}
567
		de = &fnmo->files[fnmo->files_count].de; /* Use short name. */
568
		/* Get file name from folder. */
569
		if (0 != readdir_next(&rdd, de))
570
			break;
571
		/* Get file attrs. */
572
		if (0 != fstatat(fnmo->fd, de->d_name,
573
		    &fnmo->files[fnmo->files_count].sb,
574
		    AT_SYMLINK_NOFOLLOW)) {
575
			memset(&fnmo->files[fnmo->files_count].sb, 0x00,
576
			    sizeof(struct stat));
577
		}
578
		fnmo->files[fnmo->files_count].fd = -1;
579
		fnmo->files_count ++;
580
	}
581
	/* Mem compact. */
582
	tmfi = reallocarray(fnmo->files, sizeof(file_info_t), (fnmo->files_count + 1));
583
	if (NULL != tmfi) { /* realloc ok. */
584
		fnmo->files = tmfi;
585
		fnmo->files_allocated = (fnmo->files_count + 1);
586
	}
587
588
	readdir_free(&rdd);
589
590
	return (0); /* OK. */
591
}
592
593
594
static void
595
kq_fnmo_fi_start(kq_fnmo_p fnmo, file_info_p fi) {
596
	struct kevent kev;
597
598
	if (NULL == fnmo || NULL == fi)
599
		return;
600
	fi->fd = openat(fnmo->fd, fi->de.d_name, OPEN_FILE_FLAGS);
601
	if (-1 == fi->fd)
602
		return;
603
	EV_SET(&kev, fi->fd, EVFILT_VNODE,
604
	    (EV_ADD | EV_CLEAR),
605
	    EVFILT_VNODE_SUB_FLAGS, 0, fnmo);
606
	kevent(fnmo->kfnm->fd, &kev, 1, NULL, 0, NULL);
607
}
608
609
static int
610
kq_fnmo_is_fi_monitored(kq_fnmo_p fnmo, file_info_p fi) {
611
612
	if (NULL == fnmo)
613
		return (0);
614
	if (0 == fnmo->is_local ||
615
	    (0 != fnmo->kfnm->s.max_dir_files &&
616
	     fnmo->kfnm->s.max_dir_files < fnmo->files_count))
617
		return (0);
618
	if (NULL != fi &&
619
	    0 == fnmo->kfnm->s.mon_local_subdirs &&
620
	    S_ISDIR(fi->sb.st_mode))
621
		return (0);
622
	return (1);
623
}
624
625
static void
626
kq_fnmo_init(void *arg) {
627
	kq_fnmo_p fnmo = arg;
628
	size_t i;
629
	struct statfs stfs;
630
	struct kevent kev;
631
632
	if (NULL == fnmo)
633
		return;
634
	fnmo->fd = open(fnmo->path, OPEN_FILE_FLAGS);
635
	if (-1 == fnmo->fd)
636
		return;
637
	if (0 != fstat(fnmo->fd, &fnmo->sb))
638
		goto err_out;
639
	
640
	/* Get parent folder name. */
641
	if (S_ISDIR(fnmo->sb.st_mode)) {
642
		fnmo->is_dir = 1;
643
		/* Be sure that folder contain trailing '/'. */
644
		if ('/' != fnmo->path[(fnmo->path_size - 1)]) {
645
			fnmo->path[fnmo->path_size] = '/';
646
			fnmo->path_size ++;
647
			fnmo->path[fnmo->path_size] = 0;
648
		}
649
		/* Skip last '/' for parent dir search. */
650
		fnmo->name_offset = (fnmo->path_size - 1);
651
	}
652
653
	/* Is file system local? */
654
	if (0 != fnmo->is_dir &&
655
	    0 != fnmo->kfnm->s.mon_local_subfiles &&
656
	    0 == fstatfs(fnmo->fd, &stfs)) {
657
		fnmo->is_local = is_fs_local(&stfs, fnmo->kfnm->s.local_fs,
658
		    fnmo->kfnm->s.non_local_fs);
659
	}
660
661
	/* Find parent dir path size. */
662
	while (0 < fnmo->name_offset && '/' != fnmo->path[(fnmo->name_offset - 1)]) {
663
		fnmo->name_offset --;
664
	}
665
666
	/* Dir special processing. */
667
	if (0 != fnmo->is_dir) {
668
		/* Read and remember dir content. */
669
		if (0 != kq_fnmo_readdir(fnmo, 0))
670
			goto err_out;
671
	}
672
	/* Add to kqueue. */
673
	EV_SET(&kev, fnmo->fd, EVFILT_VNODE, (EV_ADD | EV_CLEAR),
674
	    EVFILT_VNODE_FLAGS_ALL, 0, fnmo);
675
	if (-1 == kevent(fnmo->kfnm->fd, &kev, 1, NULL, 0, NULL))
676
		goto err_out;
677
	/* Add monitor sub files/dirs, ignory errors. */
678
	/* Check twice for performance reason. */
679
	if (0 != kq_fnmo_is_fi_monitored(fnmo, NULL)) {
680
		for (i = 0; i < fnmo->files_count; i ++) {
681
			if (0 != kq_fnmo_is_fi_monitored(fnmo, &fnmo->files[i])) {
682
				kq_fnmo_fi_start(fnmo, &fnmo->files[i]);
683
			}
684
		}
685
	}
686
687
	return; /* OK. */
688
689
err_out:
690
	kq_fnmo_clean(fnmo);
691
}
692
693
static void
694
kq_handle_changes(kq_fnm_p kfnm, kq_fnmo_p fnmo) {
695
	size_t i, k, files_count;
696
	file_info_p files;
697
698
	if (NULL == kfnm || NULL == fnmo)
699
		return;
700
	if (0 != fstat(fnmo->fd, &fnmo->sb) ||
701
	    0 == fnmo->sb.st_nlink) {
702
		kq_fnmo_clean(fnmo);
703
		kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_DELETED,
704
		    fnmo->path, "", NULL);
705
		return;
706
	}
707
	if (0 == fnmo->is_dir) {
708
		fnmo->path[fnmo->name_offset] = 0;
709
		kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_CHANGED,
710
		    fnmo->path, (fnmo->path + fnmo->name_offset), NULL);
711
		fnmo->path[fnmo->name_offset] = '/';
712
		return;
713
	}
714
715
	/* Dir processing. */
716
717
	/* Save prev. */
718
	files = fnmo->files;
719
	files_count = fnmo->files_count;
720
	fnmo->files = NULL;
721
	fnmo->files_count = 0;
722
	/* Update dir. */
723
	if (0 != kq_fnmo_readdir(fnmo, files_count)) {
724
		/* Restore prev state on fail. */
725
		fnmo->files = files;
726
		fnmo->files_count = files_count;
727
		return;
728
	}
729
	/* Notify removed first. */
730
	for (i = 0; i < files_count; i ++) {
731
		if (0 != file_info_find_ni(fnmo->files, fnmo->files_count, &files[i], &k)) /* Deleted? */
732
			continue;
733
		if (-1 != files[i].fd) {
734
			close(files[i].fd);
735
			files[i].fd = -1;
736
		}
737
		kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_DELETED,
738
		    fnmo->path, files[i].de.d_name, NULL);
739
	}
740
	/* Notify. */
741
	for (i = 0; i < fnmo->files_count; i ++) {
742
		/* Is new file/folder? */
743
		if (0 == file_info_find_ino(files, files_count, &fnmo->files[i], &k) &&
744
		    0 == file_info_find_name(files, files_count, &fnmo->files[i], &k)) { /* Add new. */
745
			/* Add monitor sub files/dirs, ignory errors. */
746
			if (0 != kq_fnmo_is_fi_monitored(fnmo, &fnmo->files[i])) {
747
				kq_fnmo_fi_start(fnmo, &fnmo->files[i]);
748
			}
749
			kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_CREATED,
750
			    fnmo->path, fnmo->files[i].de.d_name, NULL);
751
			continue;
752
		}
753
		/* Keep file fd. */
754
		fnmo->files[i].fd = files[k].fd;
755
		files[k].fd = -1;
756
		/* Is renamed? */
757
		if (0 == IS_DE_NAME_EQ(&files[k].de, &fnmo->files[i].de)) {
758
			kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_RENAMED,
759
			    fnmo->path, files[k].de.d_name, fnmo->files[i].de.d_name);
760
			continue;
761
		}
762
		/* Is modified? */
763
		if (0 != memcmp(&fnmo->files[i].sb, &files[k].sb, sizeof(struct stat))) {
764
			kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_CHANGED,
765
			    fnmo->path, fnmo->files[i].de.d_name, NULL);
766
			continue;
767
		}
768
		/* Not changed. */
769
	}
770
771
	/* Prevent FD leak die to race conditions.
772
	 * All fd must be -1, check this while debuging.
773
	 */
774
	file_info_fd_close(files, files_count);
775
	free(files);
776
}
777
778
static void
779
kq_handle_rename(kq_fnm_p kfnm, kq_fnmo_p fnmo) {
780
	int up_dir_fd, found = 0;
781
	readdir_ctx_t rdd;
782
	struct dirent de;
783
	struct stat sb;
784
	char old_filename[(MAXNAMLEN + 2)];
785
	size_t old_filename_size;
786
787
	if (NULL == kfnm || NULL == fnmo)
788
		return;
789
	if (0 != fstat(fnmo->fd, &fnmo->sb) ||
790
	    0 == fnmo->sb.st_nlink) {
791
notify_removed:
792
		kq_fnmo_clean(fnmo);
793
		kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_DELETED,
794
		    fnmo->path, "", NULL);
795
		return;
796
	}
797
	/* Save old file name. */
798
	old_filename_size = (fnmo->path_size - fnmo->name_offset - (size_t)fnmo->is_dir);
799
	memcpy(old_filename,
800
	    (fnmo->path + fnmo->name_offset),
801
	    old_filename_size);
802
	old_filename[old_filename_size] = 0;
803
804
	/* Get parent folder name. */
805
	fnmo->path[fnmo->name_offset] = 0;
806
	/* Try to open. */
807
	up_dir_fd = open(fnmo->path, (OPEN_FILE_FLAGS | O_DIRECTORY));
808
	/* Restore '/' after parent folder. */
809
	fnmo->path[fnmo->name_offset] = '/';
810
	if (-1 == up_dir_fd ||
811
	    0 != fstat(up_dir_fd, &sb) ||
812
	    0 != readdir_start(up_dir_fd, &sb, 0, &rdd)) {
813
		close(up_dir_fd);
814
		return;
815
	}
816
	/* Find new name by inode. */
817
	while (0 == readdir_next(&rdd, &de)) {
818
		if (0 == fstatat(up_dir_fd, de.d_name, &sb, AT_SYMLINK_NOFOLLOW) &&
819
		    0 == memcmp(&fnmo->sb, &sb, sizeof(struct stat))) {
820
			found ++;
821
			break;
822
		}
823
	}
824
	close(up_dir_fd);
825
	if (0 == found)
826
		goto notify_removed; /* Not found. */
827
	/* Update name. */
828
	if (PATH_MAX <= (fnmo->name_offset + de.d_namlen))
829
		return; /* Too long. */
830
	memcpy((fnmo->path + fnmo->name_offset), de.d_name, de.d_namlen);
831
	fnmo->path_size = (fnmo->name_offset + de.d_namlen);
832
	/* Add last '/' for dir. */
833
	fnmo->path[fnmo->path_size] = '/';
834
	fnmo->path_size += (size_t)fnmo->is_dir;
835
	fnmo->path[fnmo->path_size] = 0;
836
	/* Notify. */
837
	kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_RENAMED,
838
	    fnmo->path, old_filename, de.d_name);
839
}
840
841
842
static void
843
kq_fnm_delay_call_process(kq_fnm_p kfnm, kq_msg_cb forced_msg_cb) {
844
	ssize_t ios;
845
	kq_fnm_msg_pkt_t msg;
846
847
	for (;;) {
848
		ios = read(kfnm->pfd[0], &msg, sizeof(msg));
849
		if (0 >= ios)
850
			return;
851
		if (sizeof(msg) != ios ||
852
		    KF_MSG_PKT_MAGIC != msg.magic ||
853
		    (((size_t)msg.msg_cb) ^ ((size_t)msg.arg)) != msg.chk_sum)
854
			continue;
855
		if (NULL != forced_msg_cb) {
856
			forced_msg_cb(msg.arg);
857
			continue;
858
		}
859
		if (NULL == msg.msg_cb)
860
			continue;
861
		msg.msg_cb(msg.arg);
862
	}
863
}
864
865
static int
866
kq_fnm_delay_call(kq_fnm_p kfnm, kq_msg_cb msg_cb,
867
    void *arg) {
868
	kq_fnm_msg_pkt_t msg;
869
870
	if (NULL == kfnm || NULL == arg)
871
		return (EINVAL);
872
	msg.magic = KF_MSG_PKT_MAGIC;
873
	msg.msg_cb = msg_cb;
874
	msg.arg = arg;
875
	msg.chk_sum = (((size_t)msg.msg_cb) ^ ((size_t)msg.arg));
876
	if (sizeof(msg) == write(kfnm->pfd[1], &msg, sizeof(msg)))
877
		return (0);
878
	return (errno);
879
}
880
881
882
static void
883
kq_fnm_free_cb(void *arg) {
884
	kq_fnm_p kfnm = arg;
885
886
	if (NULL == kfnm)
887
		return;
888
	close(kfnm->fd);
889
	kfnm->fd = -1;
890
}
891
void
892
kq_fnm_free(kq_fnm_p kfnm) {
893
894
	if (NULL == kfnm)
895
		return;
896
	kq_fnm_delay_call(kfnm, kq_fnm_free_cb, kfnm);
897
	pthread_join(kfnm->tid, NULL);
898
	/* Free all in delay calls queue. */
899
	close(kfnm->pfd[1]);
900
	kq_fnm_delay_call_process(kfnm, kq_fnmo_free);
901
	close(kfnm->pfd[0]);
902
	free(kfnm);
903
}
904
905
kq_fnm_p
906
kq_fnm_create(kq_file_mon_settings_p s, kfnm_event_handler_cb cb_func) {
907
	kq_fnm_p kfnm;
908
	struct kevent kev;
909
910
	if (NULL == s || NULL == cb_func)
911
		return (NULL);
912
	kfnm = zalloc(sizeof(kq_fnm_t));
913
	if (NULL == kfnm)
914
		return (NULL);
915
	kfnm->fd = kqueue();
916
	if (-1 == kfnm->fd)
917
		goto err_out;
918
	if (-1 == pipe2(kfnm->pfd, O_NONBLOCK))
919
		goto err_out;
920
	kfnm->cb_func = cb_func;
921
	memcpy(&kfnm->s, s, sizeof(kq_file_mon_settings_t));
922
	if (kfnm->s.rate_limit_time_init >= kfnm->s.rate_limit_time_max) {
923
		kfnm->s.rate_limit_time_max = kfnm->s.rate_limit_time_init;
924
	}
925
	if (0 == kfnm->s.rate_limit_time_mul) {
926
		kfnm->s.rate_limit_time_mul ++;
927
	}
928
	kfnm->rate_lim_time_init = mstosbt(kfnm->s.rate_limit_time_init);
929
930
	EV_SET(&kev, kfnm->pfd[0], EVFILT_READ, EV_ADD, 0, 0, NULL);
931
	if (-1 == kevent(kfnm->fd, &kev, 1, NULL, 0, NULL))
932
		goto err_out;
933
	if (0 != pthread_create(&kfnm->tid, NULL,
934
	    kq_fnm_proccess_events_proc, kfnm))
935
		goto err_out;
936
937
	return (kfnm);
938
939
err_out:
940
	kq_fnm_free(kfnm);
941
	return (NULL);
942
}
943
944
kq_fnmo_p
945
kq_fnm_add(kq_fnm_p kfnm, const char *path, void *udata) {
946
	int error;
947
	kq_fnmo_p fnmo;
948
949
	if (NULL == kfnm || NULL == path)
950
		return (NULL);
951
	fnmo = kq_fnmo_alloc(kfnm, path, udata);
952
	if (NULL == fnmo)
953
		return (NULL);
954
	/* Shedule delay call to init. */
955
	error = kq_fnm_delay_call(kfnm, kq_fnmo_init, fnmo);
956
	if (0 != error) { /* Error, do no directly init to avoid freezes. */
957
		kq_fnmo_free(fnmo);
958
		return (NULL);
959
	}
960
	return (fnmo);
961
}
962
963
void
964
kq_fnm_del(kq_fnm_p kfnm, kq_fnmo_p fnmo) {
965
	int error;
966
967
	if (NULL == kfnm || NULL == fnmo)
968
		return;
969
	/* Cancel notifications. */
970
	kq_fnmo_rate_lim_stop(fnmo);
971
	close(fnmo->fd);
972
	fnmo->fd = -1;
973
	/* Shedule delay call to free. */
974
	error = kq_fnm_delay_call(kfnm, kq_fnmo_free, fnmo);
975
	if (0 == error)
976
		return;
977
	/* Error, free directly. */
978
	kq_fnmo_free(fnmo);
979
}
980
981
982
static void
983
kq_fnm_proccess_event(kq_fnm_p kfnm, struct kevent *kev) {
984
	kq_fnmo_p fnmo;
985
	file_info_p fi;
986
	size_t i;
987
	int is_rate_lim_checked = 0;
988
	struct stat sb;
989
990
	if (NULL == kfnm || NULL == kev)
991
		return;
992
993
	/* Handle delay calls. */
994
	if (kev->ident == (uintptr_t)kfnm->pfd[0]) {
995
		if (kev->filter == EVFILT_READ) {
996
			kq_fnm_delay_call_process(kfnm, NULL);
997
		}
998
		return;
999
	}
1000
1001
	if (0 == kev->udata)
1002
		return; /* No associated data, skip. */
1003
	fnmo = (kq_fnmo_p)kev->udata;
1004
1005
	/* FS delayed notifications. */
1006
	if (EVFILT_TIMER == kev->filter) {
1007
		if (0 == fnmo->rate_lim_ev_cnt) {
1008
			/* No delayed events, disable rate limit polling. */
1009
			kq_fnmo_rate_lim_stop(fnmo);
1010
			return;
1011
		}
1012
		fnmo->rate_lim_ev_cnt = 0; /* Reset counter. */
1013
		kq_fnmo_rate_lim_shedule_next(fnmo);
1014
		kq_handle_changes(kfnm, fnmo);
1015
		return;
1016
	}
1017
1018
	/* FS notifications. */
1019
	if (EVFILT_VNODE != kev->filter)
1020
		return; /* Unknown event, skip. */
1021
	/* Subdir/file */
1022
	if (kev->ident != (uintptr_t)fnmo->fd) {
1023
		/* Is files changes rate limited? */
1024
		if (1 == kq_fnmo_rate_lim_check(fnmo))
1025
			return;
1026
		is_rate_lim_checked ++;
1027
		/* Try to find file and check it, without call kq_handle_changes(). */
1028
		fi = NULL;
1029
		for (i = 0; i < fnmo->files_count; i ++) {
1030
			if (kev->ident != (uintptr_t)fnmo->files[i].fd)
1031
				continue;
1032
			fi = &fnmo->files[i];
1033
			break;
1034
		}
1035
		if (NULL != fi) {
1036
			/* Get file attrs. */
1037
			if (0 != fstat(fi->fd, &sb)) {
1038
				memset(&sb, 0x00, sizeof(struct stat));
1039
			}
1040
			/* Is modified? */
1041
			if (0 != memcmp(&fi->sb, &sb, sizeof(struct stat))) {
1042
				memcpy(&fi->sb, &sb, sizeof(struct stat));
1043
				kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_CHANGED,
1044
				    fnmo->path, fi->de.d_name, NULL);
1045
				return;
1046
			}
1047
		}
1048
		/* fd not found or changes not found, rescan dir. */
1049
		kev->fflags = NOTE_WRITE;
1050
	}
1051
	/* Monitored object. */
1052
	/* All flags from EVFILT_VNODE_FLAGS_ALL must be handled here. */
1053
	if (EV_ERROR & kev->flags) {
1054
		kev->fflags |= NOTE_REVOKE; /* Treat error as unmount. */
1055
	}
1056
	if (NOTE_RENAME & kev->fflags) {
1057
		kq_handle_rename(kfnm, fnmo);
1058
	}
1059
	if ((NOTE_WRITE | NOTE_EXTEND | NOTE_ATTRIB | NOTE_LINK | NOTE_CLOSE_WRITE) & kev->fflags) {
1060
		/* Only count changes, do not prevent NOTE_DELETE event handling. */
1061
		if (0 == is_rate_lim_checked &&
1062
		    1 != kq_fnmo_rate_lim_check(fnmo)) {
1063
			kq_handle_changes(kfnm, fnmo);
1064
		}
1065
	}
1066
	if ((NOTE_DELETE | NOTE_REVOKE) & kev->fflags) {
1067
		/* No report about childs. */
1068
		kq_fnmo_clean(fnmo);
1069
		kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_DELETED,
1070
		    fnmo->path, "", NULL);
1071
	}
1072
}
1073
1074
void *
1075
kq_fnm_proccess_events_proc(void *data) {
1076
	struct kevent kev;
1077
	kq_fnm_p kfnm = data;
1078
1079
	if (NULL == kfnm)
1080
		return (NULL);
1081
	/* Get and proccess events, no wait. */
1082
	while (0 < kevent(kfnm->fd, NULL, 0, &kev, 1, NULL)) {
1083
		kq_fnm_proccess_event(kfnm, &kev);
1084
	}
1085
	return (NULL);
1086
}
(-)devel/glib20/files/kqueue_fnm.h (+74 lines)
Line 0 Link Here
1
/*-
2
 * Copyright (c) 2016 - 2018 Rozhuk Ivan <rozhuk.im@gmail.com>
3
 * All rights reserved.
4
 *
5
 * Redistribution and use in source and binary forms, with or without
6
 * modification, are permitted provided that the following conditions
7
 * are met:
8
 * 1. Redistributions of source code must retain the above copyright
9
 *    notice, this list of conditions and the following disclaimer.
10
 * 2. Redistributions in binary form must reproduce the above copyright
11
 *    notice, this list of conditions and the following disclaimer in the
12
 *    documentation and/or other materials provided with the distribution.
13
 *
14
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
15
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24
 * SUCH DAMAGE.
25
 *
26
 * Author: Rozhuk Ivan <rozhuk.im@gmail.com>
27
 *
28
 */
29
30
#ifndef __KQUEUE_FILE_NOTIFY_MONITOR_H__
31
#define __KQUEUE_FILE_NOTIFY_MONITOR_H__
32
33
#include <sys/param.h>
34
#include <sys/types.h>
35
#include <inttypes.h>
36
37
38
typedef struct kq_file_nonify_monitor_s		*kq_fnm_p;
39
typedef struct kq_file_nmon_obj_s		*kq_fnmo_p;
40
41
typedef void (*kfnm_event_handler_cb)(kq_fnm_p kfnm,
42
					kq_fnmo_p fnmo, void *udata,
43
					uint32_t event,
44
					const char *base,
45
					const char *filename,
46
					const char *new_filename);
47
#define KF_EVENT_NOT_CHANGED	0 /* Internal use. */
48
#define KF_EVENT_CREATED	1
49
#define KF_EVENT_DELETED	2
50
#define KF_EVENT_RENAMED	3
51
#define KF_EVENT_CHANGED	4
52
53
54
typedef struct kq_file_nonify_mon_settings_s {
55
	uint32_t	rate_limit_time_init;	/* Fire events for dir min interval, mseconds. */
56
	uint32_t	rate_limit_time_max;	/* Fire events for dir max interval, mseconds. */
57
	uint32_t	rate_limit_time_mul;	/* Fire events time increment, mseconds. */
58
	size_t		max_dir_files;		/* If dir contain more than n files - do not mon files changes. */
59
	int		mon_local_subfiles;	/* Enable monitoring files changes on local file systems. */
60
	int		mon_local_subdirs;	/* Also mon for subdirs changes . */
61
	const char 	**local_fs;		/* NULL terminated fs names list that threat as local. Keep utill kq_fnm_free() return. */
62
	const char	**non_local_fs;		/* NULL terminated fs names list that threat as not local. Keep utill kq_fnm_free() return. */
63
} kq_file_mon_settings_t, *kq_file_mon_settings_p;
64
65
kq_fnm_p	kq_fnm_create(kq_file_mon_settings_p s,
66
		    kfnm_event_handler_cb cb_func);
67
void		kq_fnm_free(kq_fnm_p kfnm);
68
69
kq_fnmo_p	kq_fnm_add(kq_fnm_p kfnm,
70
			    const char *path, void *udata);
71
void		kq_fnm_del(kq_fnm_p kfnm, kq_fnmo_p fnmo);
72
73
74
#endif /* __KQUEUE_FILE_NOTIFY_MONITOR_H__ */

Return to bug 214338