xref: /lighttpd1.4/src/stat_cache.c (revision 73865025)
1 #include "first.h"
2 
3 #include "stat_cache.h"
4 #include "log.h"
5 #include "fdevent.h"
6 #include "http_etag.h"
7 #include "algo_splaytree.h"
8 
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 
12 #include <stdlib.h>
13 #include <string.h>
14 #include <errno.h>
15 #include <unistd.h>
16 #include <fcntl.h>
17 
18 #if defined(HAVE_SYS_XATTR_H)
19 # include <sys/xattr.h>
20 #elif defined(HAVE_ATTR_ATTRIBUTES_H)
21 # include <attr/attributes.h>
22 #endif
23 
24 #ifdef HAVE_SYS_EXTATTR_H
25 # include <sys/extattr.h>
26 #endif
27 
28 #ifndef HAVE_LSTAT
29 #define lstat stat
30 #ifndef S_ISLNK
31 #define S_ISLNK(mode) (0)
32 #endif
33 #endif
34 
35 /*
36  * stat-cache
37  *
38  * - a splay-tree is used as we can use the caching effect of it
39  */
40 
41 enum {
42   STAT_CACHE_ENGINE_SIMPLE  = 0  /*(default)*/
43  ,STAT_CACHE_ENGINE_NONE    = 1
44  ,STAT_CACHE_ENGINE_FAM     = 2  /* same as STAT_CACHE_ENGINE_INOTIFY */
45  ,STAT_CACHE_ENGINE_INOTIFY = 2  /* same as STAT_CACHE_ENGINE_FAM */
46  ,STAT_CACHE_ENGINE_KQUEUE  = 2  /* same as STAT_CACHE_ENGINE_FAM */
47 };
48 
49 struct stat_cache_fam;  /* declaration */
50 
51 typedef struct stat_cache {
52 	int stat_cache_engine;
53 	splay_tree *files; /* nodes of tree are (stat_cache_entry *) */
54 	struct stat_cache_fam *scf;
55 } stat_cache;
56 
57 static stat_cache sc;
58 
59 
60 static void * stat_cache_sptree_find(splay_tree ** const sptree,
61                                      const char * const name,
62                                      uint32_t len)
63 {
64     const int ndx = splaytree_djbhash(name, len);
65     *sptree = splaytree_splay(*sptree, ndx);
66     return (*sptree && (*sptree)->key == ndx) ? (*sptree)->data : NULL;
67 }
68 
69 
70 #if defined(HAVE_SYS_INOTIFY_H) \
71  || (defined(HAVE_SYS_EVENT_H) && defined(HAVE_KQUEUE))
72 #ifndef HAVE_FAM_H
73 #define HAVE_FAM_H
74 #endif
75 #endif
76 
77 #ifdef HAVE_FAM_H
78 
79 /* monitor changes in directories using FAM
80  *
81  * This implementation employing FAM monitors directories as they are used,
82  * and maintains a reference count for cache use within stat_cache.c.
83  * A periodic job runs in lighttpd every 32 seconds, expiring entries unused
84  * in last 64 seconds out of the cache and cancelling FAM monitoring.  Items
85  * within the cache are checked against the filesystem upon use if last stat()
86  * was greater than or equal to 16 seconds ago.
87  *
88  * This implementation does not monitor every directory in a tree, and therefore
89  * the cache may get out-of-sync with the filesystem.  Delays in receiving and
90  * processing events from FAM might also lead to stale cache entries.
91  *
92  * For many websites, a large number of files are seldom, if ever, modified,
93  * and a common practice with images is to create a new file with a new name
94  * when a new version is needed, in order for client browsers and CDNs to better
95  * cache the content.  Given this, most use will see little difference in
96  * performance between server.stat-cache-engine = "fam" and "simple" (default).
97  * The default server.stat-cache-engine = "simple" calls stat() on a target once
98  * per second, and reuses that information until the next second.  For use where
99  * changes must be immediately visible, server.stat-cache-engine = "disable"
100  * should be used.
101  *
102  * When considering use of server.stat-cache-engine = "fam", there are a few
103  * additional limitations for this cache implementation using FAM.
104  * - symlinks to files located outside of the current directory do not result
105  *   in changes to that file being monitored (unless that file is in a directory
106  *   which is monitored as a result of a different request).  symlinks can be
107  *   chained and can be circular.  This implementation *does not* readlink() or
108  *   realpath() to resolve the chains to find and monitor the ultimate target
109  *   directory.  While symlinks to files located outside the current directory
110  *   are not monitored, symlinks to directories *are* monitored, though chains
111  *   of symlinks to directories do not result in monitoring of the directories
112  *   containing intermediate symlinks to the target directory.
113  * - directory rename of a directory which is not currently being monitored will
114  *   result in stale information in the cache if there is a subdirectory that is
115  *   being monitored.
116  * Even though lighttpd will not receive FAM events in the above cases, lighttpd
117  * does re-validate the information in the cache upon use if the cache entry has
118  * not been checked in 16 seconds, so that is the upper limit for use of stale
119  * data.
120  *
121  * Use of server.stat-cache-engine = "fam" is discouraged for extremely volatile
122  * directories such as temporary directories (e.g. /tmp and maybe /var/tmp) due
123  * to the overhead of processing the additional noise generated from changes.
124  * Related, server.stat-cache-engine = "fam" is not recommended on trees of
125  * untrusted files where a malicious user could generate an excess of change
126  * events.
127  *
128  * Internal note: lighttpd walks the caches to prune trees in stat_cache when an
129  * event is received for a directory (or symlink to a directory) which has been
130  * deleted or renamed.  The splaytree data structure is suboptimal for frequent
131  * changes of large directories trees where there have been a large number of
132  * different files recently accessed and part of the stat_cache.
133  */
134 
135 #if defined(HAVE_SYS_INOTIFY_H) \
136  && !(defined(HAVE_SYS_EVENT_H) && defined(HAVE_KQUEUE))
137 
138 #include <sys/inotify.h>
139 
140 /*(translate FAM API to inotify; this is specific to stat_cache.c use of FAM)*/
141 #define fam fd /*(translate struct stat_cache_fam scf->fam -> scf->fd)*/
142 typedef int FAMRequest; /*(fr)*/
143 #define FAMClose(fd) \
144         close(*(fd))
145 #define FAMCancelMonitor(fd, wd) \
146         inotify_rm_watch(*(fd), *(wd))
147 #define fam_watch_mask ( IN_ATTRIB | IN_CREATE | IN_DELETE | IN_DELETE_SELF \
148                        | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM \
149                        | IN_EXCL_UNLINK | IN_ONLYDIR )
150                      /*(note: follows symlinks; not providing IN_DONT_FOLLOW)*/
151 #define FAMMonitorDirectory(fd, fn, wd, userData) \
152         ((*(wd) = inotify_add_watch(*(fd), (fn), (fam_watch_mask))) < 0)
153 typedef enum FAMCodes { /*(copied from fam.h to define arbitrary enum values)*/
154     FAMChanged=1,
155     FAMDeleted=2,
156     FAMCreated=5,
157     FAMMoved=6,
158 } FAMCodes;
159 
160 #elif defined HAVE_SYS_EVENT_H && defined HAVE_KQUEUE
161 #undef HAVE_SYS_INOTIFY_H
162 
163 #include <sys/event.h>
164 #include <sys/time.h>
165 
166 /*(translate FAM API to inotify; this is specific to stat_cache.c use of FAM)*/
167 #define fam fd /*(translate struct stat_cache_fam scf->fam -> scf->fd)*/
168 typedef int FAMRequest; /*(fr)*/
169 #define FAMClose(fd) \
170         (-1 != (*(fd)) ? close(*(fd)) : 0)
171 static int FAMCancelMonitor (const int * const fd, int * const wd)
172 {
173     if (-1 == *fd) return 0;
174     if (-1 == *wd) return 0;
175     struct timespec t0 = { 0, 0 };
176     struct kevent kev;
177     EV_SET(&kev, *wd, EVFILT_VNODE, EV_DELETE, 0, 0, 0);
178     int rc = kevent(*fd, &kev, 1, NULL, 0, &t0);
179     close(*wd);
180     *wd = -1;
181     return rc;
182 }
183 static int FAMMonitorDirectory (int * const fd, char * const fn, int * const wd, void * const userData)
184 {
185     *wd = fdevent_open_dirname(fn, 1); /*(note: follows symlinks)*/
186     if (-1 == *wd) return -1;
187     struct timespec t0 = { 0, 0 };
188     struct kevent kev;
189     unsigned short kev_flags = EV_ADD | EV_ENABLE | EV_CLEAR;
190     unsigned int kev_fflags = NOTE_ATTRIB | NOTE_EXTEND | NOTE_LINK | NOTE_WRITE
191                             | NOTE_DELETE | NOTE_REVOKE | NOTE_RENAME;
192     EV_SET(&kev, *wd, EVFILT_VNODE, kev_flags, kev_fflags, 0, userData);
193     return kevent(*fd, &kev, 1, NULL, 0, &t0);
194 }
195 typedef enum FAMCodes { /*(copied from fam.h to define arbitrary enum values)*/
196     FAMChanged=1,
197     FAMDeleted=2,
198     FAMCreated=5,
199     FAMMoved=6,
200 } FAMCodes;
201 
202 #else
203 
204 #include <fam.h>
205 
206 #ifdef HAVE_FAMNOEXISTS
207 #ifndef LIGHTTPD_STATIC
208 #include <dlfcn.h>
209 #endif
210 #endif
211 
212 #endif
213 
214 typedef struct fam_dir_entry {
215 	buffer name;
216 	int refcnt;
217 	FAMRequest req;
218 	unix_time64_t stat_ts;
219 	dev_t st_dev;
220 	ino_t st_ino;
221 	struct fam_dir_entry *fam_parent;
222 } fam_dir_entry;
223 
224 typedef struct stat_cache_fam {
225 	splay_tree *dirs; /* indexed by path; node data is fam_dir_entry */
226   #ifdef HAVE_SYS_INOTIFY_H
227 	splay_tree *wds;  /* indexed by inotify watch descriptor */
228   #elif defined HAVE_SYS_EVENT_H && defined HAVE_KQUEUE
229   #else
230 	FAMConnection fam;
231   #endif
232 	log_error_st *errh;
233 	fdevents *ev;
234 	fdnode *fdn;
235 	int fd;
236 } stat_cache_fam;
237 
238 static fam_dir_entry * fam_dir_entry_init(const char *name, size_t len)
239 {
240     fam_dir_entry * const fam_dir = calloc(1, sizeof(*fam_dir));
241     force_assert(NULL != fam_dir);
242 
243     buffer_copy_string_len(&fam_dir->name, name, len);
244     fam_dir->refcnt = 0;
245   #if defined HAVE_SYS_EVENT_H && defined HAVE_KQUEUE
246     fam_dir->req = -1;
247   #endif
248 
249     return fam_dir;
250 }
251 
252 static void fam_dir_entry_free(fam_dir_entry *fam_dir)
253 {
254     if (!fam_dir) return;
255     /*(fam_dir->fam_parent might be invalid pointer here; ignore)*/
256     free(fam_dir->name.ptr);
257   #if defined HAVE_SYS_EVENT_H && defined HAVE_KQUEUE
258     if (-1 != fam_dir->req)
259         close(fam_dir->req);
260   #endif
261     free(fam_dir);
262 }
263 
264 static void fam_dir_invalidate_node(fam_dir_entry *fam_dir)
265 {
266     fam_dir->stat_ts = 0;
267     if (fam_dir->fam_parent) {
268         --fam_dir->fam_parent->refcnt;
269         fam_dir->fam_parent = NULL;
270     }
271 }
272 
273 /*
274  * walk though splay_tree and collect contents of dir tree.
275  * remove tagged entries in a second loop
276  */
277 
278 static void fam_dir_tag_refcnt(splay_tree *t, int *keys, int *ndx)
279 {
280     if (*ndx == 512) return; /*(must match num array entries in keys[])*/
281     if (t->left)  fam_dir_tag_refcnt(t->left,  keys, ndx);
282     if (t->right) fam_dir_tag_refcnt(t->right, keys, ndx);
283     if (*ndx == 512) return; /*(must match num array entries in keys[])*/
284 
285     fam_dir_entry * const fam_dir = t->data;
286     if (0 == fam_dir->refcnt) {
287         fam_dir_invalidate_node(fam_dir);
288         keys[(*ndx)++] = t->key;
289     }
290 }
291 
292 __attribute_noinline__
293 static void fam_dir_periodic_cleanup() {
294     stat_cache_fam * const scf = sc.scf;
295     int max_ndx, i;
296     int keys[512]; /* 2k size on stack */
297   #if defined HAVE_SYS_EVENT_H && defined HAVE_KQUEUE
298     struct kevent kevl[512]; /* 32k size on stack to batch kevent EV_DELETE */
299   #endif
300     do {
301         if (!scf->dirs) break;
302         max_ndx = 0;
303         fam_dir_tag_refcnt(scf->dirs, keys, &max_ndx);
304         for (i = 0; i < max_ndx; ++i) {
305             const int ndx = keys[i];
306             splay_tree *node = scf->dirs = splaytree_splay(scf->dirs, ndx);
307             if (node && node->key == ndx) {
308                 fam_dir_entry *fam_dir = node->data;
309                 scf->dirs = splaytree_delete(scf->dirs, ndx);
310               #ifdef HAVE_SYS_INOTIFY_H
311                 scf->wds = splaytree_delete(scf->wds, fam_dir->req);
312               #elif defined HAVE_SYS_EVENT_H && defined HAVE_KQUEUE
313                 /* batch process kevent removal; defer cancel */
314                 EV_SET(kevl+i, fam_dir->req, EVFILT_VNODE, EV_DELETE, 0, 0, 0);
315                 fam_dir->req = -1; /*(make FAMCancelMonitor() a no-op)*/
316               #endif
317                 FAMCancelMonitor(&scf->fam, &fam_dir->req);
318                 fam_dir_entry_free(fam_dir);
319             }
320         }
321       #if defined HAVE_SYS_EVENT_H && defined HAVE_KQUEUE
322         /* batch process: kevent() to submit EV_DELETE, then close dir fds */
323         if (0 == max_ndx) break;
324         struct timespec t0 = { 0, 0 };
325         kevent(scf->fd, kevl, max_ndx, NULL, 0, &t0);
326         for (i = 0; i < max_ndx; ++i)
327             close((int)kevl[i].ident);
328       #endif
329     } while (max_ndx == sizeof(keys)/sizeof(int));
330 }
331 
332 static void fam_dir_invalidate_tree(splay_tree *t, const char *name, size_t len)
333 {
334   #ifdef __clang_analyzer__
335     force_assert(name);
336   #endif
337     /*force_assert(t);*/
338     if (t->left)  fam_dir_invalidate_tree(t->left,  name, len);
339     if (t->right) fam_dir_invalidate_tree(t->right, name, len);
340 
341     fam_dir_entry * const fam_dir = t->data;
342   #ifdef __clang_analyzer__
343     force_assert(fam_dir);
344   #endif
345     const buffer * const b = &fam_dir->name;
346     size_t blen = buffer_clen(b);
347     if (blen > len && b->ptr[len] == '/' && 0 == memcmp(b->ptr, name, len))
348         fam_dir_invalidate_node(fam_dir);
349 }
350 
351 /* declarations */
352 static void stat_cache_delete_tree(const char *name, uint32_t len);
353 static void stat_cache_invalidate_dir_tree(const char *name, size_t len);
354 static void stat_cache_handle_fdevent_fn(stat_cache_fam * const scf, fam_dir_entry * const fam_dir, const char * const fn, const uint32_t fnlen, int code);
355 
356 static void stat_cache_handle_fdevent_in(stat_cache_fam *scf)
357 {
358   #ifdef HAVE_SYS_INOTIFY_H
359     /*(inotify pads in->len to align struct following in->name[])*/
360     char buf[4096]
361       __attribute__ ((__aligned__(__alignof__(struct inotify_event))));
362     int rd;
363     do {
364         rd = (int)read(scf->fd, buf, sizeof(buf));
365         if (rd <= 0) {
366             if (-1 == rd && errno != EINTR && errno != EAGAIN) {
367                 log_perror(scf->errh, __FILE__, __LINE__, "inotify error");
368                 /* TODO: could flush cache, close scf->fd, and re-open inotify*/
369             }
370             break;
371         }
372         for (int i = 0; i < rd; ) {
373             struct inotify_event * const in =
374               (struct inotify_event *)((uintptr_t)buf + i);
375             uint32_t len = in->len;
376             if (len > sizeof(buf)) break; /*(should not happen)*/
377             i += sizeof(struct inotify_event) + len;
378             if (i > rd) break; /*(should not happen (partial record))*/
379             if (in->mask & IN_CREATE)
380                 continue; /*(see comment below for FAMCreated)*/
381             if (in->mask & IN_Q_OVERFLOW) {
382                 log_error(scf->errh, __FILE__, __LINE__,
383                           "inotify queue overflow");
384                 continue;
385             }
386             /* ignore events which may have been pending for
387              * paths recently cancelled via FAMCancelMonitor() */
388             scf->wds = splaytree_splay(scf->wds, in->wd);
389             if (!scf->wds || scf->wds->key != in->wd)
390                 continue;
391             fam_dir_entry *fam_dir = scf->wds->data;
392             if (NULL == fam_dir)        /*(should not happen)*/
393                 continue;
394             if (fam_dir->req != in->wd) /*(should not happen)*/
395                 continue;
396             /*(specific to use here in stat_cache.c)*/
397             int code = 0;
398             if (in->mask & (IN_ATTRIB | IN_MODIFY))
399                 code = FAMChanged;
400             else if (in->mask & (IN_DELETE | IN_DELETE_SELF | IN_UNMOUNT))
401                 code = FAMDeleted;
402             else if (in->mask & (IN_MOVE_SELF | IN_MOVED_FROM))
403                 code = FAMMoved;
404 
405             if (len) {
406                 do { --len; } while (len && in->name[len-1] == '\0');
407             }
408             stat_cache_handle_fdevent_fn(scf, fam_dir, in->name, len, code);
409         }
410     } while (rd + sizeof(struct inotify_event) + NAME_MAX + 1 > sizeof(buf));
411   #elif defined HAVE_SYS_EVENT_H && defined HAVE_KQUEUE
412     struct kevent kevl[256];
413     struct timespec t0 = { 0, 0 };
414     int n;
415     do {
416         n = kevent(scf->fd, NULL, 0, kevl, sizeof(kevl)/sizeof(*kevl), &t0);
417         if (n <= 0) break;
418         for (int i = 0; i < n; ++i) {
419             const struct kevent * const kev = kevl+i;
420             /* ignore events which may have been pending for
421              * paths recently cancelled via FAMCancelMonitor() */
422             int ndx = (int)(intptr_t)kev->udata;
423             scf->dirs = splaytree_splay(scf->dirs, ndx);
424             if (!scf->dirs || scf->dirs->key != ndx)
425                 continue;
426             fam_dir_entry *fam_dir = scf->dirs->data;
427             if (fam_dir->req != (int)kev->ident)
428                 continue;
429             /*(specific to use here in stat_cache.c)*/
430             /* note: stat_cache only monitors on directories,
431              *       so events here are only on directories
432              * note: changes are treated as FAMDeleted since
433              *       it is unknown which file in dir was changed
434              *       This is not efficient, but this stat_cache mechanism also
435              *       should not be used on frequently modified directories. */
436             int code = 0;
437             if (kev->fflags & (NOTE_WRITE|NOTE_ATTRIB|NOTE_EXTEND|NOTE_LINK))
438                 code = FAMDeleted; /*(not FAMChanged; see comment above)*/
439             else if (kev->fflags & (NOTE_DELETE|NOTE_REVOKE))
440                 code = FAMDeleted;
441             else if (kev->fflags & NOTE_RENAME)
442                 code = FAMMoved;
443             if (kev->flags & EV_ERROR) /*(not expected; treat as FAMDeleted)*/
444                 code = FAMDeleted;
445             stat_cache_handle_fdevent_fn(scf, fam_dir, NULL, 0, code);
446         }
447     } while (n == sizeof(kevl)/sizeof(*kevl));
448   #else
449     for (int i = 0, ndx; i || (i = FAMPending(&scf->fam)) > 0; --i) {
450         FAMEvent fe;
451         if (FAMNextEvent(&scf->fam, &fe) < 0) break;
452 
453         /* ignore events which may have been pending for
454          * paths recently cancelled via FAMCancelMonitor() */
455         ndx = (int)(intptr_t)fe.userdata;
456         scf->dirs = splaytree_splay(scf->dirs, ndx);
457         if (!scf->dirs || scf->dirs->key != ndx) {
458             continue;
459         }
460         fam_dir_entry *fam_dir = scf->dirs->data;
461         if (FAMREQUEST_GETREQNUM(&fam_dir->req)
462             != FAMREQUEST_GETREQNUM(&fe.fr)) {
463             continue;
464         }
465 
466         uint32_t fnlen = (fe.code != FAMCreated && fe.filename[0] != '/')
467           ? (uint32_t)strlen(fe.filename)
468           : 0;
469         stat_cache_handle_fdevent_fn(scf, fam_dir, fe.filename, fnlen, fe.code);
470     }
471   #endif
472 }
473 
474 static void stat_cache_handle_fdevent_fn(stat_cache_fam * const scf, fam_dir_entry *fam_dir, const char * const fn, const uint32_t fnlen, int code)
475 {
476         if (fnlen) {
477             buffer * const n = &fam_dir->name;
478             fam_dir_entry *fam_link;
479             uint32_t len;
480             switch (code) {
481             case FAMCreated:
482                 /* file created in monitored dir modifies dir and
483                  * we should get a separate FAMChanged event for dir.
484                  * Therefore, ignore file FAMCreated event here.
485                  * Also, if FAMNoExists() is used, might get spurious
486                  * FAMCreated events as changes are made e.g. in monitored
487                  * sub-sub-sub dirs and the library discovers new (already
488                  * existing) dir entries */
489                 return;
490             case FAMChanged:
491                 /* file changed in monitored dir does not modify dir */
492             case FAMDeleted:
493             case FAMMoved:
494                 /* file deleted or moved in monitored dir modifies dir,
495                  * but FAM provides separate notification for that */
496 
497                 /* temporarily append filename to dir in fam_dir->name to
498                  * construct path, then delete stat_cache entry (if any)*/
499                 len = buffer_clen(n);
500                 buffer_append_path_len(n, fn, fnlen);
501                 /* (alternatively, could chose to stat() and update)*/
502                 stat_cache_invalidate_entry(BUF_PTR_LEN(n));
503 
504                 fam_link = /*(check if might be symlink to monitored dir)*/
505                 stat_cache_sptree_find(&scf->dirs, BUF_PTR_LEN(n));
506                 if (fam_link && !buffer_is_equal(&fam_link->name, n))
507                     fam_link = NULL;
508 
509                 buffer_truncate(n, len);
510 
511                 if (fam_link) {
512                     /* replaced symlink changes containing dir */
513                     stat_cache_invalidate_entry(n->ptr, len);
514                     /* handle symlink to dir as deleted dir below */
515                     code = FAMDeleted;
516                     fam_dir = fam_link;
517                     break;
518                 }
519                 return;
520             default:
521                 return;
522             }
523         }
524 
525         switch(code) {
526         case FAMChanged:
527             stat_cache_invalidate_entry(BUF_PTR_LEN(&fam_dir->name));
528             break;
529         case FAMDeleted:
530         case FAMMoved:
531             stat_cache_delete_tree(BUF_PTR_LEN(&fam_dir->name));
532             fam_dir_invalidate_node(fam_dir);
533             if (scf->dirs)
534                 fam_dir_invalidate_tree(scf->dirs,
535                                         BUF_PTR_LEN(&fam_dir->name));
536             fam_dir_periodic_cleanup();
537             break;
538         default:
539             break;
540         }
541 }
542 
543 static handler_t stat_cache_handle_fdevent(void *ctx, int revent)
544 {
545 	stat_cache_fam * const scf = ctx; /* sc.scf */
546 
547 	if (revent & FDEVENT_IN) {
548 		stat_cache_handle_fdevent_in(scf);
549 	}
550 
551 	if (revent & (FDEVENT_HUP|FDEVENT_RDHUP)) {
552 		/* fam closed the connection */
553 		log_error(scf->errh, __FILE__, __LINE__,
554 		  "FAM connection closed; disabling stat_cache.");
555 		/* (although effectively STAT_CACHE_ENGINE_NONE,
556 		 *  do not change here so that periodic jobs clean up memory)*/
557 		/*sc.stat_cache_engine = STAT_CACHE_ENGINE_NONE; */
558 		fdevent_fdnode_event_del(scf->ev, scf->fdn);
559 		fdevent_unregister(scf->ev, scf->fd);
560 		scf->fdn = NULL;
561 
562 		FAMClose(&scf->fam);
563 		scf->fd = -1;
564 	}
565 
566 	return HANDLER_GO_ON;
567 }
568 
569 static stat_cache_fam * stat_cache_init_fam(fdevents *ev, log_error_st *errh) {
570 	stat_cache_fam *scf = calloc(1, sizeof(*scf));
571 	force_assert(scf);
572 	scf->fd = -1;
573 	scf->ev = ev;
574 	scf->errh = errh;
575 
576   #ifdef HAVE_SYS_INOTIFY_H
577 	scf->fd = inotify_init1(IN_NONBLOCK|IN_CLOEXEC);
578 	if (scf->fd < 0) {
579 		log_perror(errh, __FILE__, __LINE__, "inotify_init1()");
580 		free(scf);
581 		return NULL;
582 	}
583   #elif defined HAVE_SYS_EVENT_H && defined HAVE_KQUEUE
584    #ifdef __NetBSD__
585 	scf->fd = kqueue1(O_NONBLOCK|O_CLOEXEC|O_NOSIGPIPE);
586    #else
587 	scf->fd = kqueue();
588 	if (scf->fd >= 0) fdevent_setfd_cloexec(scf->fd);
589    #endif
590 	if (scf->fd < 0) {
591 		log_perror(errh, __FILE__, __LINE__, "kqueue()");
592 		free(scf);
593 		return NULL;
594 	}
595   #else
596 	/* setup FAM */
597 	if (0 != FAMOpen2(&scf->fam, "lighttpd")) {
598 		log_error(errh, __FILE__, __LINE__,
599 		  "could not open a fam connection, dying.");
600 		free(scf);
601 		return NULL;
602 	}
603       #ifdef HAVE_FAMNOEXISTS
604       #ifdef LIGHTTPD_STATIC
605 	FAMNoExists(&scf->fam);
606       #else
607 	int (*FAMNoExists_fn)(FAMConnection *);
608 	FAMNoExists_fn =
609 	  (int (*)(FAMConnection *))(intptr_t)dlsym(RTLD_DEFAULT,"FAMNoExists");
610 	if (FAMNoExists_fn) FAMNoExists_fn(&scf->fam);
611       #endif
612       #endif
613 
614 	scf->fd = FAMCONNECTION_GETFD(&scf->fam);
615 	fdevent_setfd_cloexec(scf->fd);
616   #endif
617 	scf->fdn = fdevent_register(scf->ev, scf->fd, stat_cache_handle_fdevent, scf);
618 	fdevent_fdnode_event_set(scf->ev, scf->fdn, FDEVENT_IN | FDEVENT_RDHUP);
619 
620 	return scf;
621 }
622 
623 static void stat_cache_free_fam(stat_cache_fam *scf) {
624 	if (NULL == scf) return;
625 
626       #ifdef HAVE_SYS_INOTIFY_H
627 	while (scf->wds) {
628 		splay_tree *node = scf->wds;
629 		scf->wds = splaytree_delete(scf->wds, node->key);
630 	}
631       #elif defined HAVE_SYS_EVENT_H && defined HAVE_KQUEUE
632 	/*(quicker cleanup to close kqueue() before cancel per entry)*/
633 	close(scf->fd);
634 	scf->fd = -1;
635       #endif
636 	while (scf->dirs) {
637 		/*(skip entry invalidation and FAMCancelMonitor())*/
638 		splay_tree *node = scf->dirs;
639 		fam_dir_entry_free((fam_dir_entry *)node->data);
640 		scf->dirs = splaytree_delete(scf->dirs, node->key);
641 	}
642 
643 	if (-1 != scf->fd) {
644 		/*scf->fdn already cleaned up in fdevent_free()*/
645 		FAMClose(&scf->fam);
646 		/*scf->fd = -1;*/
647 	}
648 
649 	free(scf);
650 }
651 
652 static fam_dir_entry * fam_dir_monitor(stat_cache_fam *scf, char *fn, uint32_t dirlen, struct stat *st)
653 {
654     if (NULL == scf->fdn) return NULL; /* FAM connection closed; do nothing */
655     const int fn_is_dir = S_ISDIR(st->st_mode);
656     /*force_assert(0 != dirlen);*/
657     /*force_assert(fn[0] == '/');*/
658     /* consistency: ensure fn does not end in '/' unless root "/"
659      * FAM events will not end in '/', so easier to match this way */
660     if (fn[dirlen-1] == '/') --dirlen;
661     if (0 == dirlen) dirlen = 1; /* root dir ("/") */
662     /* Note: paths are expected to be normalized before calling stat_cache,
663      * e.g. without repeated '/' */
664     if (!fn_is_dir) {
665         while (fn[--dirlen] != '/') ;
666         if (0 == dirlen) dirlen = 1; /*(should not happen for file)*/
667     }
668     int dir_ndx = splaytree_djbhash(fn, dirlen);
669     fam_dir_entry *fam_dir = NULL;
670 
671     scf->dirs = splaytree_splay(scf->dirs, dir_ndx);
672     if (NULL != scf->dirs && scf->dirs->key == dir_ndx) {
673         fam_dir = scf->dirs->data;
674         if (!buffer_eq_slen(&fam_dir->name, fn, dirlen)) {
675             /* hash collision; preserve existing
676              * do not monitor new to avoid cache thrashing */
677             return NULL;
678         }
679         /* directory already registered */
680     }
681 
682     const unix_time64_t cur_ts = log_monotonic_secs;
683     struct stat lst;
684     int ck_dir = fn_is_dir;
685     if (!fn_is_dir && (NULL==fam_dir || cur_ts - fam_dir->stat_ts >= 16)) {
686         ck_dir = 1;
687         /*(temporarily modify fn)*/
688         fn[dirlen] = '\0';
689         if (0 != lstat(fn, &lst)) {
690             fn[dirlen] = '/';
691             return NULL;
692         }
693         if (!S_ISLNK(lst.st_mode)) {
694             st = &lst;
695         }
696         else if (0 != stat(fn, st)) { /*st passed in now is stat() of dir*/
697             fn[dirlen] = '/';
698             return NULL;
699         }
700         fn[dirlen] = '/';
701     }
702 
703     int ck_lnk = (NULL == fam_dir);
704     if (ck_dir && NULL != fam_dir) {
705         /* check stat() matches device and inode, just in case an external event
706          * not being monitored occurs (e.g. rename of unmonitored parent dir)*/
707         if (st->st_dev != fam_dir->st_dev || st->st_ino != fam_dir->st_ino) {
708             ck_lnk = 1;
709             /*(modifies scf->dirs but no need to re-splay for dir_ndx since
710              * fam_dir is not NULL and so splaytree_insert not called below)*/
711             if (scf->dirs) fam_dir_invalidate_tree(scf->dirs, fn, dirlen);
712             if (!fn_is_dir) /*(if dir, caller is updating stat_cache_entry)*/
713                 stat_cache_update_entry(fn, dirlen, st, NULL);
714             /*(must not delete tree since caller is holding a valid node)*/
715             stat_cache_invalidate_dir_tree(fn, dirlen);
716           #ifdef HAVE_SYS_INOTIFY_H
717             scf->wds = splaytree_delete(scf->wds, fam_dir->req);
718           #endif
719             if (0 != FAMCancelMonitor(&scf->fam, &fam_dir->req)
720                 || 0 != FAMMonitorDirectory(&scf->fam, fam_dir->name.ptr,
721                                             &fam_dir->req,
722                                             (void *)(intptr_t)dir_ndx)) {
723                 fam_dir->stat_ts = 0; /* invalidate */
724                 return NULL;
725             }
726             fam_dir->st_dev = st->st_dev;
727             fam_dir->st_ino = st->st_ino;
728           #ifdef HAVE_SYS_INOTIFY_H
729             scf->wds = splaytree_insert(scf->wds, fam_dir->req, fam_dir);
730           #endif
731         }
732         fam_dir->stat_ts = cur_ts;
733     }
734 
735     if (NULL == fam_dir) {
736         fam_dir = fam_dir_entry_init(fn, dirlen);
737 
738         if (0 != FAMMonitorDirectory(&scf->fam,fam_dir->name.ptr,&fam_dir->req,
739                                      (void *)(intptr_t)dir_ndx)) {
740           #if defined(HAVE_SYS_INOTIFY_H) \
741            || (defined HAVE_SYS_EVENT_H && defined HAVE_KQUEUE)
742             log_perror(scf->errh, __FILE__, __LINE__,
743               "monitoring dir failed: %s file: %s",
744               fam_dir->name.ptr, fn);
745           #else
746             log_error(scf->errh, __FILE__, __LINE__,
747               "monitoring dir failed: %s file: %s %s",
748               fam_dir->name.ptr, fn, FamErrlist[FAMErrno]);
749           #endif
750             fam_dir_entry_free(fam_dir);
751             return NULL;
752         }
753 
754         scf->dirs = splaytree_insert(scf->dirs, dir_ndx, fam_dir);
755       #ifdef HAVE_SYS_INOTIFY_H
756         scf->wds = splaytree_insert(scf->wds, fam_dir->req, fam_dir);
757       #endif
758         fam_dir->stat_ts= cur_ts;
759         fam_dir->st_dev = st->st_dev;
760         fam_dir->st_ino = st->st_ino;
761     }
762 
763     if (ck_lnk) {
764         if (fn_is_dir) {
765             /*(temporarily modify fn)*/
766             char e = fn[dirlen];
767             fn[dirlen] = '\0';
768             if (0 != lstat(fn, &lst)) {
769                 fn[dirlen] = e;
770                 return NULL;
771             }
772             fn[dirlen] = e;
773         }
774         if (fam_dir->fam_parent) {
775             --fam_dir->fam_parent->refcnt;
776             fam_dir->fam_parent = NULL;
777         }
778         if (S_ISLNK(lst.st_mode)) {
779             fam_dir->fam_parent = fam_dir_monitor(scf, fn, dirlen, &lst);
780         }
781     }
782 
783     ++fam_dir->refcnt;
784     return fam_dir;
785 }
786 
787 #endif
788 
789 
790 static stat_cache_entry * stat_cache_entry_init(void) {
791     stat_cache_entry *sce = calloc(1, sizeof(*sce));
792     force_assert(NULL != sce);
793     sce->fd = -1;
794     sce->refcnt = 1;
795     return sce;
796 }
797 
798 static void stat_cache_entry_free(void *data) {
799     stat_cache_entry *sce = data;
800     if (!sce) return;
801 
802     if (--sce->refcnt) return;
803 
804   #ifdef HAVE_FAM_H
805     /*(decrement refcnt only;
806      * defer cancelling FAM monitor on dir even if refcnt reaches zero)*/
807     if (sce->fam_dir) --((fam_dir_entry *)sce->fam_dir)->refcnt;
808   #endif
809 
810     free(sce->name.ptr);
811     free(sce->etag.ptr);
812     if (sce->content_type.size) free(sce->content_type.ptr);
813     if (sce->fd >= 0) close(sce->fd);
814 
815     free(sce);
816 }
817 
818 void stat_cache_entry_refchg(void *data, int mod) {
819     /*(expect mod == -1 or mod == 1)*/
820     stat_cache_entry * const sce = data;
821     if (mod < 0 && 1 == sce->refcnt)
822         stat_cache_entry_free(data);
823     else
824         sce->refcnt += mod;
825 }
826 
827 #if defined(HAVE_XATTR) || defined(HAVE_EXTATTR)
828 
829 static const char *attrname = "Content-Type";
830 static char attrval[128];
831 static buffer attrb = { attrval, 0, 0 };
832 
833 static int stat_cache_attr_get(const char *name) {
834   #if defined(HAVE_XATTR)
835    #if defined(HAVE_SYS_XATTR_H)
836     ssize_t attrlen;
837     if (0 < (attrlen = getxattr(name, attrname,
838                                 attrval, sizeof(attrval)-1)))
839    #else
840     int attrlen = sizeof(attrval)-1;
841     if (0 == attr_get(name, attrname, attrval, &attrlen, 0))
842    #endif
843   #elif defined(HAVE_EXTATTR)
844     ssize_t attrlen;
845     if (0 < (attrlen = extattr_get_file(name, EXTATTR_NAMESPACE_USER, attrname,
846                                         attrval, sizeof(attrval)-1)))
847   #endif
848     {
849         attrval[attrlen] = '\0';
850         attrb.used = (uint32_t)(attrlen + 1);
851         return 1;
852     }
853     return 0;
854 }
855 
856 #endif
857 
858 int stat_cache_init(fdevents *ev, log_error_st *errh) {
859   #ifdef HAVE_FAM_H
860     if (sc.stat_cache_engine == STAT_CACHE_ENGINE_FAM) {
861         sc.scf = stat_cache_init_fam(ev, errh);
862         if (NULL == sc.scf) return 0;
863     }
864   #else
865     UNUSED(ev);
866     UNUSED(errh);
867   #endif
868 
869     return 1;
870 }
871 
872 void stat_cache_free(void) {
873     splay_tree *sptree = sc.files;
874     while (sptree) {
875         stat_cache_entry_free(sptree->data);
876         sptree = splaytree_delete(sptree, sptree->key);
877     }
878     sc.files = NULL;
879 
880   #ifdef HAVE_FAM_H
881     stat_cache_free_fam(sc.scf);
882     sc.scf = NULL;
883   #endif
884 
885   #if defined(HAVE_XATTR) || defined(HAVE_EXTATTR)
886     attrname = "Content-Type";
887   #endif
888 
889     sc.stat_cache_engine = STAT_CACHE_ENGINE_SIMPLE; /*(default)*/
890 }
891 
892 void stat_cache_xattrname (const char *name) {
893   #if defined(HAVE_XATTR) || defined(HAVE_EXTATTR)
894     attrname = name;
895   #else
896     UNUSED(name);
897   #endif
898 }
899 
900 int stat_cache_choose_engine (const buffer *stat_cache_string, log_error_st *errh) {
901     if (buffer_is_blank(stat_cache_string))
902         sc.stat_cache_engine = STAT_CACHE_ENGINE_SIMPLE;
903     else if (buffer_eq_slen(stat_cache_string, CONST_STR_LEN("simple")))
904         sc.stat_cache_engine = STAT_CACHE_ENGINE_SIMPLE;
905 #ifdef HAVE_SYS_INOTIFY_H
906     else if (buffer_eq_slen(stat_cache_string, CONST_STR_LEN("inotify")))
907         sc.stat_cache_engine = STAT_CACHE_ENGINE_INOTIFY;
908         /*(STAT_CACHE_ENGINE_FAM == STAT_CACHE_ENGINE_INOTIFY)*/
909 #elif defined HAVE_SYS_EVENT_H && defined HAVE_KQUEUE
910     else if (buffer_eq_slen(stat_cache_string, CONST_STR_LEN("kqueue")))
911         sc.stat_cache_engine = STAT_CACHE_ENGINE_KQUEUE;
912         /*(STAT_CACHE_ENGINE_FAM == STAT_CACHE_ENGINE_KQUEUE)*/
913 #endif
914 #ifdef HAVE_FAM_H
915     else if (buffer_eq_slen(stat_cache_string, CONST_STR_LEN("fam")))
916         sc.stat_cache_engine = STAT_CACHE_ENGINE_FAM;
917 #endif
918     else if (buffer_eq_slen(stat_cache_string, CONST_STR_LEN("disable"))
919              || buffer_eq_slen(stat_cache_string, CONST_STR_LEN("none")))
920         sc.stat_cache_engine = STAT_CACHE_ENGINE_NONE;
921     else {
922         log_error(errh, __FILE__, __LINE__,
923           "server.stat-cache-engine can be one of \"disable\", \"simple\","
924 #ifdef HAVE_SYS_INOTIFY_H
925           " \"inotify\","
926 #elif defined HAVE_SYS_EVENT_H && defined HAVE_KQUEUE
927           " \"kqueue\","
928 #endif
929 #ifdef HAVE_FAM_H
930           " \"fam\","
931 #endif
932           " but not: %s", stat_cache_string->ptr);
933         return -1;
934     }
935     return 0;
936 }
937 
938 const buffer * stat_cache_mimetype_by_ext(const array * const mimetypes, const char * const name, const uint32_t nlen)
939 {
940     const char * const end = name + nlen; /*(end of string)*/
941     const uint32_t used = mimetypes->used;
942     if (used < 16) {
943         for (uint32_t i = 0; i < used; ++i) {
944             /* suffix match */
945             const data_string *ds = (data_string *)mimetypes->data[i];
946             const size_t klen = buffer_clen(&ds->key);
947             if (klen <= nlen && buffer_eq_icase_ssn(end-klen, ds->key.ptr, klen))
948                 return &ds->value;
949         }
950     }
951     else {
952         const char *s;
953         const data_string *ds;
954         if (nlen) {
955             for (s = end-1; s != name && *s != '/'; --s) ; /*(like memrchr())*/
956             if (*s == '/') ++s;
957         }
958         else {
959             s = name;
960         }
961         /* search for basename, then longest .ext2.ext1, then .ext1, then "" */
962         ds = (const data_string *)array_get_element_klen(mimetypes, s, end - s);
963         if (NULL != ds) return &ds->value;
964         while (++s < end) {
965             while (*s != '.' && ++s != end) ;
966             if (s == end) break;
967             /* search ".ext" then "ext" */
968             ds = (const data_string *)array_get_element_klen(mimetypes, s, end - s);
969             if (NULL != ds) return &ds->value;
970             /* repeat search without leading '.' to handle situation where
971              * admin configured mimetype.assign keys without leading '.' */
972             if (++s < end) {
973                 if (*s == '.') { --s; continue; }
974                 ds = (const data_string *)array_get_element_klen(mimetypes, s, end - s);
975                 if (NULL != ds) return &ds->value;
976             }
977         }
978         /* search for ""; catchall */
979         ds = (const data_string *)array_get_element_klen(mimetypes, CONST_STR_LEN(""));
980         if (NULL != ds) return &ds->value;
981     }
982 
983     return NULL;
984 }
985 
986 #if defined(HAVE_XATTR) || defined(HAVE_EXTATTR)
987 
988 const buffer * stat_cache_mimetype_by_xattr(const char * const name)
989 {
990     return stat_cache_attr_get(name) ? &attrb : NULL;
991 }
992 
993 const buffer * stat_cache_content_type_get_by_xattr(stat_cache_entry *sce, const array *mimetypes, int use_xattr)
994 {
995     /*(invalid caching if user config has multiple, different
996      * r->conf.mimetypes for same extension (not expected))*/
997     if (!buffer_is_blank(&sce->content_type)) return &sce->content_type;
998 
999     if (!S_ISREG(sce->st.st_mode)) return NULL;
1000 
1001     /* cache mimetype */
1002     const buffer *mtype =
1003       (use_xattr) ? stat_cache_mimetype_by_xattr(sce->name.ptr) : NULL;
1004     if (NULL == mtype)
1005         mtype = stat_cache_mimetype_by_ext(mimetypes, BUF_PTR_LEN(&sce->name));
1006     if (NULL != mtype) {
1007         if (sce->content_type.size) {
1008             buffer_copy_buffer(&sce->content_type, mtype);
1009         }
1010         else if (mtype == &attrb) {
1011             sce->content_type.ptr = NULL;
1012             buffer_copy_buffer(&sce->content_type, mtype);
1013         }
1014         else {
1015             /*(copy pointers from mimetypes array; avoid allocation)*/
1016             sce->content_type.ptr = mtype->ptr;
1017             sce->content_type.used = mtype->used;
1018             /*(leave sce->content_type.size = 0 to flag not-allocated)*/
1019         }
1020     }
1021     else
1022         buffer_clear(&sce->content_type);
1023 
1024     return &sce->content_type;
1025 }
1026 
1027 #else
1028 
1029 const buffer * stat_cache_content_type_get_by_ext(stat_cache_entry *sce, const array *mimetypes)
1030 {
1031     /*(invalid caching if user config has multiple, different
1032      * r->conf.mimetypes for same extension (not expected))*/
1033     if (!buffer_is_blank(&sce->content_type)) return &sce->content_type;
1034 
1035     if (!S_ISREG(sce->st.st_mode)) return NULL;
1036 
1037     /* cache mimetype */
1038     const buffer * const mtype =
1039       stat_cache_mimetype_by_ext(mimetypes, BUF_PTR_LEN(&sce->name));
1040     if (NULL != mtype) {
1041         /*(copy pointers from mimetypes array; avoid allocation)*/
1042         sce->content_type.ptr = mtype->ptr;
1043         sce->content_type.used = mtype->used;
1044         /*(leave sce->content_type.size = 0 to flag not-allocated)*/
1045     }
1046     else
1047         buffer_clear(&sce->content_type);
1048 
1049     return &sce->content_type;
1050 }
1051 
1052 #endif
1053 
1054 const buffer * stat_cache_etag_get(stat_cache_entry *sce, int flags) {
1055     /*(invalid caching if user cfg has multiple, different r->conf.etag_flags
1056      * for same path (not expected, since etag flags should be by filesystem))*/
1057     if (!buffer_is_blank(&sce->etag)) return &sce->etag;
1058 
1059     if (S_ISREG(sce->st.st_mode) || S_ISDIR(sce->st.st_mode)) {
1060         if (0 == flags) return NULL;
1061         http_etag_create(&sce->etag, &sce->st, flags);
1062         return &sce->etag;
1063     }
1064 
1065     return NULL;
1066 }
1067 
1068 __attribute_pure__
1069 static int stat_cache_stat_eq(const struct stat * const sta, const struct stat * const stb) {
1070     return
1071       #ifdef st_mtime /* use high-precision timestamp if available */
1072       #if defined(__APPLE__) && defined(__MACH__)
1073         sta->st_mtimespec.tv_nsec == stb->st_mtimespec.tv_nsec
1074       #else
1075         sta->st_mtim.tv_nsec == stb->st_mtim.tv_nsec
1076       #endif
1077       #else
1078         1
1079       #endif
1080         && sta->st_mtime == stb->st_mtime
1081         && sta->st_size  == stb->st_size
1082         && sta->st_ino   == stb->st_ino
1083         && sta->st_dev   == stb->st_dev;
1084 }
1085 
1086 void stat_cache_update_entry(const char *name, uint32_t len,
1087                              struct stat *st, buffer *etagb)
1088 {
1089     if (sc.stat_cache_engine == STAT_CACHE_ENGINE_NONE) return;
1090     force_assert(0 != len);
1091     if (name[len-1] == '/') { if (0 == --len) len = 1; }
1092     splay_tree **sptree = &sc.files;
1093     stat_cache_entry *sce =
1094       stat_cache_sptree_find(sptree, name, len);
1095     if (sce && buffer_is_equal_string(&sce->name, name, len)) {
1096         if (!stat_cache_stat_eq(&sce->st, st)) {
1097             /* etagb might be NULL to clear etag (invalidate) */
1098             buffer_clear(&sce->etag);
1099             if (etagb)
1100                 buffer_copy_string_len(&sce->etag, BUF_PTR_LEN(etagb));
1101           #if defined(HAVE_XATTR) || defined(HAVE_EXTATTR)
1102             buffer_clear(&sce->content_type);
1103           #endif
1104             if (sce->fd >= 0) {
1105                 if (1 == sce->refcnt) {
1106                     close(sce->fd);
1107                     sce->fd = -1;
1108                 }
1109                 else {
1110                     --sce->refcnt; /* stat_cache_entry_free(sce); */
1111                     (*sptree)->data = sce = stat_cache_entry_init();
1112                     buffer_copy_string_len(&sce->name, name, len);
1113                 }
1114             }
1115             sce->st = *st;
1116         }
1117         sce->stat_ts = log_monotonic_secs;
1118     }
1119 }
1120 
1121 void stat_cache_delete_entry(const char *name, uint32_t len)
1122 {
1123     if (sc.stat_cache_engine == STAT_CACHE_ENGINE_NONE) return;
1124     force_assert(0 != len);
1125     if (name[len-1] == '/') { if (0 == --len) len = 1; }
1126     splay_tree **sptree = &sc.files;
1127     stat_cache_entry *sce = stat_cache_sptree_find(sptree, name, len);
1128     if (sce && buffer_is_equal_string(&sce->name, name, len)) {
1129         stat_cache_entry_free(sce);
1130         *sptree = splaytree_delete(*sptree, (*sptree)->key);
1131     }
1132 }
1133 
1134 void stat_cache_invalidate_entry(const char *name, uint32_t len)
1135 {
1136     splay_tree **sptree = &sc.files;
1137     stat_cache_entry *sce = stat_cache_sptree_find(sptree, name, len);
1138     if (sce && buffer_is_equal_string(&sce->name, name, len)) {
1139         sce->stat_ts = 0;
1140       #ifdef HAVE_FAM_H
1141         if (sce->fam_dir != NULL) {
1142             --((fam_dir_entry *)sce->fam_dir)->refcnt;
1143             sce->fam_dir = NULL;
1144         }
1145       #endif
1146     }
1147 }
1148 
1149 #ifdef HAVE_FAM_H
1150 
1151 static void stat_cache_invalidate_dir_tree_walk(splay_tree *t,
1152                                                 const char *name, size_t len)
1153 {
1154     if (t->left)  stat_cache_invalidate_dir_tree_walk(t->left,  name, len);
1155     if (t->right) stat_cache_invalidate_dir_tree_walk(t->right, name, len);
1156 
1157     const buffer * const b = &((stat_cache_entry *)t->data)->name;
1158     const size_t blen = buffer_clen(b);
1159     if (blen > len && b->ptr[len] == '/' && 0 == memcmp(b->ptr, name, len)) {
1160         stat_cache_entry *sce = t->data;
1161         sce->stat_ts = 0;
1162         if (sce->fam_dir != NULL) {
1163             --((fam_dir_entry *)sce->fam_dir)->refcnt;
1164             sce->fam_dir = NULL;
1165         }
1166     }
1167 }
1168 
1169 static void stat_cache_invalidate_dir_tree(const char *name, size_t len)
1170 {
1171     splay_tree * const sptree = sc.files;
1172     if (sptree) stat_cache_invalidate_dir_tree_walk(sptree, name, len);
1173 }
1174 
1175 #endif
1176 
1177 /*
1178  * walk though splay_tree and collect contents of dir tree.
1179  * remove tagged entries in a second loop
1180  */
1181 
1182 static void stat_cache_tag_dir_tree(splay_tree *t, const char *name, size_t len,
1183                                     int *keys, int *ndx)
1184 {
1185     if (*ndx == 8192) return; /*(must match num array entries in keys[])*/
1186     if (t->left)  stat_cache_tag_dir_tree(t->left,  name, len, keys, ndx);
1187     if (t->right) stat_cache_tag_dir_tree(t->right, name, len, keys, ndx);
1188     if (*ndx == 8192) return; /*(must match num array entries in keys[])*/
1189 
1190     const buffer * const b = &((stat_cache_entry *)t->data)->name;
1191     const size_t blen = buffer_clen(b);
1192     if (blen > len && b->ptr[len] == '/' && 0 == memcmp(b->ptr, name, len))
1193         keys[(*ndx)++] = t->key;
1194 }
1195 
1196 __attribute_noinline__
1197 static void stat_cache_prune_dir_tree(const char *name, size_t len)
1198 {
1199     splay_tree *sptree = sc.files;
1200     int max_ndx, i;
1201     int keys[8192]; /* 32k size on stack */
1202     do {
1203         if (!sptree) break;
1204         max_ndx = 0;
1205         stat_cache_tag_dir_tree(sptree, name, len, keys, &max_ndx);
1206         for (i = 0; i < max_ndx; ++i) {
1207             const int ndx = keys[i];
1208             splay_tree *node = sptree = splaytree_splay(sptree, ndx);
1209             if (node && node->key == ndx) {
1210                 stat_cache_entry_free(node->data);
1211                 sptree = splaytree_delete(sptree, ndx);
1212             }
1213         }
1214     } while (max_ndx == sizeof(keys)/sizeof(int));
1215     sc.files = sptree;
1216 }
1217 
1218 static void stat_cache_delete_tree(const char *name, uint32_t len)
1219 {
1220     stat_cache_delete_entry(name, len);
1221     stat_cache_prune_dir_tree(name, len);
1222 }
1223 
1224 void stat_cache_delete_dir(const char *name, uint32_t len)
1225 {
1226     force_assert(0 != len);
1227     if (name[len-1] == '/') { if (0 == --len) len = 1; }
1228     stat_cache_delete_tree(name, len);
1229   #ifdef HAVE_FAM_H
1230     if (sc.stat_cache_engine == STAT_CACHE_ENGINE_FAM) {
1231         splay_tree **sptree = &sc.scf->dirs;
1232         fam_dir_entry *fam_dir = stat_cache_sptree_find(sptree, name, len);
1233         if (fam_dir && buffer_eq_slen(&fam_dir->name, name, len))
1234             fam_dir_invalidate_node(fam_dir);
1235         if (*sptree) fam_dir_invalidate_tree(*sptree, name, len);
1236         fam_dir_periodic_cleanup();
1237     }
1238   #endif
1239 }
1240 
1241 /***
1242  *
1243  *
1244  *
1245  * returns:
1246  *  - HANDLER_FINISHED on cache-miss (don't forget to reopen the file)
1247  *  - HANDLER_ERROR on stat() failed -> see errno for problem
1248  */
1249 
1250 stat_cache_entry * stat_cache_get_entry(const buffer * const name) {
1251 	stat_cache_entry *sce = NULL;
1252 
1253 	/* consistency: ensure lookup name does not end in '/' unless root "/"
1254 	 * (but use full path given with stat(), even with trailing '/') */
1255 	int final_slash = 0;
1256 	size_t len = buffer_clen(name);
1257 	force_assert(0 != len);
1258 	if (name->ptr[len-1] == '/') { final_slash = 1; if (0 == --len) len = 1; }
1259 	/* Note: paths are expected to be normalized before calling stat_cache,
1260 	 * e.g. without repeated '/' */
1261 
1262 	if (name->ptr[0] != '/') {
1263 		errno = EINVAL;
1264 		return NULL;
1265 	}
1266 
1267 	/*
1268 	 * check if the directory for this file has changed
1269 	 */
1270 
1271 	const unix_time64_t cur_ts = log_monotonic_secs;
1272 
1273 	const int file_ndx = splaytree_djbhash(name->ptr, len);
1274 	splay_tree *sptree = sc.files = splaytree_splay(sc.files, file_ndx);
1275 
1276 	if (sptree && (sptree->key == file_ndx)) {
1277 		/* we have seen this file already and
1278 		 * don't stat() it again in the same second */
1279 
1280 		sce = sptree->data;
1281 
1282 		/* check if the name is the same, we might have a collision */
1283 
1284 		if (buffer_is_equal_string(&sce->name, name->ptr, len)) {
1285 			if (sc.stat_cache_engine == STAT_CACHE_ENGINE_SIMPLE) {
1286 				if (sce->stat_ts == cur_ts) {
1287 					if (final_slash && !S_ISDIR(sce->st.st_mode)) {
1288 						errno = ENOTDIR;
1289 						return NULL;
1290 					}
1291 					return sce;
1292 				}
1293 			}
1294 		      #ifdef HAVE_FAM_H
1295 			else if (sc.stat_cache_engine == STAT_CACHE_ENGINE_FAM
1296 				 && sce->fam_dir) { /* entry is in monitored dir */
1297 				/* re-stat() periodically, even if monitoring for changes
1298 				 * (due to limitations in stat_cache.c use of FAM)
1299 				 * (gaps due to not continually monitoring an entire tree) */
1300 				if (cur_ts - sce->stat_ts < 16) {
1301 					if (final_slash && !S_ISDIR(sce->st.st_mode)) {
1302 						errno = ENOTDIR;
1303 						return NULL;
1304 					}
1305 					return sce;
1306 				}
1307 			}
1308 		      #endif
1309 		} else {
1310 			/* collision, forget about the entry */
1311 			sce = NULL;
1312 		}
1313 	}
1314 
1315 	struct stat st;
1316 	if (-1 == stat(name->ptr, &st)) {
1317 		return NULL;
1318 	}
1319 
1320 	if (NULL == sce) {
1321 
1322 		/* fix broken stat/open for symlinks to reg files with appended slash on freebsd,osx */
1323 		if (final_slash && S_ISREG(st.st_mode)) {
1324 			errno = ENOTDIR;
1325 			return NULL;
1326 		}
1327 
1328 		sce = stat_cache_entry_init();
1329 		buffer_copy_string_len(&sce->name, name->ptr, len);
1330 
1331 		/* already splayed file_ndx */
1332 		if (NULL != sptree && sptree->key == file_ndx) {
1333 			/* hash collision: replace old entry */
1334 			stat_cache_entry_free(sptree->data);
1335 			sptree->data = sce;
1336 		} else {
1337 			/*sptree =*/ sc.files = splaytree_insert(sptree, file_ndx, sce);
1338 		}
1339 
1340 	} else {
1341 
1342 		buffer_clear(&sce->etag);
1343 	      #if defined(HAVE_XATTR) || defined(HAVE_EXTATTR)
1344 		buffer_clear(&sce->content_type);
1345 	      #endif
1346 
1347 		/* close fd if file changed */
1348 		if (sce->fd >= 0 && !stat_cache_stat_eq(&sce->st, &st)) {
1349 			if (1 == sce->refcnt) {
1350 				close(sce->fd);
1351 				sce->fd = -1;
1352 			}
1353 			else {
1354 				--sce->refcnt; /* stat_cache_entry_free(sce); */
1355 				sptree->data = sce = stat_cache_entry_init();
1356 				buffer_copy_string_len(&sce->name, name->ptr, len);
1357 			}
1358 		}
1359 	}
1360 
1361 	sce->st = st; /*(copy prior to calling fam_dir_monitor())*/
1362 
1363 #ifdef HAVE_FAM_H
1364 	if (sc.stat_cache_engine == STAT_CACHE_ENGINE_FAM) {
1365 		if (sce->fam_dir) --((fam_dir_entry *)sce->fam_dir)->refcnt;
1366 		sce->fam_dir =
1367 		  fam_dir_monitor(sc.scf, name->ptr, len, &st);
1368 	      #if 0 /*(performed below)*/
1369 		if (NULL != sce->fam_dir) {
1370 			/*(may have been invalidated by dir change)*/
1371 			sce->stat_ts = cur_ts;
1372 		}
1373 	      #endif
1374 	}
1375 #endif
1376 
1377 	sce->stat_ts = cur_ts;
1378 	return sce;
1379 }
1380 
1381 stat_cache_entry * stat_cache_get_entry_open(const buffer * const name, const int symlinks) {
1382     stat_cache_entry * const sce = stat_cache_get_entry(name);
1383     if (NULL == sce) return NULL;
1384     if (sce->fd >= 0) return sce;
1385     if (sce->st.st_size > 0) {
1386         sce->fd = stat_cache_open_rdonly_fstat(name, &sce->st, symlinks);
1387         buffer_clear(&sce->etag);
1388     }
1389     return sce; /* (note: sce->fd might still be -1 if open() failed) */
1390 }
1391 
1392 const stat_cache_st * stat_cache_path_stat (const buffer * const name) {
1393     const stat_cache_entry * const sce = stat_cache_get_entry(name);
1394     return sce ? &sce->st : NULL;
1395 }
1396 
1397 int stat_cache_path_isdir(const buffer *name) {
1398     const stat_cache_entry * const sce = stat_cache_get_entry(name);
1399     return (sce && (S_ISDIR(sce->st.st_mode) ? 1 : (errno = ENOTDIR, 0)));
1400 }
1401 
1402 int stat_cache_path_contains_symlink(const buffer *name, log_error_st *errh) {
1403     /* caller should check for symlinks only if we should block symlinks. */
1404 
1405     /* catch the obvious symlinks
1406      *
1407      * this is not a secure check as we still have a race-condition between
1408      * the stat() and the open. We can only solve this by
1409      * 1. open() the file
1410      * 2. fstat() the fd
1411      *
1412      * and keeping the file open for the rest of the time. But this can
1413      * only be done at network level.
1414      * */
1415 
1416   #ifdef HAVE_LSTAT
1417     /* we assume "/" can not be symlink,
1418      * so skip the symlink stuff if path is "/" */
1419     size_t len = buffer_clen(name);
1420     force_assert(0 != len);
1421     force_assert(name->ptr[0] == '/');
1422     if (1 == len) return 0;
1423    #ifndef PATH_MAX
1424    #define PATH_MAX 4096
1425    #endif
1426     if (len >= PATH_MAX) return -1;
1427 
1428     char buf[PATH_MAX];
1429     memcpy(buf, name->ptr, len);
1430     char *s_cur = buf+len;
1431     do {
1432         *s_cur = '\0';
1433         struct stat st;
1434         if (0 == lstat(buf, &st)) {
1435             if (S_ISLNK(st.st_mode)) return 1;
1436         }
1437         else {
1438             log_perror(errh, __FILE__, __LINE__, "lstat failed for: %s", buf);
1439             return -1;
1440         }
1441     } while ((s_cur = strrchr(buf, '/')) > buf); /*(&buf[0]==buf; NULL < buf)*/
1442   #endif
1443 
1444     return 0;
1445 }
1446 
1447 int stat_cache_open_rdonly_fstat (const buffer *name, struct stat *st, int symlinks) {
1448 	/*(Note: O_NOFOLLOW affects only the final path segment, the target file,
1449 	 * not any intermediate symlinks along the path)*/
1450 	const int fd = fdevent_open_cloexec(name->ptr, symlinks, O_RDONLY, 0);
1451 	if (fd >= 0) {
1452 		if (0 == fstat(fd, st)) {
1453 			return fd;
1454 		} else {
1455 			const int errnum = errno;
1456 			close(fd);
1457 			errno = errnum;
1458 		}
1459 	}
1460 	return -1;
1461 }
1462 
1463 /**
1464  * remove stat() from cache which haven't been stat()ed for
1465  * more than 2 seconds
1466  *
1467  *
1468  * walk though the stat-cache, collect the ids which are too old
1469  * and remove them in a second loop
1470  */
1471 
1472 static void stat_cache_tag_old_entries(splay_tree * const t, int * const keys, int * const ndx, const time_t max_age, const unix_time64_t cur_ts) {
1473     if (*ndx == 8192) return; /*(must match num array entries in keys[])*/
1474     if (t->left)
1475         stat_cache_tag_old_entries(t->left, keys, ndx, max_age, cur_ts);
1476     if (t->right)
1477         stat_cache_tag_old_entries(t->right, keys, ndx, max_age, cur_ts);
1478     if (*ndx == 8192) return; /*(must match num array entries in keys[])*/
1479 
1480     const stat_cache_entry * const sce = t->data;
1481     if (cur_ts - sce->stat_ts > max_age)
1482         keys[(*ndx)++] = t->key;
1483 }
1484 
1485 static void stat_cache_periodic_cleanup(const time_t max_age, const unix_time64_t cur_ts) {
1486     splay_tree *sptree = sc.files;
1487     int max_ndx, i;
1488     int keys[8192]; /* 32k size on stack */
1489     do {
1490         if (!sptree) break;
1491         max_ndx = 0;
1492         stat_cache_tag_old_entries(sptree, keys, &max_ndx, max_age, cur_ts);
1493         for (i = 0; i < max_ndx; ++i) {
1494             int ndx = keys[i];
1495             sptree = splaytree_splay(sptree, ndx);
1496             if (sptree && sptree->key == ndx) {
1497                 stat_cache_entry_free(sptree->data);
1498                 sptree = splaytree_delete(sptree, ndx);
1499             }
1500         }
1501     } while (max_ndx == sizeof(keys)/sizeof(int));
1502     sc.files = sptree;
1503 }
1504 
1505 void stat_cache_trigger_cleanup(void) {
1506 	time_t max_age = 2;
1507 
1508       #ifdef HAVE_FAM_H
1509 	if (STAT_CACHE_ENGINE_FAM == sc.stat_cache_engine) {
1510 		if (log_monotonic_secs & 0x1F) return;
1511 		/* once every 32 seconds (0x1F == 31) */
1512 		max_age = 32;
1513 		fam_dir_periodic_cleanup();
1514 		/* By doing this before stat_cache_periodic_cleanup(),
1515 		 * entries used within the next max_age secs will remain
1516 		 * monitored, instead of effectively flushing and
1517 		 * rebuilding the FAM monitoring every max_age seconds */
1518 	}
1519       #endif
1520 
1521 	stat_cache_periodic_cleanup(max_age, log_monotonic_secs);
1522 }
1523