1 ;;; -*- mode: lisp; syntax: common-lisp; coding: utf-8; package: cl-inotify; -*-
3 ;; Copyright (c) 2011, Olof-Joachim Frahm
4 ;; All rights reserved.
6 ;; Redistribution and use in source and binary forms, with or without
7 ;; modification, are permitted provided that the following conditions are met:
8 ;; * Redistributions of source code must retain the above copyright
9 ;; notice, this list of conditions and the following disclaimer.
10 ;; * 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 ;; * The name of the author may not be used to endorse or promote products
14 ;; derived from this software without specific prior written permission.
16 ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17 ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 ;; ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
20 ;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 ;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 ;; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 ;; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 ;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 (in-package #:cl-inotify)
29 (defbitfield (inotify-flag :uint32)
33 (:close-write #.in-close-write)
34 (:close-nowrite #.in-close-nowrite)
37 (:moved-from #.in-moved-from)
38 (:moved-to #.in-moved-to)
42 (:delete-self #.in-delete-self)
43 (:move-self #.in-move-self)
44 (:unmount #.in-unmount)
45 (:q-overflow #.in-q-overflow)
46 (:ignored #.in-ignored)
47 (:onlydir #.in-onlydir)
48 (:dont-follow #.in-dont-follow)
49 (:mask-add #.in-mask-add)
51 (:oneshot #.in-oneshot)
52 (:all-events #.in-all-events))
54 (deftype inotify-add/read-flag ()
55 "Shared valid flags for the WATCH-RAW and READ-EVENT functions."
58 :close-write :close-nowrite :close
59 :create :delete :delete-self
61 :move-self :moved-from :moved-to :move
64 (deftype inotify-read-flag ()
65 "Valid flags which are returned from READ-EVENT."
66 '(or inotify-add/read-flag
67 (member :ignored :isdir :q-overflow :unmount)))
69 (deftype inotify-add-flag ()
70 "Valid flags for the WATCH-RAW function."
71 '(or inotify-add/read-flag
72 (member :dont-follow :mask-add :oneshot :onlydir)))
74 (defun valid-watch-flag-p (x)
75 (and (typep x 'inotify-add-flag)
76 (not (eq :mask-add x))
77 (not (eq :oneshot x))))
79 (defun valid-watch-flag-list-p (list)
80 (every #'valid-watch-flag-p list))
82 (deftype watch-flag-list ()
83 "Valid flags argument for the WATCH function, a list of keywords from
84 INOTIFY-ADD-FLAG. Basically only :MASK-ADD and :ONESHOT are removed.
85 The :MASK-ADD behaviour is replicated with the REPLACE-P argument; the
86 :ONESHOT behaviour doesn't play well with the WATCH function design (and
87 thus should be used only with WATCH-RAW)."
88 '(or (satisfies valid-watch-flag-p)
89 (and list (satisfies valid-watch-flag-list-p))))
91 (defcfun ("inotify_init" c-inotify-init) :int
92 "Initialises a new inotify event queue.")
94 (defcfun ("inotify_add_watch" c-inotify-add-watch) :int
95 "Watches a path on a event queue."
100 (defcfun ("inotify_rm_watch" c-inotify-rm-watch) :int
101 "Removes a watched path from a event queue."
105 (binary-types:define-signed int #.(cffi:foreign-type-size :int))
107 (binary-types:define-binary-struct inotify-event ()
108 "An inotify native event structure.
109 WD is the watch/file descriptor,
110 MASK is the (parsed) combination of events,
111 COOKIE is a unique integer which connects related events,
112 NAME optionally identifies a file relative to a watched directory."
113 (wd 0 :binary-type int)
114 (mask 0 :binary-type binary-types:u32)
115 (cookie 0 :binary-type binary-types:u32)
118 (defstruct (inotify-instance
119 (:constructor make-inotify-instance ())
120 (:conc-name inotify-))
121 "Contains the stream and file descriptor for a inotify instance."
126 ;;;; initialisation and stuff
128 (eval-when (:compile-toplevel :load-toplevel :execute)
129 (defun read-new-value (&optional (stream *query-io*))
130 "READs a value from the STREAM and returns it (wrapped in a list)."
131 (format stream "Enter a new value: ~%")
132 (list (read *query-io*))))
134 (eval-when (:compile-toplevel :load-toplevel :execute)
135 (defun init-endian ()
136 "Initialises the endianess for the BINARY-TYPES library. Is automatically
137 called when the library is loaded."
138 (setf binary-types:*endian*
139 (restart-case #+little-endian :little-endian
140 #+big-endian :big-endian
141 #-(or little-endian big-endian) (error "unknown endianess")
143 :report "Enter a correct value (either :LITTLE-ENDIAN or :BIG-ENDIAN)."
144 :interactive read-new-value
145 ;; TODO: better way to test for correct value/retry values?
147 ((:little-endian :big-endian) value)
148 (T (error "wrong value supplied (not :LITTLE-ENDIAN or :BIG-ENDIAN)"))))))))
150 ;; initialise the endianess
151 (eval-when (:compile-toplevel :load-toplevel :execute)
154 ;;;; basic wrapping of the API
156 (defun read-raw-event-from-stream (stream)
157 "Reads a raw event from the inotify stream."
158 (let* ((event (binary-types:read-binary 'inotify-event stream))
159 (len (binary-types:read-binary 'binary-types:u32 stream)))
161 (with-slots (name) event
162 (let ((buffer (make-array len :element-type '(unsigned-byte 8))))
163 (read-sequence buffer stream :end len)
164 (setf name (trivial-utf-8:utf-8-bytes-to-string buffer :end (position 0 buffer))))))
167 (defun read-event-from-stream (stream)
168 "Reads a event from the inotify stream and converts bitmasks on reading."
169 (let ((event (read-raw-event-from-stream stream)))
170 (with-slots (mask) event
171 (setf mask (foreign-bitfield-symbols 'inotify-flag mask)))
174 (defun set-nonblocking (fd nonblocking)
175 "Enables or disables NONBLOCKING mode on a file descriptor FD."
176 (let ((flags (sb-posix:fcntl fd sb-posix:f-getfl)))
177 ;; an error is raised if this fails, so we don't have to do it ourselves
178 (sb-posix:fcntl fd sb-posix:f-setfl
179 (funcall (if nonblocking #'logior #'logxor)
180 flags sb-posix:o-nonblock)))
183 (defun init-unregistered-inotify (inotify &optional (nonblocking T))
184 "Creates a new inotify event queue. If NONBLOCKING is set (default),
185 the file descriptor is set to non-blocking I/O."
186 (let ((result (c-inotify-init)))
187 (when (minusp result)
188 (perror "inotify_init failed"))
189 (with-slots (fd stream (non-block nonblocking)) inotify
191 ;; file descriptor is collected with auto-close
195 (set-nonblocking fd T)
196 (setf non-block nonblocking))
198 (sb-sys:make-fd-stream
201 :element-type '(unsigned-byte 8)
202 :name (format NIL "inotify event queue ~A" fd)
204 :buffering (if nonblocking :none :full))))
205 ;; if stream is constructed, gc'ing it will cleanup the file descriptor
207 (sb-posix:close fd)))))
210 (defun make-unregistered-inotify ()
211 "Creates a new unregistered INOTIFY instance."
212 (init-unregistered-inotify (make-inotify-instance)))
214 (defun close-inotify (inotify)
215 "Closes the inotify event queue."
216 (close (inotify-stream inotify))
219 (defun perror (prefix-string)
220 #+sbcl (sb-int:simple-perror prefix-string)
221 #-(or sbcl) (error prefix-string))
223 (defun ensure-list (arg)
224 (if (listp arg) arg `(,arg)))
226 (defun translate-keyword-flags (flags)
229 (foreign-bitfield-value 'inotify-flag (ensure-list flags)))
232 (defun watch-raw (inotify pathname flags)
233 "Adds PATHNAME (either of type PATHNAME or STRING) to be watched. FLAGS
234 determines how exactly (see inotify(7) for detailed information) and can
235 be of type LIST, KEYWORD or a raw numerical value (which isn't checked
236 for validity though). Returns a handle which can be used with UNWATCH-RAW."
237 (let* ((path (etypecase pathname
239 (pathname (namestring pathname))))
240 (result (c-inotify-add-watch (inotify-fd inotify)
241 path (translate-keyword-flags flags))))
242 (when (minusp result)
243 (perror "inotify_add_watch failed"))
246 (defun unwatch-raw (inotify handle)
247 "Stops watching the path associated with a HANDLE established by WATCH-RAW."
248 (let ((result (c-inotify-rm-watch (inotify-fd inotify) handle)))
249 (when (minusp result)
250 (perror "inotify_rm_watch failed")))
253 ;;;; support functions, making life easier
255 (defstruct (registered-inotify-instance
256 (:include inotify-instance)
257 (:constructor make-registered-inotify-instance ())
258 (:conc-name inotify-))
259 "Additionally to the information in INOTIFY-INSTANCE, records watched
260 paths in a dictionary."
263 (defun make-inotify (&optional (nonblocking T))
264 "Creates a new registered INOTIFY instance. In NONBLOCKING mode, the file
265 descriptor is set to non-blocking mode. The resulting object has to be
266 closed with CLOSE-INOTIFY."
267 (let ((result (make-registered-inotify-instance)))
268 (init-unregistered-inotify result nonblocking)
269 (with-slots (watched) result
270 (setf watched (make-hash-table :test 'equal)))
273 (defun pathname-handle/flags (inotify pathname)
274 "Returns a CONS cell with the values HANDLE and FLAGS if PATHNAME is
275 being watched by INOTIFY, else NIL. The match is exact."
276 (gethash pathname (inotify-watched inotify)))
278 (defun event-pathname/flags (inotify event &optional (handle (slot-value event 'wd)))
279 "Returns two values PATHNAME and FLAGS for an EVENT which were used during
280 registration. If HANDLE is specified EVENT is ignored."
282 (maphash (lambda (pathname entry)
283 (when (eql (car entry) handle)
284 (return (values pathname (cdr entry)))))
285 (inotify-watched inotify))))
287 (defun sane-user-flags (inotify pathname flags &key (replace-p T))
288 (check-type flags watch-flag-list)
289 ;; now, :mask-add can't be member of flags
291 (let* ((flags (ensure-list flags))
292 (rep-flags (if replace-p
293 (cons :mask-add flags)
295 (let ((it (gethash pathname (slot-value inotify 'watched))))
297 (union (cdr it) rep-flags :test #'eq)
300 (defun watch (inotify pathname flags &key (replace-p T))
301 "Adds PATHNAME (either pathname or string) to be watched and records the
302 watched paths. FLAGS (a list of keywords) determines how exactly (see
303 inotify(7) for detailed information). Returns a handle which can be used
304 with UNWATCH and EVENT-PATHNAME/FLAGS. If REPLACE-P is set to T (default),
305 the flags mask is replaced rather than OR-ed to the current mask (if it
306 exists). The :MASK-ADD flag is therefore removed from the FLAGS argument."
307 (let* ((flags (sane-user-flags inotify pathname flags :replace-p replace-p))
308 (handle (watch-raw inotify pathname flags)))
309 (with-slots (watched) inotify
310 (setf (gethash pathname watched) (cons handle flags)))
313 (defun unwatch (inotify &key pathname event handle)
314 "Disables watching the path associated with the supplied HANDLE (which
315 may be one from a given EVENT) or PATHNAME."
316 (unless (or pathname event handle)
317 (error "either PATHNAME, EVENT or HANDLE have to be specified"))
319 (setf handle (slot-value event 'wd)))
321 (unwatch-raw inotify handle)
322 (let ((handle (car (pathname-handle/flags inotify pathname))))
324 (error "PATHNAME ~S isn't being watched" pathname))
325 ;; remove even if unwatch-raw throws an error (which can happen if :oneshot is specified)
326 (remhash pathname (inotify-watched inotify))
327 (unwatch-raw inotify handle)))
330 (defun list-watched (inotify)
331 "Returns a LIST of all watched pathnames in no particular order."
333 for pathname being each hash-key in (inotify-watched inotify)
336 (defun unix-eagain-p (fd-stream)
337 "Returns T on a FD-STREAM if trying to read from the stream raised a
339 (multiple-value-bind (result error)
340 (sb-unix:unix-read (sb-sys:fd-stream-fd fd-stream) NIL 0)
341 (declare (ignore result))
342 (= error sb-unix:eagain)))
344 (defun event-available-p (inotify)
345 "Returns T if an event is available on the queue."
346 (if (inotify-nonblocking inotify)
347 (not (unix-eagain-p (inotify-stream inotify)))
348 (listen (inotify-stream inotify))))
350 (defun read-event (inotify)
351 "Reads an event from the queue. Blocks if no event is available."
352 (read-event-from-stream (inotify-stream inotify)))
354 (defun next-event (inotify)
355 "Reads an event from the queue. Returns NIL if none is available."
356 (when (event-available-p inotify)
357 (read-event inotify)))
359 (defmacro do-events ((var inotify &key blocking-p) &body body)
360 "Loops BODY with VAR bound to the next events retrieved from INOTIFY.
361 The macro uses NEXT-EVENT, so reading an event won't block and the loop
362 terminates if no events are available."
363 (check-type var symbol)
364 (let ((inotify-sym (gensym)))
366 with ,var and ,inotify-sym = ,inotify
368 `(while (event-available-p ,inotify-sym)))
370 (setf ,var (read-event ,inotify-sym))
373 (defun next-events (inotify)
374 "Reads all available events from the queue. Returns a LIST of events."
376 while (event-available-p inotify)
377 collect (read-event inotify)))