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

Collapse All | Expand All

(-)devel/glib20/Makefile (-1 / +31 lines)
Lines 28-33 Link Here
28
# (wchar_t is used by glibmm, rawtherapee triggered this)
28
# (wchar_t is used by glibmm, rawtherapee triggered this)
29
USES+=		compiler:c11 gettext gmake gnome iconv:wchar_t libtool \
29
USES+=		compiler:c11 gettext gmake gnome iconv:wchar_t libtool \
30
		localbase pathfix perl5 pkgconfig python shebangfix
30
		localbase pathfix perl5 pkgconfig python shebangfix
31
USES+=	autoreconf
31
USE_PYTHON=	py3kplist
32
USE_PYTHON=	py3kplist
32
CONFIGURE_ARGS=	--disable-gtk-doc --with-html-dir=${PREFIX}/share/doc \
33
CONFIGURE_ARGS=	--disable-gtk-doc --with-html-dir=${PREFIX}/share/doc \
33
		--disable-man --without-xml-catalog \
34
		--disable-man --without-xml-catalog \
Lines 48-54 Link Here
48
		glib-compile-resources.1 gresource.1 gdbus-codegen.1
49
		glib-compile-resources.1 gresource.1 gdbus-codegen.1
49
gobject_MAN=	glib-genmarshal.1 glib-mkenums.1 gobject-query.1
50
gobject_MAN=	glib-genmarshal.1 glib-mkenums.1 gobject-query.1
50
51
51
OPTIONS_DEFINE=	COLLATION_FIX DEBUG NLS
52
OPTIONS_DEFINE=	COLLATION_FIX DEBUG FAM_ALTBACKEND NLS
52
OPTIONS_SUB=	yes
53
OPTIONS_SUB=	yes
53
# libc collation was fixed by https://svnweb.freebsd.org/changeset/base/290494
54
# 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)
55
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@
66
# http://www.freebsd.org/cgi/query-pr.cgi?pr=175930 see comment by ed@
66
#COLLATION_FIX_CONFIGURE_ENV+=	CFLAGS="-D__STDC_ISO_10646__"
67
#COLLATION_FIX_CONFIGURE_ENV+=	CFLAGS="-D__STDC_ISO_10646__"
67
68
69
FAM_ALTBACKEND_DESC=		Enable gio/kqueue_fnm file monitor backend
70
FAM_ALTBACKEND_CONFIGURE_ON=	--enable-kqueue-fnm=yes
71
68
.include <bsd.port.pre.mk>
72
.include <bsd.port.pre.mk>
69
73
70
# doesn't build yet
74
# doesn't build yet
Lines 94-103 Link Here
94
	@${REINPLACE_CMD} -e 's|/usr/local|${LOCALBASE}|g ; \
98
	@${REINPLACE_CMD} -e 's|/usr/local|${LOCALBASE}|g ; \
95
		s|/usr/share/locale/locale|${LOCALBASE}/share/locale/locale|g' \
99
		s|/usr/share/locale/locale|${LOCALBASE}/share/locale/locale|g' \
96
			${WRKSRC}/glib/gutils.c
100
			${WRKSRC}/glib/gutils.c
101
.if 0
97
	@${REINPLACE_CMD} -e 's|inotify_support=yes|inotify_support=no| ; \
102
	@${REINPLACE_CMD} -e 's|inotify_support=yes|inotify_support=no| ; \
98
		s|-Werror|| ; \
103
		s|-Werror|| ; \
99
		s|#define HAVE_SYS_INOTIFY_H 1||' ${WRKSRC}/configure
104
		s|#define HAVE_SYS_INOTIFY_H 1||' ${WRKSRC}/configure
105
.else
106
	@${REINPLACE_CMD} -e '/sys\/inotify.h/,/^])/d ; \
107
		s|G_THREAD_LIBS_FOR_GTHREAD.*-lpthread/.*|LDFLAGS="$$LDFLAGS -pthread"|' \
108
		${WRKSRC}/configure.ac
109
	@${REINPLACE_CMD} -e '/^SUBDIRS =/d' \
110
		${WRKSRC}/docs/reference/Makefile.am
111
	@${REINPLACE_CMD} -e 's|^install-exec-local:|not-&|' \
112
		${WRKSRC}/glib/libcharset/Makefile.am
113
	@${REINPLACE_CMD} -e 's|-Werror ||' \
114
		${WRKSRC}/m4macros/attributes.m4
100
115
116
post-patch-COLLATION_FIX-on:
117
	@${REINPLACE_CMD} -e 's|GLIB_LINK_FLAGS)|& -licui18n|' \
118
		${WRKSRC}/glib/Makefile.am
119
.endif
120
121
post-patch-FAM_ALTBACKEND-on:
122
	@${CP} -R ${FILESDIR}/kqueue_fnm ${WRKSRC}/gio
123
	@${REINPLACE_CMD} -i '.fnm.bak' \
124
		-e '/^AM_CONDITIONAL(HAVE_KQUEUE/s|$$|\${.newline}AC_ARG_ENABLE([kqueue-fnm], [AS_HELP_STRING([--enable-kqueue-fnm], [enable gio/kqueue_fnm backend, if kqueue supported])])\${.newline}AM_CONDITIONAL(ENABLE_KQUEUE_FNM, [test "$$enable_kqueue_fnm" = "yes"])| ; \
125
		/^gio\/kqueue\/Makefile/s|$$|\${.newline}gio/kqueue_fnm/Makefile|' \
126
		${WRKSRC}/configure.ac
127
	@${REINPLACE_CMD} -e '/^if HAVE_KQUEUE/s|$$|\${.newline}if ENABLE_KQUEUE_FNM\${.newline}SUBDIRS += kqueue_fnm\${.newline}platform_libadd += kqueue_fnm/libkqueue.la\${.newline}platform_deps += kqueue_fnm/libkqueue.la\${.newline}else| ; \
128
		/^platform_deps += kqueue\/libkqueue\.la$$/s|$$|\${.newline}endif|' \
129
		${WRKSRC}/gio/Makefile.am
130
101
post-install:
131
post-install:
102
	@${MKDIR} ${STAGEDIR}${PREFIX}/share/GConf/gsettings
132
	@${MKDIR} ${STAGEDIR}${PREFIX}/share/GConf/gsettings
103
	@${MKDIR} ${STAGEDIR}${PREFIX}/lib/gio/modules
133
	@${MKDIR} ${STAGEDIR}${PREFIX}/lib/gio/modules
(-)devel/glib20/files/kqueue_fnm/Makefile.am (+18 lines)
Line 0 Link Here
1
include $(top_srcdir)/glib.mk
2
3
noinst_LTLIBRARIES += libkqueue.la
4
5
libkqueue_la_SOURCES = \
6
       gkqueuefilemonitor.c \
7
       kqueue_fnm.c \
8
       kqueue_fnm.h \
9
       $(NULL)
10
11
libkqueue_la_CFLAGS = \
12
       $(GLIB_HIDDEN_VISIBILITY_CFLAGS) \
13
       -DG_LOG_DOMAIN=\"GLib-GIO\" \
14
       $(gio_INCLUDES) \
15
       $(GLIB_DEBUG_FLAGS) \
16
       -DGIO_MODULE_DIR=\"$(GIO_MODULE_DIR)\" \
17
       -DGIO_COMPILATION \
18
       -DG_DISABLE_DEPRECATED
(-)devel/glib20/files/kqueue_fnm/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/kqueue_fnm.c (+1083 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
/* To not depend from compiler version. */
150
#define MSTOSBT(__ms)		(sbintime_t)(((int64_t)__ms * (((uint64_t)1 << 63) / 500)) >> 32)
151
152
#ifndef CLOCK_MONOTONIC_FAST
153
#	define CLOCK_MONOTONIC_FAST	CLOCK_MONOTONIC
154
#endif
155
156
157
void 	*kq_fnm_proccess_events_proc(void *data);
158
159
static inline int
160
mem_cmpn(const void *buf1, const size_t buf1_size,
161
    const void *buf2, const size_t buf2_size) {
162
163
	if (buf1_size != buf2_size)
164
		return (((buf1_size > buf2_size) ? 127 : -127));
165
	if (0 == buf1_size || buf1 == buf2)
166
		return (0);
167
	if (NULL == buf1)
168
		return (-127);
169
	if (NULL == buf2)
170
		return (127);
171
	return (memcmp(buf1, buf2, buf1_size));
172
}
173
174
static int
175
realloc_items(void **items, const size_t item_size,
176
    size_t *allocated, const size_t alloc_blk_cnt, const size_t count) {
177
	size_t allocated_prev, allocated_new;
178
	uint8_t *items_new;
179
180
	if (NULL == items || 0 == item_size || NULL == allocated ||
181
	    0 == alloc_blk_cnt)
182
		return (EINVAL);
183
	allocated_prev = (*allocated);
184
	if (NULL != (*items) &&
185
	    allocated_prev > count &&
186
	    allocated_prev <= (count + alloc_blk_cnt))
187
		return (0);
188
	allocated_new = (((count / alloc_blk_cnt) + 1) * alloc_blk_cnt);
189
	items_new = (uint8_t*)reallocarray((*items), item_size, allocated_new);
190
	if (NULL == items_new) /* Realloc fail! */
191
		return (ENOMEM);
192
193
	if (allocated_new > allocated_prev) { /* Init new mem. */
194
		memset((items_new + (allocated_prev * item_size)), 0x00,
195
		    ((allocated_new - allocated_prev) * item_size));
196
	}
197
	(*items) = items_new;
198
	(*allocated) = allocated_new;
199
200
	return (0);
201
}
202
203
204
static int
205
readdir_start(int fd, struct stat *sb, size_t exp_count, readdir_ctx_p rdd) {
206
	size_t buf_size;
207
208
	if (-1 == fd || NULL == sb || NULL == rdd)
209
		return (EINVAL);
210
	if (-1 == lseek(fd, 0, SEEK_SET))
211
		return (errno);
212
	/* Calculate buf size for getdents(). */
213
	buf_size = MAX((size_t)sb->st_size, (exp_count * sizeof(struct dirent)));
214
	if (0 == buf_size) {
215
		buf_size = (16 * PAGE_SIZE);
216
	}
217
	/* Make buf size well aligned. */
218
	if (0 != sb->st_blksize) {
219
		if (powerof2(sb->st_blksize)) {
220
			buf_size = roundup2(buf_size, sb->st_blksize);
221
		} else {
222
			buf_size = roundup(buf_size, sb->st_blksize);
223
		}
224
	} else {
225
		buf_size = round_page(buf_size);
226
	}
227
	/* Init. */
228
	memset(rdd, 0x00, sizeof(readdir_ctx_t));
229
	rdd->buf = malloc(buf_size);
230
	if (NULL == rdd->buf)
231
		return (ENOMEM);
232
	rdd->buf_size = buf_size;
233
	rdd->fd = fd;
234
235
	return (0);
236
}
237
238
static void
239
readdir_free(readdir_ctx_p rdd) {
240
241
	if (NULL == rdd || NULL == rdd->buf)
242
		return;
243
	free(rdd->buf);
244
	memset(rdd, 0x00, sizeof(readdir_ctx_t));
245
}
246
247
static int
248
readdir_next(readdir_ctx_p rdd, struct dirent *de) {
249
	int error = 0, ios;
250
	uint8_t *ptr;
251
252
	if (NULL == rdd || NULL == rdd->buf || NULL == de)
253
		return (EINVAL);
254
255
	for (;;) {
256
		if (rdd->buf_used <= rdd->buf_pos) {
257
			/* Called once if buf size calculated ok. */
258
			ios = getdents(rdd->fd, (char*)rdd->buf, (int)rdd->buf_size);
259
			if (-1 == ios) {
260
				error = errno;
261
				break;
262
			}
263
			if (0 == ios) {
264
				error = ESPIPE; /* EOF. */
265
				break;
266
			}
267
			rdd->buf_used = (size_t)ios;
268
			rdd->buf_pos = 0;
269
		}
270
		/* Keep data aligned. */
271
		ptr = (rdd->buf + rdd->buf_pos);
272
		memcpy(de, ptr, (sizeof(struct dirent) - sizeof(de->d_name)));
273
		if (0 == de->d_reclen) {
274
			error = ESPIPE; /* EOF. */
275
			break;
276
		}
277
		rdd->buf_pos += de->d_reclen;
278
#ifdef DT_WHT
279
		if (DT_WHT == de->d_type)
280
			continue;
281
#endif
282
		memcpy(de, ptr, _GENERIC_DIRSIZ(de));
283
		if (!IS_NAME_DOTS(de->d_name))
284
			return (0); /* OK. */
285
	}
286
287
	/* Err or no more files. */
288
	readdir_free(rdd);
289
290
	return (error);
291
}
292
293
294
static int
295
file_info_find_ni(file_info_p files, size_t files_count,
296
    file_info_p fi, size_t *idx) {
297
	size_t i;
298
	mode_t st_ftype;
299
300
	if (NULL == files || NULL == fi || NULL == idx)
301
		return (0);
302
	st_ftype = (S_IFMT & fi->sb.st_mode);
303
	for (i = 0; i < files_count; i ++) {
304
		if ((S_IFMT & files[i].sb.st_mode) != st_ftype)
305
			continue;
306
		if ((fi->sb.st_ino != files[i].sb.st_ino ||
307
		     fi->de.d_fileno != files[i].de.d_fileno) &&
308
		    0 == IS_DE_NAME_EQ(&fi->de, &files[i].de))
309
			continue;
310
		(*idx) = i;
311
		return (1);
312
	}
313
	(*idx) = files_count;
314
	return (0);
315
}
316
317
static int
318
file_info_find_ino(file_info_p files, size_t files_count,
319
    file_info_p fi, size_t *idx) {
320
	size_t i;
321
	mode_t st_ftype;
322
323
	if (NULL == files || NULL == fi || NULL == idx)
324
		return (0);
325
	st_ftype = (S_IFMT & fi->sb.st_mode);
326
	for (i = 0; i < files_count; i ++) {
327
		if ((S_IFMT & files[i].sb.st_mode) != st_ftype ||
328
		    fi->sb.st_ino != files[i].sb.st_ino ||
329
		    fi->de.d_fileno != files[i].de.d_fileno)
330
			continue;
331
		(*idx) = i;
332
		return (1);
333
	}
334
	(*idx) = files_count;
335
	return (0);
336
}
337
338
static int
339
file_info_find_name(file_info_p files, size_t files_count,
340
    file_info_p fi, size_t *idx) {
341
	size_t i;
342
	mode_t st_ftype;
343
344
	if (NULL == files || NULL == fi || NULL == idx)
345
		return (0);
346
	st_ftype = (S_IFMT & fi->sb.st_mode);
347
	for (i = 0; i < files_count; i ++) {
348
		if ((S_IFMT & files[i].sb.st_mode) != st_ftype ||
349
		    0 == IS_DE_NAME_EQ(&fi->de, &files[i].de))
350
			continue;
351
		(*idx) = i;
352
		return (1);
353
	}
354
	(*idx) = files_count;
355
	return (0);
356
}
357
358
static void
359
file_info_fd_close(file_info_p files, size_t files_count) {
360
	size_t i;
361
362
	if (NULL == files || 0 == files_count)
363
		return;
364
	for (i = 0; i < files_count; i ++) {
365
		if (-1 == files[i].fd)
366
			continue;
367
		close(files[i].fd);
368
		files[i].fd = -1;
369
	}
370
}
371
372
373
static int
374
is_fs_local(struct statfs *stfs, const char **local_fs, const char **non_local_fs) {
375
	size_t i;
376
377
	if (NULL == stfs)
378
		return (0);
379
	if (NULL != local_fs) {
380
		for (i = 0; NULL != local_fs[i]; i ++) {
381
			if (0 == strncmp(stfs->f_fstypename, local_fs[i],
382
			    sizeof(stfs->f_fstypename)))
383
				return (1);
384
		}
385
	}
386
	if (0 == (MNT_LOCAL & stfs->f_flags))
387
		return (0);
388
	if (NULL != non_local_fs) {
389
		for (i = 0; NULL != non_local_fs[i]; i ++) {
390
			if (0 == strncmp(stfs->f_fstypename, non_local_fs[i],
391
			    sizeof(stfs->f_fstypename)))
392
				return (0);
393
		}
394
	}
395
	return (1);
396
}
397
398
399
static void
400
kq_fnmo_rate_lim_stop(kq_fnmo_p fnmo) {
401
	struct kevent kev;
402
403
	if (NULL == fnmo || -1 == fnmo->fd || 0 == fnmo->rate_lim_cur_interval)
404
		return;
405
	fnmo->rate_lim_cur_interval = 0;
406
	fnmo->rate_lim_ev_cnt = 0;
407
	EV_SET(&kev, fnmo->fd, EVFILT_TIMER, EV_DELETE, 0, 0, NULL);
408
	kevent(fnmo->kfnm->fd, &kev, 1, NULL, 0, NULL);
409
}
410
411
static int
412
kq_fnmo_rate_lim_shedule_next(kq_fnmo_p fnmo) {
413
	u_short flags = (EV_ADD | EV_CLEAR | EV_ONESHOT);
414
	struct kevent kev;
415
416
	if (NULL == fnmo || -1 == fnmo->fd || 0 == fnmo->kfnm->s.rate_limit_time_init)
417
		return (EINVAL);
418
	if (0 == fnmo->rate_lim_cur_interval) { /* First call. */
419
		fnmo->rate_lim_cur_interval = fnmo->kfnm->s.rate_limit_time_init;
420
	} else {
421
		if (fnmo->rate_lim_cur_interval == fnmo->kfnm->s.rate_limit_time_max)
422
			return (0); /* No need to modify timer. */
423
		/* Increase rate limit interval. */
424
		fnmo->rate_lim_cur_interval *= fnmo->kfnm->s.rate_limit_time_mul;
425
	}
426
	if (fnmo->rate_lim_cur_interval >= fnmo->kfnm->s.rate_limit_time_max) {
427
		/* Check upper limit and shedule periodic timer with upper rate limit time. */
428
		flags &= ~EV_ONESHOT;
429
		fnmo->rate_lim_cur_interval = fnmo->kfnm->s.rate_limit_time_max;
430
	}
431
	EV_SET(&kev, fnmo->fd, EVFILT_TIMER, flags,
432
	    NOTE_MSECONDS, fnmo->rate_lim_cur_interval, fnmo);
433
	if (-1 == kevent(fnmo->kfnm->fd, &kev, 1, NULL, 0, NULL)) {
434
		fnmo->rate_lim_cur_interval = 0;
435
		return (errno);
436
	}
437
	if (0 != (EV_ERROR & kev.flags)) {
438
		fnmo->rate_lim_cur_interval = 0;
439
		return ((int)kev.data);
440
	}
441
	return (0);
442
}
443
444
/* Return:
445
 * 0 for events that not handled
446
 * 1 for handled = rate limited
447
 * -1 on error.
448
 */
449
static int
450
kq_fnmo_rate_lim_check(kq_fnmo_p fnmo) {
451
	sbintime_t sbt, sbt_now;
452
	struct timespec ts;
453
454
	if (NULL == fnmo)
455
		return (-1);
456
	if (-1 == fnmo->fd ||
457
	    0 == fnmo->kfnm->s.rate_limit_time_init)
458
		return (0);
459
	if (0 != fnmo->rate_lim_cur_interval) {
460
		fnmo->rate_lim_ev_cnt ++; /* Count event, timer is active. */
461
		return (1);
462
	}
463
464
	/* Do we need to enable rate limit? */
465
	if (0 != clock_gettime(CLOCK_MONOTONIC_FAST, &ts))
466
		return (-1);
467
	sbt_now = tstosbt(ts);
468
	sbt = (fnmo->rate_lim_ev_last + fnmo->kfnm->rate_lim_time_init);
469
	fnmo->rate_lim_ev_last = sbt_now;
470
	if (sbt < sbt_now) /* Events rate to low. */
471
		return (0);
472
	/* Try to enable rate limit. */
473
	if (0 != kq_fnmo_rate_lim_shedule_next(fnmo))
474
		return (-1);
475
	/* Ok. */
476
	fnmo->rate_lim_ev_cnt ++;
477
478
	return (1);
479
}
480
481
static void
482
kq_fnmo_clean(kq_fnmo_p fnmo) {
483
484
	if (NULL == fnmo)
485
		return;
486
	if (-1 != fnmo->fd) {
487
		kq_fnmo_rate_lim_stop(fnmo);
488
		close(fnmo->fd);
489
		fnmo->fd = -1;
490
	}
491
	if (0 != fnmo->is_local) { /* Stop monitoring files/dirs. */
492
		file_info_fd_close(fnmo->files, fnmo->files_count);
493
	}
494
	free(fnmo->files);
495
	fnmo->files = NULL;
496
	fnmo->files_count = 0;
497
	fnmo->files_allocated = 0;
498
}
499
500
static void
501
kq_fnmo_free(void *arg) {
502
	kq_fnmo_p fnmo = arg;
503
504
	if (NULL == fnmo)
505
		return;
506
	kq_fnmo_clean(fnmo);
507
	free(fnmo);
508
}
509
510
static kq_fnmo_p
511
kq_fnmo_alloc(kq_fnm_p kfnm, const char *path, void *udata) {
512
	kq_fnmo_p fnmo;
513
514
	if (NULL == kfnm || NULL == path)
515
		return (NULL);
516
	fnmo = zalloc(sizeof(kq_fnmo_t));
517
	if (NULL == fnmo)
518
		return (NULL);
519
	/* Remember args. */
520
	fnmo->path_size = strlcpy(fnmo->path, path, PATH_MAX);
521
	fnmo->name_offset = fnmo->path_size;
522
	fnmo->udata = udata;
523
	fnmo->kfnm = kfnm;
524
525
	return (fnmo);
526
}
527
528
static int
529
kq_fnmo_readdir(kq_fnmo_p fnmo, size_t exp_count) {
530
	int error;
531
	struct dirent *de;
532
	file_info_p tmfi;
533
	readdir_ctx_t rdd;
534
535
	if (NULL == fnmo || 0 == fnmo->is_dir)
536
		return (EINVAL);
537
538
	free(fnmo->files);
539
	fnmo->files = NULL;
540
	fnmo->files_count = 0;
541
	fnmo->files_allocated = 0;
542
	/* Pre allocate. */
543
	if (0 != realloc_items((void**)&fnmo->files,
544
	    sizeof(file_info_t), &fnmo->files_allocated,
545
	    FILES_ALLOC_BLK_SIZE, (exp_count + 1)))
546
		return (ENOMEM);
547
548
	error = readdir_start(fnmo->fd, &fnmo->sb, exp_count, &rdd);
549
	if (0 != error)
550
		return (error);
551
	for (;;) {
552
		if (0 != realloc_items((void**)&fnmo->files,
553
		    sizeof(file_info_t), &fnmo->files_allocated,
554
		    FILES_ALLOC_BLK_SIZE, fnmo->files_count)) {
555
			free(fnmo->files);
556
			fnmo->files = NULL;
557
			fnmo->files_count = 0;
558
			fnmo->files_allocated = 0;
559
			readdir_free(&rdd);
560
			return (ENOMEM);
561
		}
562
		de = &fnmo->files[fnmo->files_count].de; /* Use short name. */
563
		/* Get file name from folder. */
564
		if (0 != readdir_next(&rdd, de))
565
			break;
566
		/* Get file attrs. */
567
		if (0 != fstatat(fnmo->fd, de->d_name,
568
		    &fnmo->files[fnmo->files_count].sb,
569
		    AT_SYMLINK_NOFOLLOW)) {
570
			memset(&fnmo->files[fnmo->files_count].sb, 0x00,
571
			    sizeof(struct stat));
572
		}
573
		fnmo->files[fnmo->files_count].fd = -1;
574
		fnmo->files_count ++;
575
	}
576
	/* Mem compact. */
577
	tmfi = reallocarray(fnmo->files, sizeof(file_info_t), (fnmo->files_count + 1));
578
	if (NULL != tmfi) { /* realloc ok. */
579
		fnmo->files = tmfi;
580
		fnmo->files_allocated = (fnmo->files_count + 1);
581
	}
582
583
	readdir_free(&rdd);
584
585
	return (0); /* OK. */
586
}
587
588
589
static void
590
kq_fnmo_fi_start(kq_fnmo_p fnmo, file_info_p fi) {
591
	struct kevent kev;
592
593
	if (NULL == fnmo || NULL == fi)
594
		return;
595
	fi->fd = openat(fnmo->fd, fi->de.d_name, OPEN_FILE_FLAGS);
596
	if (-1 == fi->fd)
597
		return;
598
	EV_SET(&kev, fi->fd, EVFILT_VNODE,
599
	    (EV_ADD | EV_CLEAR),
600
	    EVFILT_VNODE_SUB_FLAGS, 0, fnmo);
601
	kevent(fnmo->kfnm->fd, &kev, 1, NULL, 0, NULL);
602
}
603
604
static int
605
kq_fnmo_is_fi_monitored(kq_fnmo_p fnmo, file_info_p fi) {
606
607
	if (NULL == fnmo)
608
		return (0);
609
	if (0 == fnmo->is_local ||
610
	    (0 != fnmo->kfnm->s.max_dir_files &&
611
	     fnmo->kfnm->s.max_dir_files < fnmo->files_count))
612
		return (0);
613
	if (NULL != fi &&
614
	    0 == fnmo->kfnm->s.mon_local_subdirs &&
615
	    S_ISDIR(fi->sb.st_mode))
616
		return (0);
617
	return (1);
618
}
619
620
static void
621
kq_fnmo_init(void *arg) {
622
	kq_fnmo_p fnmo = arg;
623
	size_t i;
624
	struct statfs stfs;
625
	struct kevent kev;
626
627
	if (NULL == fnmo)
628
		return;
629
	fnmo->fd = open(fnmo->path, OPEN_FILE_FLAGS);
630
	if (-1 == fnmo->fd)
631
		return;
632
	if (0 != fstat(fnmo->fd, &fnmo->sb))
633
		goto err_out;
634
	
635
	/* Get parent folder name. */
636
	if (S_ISDIR(fnmo->sb.st_mode)) {
637
		fnmo->is_dir = 1;
638
		/* Be sure that folder contain trailing '/'. */
639
		if ('/' != fnmo->path[(fnmo->path_size - 1)]) {
640
			fnmo->path[fnmo->path_size] = '/';
641
			fnmo->path_size ++;
642
			fnmo->path[fnmo->path_size] = 0;
643
		}
644
		/* Skip last '/' for parent dir search. */
645
		fnmo->name_offset = (fnmo->path_size - 1);
646
	}
647
648
	/* Is file system local? */
649
	if (0 != fnmo->is_dir &&
650
	    0 != fnmo->kfnm->s.mon_local_subfiles &&
651
	    0 == fstatfs(fnmo->fd, &stfs)) {
652
		fnmo->is_local = is_fs_local(&stfs, fnmo->kfnm->s.local_fs,
653
		    fnmo->kfnm->s.non_local_fs);
654
	}
655
656
	/* Find parent dir path size. */
657
	while (0 < fnmo->name_offset && '/' != fnmo->path[(fnmo->name_offset - 1)]) {
658
		fnmo->name_offset --;
659
	}
660
661
	/* Dir special processing. */
662
	if (0 != fnmo->is_dir) {
663
		/* Read and remember dir content. */
664
		if (0 != kq_fnmo_readdir(fnmo, 0))
665
			goto err_out;
666
	}
667
	/* Add to kqueue. */
668
	EV_SET(&kev, fnmo->fd, EVFILT_VNODE, (EV_ADD | EV_CLEAR),
669
	    EVFILT_VNODE_FLAGS_ALL, 0, fnmo);
670
	if (-1 == kevent(fnmo->kfnm->fd, &kev, 1, NULL, 0, NULL) ||
671
	    0 != (EV_ERROR & kev.flags))
672
		goto err_out;
673
	/* Add monitor sub files/dirs, ignory errors. */
674
	/* Check twice for performance reason. */
675
	if (0 != kq_fnmo_is_fi_monitored(fnmo, NULL)) {
676
		for (i = 0; i < fnmo->files_count; i ++) {
677
			if (0 != kq_fnmo_is_fi_monitored(fnmo, &fnmo->files[i])) {
678
				kq_fnmo_fi_start(fnmo, &fnmo->files[i]);
679
			}
680
		}
681
	}
682
683
	return; /* OK. */
684
685
err_out:
686
	kq_fnmo_clean(fnmo);
687
}
688
689
static void
690
kq_handle_changes(kq_fnm_p kfnm, kq_fnmo_p fnmo) {
691
	size_t i, k, files_count;
692
	file_info_p files;
693
694
	if (NULL == kfnm || NULL == fnmo)
695
		return;
696
	if (0 != fstat(fnmo->fd, &fnmo->sb) ||
697
	    0 == fnmo->sb.st_nlink) {
698
		kq_fnmo_clean(fnmo);
699
		kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_DELETED,
700
		    fnmo->path, "", NULL);
701
		return;
702
	}
703
	if (0 == fnmo->is_dir) {
704
		fnmo->path[fnmo->name_offset] = 0;
705
		kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_CHANGED,
706
		    fnmo->path, (fnmo->path + fnmo->name_offset), NULL);
707
		fnmo->path[fnmo->name_offset] = '/';
708
		return;
709
	}
710
711
	/* Dir processing. */
712
713
	/* Save prev. */
714
	files = fnmo->files;
715
	files_count = fnmo->files_count;
716
	fnmo->files = NULL;
717
	fnmo->files_count = 0;
718
	/* Update dir. */
719
	if (0 != kq_fnmo_readdir(fnmo, files_count)) {
720
		/* Restore prev state on fail. */
721
		fnmo->files = files;
722
		fnmo->files_count = files_count;
723
		return;
724
	}
725
	/* Notify removed first. */
726
	for (i = 0; i < files_count; i ++) {
727
		if (0 != file_info_find_ni(fnmo->files, fnmo->files_count, &files[i], &k)) /* Deleted? */
728
			continue;
729
		if (-1 != files[i].fd) {
730
			close(files[i].fd);
731
			files[i].fd = -1;
732
		}
733
		kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_DELETED,
734
		    fnmo->path, files[i].de.d_name, NULL);
735
	}
736
	/* Notify. */
737
	for (i = 0; i < fnmo->files_count; i ++) {
738
		/* Is new file/folder? */
739
		if (0 == file_info_find_ino(files, files_count, &fnmo->files[i], &k) &&
740
		    0 == file_info_find_name(files, files_count, &fnmo->files[i], &k)) { /* Add new. */
741
			/* Add monitor sub files/dirs, ignory errors. */
742
			if (0 != kq_fnmo_is_fi_monitored(fnmo, &fnmo->files[i])) {
743
				kq_fnmo_fi_start(fnmo, &fnmo->files[i]);
744
			}
745
			kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_CREATED,
746
			    fnmo->path, fnmo->files[i].de.d_name, NULL);
747
			continue;
748
		}
749
		/* Keep file fd. */
750
		fnmo->files[i].fd = files[k].fd;
751
		files[k].fd = -1;
752
		/* Is renamed? */
753
		if (0 == IS_DE_NAME_EQ(&files[k].de, &fnmo->files[i].de)) {
754
			kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_RENAMED,
755
			    fnmo->path, files[k].de.d_name, fnmo->files[i].de.d_name);
756
			continue;
757
		}
758
		/* Is modified? */
759
		if (0 != memcmp(&fnmo->files[i].sb, &files[k].sb, sizeof(struct stat))) {
760
			kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_CHANGED,
761
			    fnmo->path, fnmo->files[i].de.d_name, NULL);
762
			continue;
763
		}
764
		/* Not changed. */
765
	}
766
767
	/* Prevent FD leak die to race conditions.
768
	 * All fd must be -1, check this while debuging.
769
	 */
770
	file_info_fd_close(files, files_count);
771
	free(files);
772
}
773
774
static void
775
kq_handle_rename(kq_fnm_p kfnm, kq_fnmo_p fnmo) {
776
	int up_dir_fd, found = 0;
777
	readdir_ctx_t rdd;
778
	struct dirent de;
779
	struct stat sb;
780
	char old_filename[(MAXNAMLEN + 2)];
781
	size_t old_filename_size;
782
783
	if (NULL == kfnm || NULL == fnmo)
784
		return;
785
	if (0 != fstat(fnmo->fd, &fnmo->sb) ||
786
	    0 == fnmo->sb.st_nlink) {
787
notify_removed:
788
		kq_fnmo_clean(fnmo);
789
		kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_DELETED,
790
		    fnmo->path, "", NULL);
791
		return;
792
	}
793
	/* Save old file name. */
794
	old_filename_size = (fnmo->path_size - fnmo->name_offset - (size_t)fnmo->is_dir);
795
	memcpy(old_filename,
796
	    (fnmo->path + fnmo->name_offset),
797
	    old_filename_size);
798
	old_filename[old_filename_size] = 0;
799
800
	/* Get parent folder name. */
801
	fnmo->path[fnmo->name_offset] = 0;
802
	/* Try to open. */
803
	up_dir_fd = open(fnmo->path, (OPEN_FILE_FLAGS | O_DIRECTORY));
804
	/* Restore '/' after parent folder. */
805
	fnmo->path[fnmo->name_offset] = '/';
806
	if (-1 == up_dir_fd ||
807
	    0 != fstat(up_dir_fd, &sb) ||
808
	    0 != readdir_start(up_dir_fd, &sb, 0, &rdd)) {
809
		close(up_dir_fd);
810
		return;
811
	}
812
	/* Find new name by inode. */
813
	while (0 == readdir_next(&rdd, &de)) {
814
		if (0 == fstatat(up_dir_fd, de.d_name, &sb, AT_SYMLINK_NOFOLLOW) &&
815
		    0 == memcmp(&fnmo->sb, &sb, sizeof(struct stat))) {
816
			found ++;
817
			break;
818
		}
819
	}
820
	close(up_dir_fd);
821
	if (0 == found)
822
		goto notify_removed; /* Not found. */
823
	/* Update name. */
824
	if (PATH_MAX <= (fnmo->name_offset + de.d_namlen))
825
		return; /* Too long. */
826
	memcpy((fnmo->path + fnmo->name_offset), de.d_name, de.d_namlen);
827
	fnmo->path_size = (fnmo->name_offset + de.d_namlen);
828
	/* Add last '/' for dir. */
829
	fnmo->path[fnmo->path_size] = '/';
830
	fnmo->path_size += (size_t)fnmo->is_dir;
831
	fnmo->path[fnmo->path_size] = 0;
832
	/* Notify. */
833
	kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_RENAMED,
834
	    fnmo->path, old_filename, de.d_name);
835
}
836
837
838
static void
839
kq_fnm_delay_call_process(kq_fnm_p kfnm, kq_msg_cb forced_msg_cb) {
840
	ssize_t ios;
841
	kq_fnm_msg_pkt_t msg;
842
843
	for (;;) {
844
		ios = read(kfnm->pfd[0], &msg, sizeof(msg));
845
		if (0 >= ios)
846
			return;
847
		if (sizeof(msg) != ios ||
848
		    KF_MSG_PKT_MAGIC != msg.magic ||
849
		    (((size_t)msg.msg_cb) ^ ((size_t)msg.arg)) != msg.chk_sum)
850
			continue;
851
		if (NULL != forced_msg_cb) {
852
			forced_msg_cb(msg.arg);
853
			continue;
854
		}
855
		if (NULL == msg.msg_cb)
856
			continue;
857
		msg.msg_cb(msg.arg);
858
	}
859
}
860
861
static int
862
kq_fnm_delay_call(kq_fnm_p kfnm, kq_msg_cb msg_cb,
863
    void *arg) {
864
	kq_fnm_msg_pkt_t msg;
865
866
	if (NULL == kfnm || NULL == arg)
867
		return (EINVAL);
868
	msg.magic = KF_MSG_PKT_MAGIC;
869
	msg.msg_cb = msg_cb;
870
	msg.arg = arg;
871
	msg.chk_sum = (((size_t)msg.msg_cb) ^ ((size_t)msg.arg));
872
	if (sizeof(msg) == write(kfnm->pfd[1], &msg, sizeof(msg)))
873
		return (0);
874
	return (errno);
875
}
876
877
878
static void
879
kq_fnm_free_cb(void *arg) {
880
	kq_fnm_p kfnm = arg;
881
882
	if (NULL == kfnm)
883
		return;
884
	close(kfnm->fd);
885
	kfnm->fd = -1;
886
}
887
void
888
kq_fnm_free(kq_fnm_p kfnm) {
889
890
	if (NULL == kfnm)
891
		return;
892
	kq_fnm_delay_call(kfnm, kq_fnm_free_cb, kfnm);
893
	pthread_join(kfnm->tid, NULL);
894
	/* Free all in delay calls queue. */
895
	close(kfnm->pfd[1]);
896
	kq_fnm_delay_call_process(kfnm, kq_fnmo_free);
897
	close(kfnm->pfd[0]);
898
	free(kfnm);
899
}
900
901
kq_fnm_p
902
kq_fnm_create(kq_file_mon_settings_p s, kfnm_event_handler_cb cb_func) {
903
	kq_fnm_p kfnm;
904
	struct kevent kev;
905
906
	if (NULL == s || NULL == cb_func)
907
		return (NULL);
908
	kfnm = zalloc(sizeof(kq_fnm_t));
909
	if (NULL == kfnm)
910
		return (NULL);
911
	kfnm->fd = kqueue();
912
	if (-1 == kfnm->fd)
913
		goto err_out;
914
	if (-1 == pipe2(kfnm->pfd, O_NONBLOCK))
915
		goto err_out;
916
	kfnm->cb_func = cb_func;
917
	memcpy(&kfnm->s, s, sizeof(kq_file_mon_settings_t));
918
	if (kfnm->s.rate_limit_time_init >= kfnm->s.rate_limit_time_max) {
919
		kfnm->s.rate_limit_time_max = kfnm->s.rate_limit_time_init;
920
	}
921
	if (0 == kfnm->s.rate_limit_time_mul) {
922
		kfnm->s.rate_limit_time_mul ++;
923
	}
924
	kfnm->rate_lim_time_init = MSTOSBT(kfnm->s.rate_limit_time_init);
925
926
	EV_SET(&kev, kfnm->pfd[0], EVFILT_READ, EV_ADD, 0, 0, NULL);
927
	if (-1 == kevent(kfnm->fd, &kev, 1, NULL, 0, NULL) ||
928
	    0 != (EV_ERROR & kev.flags))
929
		goto err_out;
930
	if (0 != pthread_create(&kfnm->tid, NULL,
931
	    kq_fnm_proccess_events_proc, kfnm))
932
		goto err_out;
933
934
	return (kfnm);
935
936
err_out:
937
	kq_fnm_free(kfnm);
938
	return (NULL);
939
}
940
941
kq_fnmo_p
942
kq_fnm_add(kq_fnm_p kfnm, const char *path, void *udata) {
943
	int error;
944
	kq_fnmo_p fnmo;
945
946
	if (NULL == kfnm || NULL == path)
947
		return (NULL);
948
	fnmo = kq_fnmo_alloc(kfnm, path, udata);
949
	if (NULL == fnmo)
950
		return (NULL);
951
	/* Shedule delay call to init. */
952
	error = kq_fnm_delay_call(kfnm, kq_fnmo_init, fnmo);
953
	if (0 != error) { /* Error, do no directly init to avoid freezes. */
954
		kq_fnmo_free(fnmo);
955
		return (NULL);
956
	}
957
	return (fnmo);
958
}
959
960
void
961
kq_fnm_del(kq_fnm_p kfnm, kq_fnmo_p fnmo) {
962
	int error;
963
964
	if (NULL == kfnm || NULL == fnmo)
965
		return;
966
	/* Cancel notifications. */
967
	kq_fnmo_rate_lim_stop(fnmo);
968
	close(fnmo->fd);
969
	fnmo->fd = -1;
970
	/* Shedule delay call to free. */
971
	error = kq_fnm_delay_call(kfnm, kq_fnmo_free, fnmo);
972
	if (0 == error)
973
		return;
974
	/* Error, free directly. */
975
	kq_fnmo_free(fnmo);
976
}
977
978
979
static void
980
kq_fnm_proccess_event(kq_fnm_p kfnm, struct kevent *kev) {
981
	kq_fnmo_p fnmo;
982
	file_info_p fi;
983
	size_t i;
984
	int is_rate_lim_checked = 0;
985
	struct stat sb;
986
987
	if (NULL == kfnm || NULL == kev)
988
		return;
989
990
	/* Handle delay calls. */
991
	if (kev->ident == (uintptr_t)kfnm->pfd[0]) {
992
		if (kev->filter == EVFILT_READ) {
993
			kq_fnm_delay_call_process(kfnm, NULL);
994
		}
995
		return;
996
	}
997
998
	if (0 == kev->udata)
999
		return; /* No associated data, skip. */
1000
	fnmo = (kq_fnmo_p)kev->udata;
1001
1002
	/* FS delayed notifications. */
1003
	if (EVFILT_TIMER == kev->filter) {
1004
		if (0 == fnmo->rate_lim_ev_cnt) {
1005
			/* No delayed events, disable rate limit polling. */
1006
			kq_fnmo_rate_lim_stop(fnmo);
1007
			return;
1008
		}
1009
		fnmo->rate_lim_ev_cnt = 0; /* Reset counter. */
1010
		kq_fnmo_rate_lim_shedule_next(fnmo);
1011
		kq_handle_changes(kfnm, fnmo);
1012
		return;
1013
	}
1014
1015
	/* FS notifications. */
1016
	if (EVFILT_VNODE != kev->filter)
1017
		return; /* Unknown event, skip. */
1018
	/* Subdir/file */
1019
	if (kev->ident != (uintptr_t)fnmo->fd) {
1020
		/* Is files changes rate limited? */
1021
		if (1 == kq_fnmo_rate_lim_check(fnmo))
1022
			return;
1023
		is_rate_lim_checked ++;
1024
		/* Try to find file and check it, without call kq_handle_changes(). */
1025
		fi = NULL;
1026
		for (i = 0; i < fnmo->files_count; i ++) {
1027
			if (kev->ident != (uintptr_t)fnmo->files[i].fd)
1028
				continue;
1029
			fi = &fnmo->files[i];
1030
			break;
1031
		}
1032
		if (NULL != fi) {
1033
			/* Get file attrs. */
1034
			if (0 != fstat(fi->fd, &sb)) {
1035
				memset(&sb, 0x00, sizeof(struct stat));
1036
			}
1037
			/* Is modified? */
1038
			if (0 != memcmp(&fi->sb, &sb, sizeof(struct stat))) {
1039
				memcpy(&fi->sb, &sb, sizeof(struct stat));
1040
				kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_CHANGED,
1041
				    fnmo->path, fi->de.d_name, NULL);
1042
				return;
1043
			}
1044
		}
1045
		/* fd not found or changes not found, rescan dir. */
1046
		kev->fflags = NOTE_WRITE;
1047
	}
1048
	/* Monitored object. */
1049
	/* All flags from EVFILT_VNODE_FLAGS_ALL must be handled here. */
1050
	if (EV_ERROR & kev->flags) {
1051
		kev->fflags |= NOTE_REVOKE; /* Treat error as unmount. */
1052
	}
1053
	if (NOTE_RENAME & kev->fflags) {
1054
		kq_handle_rename(kfnm, fnmo);
1055
	}
1056
	if ((NOTE_WRITE | NOTE_EXTEND | NOTE_ATTRIB | NOTE_LINK | NOTE_CLOSE_WRITE) & kev->fflags) {
1057
		/* Only count changes, do not prevent NOTE_DELETE event handling. */
1058
		if (0 == is_rate_lim_checked &&
1059
		    1 != kq_fnmo_rate_lim_check(fnmo)) {
1060
			kq_handle_changes(kfnm, fnmo);
1061
		}
1062
	}
1063
	if ((NOTE_DELETE | NOTE_REVOKE) & kev->fflags) {
1064
		/* No report about childs. */
1065
		kq_fnmo_clean(fnmo);
1066
		kfnm->cb_func(kfnm, fnmo, fnmo->udata, KF_EVENT_DELETED,
1067
		    fnmo->path, "", NULL);
1068
	}
1069
}
1070
1071
void *
1072
kq_fnm_proccess_events_proc(void *data) {
1073
	struct kevent kev;
1074
	kq_fnm_p kfnm = data;
1075
1076
	if (NULL == kfnm)
1077
		return (NULL);
1078
	/* Get and proccess events, no wait. */
1079
	while (0 < kevent(kfnm->fd, NULL, 0, &kev, 1, NULL)) {
1080
		kq_fnm_proccess_event(kfnm, &kev);
1081
	}
1082
	return (NULL);
1083
}
(-)devel/glib20/files/kqueue_fnm/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__ */
(-)devel/glib20/files/patch-gio_filemonitor (-14 / +22 lines)
Lines 22-41 Link Here
22
 
22
 
23
   G_OBJECT_CLASS (g_poll_file_monitor_parent_class)->finalize (object);
23
   G_OBJECT_CLASS (g_poll_file_monitor_parent_class)->finalize (object);
24
 }
24
 }
25
--- gio/kqueue/Makefile.in.orig	2017-02-13 15:22:04 UTC
25
--- gio/kqueue/Makefile.am.orig	2016-10-22 05:18:22 UTC
26
+++ gio/kqueue/Makefile.in
26
+++ gio/kqueue/Makefile.am
27
@@ -183,9 +183,8 @@ LTLIBRARIES = $(installed_test_LTLIBRARI
27
@@ -4,19 +4,9 @@ noinst_LTLIBRARIES += libkqueue.la
28
 libkqueue_la_LIBADD =
28
 
29
 am__objects_1 =
29
 libkqueue_la_SOURCES = \
30
 am_libkqueue_la_OBJECTS = libkqueue_la-gkqueuefilemonitor.lo \
30
        gkqueuefilemonitor.c \
31
-	libkqueue_la-kqueue-helper.lo libkqueue_la-kqueue-thread.lo \
31
-       gkqueuefilemonitor.h \
32
-	libkqueue_la-kqueue-sub.lo libkqueue_la-kqueue-missing.lo \
32
        kqueue-helper.c \
33
-	libkqueue_la-kqueue-utils.lo libkqueue_la-kqueue-exclusions.lo \
33
        kqueue-helper.h \
34
+	libkqueue_la-kqueue-helper.lo \
34
-       kqueue-thread.c \
35
+	libkqueue_la-kqueue-missing.lo \
35
-       kqueue-thread.h \
36
 	libkqueue_la-dep-list.lo $(am__objects_1)
36
-       kqueue-sub.c \
37
 libkqueue_la_OBJECTS = $(am_libkqueue_la_OBJECTS)
37
-       kqueue-sub.h \
38
 AM_V_lt = $(am__v_lt_@AM_V@)
38
        kqueue-missing.c \
39
-       kqueue-missing.h \
40
-       kqueue-utils.c \
41
-       kqueue-utils.h \
42
-       kqueue-exclusions.c \
43
-       kqueue-exclusions.h \
44
        dep-list.c \
45
        dep-list.h \
46
        $(NULL)
39
--- gio/kqueue/gkqueuefilemonitor.c.orig	2016-10-22 05:18:22 UTC
47
--- gio/kqueue/gkqueuefilemonitor.c.orig	2016-10-22 05:18:22 UTC
40
+++ gio/kqueue/gkqueuefilemonitor.c
48
+++ gio/kqueue/gkqueuefilemonitor.c
41
@@ -22,33 +22,73 @@
49
@@ -22,33 +22,73 @@

Return to bug 214338