Support long file names on Windows; more CRT function avoidance
[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         #!+win32
295         (case query-for
296           ((:existence :truename)
297            (multiple-value-bind (file kind)
298                (sb!win32::native-probe-file-name filename)
299              (when (and (not file) kind)
300                (setf file filename))
301              ;; The following OR was an AND, but that breaks files like NUL,
302              ;; for which GetLongPathName succeeds yet GetFileAttributesEx
303              ;; fails to return the file kind. --DFL
304              (if (or file kind)
305                  (values
306                   (parse-native-namestring
307                    file
308                    (pathname-host pathname)
309                    (sane-default-pathname-defaults)
310                    :as-directory (eq :directory kind)))
311                  (fail "couldn't resolve ~A" filename
312                        (- (sb!win32:get-last-error))))))
313           (:write-date
314            (or (sb!win32::native-file-write-date filename)
315                (fail "couldn't query write date of ~A" filename
316                      (- (sb!win32:get-last-error))))))
317         #!-win32
318         (multiple-value-bind (existsp errno ino mode nlink uid gid rdev size
319                                       atime mtime)
320             (sb!unix:unix-stat filename)
321           (declare (ignore ino nlink gid rdev size atime))
322           (if existsp
323               (case query-for
324                 (:existence (nth-value
325                              0
326                              (parse-native-namestring
327                               filename
328                               (pathname-host pathname)
329                               (sane-default-pathname-defaults)
330                               :as-directory (eql (logand mode sb!unix:s-ifmt)
331                                                  sb!unix:s-ifdir))))
332                 (:truename (nth-value
333                             0
334                             (parse-native-namestring
335                              ;; Note: in case the file is stat'able, POSIX
336                              ;; realpath(3) gets us a canonical absolute
337                              ;; filename, even if the post-merge PATHNAME
338                              ;; is not absolute...
339                              (multiple-value-bind (realpath errno)
340                                  (sb!unix:unix-realpath filename)
341                                (if realpath
342                                    realpath
343                                    (fail "couldn't resolve ~A" filename errno)))
344                              (pathname-host pathname)
345                              (sane-default-pathname-defaults)
346                              ;; ... but without any trailing slash.
347                              :as-directory (eql (logand  mode sb!unix:s-ifmt)
348                                                 sb!unix:s-ifdir))))
349                 (:author (sb!unix:uid-username uid))
350                 (:write-date (+ unix-to-universal-time mtime)))
351               (progn
352                 ;; SBCL has for many years had a policy that a pathname
353                 ;; that names an existing, dangling or self-referential
354                 ;; symlink denotes the symlink itself.  stat(2) fails
355                 ;; and sets errno to ENOENT or ELOOP respectively, but
356                 ;; we must distinguish cases where the symlink exists
357                 ;; from ones where there's a loop in the apparent
358                 ;; containing directory.
359                 (multiple-value-bind (linkp ignore ino mode nlink uid gid rdev
360                                             size atime mtime)
361                     (sb!unix:unix-lstat filename)
362                   (declare (ignore ignore ino mode nlink gid rdev size atime))
363                   (when (and (or (= errno sb!unix:enoent)
364                                  (= errno sb!unix:eloop))
365                              linkp)
366                     (return-from query-file-system
367                       (case query-for
368                         (:existence
369                          ;; We do this reparse so as to return a
370                          ;; normalized pathname.
371                          (parse-native-namestring
372                           filename (pathname-host pathname)))
373                         (:truename
374                          ;; So here's a trick: since lstat succeded,
375                          ;; FILENAME exists, so its directory exists and
376                          ;; only the non-directory part is loopy.  So
377                          ;; let's resolve FILENAME's directory part with
378                          ;; realpath(3), in order to get a canonical
379                          ;; absolute name for the directory, and then
380                          ;; return a pathname having PATHNAME's name,
381                          ;; type, and version, but the rest from the
382                          ;; truename of the directory.  Since we turned
383                          ;; PATHNAME into FILENAME "as a file", FILENAME
384                          ;; does not end in a slash, and so we get the
385                          ;; directory part of FILENAME by reparsing
386                          ;; FILENAME and masking off its name, type, and
387                          ;; version bits.  But note not to call ourselves
388                          ;; recursively, because we don't want to
389                          ;; re-merge against *DEFAULT-PATHNAME-DEFAULTS*,
390                          ;; since PATHNAME may be a relative pathname.
391                          (merge-pathnames
392                           (nth-value
393                            0
394                            (parse-native-namestring
395                             (multiple-value-bind (realpath errno)
396                                 (sb!unix:unix-realpath
397                                  (native-namestring
398                                   (make-pathname
399                                    :name :unspecific
400                                    :type :unspecific
401                                    :version :unspecific
402                                    :defaults (parse-native-namestring
403                                               filename
404                                               (pathname-host pathname)
405                                               (sane-default-pathname-defaults)))))
406                               (if realpath
407                                   realpath
408                                   (fail "couldn't resolve ~A" filename errno)))
409                             (pathname-host pathname)
410                             (sane-default-pathname-defaults)
411                             :as-directory t))
412                           pathname))
413                         (:author (sb!unix:uid-username uid))
414                         (:write-date (+ unix-to-universal-time mtime))))))
415                 ;; If we're still here, the file doesn't exist; error.
416                 (fail
417                  (format nil "failed to find the ~A of ~~A" query-for)
418                  pathspec errno))))))))
419
420
421 (defun probe-file (pathspec)
422   #!+sb-doc
423   "Return the truename of PATHSPEC if the truename can be found,
424 or NIL otherwise.  See TRUENAME for more information."
425   (query-file-system pathspec :truename nil))
426
427 (defun truename (pathspec)
428   #!+sb-doc
429   "If PATHSPEC is a pathname that names an existing file, return
430 a pathname that denotes a canonicalized name for the file.  If
431 pathspec is a stream associated with a file, return a pathname
432 that denotes a canonicalized name for the file associated with
433 the stream.
434
435 An error of type FILE-ERROR is signalled if no such file exists
436 or if the file system is such that a canonicalized file name
437 cannot be determined or if the pathname is wild.
438
439 Under Unix, the TRUENAME of a symlink that links to itself or to
440 a file that doesn't exist is considered to be the name of the
441 broken symlink itself."
442   ;; Note that eventually this routine might be different for streams
443   ;; than for other pathname designators.
444   (if (streamp pathspec)
445       (query-file-system pathspec :truename)
446       (query-file-system pathspec :truename)))
447
448 (defun file-author (pathspec)
449   #!+sb-doc
450   "Return the author of the file specified by PATHSPEC. Signal an
451 error of type FILE-ERROR if no such file exists, or if PATHSPEC
452 is a wild pathname."
453   (query-file-system pathspec :author))
454
455 (defun file-write-date (pathspec)
456   #!+sb-doc
457   "Return the write date of the file specified by PATHSPEC.
458 An error of type FILE-ERROR is signaled if no such file exists,
459 or if PATHSPEC is a wild pathname."
460   (query-file-system pathspec :write-date))
461 \f
462 ;;;; miscellaneous other operations
463
464 (/show0 "filesys.lisp 700")
465
466 (defun rename-file (file new-name)
467   #!+sb-doc
468   "Rename FILE to have the specified NEW-NAME. If FILE is a stream open to a
469 file, then the associated file is renamed."
470   (let* ((original (merge-pathnames file (sane-default-pathname-defaults)))
471          (old-truename (truename original))
472          (original-namestring (native-namestring (physicalize-pathname original)
473                                                  :as-file t))
474          (new-name (merge-pathnames new-name original))
475          (new-namestring (native-namestring (physicalize-pathname new-name)
476                                             :as-file t)))
477     (unless new-namestring
478       (error 'simple-file-error
479              :pathname new-name
480              :format-control "~S can't be created."
481              :format-arguments (list new-name)))
482     (multiple-value-bind (res error)
483         (sb!unix:unix-rename original-namestring new-namestring)
484       (unless res
485         (error 'simple-file-error
486                :pathname new-name
487                :format-control "~@<couldn't rename ~2I~_~A ~I~_to ~2I~_~A: ~
488                                 ~I~_~A~:>"
489                :format-arguments (list original new-name (strerror error))))
490       (when (streamp file)
491         (file-name file new-name))
492       (values new-name old-truename (truename new-name)))))
493
494 (defun delete-file (file)
495   #!+sb-doc
496   "Delete the specified FILE.
497
498 If FILE is a stream, on Windows the stream is closed immediately. On Unix
499 plaforms the stream remains open, allowing IO to continue: the OS resources
500 associated with the deleted file remain available till the stream is closed as
501 per standard Unix unlink() behaviour."
502   (let* ((pathname (translate-logical-pathname
503                     (merge-pathnames file (sane-default-pathname-defaults))))
504          (namestring (native-namestring pathname :as-file t)))
505     #!+win32
506     (when (streamp file)
507       (close file))
508     (multiple-value-bind (res err)
509         #!-win32 (sb!unix:unix-unlink namestring)
510         #!+win32 (or (sb!win32::native-delete-file namestring)
511                      (values nil (- (sb!win32:get-last-error))))
512         (unless res
513           (simple-file-perror "couldn't delete ~A" namestring err))))
514   t)
515
516 (defun directorize-pathname (pathname)
517   (if (or (pathname-name pathname)
518           (pathname-type pathname))
519       (make-pathname :directory (append (pathname-directory pathname)
520                                         (list (file-namestring pathname)))
521                      :host (pathname-host pathname)
522                      :device (pathname-device pathname))
523       pathname))
524
525 (defun delete-directory (pathspec &key recursive)
526   "Deletes the directory designated by PATHSPEC (a pathname designator).
527 Returns the truename of the directory deleted.
528
529 If RECURSIVE is false \(the default), signals an error unless the directory is
530 empty. If RECURSIVE is true, first deletes all files and subdirectories. If
531 RECURSIVE is true and the directory contains symbolic links, the links are
532 deleted, not the files and directories they point to.
533
534 Signals an error if PATHSPEC designates a file or a symbolic link instead of a
535 directory, or if the directory could not be deleted for any reason.
536
537 Both
538
539    \(DELETE-DIRECTORY \"/tmp/foo\")
540    \(DELETE-DIRECTORY \"/tmp/foo/\")
541
542 delete the \"foo\" subdirectory of \"/tmp\", or signal an error if it does not
543 exist or if is a file or a symbolic link."
544   (declare (type pathname-designator pathspec))
545   (let ((physical (directorize-pathname
546                    (physicalize-pathname
547                     (merge-pathnames
548                      pathspec (sane-default-pathname-defaults))))))
549     (labels ((recurse-merged (dir)
550                (lambda (sub)
551                  (recurse (merge-pathnames sub dir))))
552              (delete-merged (dir)
553                (lambda (file)
554                  (delete-file (merge-pathnames file dir))))
555              (recurse (dir)
556                (map-directory (recurse-merged dir) dir
557                               :files nil
558                               :directories t
559                               :classify-symlinks nil)
560                (map-directory (delete-merged dir) dir
561                               :files t
562                               :directories nil
563                               :classify-symlinks nil)
564                (delete-dir dir))
565              (delete-dir (dir)
566                (let ((namestring (native-namestring dir :as-file t)))
567                  (multiple-value-bind (res errno)
568                      #!+win32
569                      (or (sb!win32::native-delete-directory namestring)
570                          (values nil (- (sb!win32:get-last-error))))
571                      #!-win32
572                      (values
573                       (not (minusp (alien-funcall
574                                     (extern-alien "rmdir"
575                                                   (function int c-string))
576                                     namestring)))
577                       (get-errno))
578                      (if res
579                          dir
580                          (simple-file-perror
581                           "Could not delete directory ~A"
582                           namestring errno))))))
583       (if recursive
584           (recurse physical)
585           (delete-dir physical)))))
586
587 \f
588 (defun sbcl-homedir-pathname ()
589   (let ((sbcl-home (posix-getenv "SBCL_HOME")))
590     ;; SBCL_HOME isn't set for :EXECUTABLE T embedded cores
591     (when (and sbcl-home (not (string= sbcl-home "")))
592       (parse-native-namestring sbcl-home
593                                #!-win32 sb!impl::*unix-host*
594                                #!+win32 sb!impl::*win32-host*
595                                *default-pathname-defaults*
596                                :as-directory t))))
597
598 (defun user-homedir-namestring (&optional username)
599   (if username
600       (sb!unix:user-homedir username)
601       (let ((env-home (posix-getenv "HOME")))
602         (if (and env-home (not (string= env-home "")))
603             env-home
604             #!-win32
605             (sb!unix:uid-homedir (sb!unix:unix-getuid))))))
606
607 ;;; (This is an ANSI Common Lisp function.)
608 (defun user-homedir-pathname (&optional host)
609   #!+sb-doc
610   "Return the home directory of the user as a pathname. If the HOME
611 environment variable has been specified, the directory it designates
612 is returned; otherwise obtains the home directory from the operating
613 system. HOST argument is ignored by SBCL."
614   (declare (ignore host))
615   (values
616    (parse-native-namestring
617     (or (user-homedir-namestring)
618         #!+win32
619         (sb!win32::get-folder-namestring sb!win32::csidl_profile))
620     #!-win32 sb!impl::*unix-host*
621     #!+win32 sb!impl::*win32-host*
622     *default-pathname-defaults*
623     :as-directory t)))
624
625 \f
626 ;;;; DIRECTORY
627
628 (defun directory (pathspec &key (resolve-symlinks t))
629   #!+sb-doc
630   "Return a list of PATHNAMEs, each the TRUENAME of a file that matched the
631 given pathname. Note that the interaction between this ANSI-specified
632 TRUENAMEing and the semantics of the Unix filesystem (symbolic links..) means
633 this function can sometimes return files which don't have the same directory
634 as PATHNAME. If :RESOLVE-SYMLINKS is NIL, don't resolve symbolic links in
635 matching filenames."
636   (let (;; We create one entry in this hash table for each truename,
637         ;; as an asymptotically efficient way of removing duplicates
638         ;; (which can arise when e.g. multiple symlinks map to the
639         ;; same truename).
640         (truenames (make-hash-table :test #'equal)))
641     (labels ((record (pathname)
642                (let ((truename (if resolve-symlinks
643                                    ;; FIXME: Why not not TRUENAME?  As reported by
644                                    ;; Milan Zamazal sbcl-devel 2003-10-05, using
645                                    ;; TRUENAME causes a race condition whereby
646                                    ;; removal of a file during the directory
647                                    ;; operation causes an error.  It's not clear
648                                    ;; what the right thing to do is, though.  --
649                                    ;; CSR, 2003-10-13
650                                    (query-file-system pathname :truename nil)
651                                    (query-file-system pathname :existence nil))))
652                  (when truename
653                    (setf (gethash (namestring truename) truenames)
654                          truename))))
655              (do-physical-pathnames (pathname)
656                (aver (not (logical-pathname-p pathname)))
657                (let* (;; KLUDGE: Since we don't canonize pathnames on construction,
658                       ;; we really have to do it here to get #p"foo/." mean the same
659                       ;; as #p"foo/./".
660                       (pathname (canonicalize-pathname pathname))
661                       (name (pathname-name pathname))
662                       (type (pathname-type pathname))
663                       (match-name (make-matcher name))
664                       (match-type (make-matcher type)))
665                  (map-matching-directories
666                   (if (or name type)
667                       (lambda (directory)
668                         (map-matching-entries #'record
669                                               directory
670                                               match-name
671                                               match-type))
672                       #'record)
673                   pathname)))
674              (do-pathnames (pathname)
675                (if (logical-pathname-p pathname)
676                    (let ((host (intern-logical-host (pathname-host pathname))))
677                      (dolist (x (logical-host-canon-transls host))
678                        (destructuring-bind (from to) x
679                          (let ((intersections
680                                 (pathname-intersections pathname from)))
681                            (dolist (p intersections)
682                              (do-pathnames (translate-pathname p from to)))))))
683                    (do-physical-pathnames pathname))))
684       (declare (truly-dynamic-extent #'record))
685       (do-pathnames (merge-pathnames pathspec)))
686     (mapcar #'cdr
687             ;; Sorting isn't required by the ANSI spec, but sorting into some
688             ;; canonical order seems good just on the grounds that the
689             ;; implementation should have repeatable behavior when possible.
690             (sort (loop for namestring being each hash-key in truenames
691                         using (hash-value truename)
692                         collect (cons namestring truename))
693                   #'string<
694                   :key #'car))))
695
696 (defun canonicalize-pathname (pathname)
697   ;; We're really only interested in :UNSPECIFIC -> NIL, :BACK and :UP,
698   ;; and dealing with #p"foo/.." and #p"foo/."
699   (labels ((simplify (piece)
700              (unless (eq :unspecific piece)
701                piece))
702            (canonicalize-directory (directory)
703              (let (pieces)
704                (dolist (piece directory)
705                  (cond
706                     ((and pieces (member piece '(:back :up)))
707                      ;; FIXME: We should really canonicalize when we construct
708                      ;; pathnames. This is just wrong.
709                      (case (car pieces)
710                        ((:absolute :wild-inferiors)
711                         (error 'simple-file-error
712                                :format-control "Invalid use of ~S after ~S."
713                                :format-arguments (list piece (car pieces))
714                                :pathname pathname))
715                        ((:relative :up :back)
716                         (push piece pieces))
717                        (t
718                         (pop pieces))))
719                     ((equal piece ".")
720                      ;; This case only really matters on Windows,
721                      ;; because on POSIX, our call site (TRUENAME via
722                      ;; QUERY-FILE-SYSTEM) only passes in pathnames from
723                      ;; realpath(3), in which /./ has been removed
724                      ;; already.  Windows, however, depends on us to
725                      ;; perform this fixup. -- DFL
726                      )
727                     (t
728                      (push piece pieces))))
729                (nreverse pieces))))
730     (let ((name (simplify (pathname-name pathname)))
731           (type (simplify (pathname-type pathname)))
732           (dir (canonicalize-directory (pathname-directory pathname))))
733       (cond ((equal "." name)
734              (cond ((not type)
735                     (make-pathname :name nil :defaults pathname))
736                    ((equal "" type)
737                     (make-pathname :name nil
738                                    :type nil
739                                    :directory (butlast dir)
740                                    :defaults pathname))))
741             (t
742              (make-pathname :name name :type type
743                             :directory dir
744                             :defaults pathname))))))
745
746 ;;; Given a native namestring, provides a WITH-HASH-TABLE-ITERATOR style
747 ;;; interface to mapping over namestrings of entries in the corresponding
748 ;;; directory.
749 (defmacro with-native-directory-iterator ((iterator namestring &key errorp) &body body)
750   (with-unique-names (one-iter)
751     `(dx-flet
752          ((iterate (,one-iter)
753             (declare (type function ,one-iter))
754             (macrolet ((,iterator ()
755                          `(funcall ,',one-iter)))
756               ,@body)))
757        #!+win32
758        (sb!win32::native-call-with-directory-iterator
759         #'iterate ,namestring ,errorp)
760        #!-win32
761        (call-with-native-directory-iterator #'iterate ,namestring ,errorp))))
762
763 (defun call-with-native-directory-iterator (function namestring errorp)
764   (declare (type (or null string) namestring)
765            (function function))
766   (let (dp)
767     (when namestring
768       (dx-flet
769           ((one-iter ()
770              (tagbody
771               :next
772                 (let ((ent (sb!unix:unix-readdir dp nil)))
773                   (when ent
774                     (let ((name (sb!unix:unix-dirent-name ent)))
775                       (when name
776                         (cond ((equal "." name)
777                                (go :next))
778                               ((equal ".." name)
779                                (go :next))
780                               (t
781                                (return-from one-iter name))))))))))
782         (unwind-protect
783              (progn
784                (setf dp (sb!unix:unix-opendir namestring errorp))
785                (when dp
786                  (funcall function #'one-iter)))
787           (when dp
788             (sb!unix:unix-closedir dp nil)))))))
789
790 ;;; This is our core directory access interface that we use to implement
791 ;;; DIRECTORY.
792 (defun map-directory (function directory &key (files t) (directories t)
793                       (classify-symlinks t) (errorp t))
794   #!+sb-doc
795   "Map over entries in DIRECTORY. Keyword arguments specify which entries to
796 map over, and how:
797
798  :FILES
799     If true, call FUNCTION with the pathname of each file in DIRECTORY.
800     Defaults to T.
801
802  :DIRECTORIES
803    If true, call FUNCTION with a pathname for each subdirectory of DIRECTORY.
804    If :AS-FILES, the pathname used is a pathname designating the subdirectory
805    as a file in DIRECTORY. Otherwise the pathname used is a directory
806    pathname. Defaults to T.
807
808  :CLASSIFY-SYMLINKS
809    If true, the decision to call FUNCTION with the pathname of a symbolic link
810    depends on the resolution of the link: if it points to a directory, it is
811    considered a directory entry, otherwise a file entry. If false, all
812    symbolic links are considered file entries. In both cases the pathname used
813    for the symbolic link is not fully resolved, but names it as an immediate
814    child of DIRECTORY. Defaults to T.
815
816  :ERRORP
817    If true, signal an error if DIRECTORY does not exist, cannot be read, etc.
818    Defaults to T.
819
820 Experimental: interface subject to change."
821   (declare (pathname-designator directory))
822   (let* ((fun (%coerce-callable-to-fun function))
823          (as-files (eq :as-files directories))
824          (physical (physicalize-pathname directory))
825          (realname (query-file-system physical :existence nil))
826          (canonical (if realname
827                         (parse-native-namestring realname
828                                                  (pathname-host physical)
829                                                  (sane-default-pathname-defaults)
830                                                  :as-directory t)
831                         (return-from map-directory nil)))
832          (dirname (native-namestring canonical)))
833     (flet ((map-it (name dirp)
834              (funcall fun
835                       (merge-pathnames (parse-native-namestring
836                                         name nil physical
837                                         :as-directory (and dirp (not as-files)))
838                                        physical))))
839       (with-native-directory-iterator (next dirname :errorp errorp)
840         (loop
841           ;; provision for FindFirstFileExW-based iterator that should be used
842           ;; on Windows: file kind is known instantly there, so we'll have it
843           ;; returned by (next) soon.
844           (multiple-value-bind (name kind) (next)
845             (unless (or name kind) (return))
846             (unless kind
847               (setf kind (native-file-kind
848                           (concatenate 'string dirname name))))
849             (when kind
850               (case kind
851                 (:directory
852                  (when directories
853                    (map-it name t)))
854                 (:symlink
855                  (if classify-symlinks
856                      (let* ((tmpname (merge-pathnames
857                                       (parse-native-namestring
858                                        name nil physical :as-directory nil)
859                                       physical))
860                             (truename (query-file-system tmpname :truename nil)))
861                        (if (or (not truename)
862                                (or (pathname-name truename) (pathname-type truename)))
863                            (when files
864                              (funcall fun tmpname))
865                            (when directories
866                              (map-it name t))))
867                      (when files
868                        (map-it name nil))))
869                 (t
870                  ;; Anything else parses as a file.
871                  (when files
872                    (map-it name nil)))))))))))
873
874 ;;; Part of DIRECTORY: implements matching the directory spec. Calls FUNCTION
875 ;;; with all DIRECTORIES that match the directory portion of PATHSPEC.
876 (defun map-matching-directories (function pathspec)
877   (let* ((dir (pathname-directory pathspec))
878          (length (length dir))
879          (wild (position-if (lambda (elt)
880                               (or (eq :wild elt) (typep elt 'pattern)))
881                             dir))
882          (wild-inferiors (position :wild-inferiors dir))
883          (end (cond ((and wild wild-inferiors)
884                      (min wild wild-inferiors))
885                     (t
886                      (or wild wild-inferiors length))))
887          (rest (subseq dir end))
888          (starting-point (make-pathname :directory (subseq dir 0 end)
889                                         :device (pathname-device pathspec)
890                                         :host (pathname-host pathspec)
891                                         :name nil
892                                         :type nil
893                                         :version nil)))
894     (cond (wild-inferiors
895            (map-wild-inferiors function rest starting-point))
896           (wild
897            (map-wild function rest starting-point))
898           (t
899            ;; Nothing wild -- the directory matches itself.
900            (funcall function starting-point))))
901   nil)
902
903 (defun last-directory-piece (pathname)
904   (car (last (pathname-directory pathname))))
905
906 ;;; Part of DIRECTORY: implements iterating over a :WILD or pattern component
907 ;;; in the directory spec.
908 (defun map-wild (function more directory)
909   (let ((this (pop more))
910         (next (car more)))
911     (flet ((cont (subdirectory)
912              (cond ((not more)
913                     ;; end of the line
914                     (funcall function subdirectory))
915                    ((or (eq :wild next) (typep next 'pattern))
916                     (map-wild function more subdirectory))
917                    ((eq :wild-inferiors next)
918                     (map-wild-inferiors function more subdirectory))
919                    (t
920                     (let ((this (pathname-directory subdirectory)))
921                       (map-matching-directories
922                        function
923                        (make-pathname :directory (append this more)
924                                       :defaults subdirectory)))))))
925       (map-directory
926        (if (eq :wild this)
927            #'cont
928            (lambda (sub)
929              (when (pattern-matches this (last-directory-piece sub))
930                (funcall #'cont sub))))
931        directory
932        :files nil
933        :directories t
934        :errorp nil))))
935
936 ;;; Part of DIRECTORY: implements iterating over a :WILD-INFERIORS component
937 ;;; in the directory spec.
938 (defun map-wild-inferiors (function more directory)
939   (loop while (member (car more) '(:wild :wild-inferiors))
940         do (pop more))
941   (let ((next (car more))
942         (rest (cdr more)))
943     (unless more
944       (funcall function directory))
945     (map-directory
946      (cond ((not more)
947             (lambda (pathname)
948               (funcall function pathname)
949               (map-wild-inferiors function more pathname)))
950            (t
951             (lambda (pathname)
952               (let ((this (pathname-directory pathname)))
953                 (when (equal next (car (last this)))
954                   (map-matching-directories
955                    function
956                    (make-pathname :directory (append this rest)
957                                   :defaults pathname)))
958                 (map-wild-inferiors function more pathname)))))
959      directory
960      :files nil
961      :directories t
962      :errorp nil)))
963
964 ;;; Part of DIRECTORY: implements iterating over entries in a directory, and
965 ;;; matching them.
966 (defun map-matching-entries (function directory match-name match-type)
967   (map-directory
968    (lambda (file)
969      (when (and (funcall match-name (pathname-name file))
970                 (funcall match-type (pathname-type file)))
971        (funcall function file)))
972    directory
973    :files t
974    :directories :as-files
975    :errorp nil))
976
977 ;;; NOTE: There is a fair amount of hair below that is probably not
978 ;;; strictly necessary.
979 ;;;
980 ;;; The issue is the following: what does (DIRECTORY "SYS:*;") mean?
981 ;;; Until 2004-01, SBCL's behaviour was unquestionably wrong, as it
982 ;;; did not translate the logical pathname at all, but instead treated
983 ;;; it as a physical one.  Other Lisps seem to to treat this call as
984 ;;; equivalent to (DIRECTORY (TRANSLATE-LOGICAL-PATHNAME "SYS:*;")),
985 ;;; which is fine as far as it goes, but not very interesting, and
986 ;;; arguably counterintuitive.  (PATHNAME-MATCH-P "SYS:SRC;" "SYS:*;")
987 ;;; is true, so why should "SYS:SRC;" not show up in the call to
988 ;;; DIRECTORY?  (assuming the physical pathname corresponding to it
989 ;;; exists, of course).
990 ;;;
991 ;;; So, the interpretation that I am pushing is for all pathnames
992 ;;; matching the input pathname to be queried.  This means that we
993 ;;; need to compute the intersection of the input pathname and the
994 ;;; logical host FROM translations, and then translate the resulting
995 ;;; pathname using the host to the TO translation; this treatment is
996 ;;; recursively invoked until we get a physical pathname, whereupon
997 ;;; our physical DIRECTORY implementation takes over.
998
999 ;;; FIXME: this is an incomplete implementation.  It only works when
1000 ;;; both are logical pathnames (which is OK, because that's the only
1001 ;;; case when we call it), but there are other pitfalls as well: see
1002 ;;; the DIRECTORY-HELPER below for some, but others include a lack of
1003 ;;; pattern handling.
1004
1005 ;;; The above was written by CSR, I (RMK) believe.  The argument that
1006 ;;; motivates the interpretation is faulty, however: PATHNAME-MATCH-P
1007 ;;; returns true for (PATHNAME-MATCH-P #P"/tmp/*/" #P"/tmp/../"), but
1008 ;;; the latter pathname is not in the result of DIRECTORY on the
1009 ;;; former.  Indeed, if DIRECTORY were constrained to return the
1010 ;;; truename for every pathname for which PATHNAME-MATCH-P returned
1011 ;;; true and which denoted a filename that named an existing file,
1012 ;;; (DIRECTORY #P"/tmp/**/") would be required to list every file on a
1013 ;;; Unix system, since any file can be named as though it were "below"
1014 ;;; /tmp, given the dotdot entries.  So I think the strongest
1015 ;;; "consistency" we can define between PATHNAME-MATCH-P and DIRECTORY
1016 ;;; is that PATHNAME-MATCH-P returns true of everything DIRECTORY
1017 ;;; returns, but not vice versa.
1018
1019 ;;; In any case, even if the motivation were sound, DIRECTORY on a
1020 ;;; wild logical pathname has no portable semantics.  I see nothing in
1021 ;;; ANSI that requires implementations to support wild physical
1022 ;;; pathnames, and so there need not be any translation of a wild
1023 ;;; logical pathname to a phyiscal pathname.  So a program that calls
1024 ;;; DIRECTORY on a wild logical pathname is doing something
1025 ;;; non-portable at best.  And if the only sensible semantics for
1026 ;;; DIRECTORY on a wild logical pathname is something like the
1027 ;;; following, it would be just as well if it signaled an error, since
1028 ;;; a program can't possibly rely on the result of an intersection of
1029 ;;; user-defined translations with a file system probe.  (Potentially
1030 ;;; useful kinds of "pathname" that might not support wildcards could
1031 ;;; include pathname hosts that model unqueryable namespaces like HTTP
1032 ;;; URIs, or that model namespaces that it's not convenient to
1033 ;;; investigate, such as the namespace of TCP ports that some network
1034 ;;; host listens on.  I happen to think it a bad idea to try to
1035 ;;; shoehorn such namespaces into a pathnames system, but people
1036 ;;; sometimes claim to want pathnames for these things.)  -- RMK
1037 ;;; 2007-12-31.
1038
1039 (defun pathname-intersections (one two)
1040   (aver (logical-pathname-p one))
1041   (aver (logical-pathname-p two))
1042   (labels
1043       ((intersect-version (one two)
1044          (aver (typep one '(or null (member :newest :wild :unspecific)
1045                             integer)))
1046          (aver (typep two '(or null (member :newest :wild :unspecific)
1047                             integer)))
1048          (cond
1049            ((eq one :wild) two)
1050            ((eq two :wild) one)
1051            ((or (null one) (eq one :unspecific)) two)
1052            ((or (null two) (eq two :unspecific)) one)
1053            ((eql one two) one)
1054            (t nil)))
1055        (intersect-name/type (one two)
1056          (aver (typep one '(or null (member :wild :unspecific) string)))
1057          (aver (typep two '(or null (member :wild :unspecific) string)))
1058          (cond
1059            ((eq one :wild) two)
1060            ((eq two :wild) one)
1061            ((or (null one) (eq one :unspecific)) two)
1062            ((or (null two) (eq two :unspecific)) one)
1063            ((string= one two) one)
1064            (t (return-from pathname-intersections nil))))
1065        (intersect-directory (one two)
1066          (aver (typep one '(or null (member :wild :unspecific) list)))
1067          (aver (typep two '(or null (member :wild :unspecific) list)))
1068          (cond
1069            ((eq one :wild) two)
1070            ((eq two :wild) one)
1071            ((or (null one) (eq one :unspecific)) two)
1072            ((or (null two) (eq two :unspecific)) one)
1073            (t (aver (eq (car one) (car two)))
1074               (mapcar
1075                (lambda (x) (cons (car one) x))
1076                (intersect-directory-helper (cdr one) (cdr two)))))))
1077     (let ((version (intersect-version
1078                     (pathname-version one) (pathname-version two)))
1079           (name (intersect-name/type
1080                  (pathname-name one) (pathname-name two)))
1081           (type (intersect-name/type
1082                  (pathname-type one) (pathname-type two)))
1083           (host (pathname-host one)))
1084       (mapcar (lambda (d)
1085                 (make-pathname :host host :name name :type type
1086                                :version version :directory d))
1087               (intersect-directory
1088                (pathname-directory one) (pathname-directory two))))))
1089
1090 ;;; FIXME: written as its own function because I (CSR) don't
1091 ;;; understand it, so helping both debuggability and modularity.  In
1092 ;;; case anyone is motivated to rewrite it, it returns a list of
1093 ;;; sublists representing the intersection of the two input directory
1094 ;;; paths (excluding the initial :ABSOLUTE or :RELATIVE).
1095 ;;;
1096 ;;; FIXME: Does not work with :UP or :BACK
1097 ;;; FIXME: Does not work with patterns
1098 ;;;
1099 ;;; FIXME: PFD suggests replacing this implementation with a DFA
1100 ;;; conversion of a NDFA.  Find out (a) what this means and (b) if it
1101 ;;; turns out to be worth it.
1102 (defun intersect-directory-helper (one two)
1103   (flet ((simple-intersection (cone ctwo)
1104            (cond
1105              ((eq cone :wild) ctwo)
1106              ((eq ctwo :wild) cone)
1107              (t (aver (typep cone 'string))
1108                 (aver (typep ctwo 'string))
1109                 (if (string= cone ctwo) cone nil)))))
1110     (macrolet
1111         ((loop-possible-wild-inferiors-matches
1112              (lower-bound bounding-sequence order)
1113            (let ((index (gensym)) (g2 (gensym)) (g3 (gensym)) (l (gensym)))
1114              `(let ((,l (length ,bounding-sequence)))
1115                (loop for ,index from ,lower-bound to ,l
1116                 append (mapcar (lambda (,g2)
1117                                  (append
1118                                   (butlast ,bounding-sequence (- ,l ,index))
1119                                   ,g2))
1120                         (mapcar
1121                          (lambda (,g3)
1122                            (append
1123                             (if (eq (car (nthcdr ,index ,bounding-sequence))
1124                                     :wild-inferiors)
1125                                 '(:wild-inferiors)
1126                                 nil) ,g3))
1127                          (intersect-directory-helper
1128                           ,@(if order
1129                                 `((nthcdr ,index one) (cdr two))
1130                                 `((cdr one) (nthcdr ,index two)))))))))))
1131       (cond
1132         ((and (eq (car one) :wild-inferiors)
1133               (eq (car two) :wild-inferiors))
1134          (delete-duplicates
1135           (append (mapcar (lambda (x) (cons :wild-inferiors x))
1136                           (intersect-directory-helper (cdr one) (cdr two)))
1137                   (loop-possible-wild-inferiors-matches 2 one t)
1138                   (loop-possible-wild-inferiors-matches 2 two nil))
1139           :test 'equal))
1140         ((eq (car one) :wild-inferiors)
1141          (delete-duplicates (loop-possible-wild-inferiors-matches 0 two nil)
1142                             :test 'equal))
1143         ((eq (car two) :wild-inferiors)
1144          (delete-duplicates (loop-possible-wild-inferiors-matches 0 one t)
1145                             :test 'equal))
1146         ((and (null one) (null two)) (list nil))
1147         ((null one) nil)
1148         ((null two) nil)
1149         (t (and (simple-intersection (car one) (car two))
1150                 (mapcar (lambda (x) (cons (simple-intersection
1151                                            (car one) (car two)) x))
1152                         (intersect-directory-helper (cdr one) (cdr two)))))))))
1153 \f
1154
1155 (defun directory-pathname-p (pathname)
1156   (and (pathnamep pathname)
1157        (null (pathname-name pathname))
1158        (null (pathname-type pathname))))
1159
1160 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
1161   #!+sb-doc
1162   "Test whether the directories containing the specified file
1163   actually exist, and attempt to create them if they do not.
1164   The MODE argument is a CMUCL/SBCL-specific extension to control
1165   the Unix permission bits."
1166   (let ((pathname (physicalize-pathname (merge-pathnames (pathname pathspec))))
1167         (created-p nil))
1168     (when (wild-pathname-p pathname)
1169       (error 'simple-file-error
1170              :format-control "bad place for a wild pathname"
1171              :pathname pathspec))
1172     (let* ((dir (pathname-directory pathname))
1173            (*default-pathname-defaults*
1174              (make-pathname :directory dir :device (pathname-device pathname)))
1175           (dev (pathname-device pathname)))
1176       (loop for i from (case dev (:unc 3) (otherwise 2))
1177               upto (length dir)
1178             do
1179             (let* ((newpath (make-pathname
1180                              :host (pathname-host pathname)
1181                              :device dev
1182                              :directory (subseq dir 0 i)))
1183                    (probed (probe-file newpath)))
1184               (unless (directory-pathname-p probed)
1185                 (let ((namestring (coerce (native-namestring newpath)
1186                                           'string)))
1187                   (when verbose
1188                     (format *standard-output*
1189                             "~&creating directory: ~A~%"
1190                             namestring))
1191                   (sb!unix:unix-mkdir namestring mode)
1192                   (unless (directory-pathname-p (probe-file newpath))
1193                     (restart-case
1194                         (error
1195                          'simple-file-error
1196                          :pathname pathspec
1197                          :format-control
1198                          (if (and probed
1199                                   (not (directory-pathname-p probed)))
1200                              "Can't create directory ~A,~
1201                                  ~%a file with the same name already exists."
1202                              "Can't create directory ~A")
1203                          :format-arguments (list namestring))
1204                       (retry ()
1205                         :report "Retry directory creation."
1206                         (ensure-directories-exist
1207                          pathspec
1208                          :verbose verbose :mode mode))
1209                       (continue ()
1210                         :report
1211                         "Continue as if directory creation was successful."
1212                         nil)))
1213                   (setf created-p t)))))
1214       (values pathspec created-p))))
1215
1216 (/show0 "filesys.lisp 1000")