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-59 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=	DEBUG MANPAGES NLS
51
OPTIONS_DEFINE=	DEBUG FAM_ALTBACKEND MANPAGES NLS
52
OPTIONS_DEFAULT=	MANPAGES
52
OPTIONS_DEFAULT=	MANPAGES
53
OPTIONS_SUB=	yes
53
OPTIONS_SUB=	yes
54
54
55
DEBUG_CONFIGURE_ON=	--enable-debug=yes
55
DEBUG_CONFIGURE_ON=	--enable-debug=yes
56
56
57
FAM_ALTBACKEND_DESC=	Alternate file monitor backend
58
57
MANPAGES_BUILD_DEPENDS=		docbook-xml>4.1.2:textproc/docbook-xml \
59
MANPAGES_BUILD_DEPENDS=		docbook-xml>4.1.2:textproc/docbook-xml \
58
				docbook-xsl>0:textproc/docbook-xsl
60
				docbook-xsl>0:textproc/docbook-xsl
59
MANPAGES_USE=			GNOME=libxslt:build
61
MANPAGES_USE=			GNOME=libxslt:build
Lines 93-98 Link Here
93
		s|-Werror|| ; \
95
		s|-Werror|| ; \
94
		s|#define HAVE_SYS_INOTIFY_H 1||' ${WRKSRC}/configure
96
		s|#define HAVE_SYS_INOTIFY_H 1||' ${WRKSRC}/configure
95
97
98
post-patch-FAM_ALTBACKEND-on:
99
	@${REINPLACE_CMD} -e '/^libkqueue_la_OBJECTS =/s|$$(am_libkqueue_la_OBJECTS)|libkqueue_la-gkqueuefilemonitor.lo libkqueue_la-kqueue-helper.lo|' \
100
		${WRKSRC}/gio/kqueue/Makefile.in
101
	@${CP} -f ${FILESDIR}/gkqueuefilemonitor.c ${WRKSRC}/gio/kqueue/gkqueuefilemonitor.c
102
	@${CP} -f ${FILESDIR}/kqueue_fnm.c ${WRKSRC}/gio/kqueue/kqueue-helper.c
103
	@${CP} ${FILESDIR}/kqueue_fnm.h ${WRKSRC}/gio/kqueue/kqueue_fnm.h
104
96
do-build-MANPAGES-on:
105
do-build-MANPAGES-on:
97
.for m in glib gio gobject
106
.for m in glib gio gobject
98
. for file in ${${m}_MAN}
107
. for file in ${${m}_MAN}
(-)devel/glib20/files/gkqueuefilemonitor.c (+224 lines)
Line 0 Link Here
1
/*-
2
 * Copyright (c) 2016 - 2019 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
#ifdef __clang__
42
#pragma clang diagnostic pop
43
#endif
44
45
/* Defaults. */
46
#ifndef KQUEUE_MON_RATE_LIMIT_TIME_INIT
47
#	define KQUEUE_MON_RATE_LIMIT_TIME_INIT		1000
48
#endif
49
50
#ifndef KQUEUE_MON_RATE_LIMIT_TIME_MAX
51
#	define KQUEUE_MON_RATE_LIMIT_TIME_MAX		8000
52
#endif
53
#ifndef KQUEUE_MON_RATE_LIMIT_TIME_MUL
54
#	define KQUEUE_MON_RATE_LIMIT_TIME_MUL		2
55
#endif
56
#ifndef KQUEUE_MON_MAX_DIR_FILES
57
#	define KQUEUE_MON_MAX_DIR_FILES			128
58
#endif
59
#ifndef KQUEUE_MON_LOCAL_SUBFILES
60
#	define KQUEUE_MON_LOCAL_SUBFILES		1
61
#endif
62
#ifndef KQUEUE_MON_LOCAL_SUBDIRS
63
#	define KQUEUE_MON_LOCAL_SUBDIRS			0
64
#endif
65
66
67
static GMutex			kqueue_lock;
68
static volatile kq_fnm_p	kqueue_fnm = NULL;
69
/* Exclude from file changes monitoring, watch only for dirs. */
70
static const char *non_local_fs[] = {
71
	"fusefs.sshfs",
72
	NULL
73
};
74
75
#define G_TYPE_KQUEUE_FILE_MONITOR      (g_kqueue_file_monitor_get_type())
76
#define G_KQUEUE_FILE_MONITOR(inst)     (G_TYPE_CHECK_INSTANCE_CAST((inst), \
77
					 G_TYPE_KQUEUE_FILE_MONITOR, GKqueueFileMonitor))
78
79
typedef GLocalFileMonitorClass	GKqueueFileMonitorClass;
80
81
typedef struct {
82
	GLocalFileMonitor	parent_instance;
83
	kq_fnme_p		fnme;
84
} GKqueueFileMonitor;
85
86
GType g_kqueue_file_monitor_get_type(void);
87
G_DEFINE_TYPE_WITH_CODE (GKqueueFileMonitor, g_kqueue_file_monitor, G_TYPE_LOCAL_FILE_MONITOR,
88
       g_io_extension_point_implement(G_LOCAL_FILE_MONITOR_EXTENSION_POINT_NAME,
89
               g_define_type_id,
90
               "kqueue",
91
               10))
92
93
94
static void
95
kqueue_event_handler(kq_fnm_p kfnm,
96
    kq_fnme_p fnme, void *udata, uint32_t event,
97
    const char *base, const char *filename, const char *new_filename) {
98
	static const uint32_t kfnm_to_glib_map[] = {
99
		0,				/* KF_EVENT_NOT_CHANGED */
100
		G_FILE_MONITOR_EVENT_CREATED,	/* KF_EVENT_CREATED */
101
		G_FILE_MONITOR_EVENT_DELETED,	/* KF_EVENT_DELETED */
102
		G_FILE_MONITOR_EVENT_RENAMED,	/* KF_EVENT_RENAMED */
103
		G_FILE_MONITOR_EVENT_CHANGED	/* KF_EVENT_CHANGED */
104
	};
105
106
	if (NULL == kfnm || NULL == filename || 0 == filename[0] ||
107
	    strchr(filename, '/') ||
108
	    KF_EVENT_CREATED > event ||
109
	    KF_EVENT_CHANGED < event)
110
		return;
111
112
	g_file_monitor_source_handle_event(udata,
113
	    kfnm_to_glib_map[event],
114
	    filename, new_filename, NULL,
115
	    g_get_monotonic_time());
116
}
117
118
static gboolean
119
g_kqueue_file_monitor_is_supported(void) {
120
	kq_file_mon_settings_t kfms;
121
122
	if (NULL != kqueue_fnm)
123
		return (TRUE);
124
	/* Init only once. */
125
	g_mutex_lock(&kqueue_lock);
126
	if (NULL != kqueue_fnm) {
127
		g_mutex_unlock(&kqueue_lock);
128
		return (TRUE); /* Initialized while wait lock. */
129
	}
130
131
	memset(&kfms, 0x00, sizeof(kq_file_mon_settings_t));
132
	kfms.rate_limit_time_init = KQUEUE_MON_RATE_LIMIT_TIME_INIT;
133
	kfms.rate_limit_time_max = KQUEUE_MON_RATE_LIMIT_TIME_MAX;
134
	kfms.rate_limit_time_mul = KQUEUE_MON_RATE_LIMIT_TIME_MUL;
135
	kfms.max_dir_files = KQUEUE_MON_MAX_DIR_FILES;
136
	kfms.mon_local_subfiles = KQUEUE_MON_LOCAL_SUBFILES;
137
	kfms.mon_local_subdirs = KQUEUE_MON_LOCAL_SUBDIRS;
138
	kfms.local_fs = NULL;
139
	kfms.non_local_fs = non_local_fs;
140
141
	kqueue_fnm = kq_fnm_create(&kfms, kqueue_event_handler);
142
	if (NULL == kqueue_fnm) {
143
		g_mutex_unlock(&kqueue_lock);
144
		return (FALSE); /* Init fail. */
145
	}
146
	g_mutex_unlock(&kqueue_lock);
147
148
	return (TRUE);
149
}
150
151
static gboolean
152
g_kqueue_file_monitor_cancel(GFileMonitor *monitor) {
153
	GKqueueFileMonitor *gffm = G_KQUEUE_FILE_MONITOR(monitor);
154
155
	kq_fnm_del(kqueue_fnm, gffm->fnme);
156
	gffm->fnme = NULL;
157
158
	return (TRUE);
159
}
160
161
static void
162
g_kqueue_file_monitor_finalize(GObject *object) {
163
	//GKqueueFileMonitor *gffm = G_KQUEUE_FILE_MONITOR(object);
164
165
	//g_mutex_lock(&kqueue_lock);
166
	//kq_fnm_free(kqueue_fnm);
167
	//kqueue_fnm = NULL;
168
	//g_mutex_unlock(&kqueue_lock);
169
	//G_OBJECT_CLASS(g_kqueue_file_monitor_parent_class)->finalize(object);
170
}
171
172
static void
173
g_kqueue_file_monitor_start(GLocalFileMonitor *local_monitor,
174
    const gchar *dirname, const gchar *basename,
175
    const gchar *filename, GFileMonitorSource *source) {
176
	GKqueueFileMonitor *gffm = G_KQUEUE_FILE_MONITOR(local_monitor);
177
178
	g_assert(NULL != kqueue_fnm);
179
	//g_source_ref((GSource*)source);
180
181
	if (NULL == filename) {
182
		filename = dirname;
183
	}
184
	gffm->fnme = kq_fnm_add(kqueue_fnm, filename, source);
185
}
186
187
static void
188
g_kqueue_file_monitor_init(GKqueueFileMonitor *monitor) {
189
190
}
191
192
static void
193
g_kqueue_file_monitor_class_init(GKqueueFileMonitorClass *class) {
194
	GObjectClass *gobject_class = G_OBJECT_CLASS(class);
195
	GFileMonitorClass *file_monitor_class = G_FILE_MONITOR_CLASS(class);
196
197
	class->is_supported = g_kqueue_file_monitor_is_supported;
198
	class->start = g_kqueue_file_monitor_start;
199
	class->mount_notify = TRUE; /* TODO: ??? */
200
	file_monitor_class->cancel = g_kqueue_file_monitor_cancel;
201
	gobject_class->finalize = g_kqueue_file_monitor_finalize;
202
}
203
204
static void
205
g_kqueue_file_monitor_class_finalize(GKqueueFileMonitorClass *class) {
206
207
}
208
209
void
210
g_io_module_load(GIOModule *module) {
211
212
	g_type_module_use(G_TYPE_MODULE(module));
213
214
	g_io_extension_point_implement(G_LOCAL_FILE_MONITOR_EXTENSION_POINT_NAME,
215
	    G_TYPE_KQUEUE_FILE_MONITOR, "kqueue", 10);
216
	g_io_extension_point_implement(G_NFS_FILE_MONITOR_EXTENSION_POINT_NAME,
217
	    G_TYPE_KQUEUE_FILE_MONITOR, "kqueue", 10);
218
}
219
220
void
221
g_io_module_unload(GIOModule *module) {
222
223
	g_assert_not_reached();
224
}
(-)devel/glib20/files/kqueue_fnm.c (+1238 lines)
Line 0 Link Here
1
/*-
2
 * Copyright (c) 2016 - 2019 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
#include <sys/queue.h>
38
39
#include <inttypes.h>
40
#include <stdlib.h> /* malloc, exit */
41
#include <unistd.h> /* close, write, sysconf */
42
#include <string.h> /* bcopy, bzero, memcpy, memmove, memset, strerror... */
43
#include <dirent.h> /* opendir, readdir */
44
#include <errno.h>
45
#include <pthread.h>
46
#include <glib.h>
47
48
#include "kqueue_fnm.h"
49
50
51
/* Preallocate items count. */
52
#ifndef FILES_ALLOC_BLK_SIZE
53
#	define FILES_ALLOC_BLK_SIZE	32
54
#endif
55
56
57
typedef struct readdir_context_s {
58
	int		fd;
59
	uint8_t		*buf;
60
	size_t		buf_size;
61
	size_t		buf_used;
62
	size_t		buf_pos;
63
} readdir_ctx_t, *readdir_ctx_p;
64
65
66
typedef struct file_info_s { /* Directory file. */
67
	int		fd;		/* For notify kqueue(). */
68
	struct dirent 	de;		/* d_reclen used for action. */
69
	struct stat	sb;
70
} file_info_t, *file_info_p;
71
72
73
typedef struct kq_file_nonify_monitor_obj_s	*kq_fnmo_p;
74
75
typedef struct kq_file_nonify_monitor_entry_s {
76
	TAILQ_ENTRY(kq_file_nonify_monitor_entry_s) next;
77
	kq_fnmo_p	fnmo;
78
	void		*udata;
79
	volatile int	enabled;
80
} kq_fnme_t;
81
82
TAILQ_HEAD(kq_fnme_head, kq_file_nonify_monitor_entry_s);
83
84
typedef struct kq_file_nonify_monitor_obj_s {
85
	int		fd;		/* For notify kqueue(). */
86
	int		is_dir;
87
	int		is_local;	/* Is file system local. */
88
	struct stat	sb;
89
	char		path[(PATH_MAX + 2)];
90
	size_t		path_size;
91
	size_t		name_offset;	/* Parent path size. */
92
	uint32_t	rate_lim_cur_interval;	/* From rate_limit_time_init to rate_limit_time_max. 0 disabled. */
93
	size_t		rate_lim_ev_cnt;	/* Events count then rate_lim_cur_interval != 0 since last report. */
94
	sbintime_t	rate_lim_ev_last;	/* Last event time. */
95
	void		*udata;
96
	kq_fnm_p	kfnm;
97
	struct kq_fnme_head entry_head;
98
	/* For dir. */
99
	file_info_p	files;
100
	volatile size_t	files_count;
101
	size_t		files_allocated;
102
} kq_fnmo_t;
103
104
105
typedef struct kq_file_nonify_monitor_s {
106
	int		fd;		/* kqueue() fd. */
107
	int		pfd[2];		/* pipe queue specific. */
108
	GHashTable	*fnmo_cache;
109
	kfnm_event_handler_cb cb_func;	/* Callback on dir/file change. */
110
	kq_file_mon_settings_t s;
111
	sbintime_t	rate_lim_time_init; /* rate_limit_time_init */
112
	pthread_t	tid;
113
} kq_fnm_t;
114
115
116
typedef void (*kq_msg_cb)(void *arg);
117
118
typedef struct kq_file_mon_msg_pkt_s {
119
	size_t		magic;
120
	kq_msg_cb	msg_cb;
121
	void		*arg;
122
	size_t		chk_sum;
123
} kq_fnm_msg_pkt_t, *kq_fnm_msg_pkt_p;
124
125
#define KF_MSG_PKT_MAGIC	0xffddaa00
126
127
128
#ifndef O_NOATIME
129
#	define O_NOATIME	0
130
#endif
131
#ifndef O_EVTONLY
132
#	define O_EVTONLY	O_RDONLY
133
#endif
134
#define OPEN_FILE_FLAGS		(O_EVTONLY | O_NONBLOCK | O_NOFOLLOW | O_NOATIME | O_CLOEXEC)
135
136
#ifndef NOTE_CLOSE_WRITE
137
#	define NOTE_CLOSE_WRITE	0
138
#endif
139
#define EVFILT_VNODE_SUB_FLAGS	(NOTE_WRITE |				\
140
				NOTE_EXTEND |				\
141
				NOTE_ATTRIB |				\
142
				NOTE_LINK |				\
143
				NOTE_CLOSE_WRITE)
144
145
#define EVFILT_VNODE_FLAGS_ALL	(NOTE_DELETE |				\
146
				EVFILT_VNODE_SUB_FLAGS |		\
147
				NOTE_RENAME |				\
148
				NOTE_REVOKE)
149
150
#ifndef _GENERIC_DIRSIZ
151
#	define _GENERIC_DIRSIZ(__de)	MIN((__de)->d_reclen, sizeof(struct dirent))
152
#endif
153
154
#define IS_NAME_DOTS(__name)	('.' == (__name)[0] &&			\
155
				 ('\0' == (__name)[1] || 		\
156
				  ('.' == (__name)[1] && '\0' == (__name)[2])))
157
#define IS_DE_NAME_EQ(__de1, __de2)  (0 == mem_cmpn((__de1)->d_name,	\
158
						    (__de1)->d_namlen,	\
159
						    (__de2)->d_name,	\
160
						    (__de2)->d_namlen))
161
#define zalloc(__size)		calloc(1, (__size))
162
163
#if (!defined(HAVE_REALLOCARRAY) && (!defined(__FreeBSD_version) || __FreeBSD_version < 1100000))
164
#	define reallocarray(__mem, __size, __count)	realloc((__mem), ((__size) * (__count)))
165
#endif
166
167
/* To not depend from compiler version. */
168
#define MSTOSBT(__ms)		(sbintime_t)(((int64_t)__ms * (((uint64_t)1 << 63) / 500)) >> 32)
169
170
#ifndef TAILQ_FOREACH_SAFE
171
#define	TAILQ_FOREACH_SAFE(var, head, field, tvar)			\
172
	for ((var) = TAILQ_FIRST((head));				\
173
	    (var) && ((tvar) = TAILQ_NEXT((var), field), 1);		\
174
	    (var) = (tvar))
175
#endif
176
177
#ifndef CLOCK_MONOTONIC_FAST
178
#	define CLOCK_MONOTONIC_FAST	CLOCK_MONOTONIC
179
#endif
180
181
182
void 	*kq_fnm_proccess_events_proc(void *data);
183
184
static inline int
185
mem_cmpn(const void *buf1, const size_t buf1_size,
186
    const void *buf2, const size_t buf2_size) {
187
188
	if (buf1_size != buf2_size)
189
		return (((buf1_size > buf2_size) ? 127 : -127));
190
	if (0 == buf1_size || buf1 == buf2)
191
		return (0);
192
	if (NULL == buf1)
193
		return (-127);
194
	if (NULL == buf2)
195
		return (127);
196
	return (memcmp(buf1, buf2, buf1_size));
197
}
198
199
static int
200
realloc_items(void **items, const size_t item_size,
201
    size_t *allocated, const size_t alloc_blk_cnt, const size_t count) {
202
	size_t allocated_prev, allocated_new;
203
	uint8_t *items_new;
204
205
	if (NULL == items || 0 == item_size || NULL == allocated ||
206
	    0 == alloc_blk_cnt)
207
		return (EINVAL);
208
	allocated_prev = (*allocated);
209
	if (NULL != (*items) &&
210
	    allocated_prev > count &&
211
	    allocated_prev <= (count + alloc_blk_cnt))
212
		return (0);
213
	allocated_new = (((count / alloc_blk_cnt) + 1) * alloc_blk_cnt);
214
	items_new = (uint8_t*)reallocarray((*items), item_size, allocated_new);
215
	if (NULL == items_new) /* Realloc fail! */
216
		return (ENOMEM);
217
218
	if (allocated_new > allocated_prev) { /* Init new mem. */
219
		memset((items_new + (allocated_prev * item_size)), 0x00,
220
		    ((allocated_new - allocated_prev) * item_size));
221
	}
222
	(*items) = items_new;
223
	(*allocated) = allocated_new;
224
225
	return (0);
226
}
227
228
229
static int
230
readdir_start(int fd, struct stat *sb, size_t exp_count, readdir_ctx_p rdd) {
231
	size_t buf_size;
232
233
	if (-1 == fd || NULL == sb || NULL == rdd)
234
		return (EINVAL);
235
	if (-1 == lseek(fd, 0, SEEK_SET))
236
		return (errno);
237
	/* Calculate buf size for getdents(). */
238
	buf_size = MAX((size_t)sb->st_size, (exp_count * sizeof(struct dirent)));
239
	if (0 == buf_size) {
240
		buf_size = (16 * PAGE_SIZE);
241
	}
242
	/* Make buf size well aligned. */
243
	if (0 != sb->st_blksize) {
244
		if (powerof2(sb->st_blksize)) {
245
			buf_size = roundup2(buf_size, sb->st_blksize);
246
		} else {
247
			buf_size = roundup(buf_size, sb->st_blksize);
248
		}
249
	} else {
250
		buf_size = round_page(buf_size);
251
	}
252
	/* Init. */
253
	memset(rdd, 0x00, sizeof(readdir_ctx_t));
254
	rdd->buf = malloc(buf_size);
255
	if (NULL == rdd->buf)
256
		return (ENOMEM);
257
	rdd->buf_size = buf_size;
258
	rdd->fd = fd;
259
260
	return (0);
261
}
262
263
static void
264
readdir_free(readdir_ctx_p rdd) {
265
266
	if (NULL == rdd || NULL == rdd->buf)
267
		return;
268
	free(rdd->buf);
269
	memset(rdd, 0x00, sizeof(readdir_ctx_t));
270
}
271
272
static int
273
readdir_next(readdir_ctx_p rdd, struct dirent *de) {
274
	int error = 0;
275
	ssize_t ios;
276
	uint8_t *ptr;
277
278
	if (NULL == rdd || NULL == rdd->buf || NULL == de)
279
		return (EINVAL);
280
281
	for (;;) {
282
		if (rdd->buf_used <= rdd->buf_pos) {
283
			/* Called once if buf size calculated ok. */
284
			ios = getdents(rdd->fd, (char*)rdd->buf, rdd->buf_size);
285
			if (-1 == ios) {
286
				error = errno;
287
				break;
288
			}
289
			if (0 == ios) {
290
				error = ESPIPE; /* EOF. */
291
				break;
292
			}
293
			rdd->buf_used = (size_t)ios;
294
			rdd->buf_pos = 0;
295
		}
296
		/* Keep data aligned. */
297
		ptr = (rdd->buf + rdd->buf_pos);
298
		memcpy(de, ptr, (sizeof(struct dirent) - sizeof(de->d_name)));
299
		if (0 == de->d_reclen) {
300
			error = ESPIPE; /* EOF. */
301
			break;
302
		}
303
		rdd->buf_pos += de->d_reclen;
304
#ifdef DT_WHT
305
		if (DT_WHT == de->d_type)
306
			continue;
307
#endif
308
		memcpy(de, ptr, _GENERIC_DIRSIZ(de));
309
		if (!IS_NAME_DOTS(de->d_name))
310
			return (0); /* OK. */
311
	}
312
313
	/* Err or no more files. */
314
	readdir_free(rdd);
315
316
	return (error);
317
}
318
319
320
static int
321
file_info_find_ni(file_info_p files, size_t files_count,
322
    file_info_p fi, size_t *idx) {
323
	size_t i;
324
	mode_t st_ftype;
325
326
	if (NULL == files || NULL == fi || NULL == idx)
327
		return (0);
328
	st_ftype = (S_IFMT & fi->sb.st_mode);
329
	for (i = 0; i < files_count; i ++) {
330
		if ((S_IFMT & files[i].sb.st_mode) != st_ftype)
331
			continue;
332
		if ((fi->sb.st_ino != files[i].sb.st_ino ||
333
		     fi->de.d_fileno != files[i].de.d_fileno) &&
334
		    0 == IS_DE_NAME_EQ(&fi->de, &files[i].de))
335
			continue;
336
		(*idx) = i;
337
		return (1);
338
	}
339
	(*idx) = files_count;
340
	return (0);
341
}
342
343
static int
344
file_info_find_ino(file_info_p files, size_t files_count,
345
    file_info_p fi, size_t *idx) {
346
	size_t i;
347
	mode_t st_ftype;
348
349
	if (NULL == files || NULL == fi || NULL == idx)
350
		return (0);
351
	st_ftype = (S_IFMT & fi->sb.st_mode);
352
	for (i = 0; i < files_count; i ++) {
353
		if ((S_IFMT & files[i].sb.st_mode) != st_ftype ||
354
		    fi->sb.st_ino != files[i].sb.st_ino ||
355
		    fi->de.d_fileno != files[i].de.d_fileno)
356
			continue;
357
		(*idx) = i;
358
		return (1);
359
	}
360
	(*idx) = files_count;
361
	return (0);
362
}
363
364
static int
365
file_info_find_name(file_info_p files, size_t files_count,
366
    file_info_p fi, size_t *idx) {
367
	size_t i;
368
	mode_t st_ftype;
369
370
	if (NULL == files || NULL == fi || NULL == idx)
371
		return (0);
372
	st_ftype = (S_IFMT & fi->sb.st_mode);
373
	for (i = 0; i < files_count; i ++) {
374
		if ((S_IFMT & files[i].sb.st_mode) != st_ftype ||
375
		    0 == IS_DE_NAME_EQ(&fi->de, &files[i].de))
376
			continue;
377
		(*idx) = i;
378
		return (1);
379
	}
380
	(*idx) = files_count;
381
	return (0);
382
}
383
384
static void
385
file_info_fd_close(file_info_p files, size_t files_count) {
386
	size_t i;
387
388
	if (NULL == files || 0 == files_count)
389
		return;
390
	for (i = 0; i < files_count; i ++) {
391
		if (-1 == files[i].fd)
392
			continue;
393
		close(files[i].fd);
394
		files[i].fd = -1;
395
	}
396
}
397
398
399
static int
400
is_fs_local(struct statfs *stfs, const char **local_fs, const char **non_local_fs) {
401
	size_t i;
402
403
	if (NULL == stfs)
404
		return (0);
405
	if (NULL != local_fs) {
406
		for (i = 0; NULL != local_fs[i]; i ++) {
407
			if (0 == strncmp(stfs->f_fstypename, local_fs[i],
408
			    sizeof(stfs->f_fstypename)))
409
				return (1);
410
		}
411
	}
412
	if (0 == (MNT_LOCAL & stfs->f_flags))
413
		return (0);
414
	if (NULL != non_local_fs) {
415
		for (i = 0; NULL != non_local_fs[i]; i ++) {
416
			if (0 == strncmp(stfs->f_fstypename, non_local_fs[i],
417
			    sizeof(stfs->f_fstypename)))
418
				return (0);
419
		}
420
	}
421
	return (1);
422
}
423
424
425
static void
426
kq_fnmo_rate_lim_stop(kq_fnmo_p fnmo) {
427
	struct kevent kev;
428
429
	if (NULL == fnmo || -1 == fnmo->fd || 0 == fnmo->rate_lim_cur_interval)
430
		return;
431
	fnmo->rate_lim_cur_interval = 0;
432
	fnmo->rate_lim_ev_cnt = 0;
433
	EV_SET(&kev, fnmo->fd, EVFILT_TIMER, EV_DELETE, 0, 0, NULL);
434
	kevent(fnmo->kfnm->fd, &kev, 1, NULL, 0, NULL);
435
}
436
437
static int
438
kq_fnmo_rate_lim_shedule_next(kq_fnmo_p fnmo) {
439
	u_short flags = (EV_ADD | EV_CLEAR | EV_ONESHOT);
440
	struct kevent kev;
441
442
	if (NULL == fnmo || -1 == fnmo->fd || 0 == fnmo->kfnm->s.rate_limit_time_init)
443
		return (EINVAL);
444
	if (0 == fnmo->rate_lim_cur_interval) { /* First call. */
445
		fnmo->rate_lim_cur_interval = fnmo->kfnm->s.rate_limit_time_init;
446
	} else {
447
		if (fnmo->rate_lim_cur_interval == fnmo->kfnm->s.rate_limit_time_max)
448
			return (0); /* No need to modify timer. */
449
		/* Increase rate limit interval. */
450
		fnmo->rate_lim_cur_interval *= fnmo->kfnm->s.rate_limit_time_mul;
451
	}
452
	if (fnmo->rate_lim_cur_interval >= fnmo->kfnm->s.rate_limit_time_max) {
453
		/* Check upper limit and shedule periodic timer with upper rate limit time. */
454
		flags &= ~EV_ONESHOT;
455
		fnmo->rate_lim_cur_interval = fnmo->kfnm->s.rate_limit_time_max;
456
	}
457
	EV_SET(&kev, fnmo->fd, EVFILT_TIMER, flags,
458
	    NOTE_MSECONDS, fnmo->rate_lim_cur_interval, fnmo);
459
	if (-1 == kevent(fnmo->kfnm->fd, &kev, 1, NULL, 0, NULL)) {
460
		fnmo->rate_lim_cur_interval = 0;
461
		return (errno);
462
	}
463
	if (0 != (EV_ERROR & kev.flags)) {
464
		fnmo->rate_lim_cur_interval = 0;
465
		return ((int)kev.data);
466
	}
467
	return (0);
468
}
469
470
/* Return:
471
 * 0 for events that not handled
472
 * 1 for handled = rate limited
473
 * -1 on error.
474
 */
475
static int
476
kq_fnmo_rate_lim_check(kq_fnmo_p fnmo) {
477
	sbintime_t sbt, sbt_now;
478
	struct timespec ts;
479
480
	if (NULL == fnmo)
481
		return (-1);
482
	if (-1 == fnmo->fd ||
483
	    0 == fnmo->kfnm->s.rate_limit_time_init)
484
		return (0);
485
	if (0 != fnmo->rate_lim_cur_interval) {
486
		fnmo->rate_lim_ev_cnt ++; /* Count event, timer is active. */
487
		return (1);
488
	}
489
490
	/* Do we need to enable rate limit? */
491
	if (0 != clock_gettime(CLOCK_MONOTONIC_FAST, &ts))
492
		return (-1);
493
	sbt_now = tstosbt(ts);
494
	sbt = (fnmo->rate_lim_ev_last + fnmo->kfnm->rate_lim_time_init);
495
	fnmo->rate_lim_ev_last = sbt_now;
496
	if (sbt < sbt_now) /* Events rate to low. */
497
		return (0);
498
	/* Try to enable rate limit. */
499
	if (0 != kq_fnmo_rate_lim_shedule_next(fnmo))
500
		return (-1);
501
	/* Ok. */
502
	fnmo->rate_lim_ev_cnt ++;
503
504
	return (1);
505
}
506
507
static void
508
kq_fnmo_clean(kq_fnmo_p fnmo) {
509
510
	if (NULL == fnmo)
511
		return;
512
	if (-1 != fnmo->fd) {
513
		kq_fnmo_rate_lim_stop(fnmo);
514
		close(fnmo->fd);
515
		fnmo->fd = -1;
516
	}
517
	if (0 != fnmo->is_local) { /* Stop monitoring files/dirs. */
518
		file_info_fd_close(fnmo->files, fnmo->files_count);
519
	}
520
	free(fnmo->files);
521
	fnmo->files = NULL;
522
	fnmo->files_count = 0;
523
	fnmo->files_allocated = 0;
524
}
525
526
static void
527
kq_fnmo_free(kq_fnmo_p fnmo, const int remove_from_cache) {
528
529
	if (NULL == fnmo)
530
		return;
531
	kq_fnmo_clean(fnmo);
532
	if (0 != remove_from_cache &&
533
	    NULL != fnmo->kfnm &&
534
	    g_hash_table_lookup(fnmo->kfnm->fnmo_cache, fnmo->path) == fnmo) {
535
		g_hash_table_remove(fnmo->kfnm->fnmo_cache, fnmo->path);
536
	}
537
	free(fnmo);
538
}
539
540
static kq_fnmo_p
541
kq_fnmo_alloc(kq_fnm_p kfnm, const char *path, kq_fnme_p fnme) {
542
	kq_fnmo_p fnmo;
543
544
	if (NULL == kfnm || NULL == path)
545
		return (NULL);
546
	fnmo = zalloc(sizeof(kq_fnmo_t));
547
	if (NULL == fnmo)
548
		return (NULL);
549
	/* Remember args. */
550
	fnmo->path_size = strlcpy(fnmo->path, path, PATH_MAX);
551
	/* Make sure that no trailing '/'. */
552
	while (1 < fnmo->path_size && '/' == fnmo->path[(fnmo->path_size - 1)]) {
553
		fnmo->path_size --;
554
		fnmo->path[fnmo->path_size] = 0;
555
	}
556
	fnmo->name_offset = fnmo->path_size;
557
	fnmo->kfnm = kfnm;
558
	TAILQ_INIT(&fnmo->entry_head);
559
	if (NULL != fnme) {
560
		TAILQ_INSERT_HEAD(&fnmo->entry_head, fnme, next);
561
	}
562
563
	return (fnmo);
564
}
565
566
static void
567
kq_fnmo_cb_func_call(kq_fnmo_p fnmo, uint32_t event,
568
    const char *base, const char *filename, const char *new_filename) {
569
	kq_fnm_p kfnm;
570
	kq_fnme_p fnme;
571
572
	if (NULL == fnmo)
573
		return;
574
	kfnm = fnmo->kfnm;
575
	TAILQ_FOREACH(fnme, &fnmo->entry_head, next) {
576
		if (0 == fnme->enabled)
577
			continue;
578
		kfnm->cb_func(kfnm, fnme, fnme->udata, event,
579
		    base, filename, new_filename);
580
	}
581
582
}
583
584
static int
585
kq_fnmo_readdir(kq_fnmo_p fnmo, size_t exp_count) {
586
	int error;
587
	struct dirent *de;
588
	file_info_p tmfi;
589
	readdir_ctx_t rdd;
590
591
	if (NULL == fnmo || 0 == fnmo->is_dir)
592
		return (EINVAL);
593
594
	free(fnmo->files);
595
	fnmo->files = NULL;
596
	fnmo->files_count = 0;
597
	fnmo->files_allocated = 0;
598
	/* Pre allocate. */
599
	if (0 != realloc_items((void**)&fnmo->files,
600
	    sizeof(file_info_t), &fnmo->files_allocated,
601
	    FILES_ALLOC_BLK_SIZE, (exp_count + 1)))
602
		return (ENOMEM);
603
604
	error = readdir_start(fnmo->fd, &fnmo->sb, exp_count, &rdd);
605
	if (0 != error)
606
		return (error);
607
	for (;;) {
608
		if (0 != realloc_items((void**)&fnmo->files,
609
		    sizeof(file_info_t), &fnmo->files_allocated,
610
		    FILES_ALLOC_BLK_SIZE, fnmo->files_count)) {
611
			free(fnmo->files);
612
			fnmo->files = NULL;
613
			fnmo->files_count = 0;
614
			fnmo->files_allocated = 0;
615
			readdir_free(&rdd);
616
			return (ENOMEM);
617
		}
618
		de = &fnmo->files[fnmo->files_count].de; /* Use short name. */
619
		/* Get file name from folder. */
620
		if (0 != readdir_next(&rdd, de))
621
			break;
622
		/* Get file attrs. */
623
		if (0 != fstatat(fnmo->fd, de->d_name,
624
		    &fnmo->files[fnmo->files_count].sb,
625
		    AT_SYMLINK_NOFOLLOW)) {
626
			memset(&fnmo->files[fnmo->files_count].sb, 0x00,
627
			    sizeof(struct stat));
628
		}
629
		fnmo->files[fnmo->files_count].fd = -1;
630
		fnmo->files_count ++;
631
	}
632
	/* Mem compact. */
633
	tmfi = reallocarray(fnmo->files, sizeof(file_info_t), (fnmo->files_count + 1));
634
	if (NULL != tmfi) { /* realloc ok. */
635
		fnmo->files = tmfi;
636
		fnmo->files_allocated = (fnmo->files_count + 1);
637
	}
638
639
	readdir_free(&rdd);
640
641
	return (0); /* OK. */
642
}
643
644
645
static void
646
kq_fnmo_fi_start(kq_fnmo_p fnmo, file_info_p fi) {
647
	struct kevent kev;
648
649
	if (NULL == fnmo || NULL == fi)
650
		return;
651
	fi->fd = openat(fnmo->fd, fi->de.d_name, OPEN_FILE_FLAGS);
652
	if (-1 == fi->fd)
653
		return;
654
	EV_SET(&kev, fi->fd, EVFILT_VNODE,
655
	    (EV_ADD | EV_CLEAR),
656
	    EVFILT_VNODE_SUB_FLAGS, 0, fnmo);
657
	kevent(fnmo->kfnm->fd, &kev, 1, NULL, 0, NULL);
658
}
659
660
static int
661
kq_fnmo_is_fi_monitored(kq_fnmo_p fnmo, file_info_p fi) {
662
663
	if (NULL == fnmo)
664
		return (0);
665
	if (0 == fnmo->is_local ||
666
	    (0 != fnmo->kfnm->s.max_dir_files &&
667
	     fnmo->kfnm->s.max_dir_files < fnmo->files_count))
668
		return (0);
669
	if (NULL != fi &&
670
	    0 == fnmo->kfnm->s.mon_local_subdirs &&
671
	    S_ISDIR(fi->sb.st_mode))
672
		return (0);
673
	return (1);
674
}
675
676
static int
677
kq_fnmo_init(kq_fnmo_p fnmo, const int read_dir) {
678
	int error;
679
	size_t i;
680
	struct statfs stfs;
681
	struct kevent kev;
682
683
	if (NULL == fnmo)
684
		return (EINVAL);
685
686
	fnmo->fd = open(fnmo->path, OPEN_FILE_FLAGS);
687
	if (-1 == fnmo->fd) {
688
		error = errno;
689
		goto err_out;
690
	}
691
	if (0 != fstat(fnmo->fd, &fnmo->sb)) {
692
		error = errno;
693
		goto err_out;
694
	}
695
696
	/* Get parent folder name. */
697
	if (S_ISDIR(fnmo->sb.st_mode)) {
698
		fnmo->is_dir = 1;
699
	}
700
	while (0 < fnmo->name_offset && '/' != fnmo->path[(fnmo->name_offset - 1)]) {
701
		fnmo->name_offset --;
702
	}
703
704
	/* Is file system local? */
705
	if (0 != fnmo->is_dir &&
706
	    0 != fnmo->kfnm->s.mon_local_subfiles &&
707
	    0 == fstatfs(fnmo->fd, &stfs)) {
708
		fnmo->is_local = is_fs_local(&stfs, fnmo->kfnm->s.local_fs,
709
		    fnmo->kfnm->s.non_local_fs);
710
	}
711
712
	/* Dir special processing. */
713
	if (0 != fnmo->is_dir &&
714
	    0 != read_dir) {
715
		/* Read and remember dir content. */
716
		error = kq_fnmo_readdir(fnmo, 0);
717
		if (0 != error)
718
			goto err_out;
719
	}
720
	/* Add to kqueue. */
721
	EV_SET(&kev, fnmo->fd, EVFILT_VNODE, (EV_ADD | EV_CLEAR),
722
	    EVFILT_VNODE_FLAGS_ALL, 0, fnmo);
723
	if (-1 == kevent(fnmo->kfnm->fd, &kev, 1, NULL, 0, NULL) ||
724
	    0 != (EV_ERROR & kev.flags)) {
725
		error = errno;
726
		goto err_out;
727
	}
728
	/* Add monitor sub files/dirs, ignory errors. */
729
	/* Check twice for performance reason. */
730
	if (0 != kq_fnmo_is_fi_monitored(fnmo, NULL)) {
731
		for (i = 0; i < fnmo->files_count; i ++) {
732
			if (0 != kq_fnmo_is_fi_monitored(fnmo, &fnmo->files[i])) {
733
				kq_fnmo_fi_start(fnmo, &fnmo->files[i]);
734
			}
735
		}
736
	}
737
738
	return (0); /* OK. */
739
740
err_out:
741
	kq_fnmo_clean(fnmo);
742
	return (error);
743
}
744
745
static void
746
kq_fnme_init_cb(void *arg) {
747
	kq_fnme_p fnme = arg;
748
	kq_fnmo_p fnmo;
749
	kq_fnm_p kfnm;
750
751
	if (NULL == fnme || NULL == fnme->fnmo)
752
		return;
753
	kfnm = fnme->fnmo->kfnm;
754
	/* Is in cache? */
755
	fnmo = g_hash_table_lookup(kfnm->fnmo_cache, fnme->fnmo->path);
756
	if (NULL == fnmo) {
757
		/* Init and add to cache. */
758
		g_hash_table_insert(kfnm->fnmo_cache,
759
		    fnme->fnmo->path, fnme->fnmo);
760
		kq_fnmo_init(fnme->fnmo, 1);
761
		return;
762
	}
763
	/* Found in cache, use it. */
764
	TAILQ_REMOVE(&fnme->fnmo->entry_head, fnme, next);
765
	kq_fnmo_free(fnme->fnmo, 0); /* Prevent remove from cache. */
766
	fnme->fnmo = fnmo;
767
	TAILQ_INSERT_HEAD(&fnmo->entry_head, fnme, next);
768
}
769
770
static void
771
kq_fnme_free(kq_fnme_p fnme, const int free_parent) {
772
773
	if (NULL == fnme)
774
		return;
775
	if (NULL != fnme->fnmo) {
776
		TAILQ_REMOVE(&fnme->fnmo->entry_head, fnme, next);
777
		if (0 != free_parent &&
778
		    TAILQ_EMPTY(&fnme->fnmo->entry_head)) {
779
			kq_fnmo_free(fnme->fnmo, 1); /* Remove frome cache on free. */
780
			fnme->fnmo = NULL;
781
		}
782
	}
783
	free(fnme);
784
}
785
786
static void
787
kq_fnme_free_cb(void *arg) {
788
789
	kq_fnme_free((kq_fnme_p)arg, 1);
790
}
791
792
793
static void
794
kq_handle_notify_removed(kq_fnmo_p fnmo) {
795
	size_t i;
796
797
	if (NULL == fnmo)
798
		return;
799
800
	if (0 != fnmo->is_dir) {
801
		/* Notify removed files first. */
802
		for (i = 0; i < fnmo->files_count; i ++) {
803
			kq_fnmo_cb_func_call(fnmo, KF_EVENT_DELETED,
804
			    fnmo->path, fnmo->files[i].de.d_name, NULL);
805
		}
806
	}
807
	fnmo->path[fnmo->name_offset - 1] = 0;
808
	kq_fnmo_cb_func_call(fnmo, KF_EVENT_DELETED, fnmo->path,
809
	    (fnmo->path + fnmo->name_offset), NULL);
810
	fnmo->path[fnmo->name_offset - 1] = '/';
811
	kq_fnmo_clean(fnmo);
812
}
813
814
static void
815
kq_handle_changes(kq_fnmo_p fnmo) {
816
	size_t i, k, files_count;
817
	file_info_p files;
818
819
	if (NULL == fnmo)
820
		return;
821
	if (0 != fstat(fnmo->fd, &fnmo->sb) ||
822
	    0 == fnmo->sb.st_nlink) {
823
		kq_handle_notify_removed(fnmo);
824
		return;
825
	}
826
	if (0 == fnmo->is_dir) {
827
		fnmo->path[fnmo->name_offset - 1] = 0;
828
		kq_fnmo_cb_func_call(fnmo, KF_EVENT_CHANGED, fnmo->path,
829
		    (fnmo->path + fnmo->name_offset), NULL);
830
		fnmo->path[fnmo->name_offset - 1] = '/';
831
		return;
832
	}
833
834
	/* Dir processing. */
835
836
	/* Save prev. */
837
	files = fnmo->files;
838
	files_count = fnmo->files_count;
839
	fnmo->files = NULL;
840
	fnmo->files_count = 0;
841
	/* Update dir. */
842
	if (0 != kq_fnmo_readdir(fnmo, files_count)) {
843
		/* Restore prev state on fail. */
844
		fnmo->files = files;
845
		fnmo->files_count = files_count;
846
		return;
847
	}
848
	/* Notify removed first. */
849
	for (i = 0; i < files_count; i ++) {
850
		if (0 != file_info_find_ni(fnmo->files, fnmo->files_count, &files[i], &k)) /* Deleted? */
851
			continue;
852
		if (-1 != files[i].fd) {
853
			close(files[i].fd);
854
			files[i].fd = -1;
855
		}
856
		kq_fnmo_cb_func_call(fnmo, KF_EVENT_DELETED, fnmo->path,
857
		    files[i].de.d_name, NULL);
858
	}
859
	/* Notify. */
860
	for (i = 0; i < fnmo->files_count; i ++) {
861
		/* Is new file/folder? */
862
		if (0 == file_info_find_ino(files, files_count, &fnmo->files[i], &k) &&
863
		    0 == file_info_find_name(files, files_count, &fnmo->files[i], &k)) { /* Add new. */
864
			/* Add monitor sub files/dirs, ignory errors. */
865
			if (0 != kq_fnmo_is_fi_monitored(fnmo, &fnmo->files[i])) {
866
				kq_fnmo_fi_start(fnmo, &fnmo->files[i]);
867
			}
868
			kq_fnmo_cb_func_call(fnmo, KF_EVENT_CREATED,
869
			    fnmo->path, fnmo->files[i].de.d_name, NULL);
870
			continue;
871
		}
872
		/* Keep file fd. */
873
		fnmo->files[i].fd = files[k].fd;
874
		files[k].fd = -1;
875
		/* Is renamed? */
876
		if (0 == IS_DE_NAME_EQ(&files[k].de, &fnmo->files[i].de)) {
877
			kq_fnmo_cb_func_call(fnmo, KF_EVENT_RENAMED,
878
			    fnmo->path, files[k].de.d_name,
879
			    fnmo->files[i].de.d_name);
880
			continue;
881
		}
882
		/* Is modified? */
883
		if (0 != memcmp(&fnmo->files[i].sb, &files[k].sb, sizeof(struct stat))) {
884
			kq_fnmo_cb_func_call(fnmo, KF_EVENT_CHANGED,
885
			    fnmo->path, fnmo->files[i].de.d_name, NULL);
886
			continue;
887
		}
888
		/* Not changed. */
889
	}
890
891
	/* Prevent FD leak die to race conditions.
892
	 * All fd must be -1, check this while debuging.
893
	 */
894
	file_info_fd_close(files, files_count);
895
	free(files);
896
}
897
898
static void
899
kq_handle_rename(kq_fnmo_p fnmo) {
900
	int up_dir_fd, found = 0;
901
	readdir_ctx_t rdd;
902
	struct dirent de;
903
	struct stat sb;
904
	char old_filename[(MAXNAMLEN + 2)];
905
	size_t old_filename_size;
906
907
	if (NULL == fnmo)
908
		return;
909
	if (0 != fstat(fnmo->fd, &fnmo->sb) ||
910
	    0 == fnmo->sb.st_nlink) {
911
notify_removed:
912
		kq_handle_notify_removed(fnmo);
913
		return;
914
	}
915
	/* Save old file name. */
916
	old_filename_size = (fnmo->path_size - fnmo->name_offset);
917
	memcpy(old_filename,
918
	    (fnmo->path + fnmo->name_offset),
919
	    old_filename_size);
920
	old_filename[old_filename_size] = 0;
921
922
	/* Get parent folder name. */
923
	fnmo->path[fnmo->name_offset] = 0;
924
	/* Try to open. */
925
	up_dir_fd = open(fnmo->path, (OPEN_FILE_FLAGS | O_DIRECTORY));
926
	/* Restore '/' after parent folder. */
927
	fnmo->path[fnmo->name_offset] = '/';
928
	if (-1 == up_dir_fd ||
929
	    0 != fstat(up_dir_fd, &sb) ||
930
	    0 != readdir_start(up_dir_fd, &sb, 0, &rdd)) {
931
		close(up_dir_fd);
932
		return;
933
	}
934
	/* Find new name by inode. */
935
	while (0 == readdir_next(&rdd, &de)) {
936
		if (0 == fstatat(up_dir_fd, de.d_name, &sb, AT_SYMLINK_NOFOLLOW) &&
937
		    0 == memcmp(&fnmo->sb, &sb, sizeof(struct stat))) {
938
			found ++;
939
			break;
940
		}
941
	}
942
	close(up_dir_fd);
943
	if (0 == found)
944
		goto notify_removed; /* Not found. */
945
	/* Update name. */
946
	if (PATH_MAX <= (fnmo->name_offset + de.d_namlen))
947
		return; /* Too long. */
948
	memcpy((fnmo->path + fnmo->name_offset), de.d_name, de.d_namlen);
949
	fnmo->path_size = (fnmo->name_offset + de.d_namlen);
950
	fnmo->path[fnmo->path_size] = 0;
951
	/* Notify. */
952
	kq_fnmo_cb_func_call(fnmo, KF_EVENT_RENAMED, fnmo->path,
953
	    old_filename, de.d_name);
954
}
955
956
957
static void
958
kq_fnm_delay_call_process(kq_fnm_p kfnm, kq_msg_cb forced_msg_cb) {
959
	ssize_t ios;
960
	kq_fnm_msg_pkt_t msg;
961
962
	for (;;) {
963
		ios = read(kfnm->pfd[0], &msg, sizeof(msg));
964
		if (0 >= ios)
965
			return;
966
		if (sizeof(msg) != ios ||
967
		    KF_MSG_PKT_MAGIC != msg.magic ||
968
		    (((size_t)msg.msg_cb) ^ ((size_t)msg.arg)) != msg.chk_sum)
969
			continue;
970
		if (NULL != forced_msg_cb) {
971
			forced_msg_cb(msg.arg);
972
			continue;
973
		}
974
		if (NULL == msg.msg_cb)
975
			continue;
976
		msg.msg_cb(msg.arg);
977
	}
978
}
979
980
static int
981
kq_fnm_delay_call(kq_fnm_p kfnm, kq_msg_cb msg_cb,
982
    void *arg) {
983
	kq_fnm_msg_pkt_t msg;
984
985
	if (NULL == kfnm || NULL == arg)
986
		return (EINVAL);
987
	msg.magic = KF_MSG_PKT_MAGIC;
988
	msg.msg_cb = msg_cb;
989
	msg.arg = arg;
990
	msg.chk_sum = (((size_t)msg.msg_cb) ^ ((size_t)msg.arg));
991
	if (sizeof(msg) == write(kfnm->pfd[1], &msg, sizeof(msg)))
992
		return (0);
993
	return (errno);
994
}
995
996
997
static void
998
kq_fnm_free_cb(void *arg) {
999
	kq_fnm_p kfnm = arg;
1000
1001
	if (NULL == kfnm)
1002
		return;
1003
	close(kfnm->fd);
1004
	kfnm->fd = -1;
1005
}
1006
void
1007
kq_fnm_free(kq_fnm_p kfnm) {
1008
	GHashTableIter iter;
1009
	gpointer key;
1010
	kq_fnmo_p fnmo;
1011
	kq_fnme_p fnme, fnme_temp;
1012
1013
	if (NULL == kfnm)
1014
		return;
1015
	kq_fnm_delay_call(kfnm, kq_fnm_free_cb, kfnm);
1016
	pthread_join(kfnm->tid, NULL);
1017
	/* Free all in delay calls queue. */
1018
	close(kfnm->pfd[1]);
1019
	kq_fnm_delay_call_process(kfnm, kq_fnme_free_cb);
1020
	close(kfnm->pfd[0]);
1021
	/* Remove all objects. */
1022
	g_hash_table_iter_init(&iter, kfnm->fnmo_cache);
1023
	while (g_hash_table_iter_next(&iter, &key, (gpointer)&fnmo)) {
1024
		TAILQ_FOREACH_SAFE(fnme, &fnmo->entry_head, next, fnme_temp) {
1025
			kq_fnme_free(fnme, 0); /* Do not free fnmo here. */
1026
		}
1027
		g_hash_table_iter_remove(&iter); /* Remove from cache here. */
1028
		kq_fnmo_free(fnmo, 0); /* Prevent remove from cache. */
1029
	}
1030
	g_hash_table_destroy(kfnm->fnmo_cache);
1031
1032
	free(kfnm);
1033
}
1034
1035
kq_fnm_p
1036
kq_fnm_create(kq_file_mon_settings_p s, kfnm_event_handler_cb cb_func) {
1037
	kq_fnm_p kfnm;
1038
	struct kevent kev;
1039
1040
	if (NULL == s || NULL == cb_func)
1041
		return (NULL);
1042
	kfnm = zalloc(sizeof(kq_fnm_t));
1043
	if (NULL == kfnm)
1044
		return (NULL);
1045
	kfnm->fd = kqueue();
1046
	if (-1 == kfnm->fd)
1047
		goto err_out;
1048
	if (-1 == pipe2(kfnm->pfd, O_NONBLOCK))
1049
		goto err_out;
1050
	kfnm->fnmo_cache = g_hash_table_new(g_str_hash, g_str_equal);
1051
	kfnm->cb_func = cb_func;
1052
	memcpy(&kfnm->s, s, sizeof(kq_file_mon_settings_t));
1053
	if (kfnm->s.rate_limit_time_init >= kfnm->s.rate_limit_time_max) {
1054
		kfnm->s.rate_limit_time_max = kfnm->s.rate_limit_time_init;
1055
	}
1056
	if (0 == kfnm->s.rate_limit_time_mul) {
1057
		kfnm->s.rate_limit_time_mul ++;
1058
	}
1059
	kfnm->rate_lim_time_init = MSTOSBT(kfnm->s.rate_limit_time_init);
1060
1061
	EV_SET(&kev, kfnm->pfd[0], EVFILT_READ, EV_ADD, 0, 0, NULL);
1062
	if (-1 == kevent(kfnm->fd, &kev, 1, NULL, 0, NULL) ||
1063
	    0 != (EV_ERROR & kev.flags))
1064
		goto err_out;
1065
	if (0 != pthread_create(&kfnm->tid, NULL,
1066
	    kq_fnm_proccess_events_proc, kfnm))
1067
		goto err_out;
1068
1069
	return (kfnm);
1070
1071
err_out:
1072
	kq_fnm_free(kfnm);
1073
	return (NULL);
1074
}
1075
1076
kq_fnme_p
1077
kq_fnm_add(kq_fnm_p kfnm, const char *path, void *udata) {
1078
	int error;
1079
	kq_fnme_p fnme;
1080
1081
	if (NULL == kfnm || NULL == path)
1082
		return (NULL);
1083
	fnme = zalloc(sizeof(kq_fnmo_t));
1084
	if (NULL == fnme)
1085
		return (NULL);
1086
	fnme->fnmo = kq_fnmo_alloc(kfnm, path, fnme);
1087
	if (NULL == fnme->fnmo)
1088
		goto err_out;
1089
	fnme->udata = udata;
1090
	fnme->enabled = 1;
1091
	/* Shedule delay call to init. */
1092
	error = kq_fnm_delay_call(kfnm, kq_fnme_init_cb, fnme);
1093
	if (0 != error) { /* Error, do no directly init to avoid freezes. */
1094
		kq_fnmo_free(fnme->fnmo, 0); /* Prevent remove from cache. */
1095
err_out:
1096
		kq_fnme_free(fnme, 0); /* Do not free fnmo here. */
1097
		return (NULL);
1098
	}
1099
	return (fnme);
1100
}
1101
1102
void
1103
kq_fnm_del(kq_fnm_p kfnm, kq_fnme_p fnme) {
1104
	int error;
1105
1106
	if (NULL == kfnm || NULL == fnme)
1107
		return;
1108
	/* Cancel notifications. */
1109
	//kq_fnmo_rate_lim_stop(fnmo);
1110
	//close(fnmo->fd);
1111
	//fnmo->fd = -1;
1112
	fnme->enabled = 0;
1113
	/* Shedule delay call to free. */
1114
	error = kq_fnm_delay_call(kfnm, kq_fnme_free_cb, fnme);
1115
	if (0 == error)
1116
		return;
1117
	/* Error, free directly. */
1118
	kq_fnme_free(fnme, 1); /* Also free fnmo. */
1119
}
1120
1121
1122
static void
1123
kq_fnm_proccess_event(kq_fnm_p kfnm, struct kevent *kev) {
1124
	int error;
1125
	kq_fnmo_p fnmo;
1126
	file_info_p fi;
1127
	size_t i;
1128
	int is_rate_lim_checked = 0;
1129
	struct stat sb;
1130
1131
	if (NULL == kfnm || NULL == kev)
1132
		return;
1133
1134
	/* Handle delay calls. */
1135
	if (kev->ident == (uintptr_t)kfnm->pfd[0]) {
1136
		if (kev->filter == EVFILT_READ) {
1137
			kq_fnm_delay_call_process(kfnm, NULL);
1138
		}
1139
		return;
1140
	}
1141
1142
	if (0 == kev->udata)
1143
		return; /* No associated data, skip. */
1144
	fnmo = (kq_fnmo_p)kev->udata;
1145
1146
	/* FS delayed notifications. */
1147
	if (EVFILT_TIMER == kev->filter) {
1148
		if (0 == fnmo->rate_lim_ev_cnt) {
1149
			/* No delayed events, disable rate limit polling. */
1150
			kq_fnmo_rate_lim_stop(fnmo);
1151
			return;
1152
		}
1153
		fnmo->rate_lim_ev_cnt = 0; /* Reset counter. */
1154
		kq_fnmo_rate_lim_shedule_next(fnmo);
1155
		kq_handle_changes(fnmo);
1156
		return;
1157
	}
1158
1159
	/* FS notifications. */
1160
	if (EVFILT_VNODE != kev->filter)
1161
		return; /* Unknown event, skip. */
1162
	/* Subdir/file */
1163
	if (kev->ident != (uintptr_t)fnmo->fd) {
1164
		/* Is files changes rate limited? */
1165
		if (1 == kq_fnmo_rate_lim_check(fnmo))
1166
			return;
1167
		is_rate_lim_checked ++;
1168
		/* Try to find file and check it, without call kq_handle_changes(). */
1169
		fi = NULL;
1170
		for (i = 0; i < fnmo->files_count; i ++) {
1171
			if (kev->ident != (uintptr_t)fnmo->files[i].fd)
1172
				continue;
1173
			fi = &fnmo->files[i];
1174
			break;
1175
		}
1176
		if (NULL != fi) {
1177
			/* Get file attrs. */
1178
			if (0 != fstat(fi->fd, &sb)) {
1179
				memset(&sb, 0x00, sizeof(struct stat));
1180
			}
1181
			/* Is modified? */
1182
			if (0 != memcmp(&fi->sb, &sb, sizeof(struct stat))) {
1183
				memcpy(&fi->sb, &sb, sizeof(struct stat));
1184
				kq_fnmo_cb_func_call(fnmo, KF_EVENT_CHANGED,
1185
				    fnmo->path, fi->de.d_name, NULL);
1186
				return;
1187
			}
1188
		}
1189
		/* fd not found or changes not found, rescan dir. */
1190
		kev->fflags = NOTE_WRITE;
1191
	}
1192
	/* Monitored object. */
1193
	/* All flags from EVFILT_VNODE_FLAGS_ALL must be handled here. */
1194
	if (EV_ERROR & kev->flags) {
1195
		kev->fflags |= NOTE_REVOKE; /* Treat error as unmount. */
1196
	}
1197
	if (NOTE_RENAME & kev->fflags) {
1198
		kq_handle_rename(fnmo);
1199
	}
1200
	if ((NOTE_WRITE | NOTE_EXTEND | NOTE_ATTRIB | NOTE_LINK | NOTE_CLOSE_WRITE) & kev->fflags) {
1201
		/* Only count changes, do not prevent NOTE_DELETE event handling. */
1202
		if (0 == is_rate_lim_checked &&
1203
		    1 != kq_fnmo_rate_lim_check(fnmo)) {
1204
			kq_handle_changes(fnmo);
1205
		}
1206
	}
1207
	if ((NOTE_DELETE | NOTE_REVOKE) & kev->fflags) {
1208
		/* No report about childs. */
1209
		if (0 != fnmo->is_dir) {
1210
			/* Try to reopen mount point after unmount. */
1211
			error = kq_fnmo_init(fnmo, 0);
1212
			if (0 == error) {
1213
				/* This will reread dir and notify about
1214
				 * deleted and new files. */
1215
				kq_handle_changes(fnmo);
1216
			}
1217
		} else {
1218
			error = -1;
1219
		}
1220
		if (0 != error) {
1221
			kq_handle_notify_removed(fnmo);
1222
		}
1223
	}
1224
}
1225
1226
void *
1227
kq_fnm_proccess_events_proc(void *data) {
1228
	struct kevent kev;
1229
	kq_fnm_p kfnm = data;
1230
1231
	if (NULL == kfnm)
1232
		return (NULL);
1233
	/* Get and proccess events, no wait. */
1234
	while (0 < kevent(kfnm->fd, NULL, 0, &kev, 1, NULL)) {
1235
		kq_fnm_proccess_event(kfnm, &kev);
1236
	}
1237
	return (NULL);
1238
}
(-)devel/glib20/files/kqueue_fnm.h (+74 lines)
Line 0 Link Here
1
/*-
2
 * Copyright (c) 2016 - 2019 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_nonify_monitor_entry_s	*kq_fnme_p;
40
41
typedef void (*kfnm_event_handler_cb)(kq_fnm_p kfnm,
42
					kq_fnme_p fnme, 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_fnme_p	kq_fnm_add(kq_fnm_p kfnm,
70
			    const char *path, void *udata);
71
void		kq_fnm_del(kq_fnm_p kfnm, kq_fnme_p fnme);
72
73
74
#endif /* __KQUEUE_FILE_NOTIFY_MONITOR_H__ */

Return to bug 214338