Fix QUERY-FILE-SYSTEM for Windows UNC and device file names
[sbcl.git] / src / code / filesys.lisp
1 ;;;; file system interface functions -- fairly Unix-centric, but with
2 ;;;; differences between Unix and Win32 papered over.
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!IMPL")
14 \f
15 ;;;; Unix pathname host support
16
17 ;;; FIXME: the below shouldn't really be here, but in documentation
18 ;;; (chapter 19 makes a lot of requirements for documenting
19 ;;; implementation-dependent decisions), but anyway it's probably not
20 ;;; what we currently do.
21 ;;;
22 ;;; Unix namestrings have the following format:
23 ;;;
24 ;;; namestring := [ directory ] [ file [ type [ version ]]]
25 ;;; directory := [ "/" ] { file "/" }*
26 ;;; file := [^/]*
27 ;;; type := "." [^/.]*
28 ;;; version := "." ([0-9]+ | "*")
29 ;;;
30 ;;; Note: this grammar is ambiguous. The string foo.bar.5 can be
31 ;;; parsed as either just the file specified or as specifying the
32 ;;; file, type, and version. Therefore, we use the following rules
33 ;;; when confronted with an ambiguous file.type.version string:
34 ;;;
35 ;;; - If the first character is a dot, it's part of the file. It is not
36 ;;; considered a dot in the following rules.
37 ;;;
38 ;;; - Otherwise, the last dot separates the file and the type.
39 ;;;
40 ;;; Wildcard characters:
41 ;;;
42 ;;; If the directory, file, type components contain any of the
43 ;;; following characters, it is considered part of a wildcard pattern
44 ;;; and has the following meaning.
45 ;;;
46 ;;; ? - matches any one character
47 ;;; * - matches any zero or more characters.
48 ;;; [abc] - matches any of a, b, or c.
49 ;;; {str1,str2,...,strn} - matches any of str1, str2, ..., or strn.
50 ;;;   (FIXME: no it doesn't)
51 ;;;
52 ;;; Any of these special characters can be preceded by a backslash to
53 ;;; cause it to be treated as a regular character.
54 (defun remove-backslashes (namestr start end)
55   #!+sb-doc
56   "Remove any occurrences of #\\ from the string because we've already
57    checked for whatever they may have protected."
58   (declare (type simple-string namestr)
59            (type index start end))
60   (let* ((result (make-string (- end start) :element-type 'character))
61          (dst 0)
62          (quoted nil))
63     (do ((src start (1+ src)))
64         ((= src end))
65       (cond (quoted
66              (setf (schar result dst) (schar namestr src))
67              (setf quoted nil)
68              (incf dst))
69             (t
70              (let ((char (schar namestr src)))
71                (cond ((char= char #\\)
72                       (setq quoted t))
73                      (t
74                       (setf (schar result dst) char)
75                       (incf dst)))))))
76     (when quoted
77       (error 'namestring-parse-error
78              :complaint "backslash in a bad place"
79              :namestring namestr
80              :offset (1- end)))
81     (%shrink-vector result dst)))
82
83 (defun maybe-make-pattern (namestr start end)
84   (declare (type simple-string namestr)
85            (type index start end))
86   (collect ((pattern))
87     (let ((quoted nil)
88           (any-quotes nil)
89           (last-regular-char nil)
90           (index start))
91       (flet ((flush-pending-regulars ()
92                (when last-regular-char
93                  (pattern (if any-quotes
94                               (remove-backslashes namestr
95                                                   last-regular-char
96                                                   index)
97                               (subseq namestr last-regular-char index)))
98                  (setf any-quotes nil)
99                  (setf last-regular-char nil))))
100         (loop
101           (when (>= index end)
102             (return))
103           (let ((char (schar namestr index)))
104             (cond (quoted
105                    (incf index)
106                    (setf quoted nil))
107                   ((char= char #\\)
108                    (setf quoted t)
109                    (setf any-quotes t)
110                    (unless last-regular-char
111                      (setf last-regular-char index))
112                    (incf index))
113                   ((char= char #\?)
114                    (flush-pending-regulars)
115                    (pattern :single-char-wild)
116                    (incf index))
117                   ((char= char #\*)
118                    (flush-pending-regulars)
119                    (pattern :multi-char-wild)
120                    (incf index))
121                   ((char= char #\[)
122                    (flush-pending-regulars)
123                    (let ((close-bracket
124                           (position #\] namestr :start index :end end)))
125                      (unless close-bracket
126                        (error 'namestring-parse-error
127                               :complaint "#\\[ with no corresponding #\\]"
128                               :namestring namestr
129                               :offset index))
130                      (pattern (cons :character-set
131                                     (subseq namestr
132                                             (1+ index)
133                                             close-bracket)))
134                      (setf index (1+ close-bracket))))
135                   (t
136                    (unless last-regular-char
137                      (setf last-regular-char index))
138                    (incf index)))))
139         (flush-pending-regulars)))
140     (cond ((null (pattern))
141            "")
142           ((null (cdr (pattern)))
143            (let ((piece (first (pattern))))
144              (typecase piece
145                ((member :multi-char-wild) :wild)
146                (simple-string piece)
147                (t
148                 (make-pattern (pattern))))))
149           (t
150            (make-pattern (pattern))))))
151
152 (defun unparse-physical-piece (thing)
153   (etypecase thing
154     ((member :wild) "*")
155     (simple-string
156      (let* ((srclen (length thing))
157             (dstlen srclen))
158        (dotimes (i srclen)
159          (case (schar thing i)
160            ((#\* #\? #\[)
161             (incf dstlen))))
162        (let ((result (make-string dstlen))
163              (dst 0))
164          (dotimes (src srclen)
165            (let ((char (schar thing src)))
166              (case char
167                ((#\* #\? #\[)
168                 (setf (schar result dst) #\\)
169                 (incf dst)))
170              (setf (schar result dst) char)
171              (incf dst)))
172          result)))
173     (pattern
174      (with-output-to-string (s)
175        (dolist (piece (pattern-pieces thing))
176          (etypecase piece
177            (simple-string
178             (write-string piece s))
179            (symbol
180             (ecase piece
181               (:multi-char-wild
182                (write-string "*" s))
183               (:single-char-wild
184                (write-string "?" s))))
185            (cons
186             (case (car piece)
187               (:character-set
188                (write-string "[" s)
189                (write-string (cdr piece) s)
190                (write-string "]" s))
191               (t
192                (error "invalid pattern piece: ~S" piece))))))))))
193
194 (defun make-matcher (piece)
195   (cond ((eq piece :wild)
196          (constantly t))
197         ((typep piece 'pattern)
198          (lambda (other)
199            (when (stringp other)
200              (pattern-matches piece other))))
201         (t
202          (lambda (other)
203            (equal piece other)))))
204
205 (/show0 "filesys.lisp 160")
206
207 (defun extract-name-type-and-version (namestr start end)
208   (declare (type simple-string namestr)
209            (type index start end))
210   (let* ((last-dot (position #\. namestr :start (1+ start) :end end
211                              :from-end t)))
212     (cond
213       (last-dot
214        (values (maybe-make-pattern namestr start last-dot)
215                (maybe-make-pattern namestr (1+ last-dot) end)
216                :newest))
217       (t
218        (values (maybe-make-pattern namestr start end)
219                nil
220                :newest)))))
221
222 (/show0 "filesys.lisp 200")
223
224 \f
225 ;;;; Grabbing the kind of file when we have a namestring.
226 (defun native-file-kind (namestring)
227   (multiple-value-bind (existsp errno ino mode)
228       #!-win32
229       (sb!unix:unix-lstat namestring)
230       #!+win32
231       (sb!unix:unix-stat namestring)
232     (declare (ignore errno ino))
233     (when existsp
234       (let ((ifmt (logand mode sb!unix:s-ifmt)))
235        (case ifmt
236          (#.sb!unix:s-ifreg :file)
237          (#.sb!unix:s-ifdir :directory)
238          #!-win32
239          (#.sb!unix:s-iflnk :symlink)
240          (t :special))))))
241 \f
242 ;;;; TRUENAME, PROBE-FILE, FILE-AUTHOR, FILE-WRITE-DATE.
243
244 ;;; Rewritten in 12/2007 by RMK, replacing 13+ year old CMU code that
245 ;;; made a mess of things in order to support search lists (which SBCL
246 ;;; has never had).  These are now all relatively straightforward
247 ;;; wrappers around stat(2) and realpath(2), with the same basic logic
248 ;;; in all cases.  The wrinkles to be aware of:
249 ;;;
250 ;;; * SBCL defines the truename of an existing, dangling or
251 ;;;   self-referring symlink to be the symlink itself.
252 ;;; * The old version of PROBE-FILE merged the pathspec against
253 ;;;   *DEFAULT-PATHNAME-DEFAULTS* twice, and so lost when *D-P-D*
254 ;;;   was a relative pathname.  Even if the case where *D-P-D* is a
255 ;;;   relative pathname is problematic, there's no particular reason
256 ;;;   to get that wrong, so let's try not to.
257 ;;; * Note that while stat(2) is probably atomic, getting the truename
258 ;;;   for a filename involves poking all over the place, and so is
259 ;;;   subject to race conditions if other programs mutate the file
260 ;;;   system while we're resolving symlinks.  So it's not implausible for
261 ;;;   realpath(3) to fail even if stat(2) succeeded.  There's nothing
262 ;;;   obvious we can do about this, however.
263 ;;; * Windows' apparent analogue of realpath(3) is called
264 ;;;   GetFullPathName, and it's a bit less useful than realpath(3).
265 ;;;   In particular, while realpath(3) errors in case the file doesn't
266 ;;;   exist, GetFullPathName seems to return a filename in all cases.
267 ;;;   As realpath(3) is not atomic anyway, we only ever call it when
268 ;;;   we think a file exists, so just be careful when rewriting this
269 ;;;   routine.
270 ;;;
271 ;;; Given a pathname designator, some quality to query for, return one
272 ;;; of a pathname, a universal time, or a string (a file-author), or
273 ;;; NIL.  QUERY-FOR may be one of :TRUENAME, :EXISTENCE, :WRITE-DATE,
274 ;;; :AUTHOR.  If ERRORP is false, return NIL in case the file system
275 ;;; returns an error code; otherwise, signal an error.  Accepts
276 ;;; logical pathnames, too (but never returns LPNs).  For internal
277 ;;; use.
278 (defun query-file-system (pathspec query-for &optional (errorp t))
279   (let ((pathname (translate-logical-pathname
280                    (merge-pathnames
281                     (pathname pathspec)
282                     (sane-default-pathname-defaults)))))
283     (when (wild-pathname-p pathname)
284       (error 'simple-file-error
285              :pathname pathname
286              :format-control "~@<can't find the ~A of wild pathname ~A~
287                               (physicalized from ~A).~:>"
288              :format-arguments (list query-for pathname pathspec)))
289     (flet ((fail (note-format pathname errno)
290              (if errorp
291                  (simple-file-perror note-format pathname errno)
292                  (return-from query-file-system nil))))
293       (let ((filename (native-namestring pathname :as-file t)))
294         (multiple-value-bind (existsp errno ino mode nlink uid gid rdev size
295                                       atime mtime)
296             (sb!unix:unix-stat filename)
297           (declare (ignore ino nlink gid rdev size atime
298                            #!+win32 uid))
299           #!+win32
300           ;; On win32, stat regards UNC pathnames and device names as
301           ;; nonexisting, so we check once more with the native API.
302           (unless existsp
303             (setf existsp
304                   (let ((handle (sb!win32:create-file
305                                  filename 0 0 nil
306                                  sb!win32:file-open-existing
307                                  0 0)))
308                     (when (/= -1 handle)
309                       (setf mode
310                             (or mode
311                                 (if (logbitp 4
312                                              (sb!win32:get-file-attributes filename))
313                                     sb!unix:s-ifdir 0)))
314                       (progn (sb!win32:close-handle handle) t)))))
315           (if existsp
316               (case query-for
317                 (:existence (nth-value
318                              0
319                              (parse-native-namestring
320                               filename
321                               (pathname-host pathname)
322                               (sane-default-pathname-defaults)
323                               :as-directory (eql (logand mode sb!unix:s-ifmt)
324                                                  sb!unix:s-ifdir))))
325                 (:truename (nth-value
326                             0
327                             (parse-native-namestring
328                              ;; Note: in case the file is stat'able, POSIX
329                              ;; realpath(3) gets us a canonical absolute
330                              ;; filename, even if the post-merge PATHNAME
331                              ;; is not absolute...
332                              (multiple-value-bind (realpath errno)
333                                  (sb!unix:unix-realpath filename)
334                                (if realpath
335                                    realpath
336                                    (fail "couldn't resolve ~A" filename errno)))
337                              (pathname-host pathname)
338                              (sane-default-pathname-defaults)
339                              ;; ... but without any trailing slash.
340                              :as-directory (eql (logand  mode sb!unix:s-ifmt)
341                                                 sb!unix:s-ifdir))))
342                 (:author
343                  #!-win32
344                  (sb!unix:uid-username uid))
345                 (:write-date (+ unix-to-universal-time mtime)))
346               (progn
347                 ;; SBCL has for many years had a policy that a pathname
348                 ;; that names an existing, dangling or self-referential
349                 ;; symlink denotes the symlink itself.  stat(2) fails
350                 ;; and sets errno to ENOENT or ELOOP respectively, but
351                 ;; we must distinguish cases where the symlink exists
352                 ;; from ones where there's a loop in the apparent
353                 ;; containing directory.
354                 #!-win32
355                 (multiple-value-bind (linkp ignore ino mode nlink uid gid rdev
356                                             size atime mtime)
357                     (sb!unix:unix-lstat filename)
358                   (declare (ignore ignore ino mode nlink gid rdev size atime))
359                   (when (and (or (= errno sb!unix:enoent)
360                                  (= errno sb!unix:eloop))
361                              linkp)
362                     (return-from query-file-system
363                       (case query-for
364                         (:existence
365                          ;; We do this reparse so as to return a
366                          ;; normalized pathname.
367                          (parse-native-namestring
368                           filename (pathname-host pathname)))
369                         (:truename
370                          ;; So here's a trick: since lstat succeded,
371                          ;; FILENAME exists, so its directory exists and
372                          ;; only the non-directory part is loopy.  So
373                          ;; let's resolve FILENAME's directory part with
374                          ;; realpath(3), in order to get a canonical
375                          ;; absolute name for the directory, and then
376                          ;; return a pathname having PATHNAME's name,
377                          ;; type, and version, but the rest from the
378                          ;; truename of the directory.  Since we turned
379                          ;; PATHNAME into FILENAME "as a file", FILENAME
380                          ;; does not end in a slash, and so we get the
381                          ;; directory part of FILENAME by reparsing
382                          ;; FILENAME and masking off its name, type, and
383                          ;; version bits.  But note not to call ourselves
384                          ;; recursively, because we don't want to
385                          ;; re-merge against *DEFAULT-PATHNAME-DEFAULTS*,
386                          ;; since PATHNAME may be a relative pathname.
387                          (merge-pathnames
388                           (nth-value
389                            0
390                            (parse-native-namestring
391                             (multiple-value-bind (realpath errno)
392                                 (sb!unix:unix-realpath
393                                  (native-namestring
394                                   (make-pathname
395                                    :name :unspecific
396                                    :type :unspecific
397                                    :version :unspecific
398                                    :defaults (parse-native-namestring
399                                               filename
400                                               (pathname-host pathname)
401                                               (sane-default-pathname-defaults)))))
402                               (if realpath
403                                   realpath
404                                   (fail "couldn't resolve ~A" filename errno)))
405                             (pathname-host pathname)
406                             (sane-default-pathname-defaults)
407                             :as-directory t))
408                           pathname))
409                         (:author (sb!unix:uid-username uid))
410                         (:write-date (+ unix-to-universal-time mtime))))))
411                 ;; If we're still here, the file doesn't exist; error.
412                 (fail
413                  (format nil "failed to find the ~A of ~~A" query-for)
414                  pathspec errno))))))))
415
416
417 (defun probe-file (pathspec)
418   #!+sb-doc
419   "Return the truename of PATHSPEC if the truename can be found,
420 or NIL otherwise.  See TRUENAME for more information."
421   (query-file-system pathspec :truename nil))
422
423 (defun truename (pathspec)
424   #!+sb-doc
425   "If PATHSPEC is a pathname that names an existing file, return
426 a pathname that denotes a canonicalized name for the file.  If
427 pathspec is a stream associated with a file, return a pathname
428 that denotes a canonicalized name for the file associated with
429 the stream.
430
431 An error of type FILE-ERROR is signalled if no such file exists
432 or if the file system is such that a canonicalized file name
433 cannot be determined or if the pathname is wild.
434
435 Under Unix, the TRUENAME of a symlink that links to itself or to
436 a file that doesn't exist is considered to be the name of the
437 broken symlink itself."
438   ;; Note that eventually this routine might be different for streams
439   ;; than for other pathname designators.
440   (if (streamp pathspec)
441       (query-file-system pathspec :truename)
442       (query-file-system pathspec :truename)))
443
444 (defun file-author (pathspec)
445   #!+sb-doc
446   "Return the author of the file specified by PATHSPEC. Signal an
447 error of type FILE-ERROR if no such file exists, or if PATHSPEC
448 is a wild pathname."
449   (query-file-system pathspec :author))
450
451 (defun file-write-date (pathspec)
452   #!+sb-doc
453   "Return the write date of the file specified by PATHSPEC.
454 An error of type FILE-ERROR is signaled if no such file exists,
455 or if PATHSPEC is a wild pathname."
456   (query-file-system pathspec :write-date))
457 \f
458 ;;;; miscellaneous other operations
459
460 (/show0 "filesys.lisp 700")
461
462 (defun rename-file (file new-name)
463   #!+sb-doc
464   "Rename FILE to have the specified NEW-NAME. If FILE is a stream open to a
465   file, then the associated file is renamed."
466   (let* ((original (truename file))
467          (original-namestring (native-namestring original :as-file t))
468          (new-name (merge-pathnames new-name original))
469          (new-namestring (native-namestring (physicalize-pathname new-name)
470                                             :as-file t)))
471     (unless new-namestring
472       (error 'simple-file-error
473              :pathname new-name
474              :format-control "~S can't be created."
475              :format-arguments (list new-name)))
476     (multiple-value-bind (res error)
477         (sb!unix:unix-rename original-namestring new-namestring)
478       (unless res
479         (error 'simple-file-error
480                :pathname new-name
481                :format-control "~@<couldn't rename ~2I~_~A ~I~_to ~2I~_~A: ~
482                                 ~I~_~A~:>"
483                :format-arguments (list original new-name (strerror error))))
484       (when (streamp file)
485         (file-name file new-name))
486       (values new-name original (truename new-name)))))
487
488 (defun delete-file (file)
489   #!+sb-doc
490   "Delete the specified FILE.
491
492 If FILE is a stream, on Windows the stream is closed immediately. On Unix
493 plaforms the stream remains open, allowing IO to continue: the OS resources
494 associated with the deleted file remain available till the stream is closed as
495 per standard Unix unlink() behaviour."
496   (let* ((pathname (translate-logical-pathname file))
497          (namestring (native-namestring pathname :as-file t)))
498     (truename file) ; for error-checking side-effect
499     #!+win32
500     (when (streamp file)
501       (close file))
502     (multiple-value-bind (res err) (sb!unix:unix-unlink namestring)
503       (unless res
504         (simple-file-perror "couldn't delete ~A" namestring err))))
505   t)
506
507 (defun delete-directory (pathspec &key recursive)
508   "Deletes the directory designated by PATHSPEC (a pathname designator).
509 Returns the truename of the directory deleted.
510
511 If RECURSIVE is false \(the default), signals an error unless the directory is
512 empty. If RECURSIVE is true, first deletes all files and subdirectories. If
513 RECURSIVE is true and the directory contains symbolic links, the links are
514 deleted, not the files and directories they point to.
515
516 Signals an error if PATHSPEC designates a file instead of a directory, or if
517 the directory could not be deleted for any reason.
518
519 \(DELETE-DIRECTORY \"/tmp/foo\") and \(DELETE-DIRECTORY \"/tmp/foo/\") both
520 delete the \"foo\" subdirectory of \"/tmp\", or signal an error if it does not
521 exist or is a file.
522
523 Experimental: interface subject to change."
524   (declare (type pathname-designator pathspec))
525   (with-pathname (pathname pathspec)
526     (let ((truename (truename (translate-logical-pathname pathname))))
527       (labels ((recurse (dir)
528                  (map-directory #'recurse dir
529                                 :files nil
530                                 :directories t
531                                 :classify-symlinks nil)
532                  (map-directory #'delete-file dir
533                                 :files t
534                                 :directories nil
535                                 :classify-symlinks nil)
536                  (delete-dir dir))
537                (delete-dir (dir)
538                  (let* ((namestring (native-namestring dir :as-file t))
539                         (res (alien-funcall (extern-alien #!-win32 "rmdir"
540                                                           #!+win32 "_rmdir"
541                                                           (function int c-string))
542                                             namestring)))
543                    (if (minusp res)
544                        (simple-file-perror "Could not delete directory ~A:~%  ~A"
545                                            namestring (get-errno))
546                        dir))))
547         (if recursive
548             (recurse truename)
549             (delete-dir truename))))))
550 \f
551 (defun sbcl-homedir-pathname ()
552   (let ((sbcl-home (posix-getenv "SBCL_HOME")))
553     ;; SBCL_HOME isn't set for :EXECUTABLE T embedded cores
554     (when (and sbcl-home (not (string= sbcl-home "")))
555       (parse-native-namestring sbcl-home
556                                #!-win32 sb!impl::*unix-host*
557                                #!+win32 sb!impl::*win32-host*
558                                *default-pathname-defaults*
559                                :as-directory t))))
560
561 (defun user-homedir-namestring (&optional username)
562   (if username
563       (sb!unix:user-homedir username)
564       (let ((env-home (posix-getenv "HOME")))
565         (if (and env-home (not (string= env-home "")))
566             env-home
567             #!-win32
568             (sb!unix:uid-homedir (sb!unix:unix-getuid))))))
569
570 ;;; (This is an ANSI Common Lisp function.)
571 (defun user-homedir-pathname (&optional host)
572   #!+sb-doc
573   "Return the home directory of the user as a pathname. If the HOME
574 environment variable has been specified, the directory it designates
575 is returned; otherwise obtains the home directory from the operating
576 system. HOST argument is ignored by SBCL."
577   (declare (ignore host))
578   (values
579    (parse-native-namestring
580     (or (user-homedir-namestring)
581         #!+win32
582         (sb!win32::get-folder-namestring sb!win32::csidl_profile))
583     #!-win32 sb!impl::*unix-host*
584     #!+win32 sb!impl::*win32-host*
585     *default-pathname-defaults*
586     :as-directory t)))
587
588 \f
589 ;;;; DIRECTORY
590
591 (defun directory (pathspec &key (resolve-symlinks t))
592   #!+sb-doc
593   "Return a list of PATHNAMEs, each the TRUENAME of a file that matched the
594 given pathname. Note that the interaction between this ANSI-specified
595 TRUENAMEing and the semantics of the Unix filesystem (symbolic links..) means
596 this function can sometimes return files which don't have the same directory
597 as PATHNAME. If :RESOLVE-SYMLINKS is NIL, don't resolve symbolic links in
598 matching filenames."
599   (let (;; We create one entry in this hash table for each truename,
600         ;; as an asymptotically efficient way of removing duplicates
601         ;; (which can arise when e.g. multiple symlinks map to the
602         ;; same truename).
603         (truenames (make-hash-table :test #'equal)))
604     (labels ((record (pathname)
605                (let ((truename (if resolve-symlinks
606                                    ;; FIXME: Why not not TRUENAME?  As reported by
607                                    ;; Milan Zamazal sbcl-devel 2003-10-05, using
608                                    ;; TRUENAME causes a race condition whereby
609                                    ;; removal of a file during the directory
610                                    ;; operation causes an error.  It's not clear
611                                    ;; what the right thing to do is, though.  --
612                                    ;; CSR, 2003-10-13
613                                    (query-file-system pathname :truename nil)
614                                    (query-file-system pathname :existence nil))))
615                  (when truename
616                    (setf (gethash (namestring truename) truenames)
617                          truename))))
618              (do-physical-pathnames (pathname)
619                (aver (not (logical-pathname-p pathname)))
620                (let* (;; KLUDGE: Since we don't canonize pathnames on construction,
621                       ;; we really have to do it here to get #p"foo/." mean the same
622                       ;; as #p"foo/./".
623                       (pathname (canonicalize-pathname pathname))
624                       (name (pathname-name pathname))
625                       (type (pathname-type pathname))
626                       (match-name (make-matcher name))
627                       (match-type (make-matcher type)))
628                  (map-matching-directories
629                   (if (or name type)
630                       (lambda (directory)
631                         (map-matching-entries #'record
632                                               directory
633                                               match-name
634                                               match-type))
635                       #'record)
636                   pathname)))
637              (do-pathnames (pathname)
638                (if (logical-pathname-p pathname)
639                    (let ((host (intern-logical-host (pathname-host pathname))))
640                      (dolist (x (logical-host-canon-transls host))
641                        (destructuring-bind (from to) x
642                          (let ((intersections
643                                 (pathname-intersections pathname from)))
644                            (dolist (p intersections)
645                              (do-pathnames (translate-pathname p from to)))))))
646                    (do-physical-pathnames pathname))))
647       (declare (truly-dynamic-extent #'record))
648       (do-pathnames (merge-pathnames pathspec)))
649     (mapcar #'cdr
650             ;; Sorting isn't required by the ANSI spec, but sorting into some
651             ;; canonical order seems good just on the grounds that the
652             ;; implementation should have repeatable behavior when possible.
653             (sort (loop for namestring being each hash-key in truenames
654                         using (hash-value truename)
655                         collect (cons namestring truename))
656                   #'string<
657                   :key #'car))))
658
659 (defun canonicalize-pathname (pathname)
660   ;; We're really only interested in :UNSPECIFIC -> NIL, :BACK and :UP,
661   ;; and dealing with #p"foo/.." and #p"foo/."
662   (labels ((simplify (piece)
663              (unless (eq :unspecific piece)
664                piece))
665            (canonicalize-directory (directory)
666              (let (pieces)
667                (dolist (piece directory)
668                  (if (and pieces (member piece '(:back :up)))
669                      ;; FIXME: We should really canonicalize when we construct
670                      ;; pathnames. This is just wrong.
671                      (case (car pieces)
672                        ((:absolute :wild-inferiors)
673                         (error 'simple-file-error
674                                :format-control "Invalid use of ~S after ~S."
675                                :format-arguments (list piece (car pieces))
676                                :pathname pathname))
677                        ((:relative :up :back)
678                         (push piece pieces))
679                        (t
680                         (pop pieces)))
681                      (push piece pieces)))
682                (nreverse pieces))))
683     (let ((name (simplify (pathname-name pathname)))
684           (type (simplify (pathname-type pathname)))
685           (dir (canonicalize-directory (pathname-directory pathname))))
686       (cond ((equal "." name)
687              (cond ((not type)
688                     (make-pathname :name nil :defaults pathname))
689                    ((equal "" type)
690                     (make-pathname :name nil
691                                    :type nil
692                                    :directory (butlast dir)
693                                    :defaults pathname))))
694             (t
695              (make-pathname :name name :type type
696                             :directory dir
697                             :defaults pathname))))))
698
699 ;;; Given a native namestring, provides a WITH-HASH-TABLE-ITERATOR style
700 ;;; interface to mapping over namestrings of entries in the corresponding
701 ;;; directory.
702 (defmacro with-native-directory-iterator ((iterator namestring &key errorp) &body body)
703   (with-unique-names (one-iter)
704     `(dx-flet
705          ((iterate (,one-iter)
706             (declare (type function ,one-iter))
707             (macrolet ((,iterator ()
708                          `(funcall ,',one-iter)))
709               ,@body)))
710        (call-with-native-directory-iterator #'iterate ,namestring ,errorp))))
711
712 (defun call-with-native-directory-iterator (function namestring errorp)
713   (declare (type (or null string) namestring)
714            (function function))
715   (let (dp)
716     (when namestring
717       (dx-flet
718           ((one-iter ()
719              (tagbody
720               :next
721                 (let ((ent (sb!unix:unix-readdir dp nil)))
722                   (when ent
723                     (let ((name (sb!unix:unix-dirent-name ent)))
724                       (when name
725                         (cond ((equal "." name)
726                                (go :next))
727                               ((equal ".." name)
728                                (go :next))
729                               (t
730                                (return-from one-iter name))))))))))
731         (unwind-protect
732              (progn
733                (setf dp (sb!unix:unix-opendir namestring errorp))
734                (when dp
735                  (funcall function #'one-iter)))
736           (when dp
737             (sb!unix:unix-closedir dp nil)))))))
738
739 ;;; This is our core directory access interface that we use to implement
740 ;;; DIRECTORY.
741 (defun map-directory (function directory &key (files t) (directories t)
742                       (classify-symlinks) (errorp t))
743   #!+sb-doc
744   "Map over entries in DIRECTORY. Keyword arguments specify which entries to
745 map over, and how:
746
747  :FILES
748     If true, call FUNCTION with the pathname of each file in DIRECTORY.
749     Defaults to T.
750
751  :DIRECTORIES
752    If true, call FUNCTION with a pathname for each subdirectory of DIRECTORY.
753    If :AS-FILES, the pathname used is a pathname designating the subdirectory
754    as a file in DIRECTORY. Otherwise the pathname used is a directory
755    pathname. Defaults to T.
756
757  :CLASSIFY-SYMLINKS
758    If T, the decision to call FUNCTION with the pathname of a symbolic link
759    depends on the resolution of the link: if it points to a directory, it is
760    considered a directory entry, otherwise a file entry. If false, all
761    symbolic links are considered file entries. Defaults to T. In both cases
762    the pathname used for the symbolic link is not fully resolved, but names it
763    as an immediate child of DIRECTORY.
764
765  :ERRORP
766    If true, signal an error if DIRECTORY does not exist, cannot be read, etc.
767    Defaults to T.
768
769 Experimental: interface subject to change."
770   (declare (pathname-designator directory))
771   (let* ((fun (%coerce-callable-to-fun function))
772          (as-files (eq :as-files directories))
773          (physical (physicalize-pathname directory))
774          ;; Not QUERY-FILE-SYSTEM :EXISTENCE, since it doesn't work on Windows
775          ;; network shares.
776          (realname (sb!unix:unix-realpath (native-namestring physical :as-file t)))
777          (canonical (if realname
778                         (parse-native-namestring realname
779                                                  (pathname-host physical)
780                                                  (sane-default-pathname-defaults)
781                                                  :as-directory t)
782                         (return-from map-directory nil)))
783          (dirname (native-namestring canonical)))
784     (flet ((map-it (name dirp)
785              (funcall fun
786                       (merge-pathnames (parse-native-namestring
787                                         name nil physical
788                                         :as-directory (and dirp (not as-files)))
789                                        physical))))
790       (with-native-directory-iterator (next dirname :errorp errorp)
791        (loop for name = (next)
792              while name
793              do (let* ((full (concatenate 'string dirname name))
794                        (kind (native-file-kind full)))
795                   (when kind
796                     (case kind
797                       (:directory
798                        (when directories
799                          (map-it name t)))
800                       (:symlink
801                        (if classify-symlinks
802                            (let* ((tmpname (merge-pathnames
803                                             (parse-native-namestring
804                                              name nil physical :as-directory nil)
805                                             physical))
806                                   (truename (query-file-system tmpname :truename nil)))
807                              (if (or (not truename)
808                                      (or (pathname-name truename) (pathname-type truename)))
809                                  (when files
810                                    (funcall fun tmpname))
811                                  (when directories
812                                    (map-it name t))))
813                            (when files
814                              (map-it name nil))))
815                       (t
816                        ;; Anything else parses as a file.
817                        (when files
818                          (map-it name nil)))))))))))
819
820 ;;; Part of DIRECTORY: implements matching the directory spec. Calls FUNCTION
821 ;;; with all DIRECTORIES that match the directory portion of PATHSPEC.
822 (defun map-matching-directories (function pathspec)
823   (let* ((dir (pathname-directory pathspec))
824          (length (length dir))
825          (wild (position-if (lambda (elt)
826                               (or (eq :wild elt) (typep elt 'pattern)))
827                             dir))
828          (wild-inferiors (position :wild-inferiors dir))
829          (end (cond ((and wild wild-inferiors)
830                      (min wild wild-inferiors))
831                     (t
832                      (or wild wild-inferiors length))))
833          (rest (subseq dir end))
834          (starting-point (make-pathname :directory (subseq dir 0 end)
835                                         :device (pathname-device pathspec)
836                                         :host (pathname-host pathspec)
837                                         :name nil
838                                         :type nil
839                                         :version nil)))
840     (cond (wild-inferiors
841            (map-wild-inferiors function rest starting-point))
842           (wild
843            (map-wild function rest starting-point))
844           (t
845            ;; Nothing wild -- the directory matches itself.
846            (funcall function starting-point))))
847   nil)
848
849 (defun last-directory-piece (pathname)
850   (car (last (pathname-directory pathname))))
851
852 ;;; Part of DIRECTORY: implements iterating over a :WILD or pattern component
853 ;;; in the directory spec.
854 (defun map-wild (function more directory)
855   (let ((this (pop more))
856         (next (car more)))
857     (flet ((cont (subdirectory)
858              (cond ((not more)
859                     ;; end of the line
860                     (funcall function subdirectory))
861                    ((or (eq :wild next) (typep next 'pattern))
862                     (map-wild function more subdirectory))
863                    ((eq :wild-inferiors next)
864                     (map-wild-inferiors function more subdirectory))
865                    (t
866                     (let ((this (pathname-directory subdirectory)))
867                       (map-matching-directories
868                        function
869                        (make-pathname :directory (append this more)
870                                       :defaults subdirectory)))))))
871       (map-directory
872        (if (eq :wild this)
873            #'cont
874            (lambda (sub)
875              (when (pattern-matches this (last-directory-piece sub))
876                (funcall #'cont sub))))
877        directory
878        :files nil
879        :directories t
880        :errorp nil))))
881
882 ;;; Part of DIRECTORY: implements iterating over a :WILD-INFERIORS component
883 ;;; in the directory spec.
884 (defun map-wild-inferiors (function more directory)
885   (loop while (member (car more) '(:wild :wild-inferiors))
886         do (pop more))
887   (let ((next (car more))
888         (rest (cdr more)))
889     (unless more
890       (funcall function directory))
891     (map-directory
892      (cond ((not more)
893             (lambda (pathname)
894               (funcall function pathname)
895               (map-wild-inferiors function more pathname)))
896            (t
897             (lambda (pathname)
898               (let ((this (pathname-directory pathname)))
899                 (when (equal next (car (last this)))
900                   (map-matching-directories
901                    function
902                    (make-pathname :directory (append this rest)
903                                   :defaults pathname)))
904                 (map-wild-inferiors function more pathname)))))
905      directory
906      :files nil
907      :directories t
908      :errorp nil)))
909
910 ;;; Part of DIRECTORY: implements iterating over entries in a directory, and
911 ;;; matching them.
912 (defun map-matching-entries (function directory match-name match-type)
913   (map-directory
914    (lambda (file)
915      (when (and (funcall match-name (pathname-name file))
916                 (funcall match-type (pathname-type file)))
917        (funcall function file)))
918    directory
919    :files t
920    :directories :as-files
921    :errorp nil))
922
923 ;;; NOTE: There is a fair amount of hair below that is probably not
924 ;;; strictly necessary.
925 ;;;
926 ;;; The issue is the following: what does (DIRECTORY "SYS:*;") mean?
927 ;;; Until 2004-01, SBCL's behaviour was unquestionably wrong, as it
928 ;;; did not translate the logical pathname at all, but instead treated
929 ;;; it as a physical one.  Other Lisps seem to to treat this call as
930 ;;; equivalent to (DIRECTORY (TRANSLATE-LOGICAL-PATHNAME "SYS:*;")),
931 ;;; which is fine as far as it goes, but not very interesting, and
932 ;;; arguably counterintuitive.  (PATHNAME-MATCH-P "SYS:SRC;" "SYS:*;")
933 ;;; is true, so why should "SYS:SRC;" not show up in the call to
934 ;;; DIRECTORY?  (assuming the physical pathname corresponding to it
935 ;;; exists, of course).
936 ;;;
937 ;;; So, the interpretation that I am pushing is for all pathnames
938 ;;; matching the input pathname to be queried.  This means that we
939 ;;; need to compute the intersection of the input pathname and the
940 ;;; logical host FROM translations, and then translate the resulting
941 ;;; pathname using the host to the TO translation; this treatment is
942 ;;; recursively invoked until we get a physical pathname, whereupon
943 ;;; our physical DIRECTORY implementation takes over.
944
945 ;;; FIXME: this is an incomplete implementation.  It only works when
946 ;;; both are logical pathnames (which is OK, because that's the only
947 ;;; case when we call it), but there are other pitfalls as well: see
948 ;;; the DIRECTORY-HELPER below for some, but others include a lack of
949 ;;; pattern handling.
950
951 ;;; The above was written by CSR, I (RMK) believe.  The argument that
952 ;;; motivates the interpretation is faulty, however: PATHNAME-MATCH-P
953 ;;; returns true for (PATHNAME-MATCH-P #P"/tmp/*/" #P"/tmp/../"), but
954 ;;; the latter pathname is not in the result of DIRECTORY on the
955 ;;; former.  Indeed, if DIRECTORY were constrained to return the
956 ;;; truename for every pathname for which PATHNAME-MATCH-P returned
957 ;;; true and which denoted a filename that named an existing file,
958 ;;; (DIRECTORY #P"/tmp/**/") would be required to list every file on a
959 ;;; Unix system, since any file can be named as though it were "below"
960 ;;; /tmp, given the dotdot entries.  So I think the strongest
961 ;;; "consistency" we can define between PATHNAME-MATCH-P and DIRECTORY
962 ;;; is that PATHNAME-MATCH-P returns true of everything DIRECTORY
963 ;;; returns, but not vice versa.
964
965 ;;; In any case, even if the motivation were sound, DIRECTORY on a
966 ;;; wild logical pathname has no portable semantics.  I see nothing in
967 ;;; ANSI that requires implementations to support wild physical
968 ;;; pathnames, and so there need not be any translation of a wild
969 ;;; logical pathname to a phyiscal pathname.  So a program that calls
970 ;;; DIRECTORY on a wild logical pathname is doing something
971 ;;; non-portable at best.  And if the only sensible semantics for
972 ;;; DIRECTORY on a wild logical pathname is something like the
973 ;;; following, it would be just as well if it signaled an error, since
974 ;;; a program can't possibly rely on the result of an intersection of
975 ;;; user-defined translations with a file system probe.  (Potentially
976 ;;; useful kinds of "pathname" that might not support wildcards could
977 ;;; include pathname hosts that model unqueryable namespaces like HTTP
978 ;;; URIs, or that model namespaces that it's not convenient to
979 ;;; investigate, such as the namespace of TCP ports that some network
980 ;;; host listens on.  I happen to think it a bad idea to try to
981 ;;; shoehorn such namespaces into a pathnames system, but people
982 ;;; sometimes claim to want pathnames for these things.)  -- RMK
983 ;;; 2007-12-31.
984
985 (defun pathname-intersections (one two)
986   (aver (logical-pathname-p one))
987   (aver (logical-pathname-p two))
988   (labels
989       ((intersect-version (one two)
990          (aver (typep one '(or null (member :newest :wild :unspecific)
991                             integer)))
992          (aver (typep two '(or null (member :newest :wild :unspecific)
993                             integer)))
994          (cond
995            ((eq one :wild) two)
996            ((eq two :wild) one)
997            ((or (null one) (eq one :unspecific)) two)
998            ((or (null two) (eq two :unspecific)) one)
999            ((eql one two) one)
1000            (t nil)))
1001        (intersect-name/type (one two)
1002          (aver (typep one '(or null (member :wild :unspecific) string)))
1003          (aver (typep two '(or null (member :wild :unspecific) string)))
1004          (cond
1005            ((eq one :wild) two)
1006            ((eq two :wild) one)
1007            ((or (null one) (eq one :unspecific)) two)
1008            ((or (null two) (eq two :unspecific)) one)
1009            ((string= one two) one)
1010            (t (return-from pathname-intersections nil))))
1011        (intersect-directory (one two)
1012          (aver (typep one '(or null (member :wild :unspecific) list)))
1013          (aver (typep two '(or null (member :wild :unspecific) list)))
1014          (cond
1015            ((eq one :wild) two)
1016            ((eq two :wild) one)
1017            ((or (null one) (eq one :unspecific)) two)
1018            ((or (null two) (eq two :unspecific)) one)
1019            (t (aver (eq (car one) (car two)))
1020               (mapcar
1021                (lambda (x) (cons (car one) x))
1022                (intersect-directory-helper (cdr one) (cdr two)))))))
1023     (let ((version (intersect-version
1024                     (pathname-version one) (pathname-version two)))
1025           (name (intersect-name/type
1026                  (pathname-name one) (pathname-name two)))
1027           (type (intersect-name/type
1028                  (pathname-type one) (pathname-type two)))
1029           (host (pathname-host one)))
1030       (mapcar (lambda (d)
1031                 (make-pathname :host host :name name :type type
1032                                :version version :directory d))
1033               (intersect-directory
1034                (pathname-directory one) (pathname-directory two))))))
1035
1036 ;;; FIXME: written as its own function because I (CSR) don't
1037 ;;; understand it, so helping both debuggability and modularity.  In
1038 ;;; case anyone is motivated to rewrite it, it returns a list of
1039 ;;; sublists representing the intersection of the two input directory
1040 ;;; paths (excluding the initial :ABSOLUTE or :RELATIVE).
1041 ;;;
1042 ;;; FIXME: Does not work with :UP or :BACK
1043 ;;; FIXME: Does not work with patterns
1044 ;;;
1045 ;;; FIXME: PFD suggests replacing this implementation with a DFA
1046 ;;; conversion of a NDFA.  Find out (a) what this means and (b) if it
1047 ;;; turns out to be worth it.
1048 (defun intersect-directory-helper (one two)
1049   (flet ((simple-intersection (cone ctwo)
1050            (cond
1051              ((eq cone :wild) ctwo)
1052              ((eq ctwo :wild) cone)
1053              (t (aver (typep cone 'string))
1054                 (aver (typep ctwo 'string))
1055                 (if (string= cone ctwo) cone nil)))))
1056     (macrolet
1057         ((loop-possible-wild-inferiors-matches
1058              (lower-bound bounding-sequence order)
1059            (let ((index (gensym)) (g2 (gensym)) (g3 (gensym)) (l (gensym)))
1060              `(let ((,l (length ,bounding-sequence)))
1061                (loop for ,index from ,lower-bound to ,l
1062                 append (mapcar (lambda (,g2)
1063                                  (append
1064                                   (butlast ,bounding-sequence (- ,l ,index))
1065                                   ,g2))
1066                         (mapcar
1067                          (lambda (,g3)
1068                            (append
1069                             (if (eq (car (nthcdr ,index ,bounding-sequence))
1070                                     :wild-inferiors)
1071                                 '(:wild-inferiors)
1072                                 nil) ,g3))
1073                          (intersect-directory-helper
1074                           ,@(if order
1075                                 `((nthcdr ,index one) (cdr two))
1076                                 `((cdr one) (nthcdr ,index two)))))))))))
1077       (cond
1078         ((and (eq (car one) :wild-inferiors)
1079               (eq (car two) :wild-inferiors))
1080          (delete-duplicates
1081           (append (mapcar (lambda (x) (cons :wild-inferiors x))
1082                           (intersect-directory-helper (cdr one) (cdr two)))
1083                   (loop-possible-wild-inferiors-matches 2 one t)
1084                   (loop-possible-wild-inferiors-matches 2 two nil))
1085           :test 'equal))
1086         ((eq (car one) :wild-inferiors)
1087          (delete-duplicates (loop-possible-wild-inferiors-matches 0 two nil)
1088                             :test 'equal))
1089         ((eq (car two) :wild-inferiors)
1090          (delete-duplicates (loop-possible-wild-inferiors-matches 0 one t)
1091                             :test 'equal))
1092         ((and (null one) (null two)) (list nil))
1093         ((null one) nil)
1094         ((null two) nil)
1095         (t (and (simple-intersection (car one) (car two))
1096                 (mapcar (lambda (x) (cons (simple-intersection
1097                                            (car one) (car two)) x))
1098                         (intersect-directory-helper (cdr one) (cdr two)))))))))
1099 \f
1100 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
1101   #!+sb-doc
1102   "Test whether the directories containing the specified file
1103   actually exist, and attempt to create them if they do not.
1104   The MODE argument is a CMUCL/SBCL-specific extension to control
1105   the Unix permission bits."
1106   (let ((pathname (physicalize-pathname (merge-pathnames (pathname pathspec))))
1107         (created-p nil))
1108     (when (wild-pathname-p pathname)
1109       (error 'simple-file-error
1110              :format-control "bad place for a wild pathname"
1111              :pathname pathspec))
1112     (let ((dir (pathname-directory pathname)))
1113       (loop for i from 1 upto (length dir)
1114             do (let ((newpath (make-pathname
1115                                :host (pathname-host pathname)
1116                                :device (pathname-device pathname)
1117                                :directory (subseq dir 0 i))))
1118                  (unless (probe-file newpath)
1119                    (let ((namestring (coerce (native-namestring newpath)
1120                                              'string)))
1121                      (when verbose
1122                        (format *standard-output*
1123                                "~&creating directory: ~A~%"
1124                                namestring))
1125                      (sb!unix:unix-mkdir namestring mode)
1126                      (unless (probe-file newpath)
1127                        (restart-case (error
1128                                       'simple-file-error
1129                                       :pathname pathspec
1130                                       :format-control
1131                                       "can't create directory ~A"
1132                                       :format-arguments (list namestring))
1133                          (retry ()
1134                            :report "Retry directory creation."
1135                            (ensure-directories-exist
1136                             pathspec
1137                             :verbose verbose :mode mode))
1138                          (continue ()
1139                            :report
1140                            "Continue as if directory creation was successful."
1141                            nil)))
1142                      (setf created-p t)))))
1143       (values pathspec created-p))))
1144
1145 (/show0 "filesys.lisp 1000")