1.0.15.26: only one return value from USER-HOMEDIR-PATHNAME
[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 (defvar *ignore-wildcards* nil)
84
85 (/show0 "filesys.lisp 86")
86
87 (defun maybe-make-pattern (namestr start end)
88   (declare (type simple-string namestr)
89            (type index start end))
90   (if *ignore-wildcards*
91       (subseq namestr start end)
92       (collect ((pattern))
93         (let ((quoted nil)
94               (any-quotes nil)
95               (last-regular-char nil)
96               (index start))
97           (flet ((flush-pending-regulars ()
98                    (when last-regular-char
99                      (pattern (if any-quotes
100                                   (remove-backslashes namestr
101                                                       last-regular-char
102                                                       index)
103                                   (subseq namestr last-regular-char index)))
104                      (setf any-quotes nil)
105                      (setf last-regular-char nil))))
106             (loop
107               (when (>= index end)
108                 (return))
109               (let ((char (schar namestr index)))
110                 (cond (quoted
111                        (incf index)
112                        (setf quoted nil))
113                       ((char= char #\\)
114                        (setf quoted t)
115                        (setf any-quotes t)
116                        (unless last-regular-char
117                          (setf last-regular-char index))
118                        (incf index))
119                       ((char= char #\?)
120                        (flush-pending-regulars)
121                        (pattern :single-char-wild)
122                        (incf index))
123                       ((char= char #\*)
124                        (flush-pending-regulars)
125                        (pattern :multi-char-wild)
126                        (incf index))
127                       ((char= char #\[)
128                        (flush-pending-regulars)
129                        (let ((close-bracket
130                               (position #\] namestr :start index :end end)))
131                          (unless close-bracket
132                            (error 'namestring-parse-error
133                                   :complaint "#\\[ with no corresponding #\\]"
134                                   :namestring namestr
135                                   :offset index))
136                          (pattern (cons :character-set
137                                         (subseq namestr
138                                                 (1+ index)
139                                                 close-bracket)))
140                          (setf index (1+ close-bracket))))
141                       (t
142                        (unless last-regular-char
143                          (setf last-regular-char index))
144                        (incf index)))))
145             (flush-pending-regulars)))
146         (cond ((null (pattern))
147                "")
148               ((null (cdr (pattern)))
149                (let ((piece (first (pattern))))
150                  (typecase piece
151                    ((member :multi-char-wild) :wild)
152                    (simple-string piece)
153                    (t
154                     (make-pattern (pattern))))))
155               (t
156                (make-pattern (pattern)))))))
157
158 (/show0 "filesys.lisp 160")
159
160 (defun extract-name-type-and-version (namestr start end)
161   (declare (type simple-string namestr)
162            (type index start end))
163   (let* ((last-dot (position #\. namestr :start (1+ start) :end end
164                              :from-end t)))
165     (cond
166       (last-dot
167        (values (maybe-make-pattern namestr start last-dot)
168                (maybe-make-pattern namestr (1+ last-dot) end)
169                :newest))
170       (t
171        (values (maybe-make-pattern namestr start end)
172                nil
173                :newest)))))
174
175 (/show0 "filesys.lisp 200")
176
177 \f
178 ;;;; wildcard matching stuff
179
180 ;;; Return a list of all the Lispy filenames (not including e.g. the
181 ;;; Unix magic "." and "..") in the directory named by DIRECTORY-NAME.
182 (defun directory-lispy-filenames (directory-name)
183   (with-alien ((adlf (* c-string)
184                      (alien-funcall (extern-alien
185                                      "alloc_directory_lispy_filenames"
186                                      (function (* c-string) c-string))
187                                     directory-name)))
188     (if (null-alien adlf)
189         (error 'simple-file-error
190                :pathname directory-name
191                :format-control "~@<couldn't read directory ~S: ~2I~_~A~:>"
192                :format-arguments (list directory-name (strerror)))
193         (unwind-protect
194             (c-strings->string-list adlf)
195           (alien-funcall (extern-alien "free_directory_lispy_filenames"
196                                        (function void (* c-string)))
197                          adlf)))))
198
199 (/show0 "filesys.lisp 498")
200
201 (defmacro !enumerate-matches ((var pathname &optional result
202                                    &key (verify-existence t)
203                                    (follow-links t))
204                               &body body)
205   `(block nil
206      (%enumerate-matches (pathname ,pathname)
207                          ,verify-existence
208                          ,follow-links
209                          (lambda (,var) ,@body))
210      ,result))
211
212 (/show0 "filesys.lisp 500")
213
214 ;;; Call FUNCTION on matches.
215 ;;;
216 ;;; KLUDGE: this assumes that an absolute pathname is indicated to the
217 ;;; operating system by having a directory separator as the first
218 ;;; character in the directory part.  This is true for Win32 pathnames
219 ;;; and for Unix pathnames, but it isn't true for LispM pathnames (and
220 ;;; their bastard offspring, logical pathnames.  Also it assumes that
221 ;;; Unix pathnames have an empty or :unspecific device, and that
222 ;;; windows drive letters are the only kinds of non-empty/:UNSPECIFIC
223 ;;; devices.
224 (defun %enumerate-matches (pathname verify-existence follow-links function)
225   (/noshow0 "entering %ENUMERATE-MATCHES")
226   (when (pathname-type pathname)
227     (unless (pathname-name pathname)
228       (error "cannot supply a type without a name:~%  ~S" pathname)))
229   (when (and (integerp (pathname-version pathname))
230              (member (pathname-type pathname) '(nil :unspecific)))
231     (error "cannot supply a version without a type:~%  ~S" pathname))
232   (let ((host (pathname-host pathname))
233         (device (pathname-device pathname))
234         (directory (pathname-directory pathname)))
235     (/noshow0 "computed HOST and DIRECTORY")
236     (let* ((dirstring (if directory
237                           (ecase (first directory)
238                             (:absolute (host-unparse-directory-separator host))
239                             (:relative ""))
240                           ""))
241            (devstring (if (and device (not (eq device :unspecific)))
242                           (concatenate 'simple-string (string device) (string #\:))
243                           ""))
244            (headstring (concatenate 'simple-string devstring dirstring)))
245       (if directory
246           (%enumerate-directories headstring (rest directory) pathname
247                                   verify-existence follow-links nil function)
248           (%enumerate-files headstring pathname verify-existence function)))))
249
250 ;;; Call FUNCTION on directories.
251 (defun %enumerate-directories (head tail pathname verify-existence
252                                follow-links nodes function
253                                &aux (host (pathname-host pathname)))
254   (declare (simple-string head))
255   #!+win32
256   (setf follow-links nil)
257   (macrolet ((unix-xstat (name)
258                `(if follow-links
259                     (sb!unix:unix-stat ,name)
260                     (sb!unix:unix-lstat ,name)))
261              (with-directory-node-noted ((head) &body body)
262                `(multiple-value-bind (res dev ino mode)
263                     (unix-xstat ,head)
264                   (when (and res (eql (logand mode sb!unix:s-ifmt)
265                                       sb!unix:s-ifdir))
266                     (let ((nodes (cons (cons dev ino) nodes)))
267                       ,@body))))
268              (with-directory-node-removed ((head) &body body)
269                `(multiple-value-bind (res dev ino mode)
270                     (unix-xstat ,head)
271                   (when (and res (eql (logand mode sb!unix:s-ifmt)
272                                       sb!unix:s-ifdir))
273                     (let ((nodes (remove (cons dev ino) nodes :test #'equal)))
274                       ,@body)))))
275     (if tail
276         (let ((piece (car tail)))
277           (etypecase piece
278             (simple-string
279              (let ((head (concatenate 'string head piece)))
280                (with-directory-node-noted (head)
281                  (%enumerate-directories
282                   (concatenate 'string head
283                                (host-unparse-directory-separator host))
284                   (cdr tail) pathname
285                   verify-existence follow-links
286                   nodes function))))
287             ((member :wild-inferiors)
288              ;; now with extra error case handling from CLHS
289              ;; 19.2.2.4.3 -- CSR, 2004-01-24
290              (when (member (cadr tail) '(:up :back))
291                (error 'simple-file-error
292                       :pathname pathname
293                       :format-control "~@<invalid use of ~S after :WILD-INFERIORS~@:>."
294                       :format-arguments (list (cadr tail))))
295              (%enumerate-directories head (rest tail) pathname
296                                      verify-existence follow-links
297                                      nodes function)
298              (dolist (name (directory-lispy-filenames head))
299                (let ((subdir (concatenate 'string head name)))
300                  (multiple-value-bind (res dev ino mode)
301                      (unix-xstat subdir)
302                    (declare (type (or fixnum null) mode))
303                    (when (and res (eql (logand mode sb!unix:s-ifmt)
304                                        sb!unix:s-ifdir))
305                      (unless (dolist (dir nodes nil)
306                                (when (and (eql (car dir) dev)
307                                           #!+win32 ;; KLUDGE
308                                           (not (zerop ino))
309                                           (eql (cdr dir) ino))
310                                  (return t)))
311                        (let ((nodes (cons (cons dev ino) nodes))
312                              (subdir (concatenate 'string subdir (host-unparse-directory-separator host))))
313                          (%enumerate-directories subdir tail pathname
314                                                  verify-existence follow-links
315                                                  nodes function))))))))
316             ((or pattern (member :wild))
317              (dolist (name (directory-lispy-filenames head))
318                (when (or (eq piece :wild) (pattern-matches piece name))
319                  (let ((subdir (concatenate 'string head name)))
320                    (multiple-value-bind (res dev ino mode)
321                        (unix-xstat subdir)
322                      (declare (type (or fixnum null) mode))
323                      (when (and res
324                                 (eql (logand mode sb!unix:s-ifmt)
325                                      sb!unix:s-ifdir))
326                        (let ((nodes (cons (cons dev ino) nodes))
327                              (subdir (concatenate 'string subdir (host-unparse-directory-separator host))))
328                          (%enumerate-directories subdir (rest tail) pathname
329                                                  verify-existence follow-links
330                                                  nodes function))))))))
331           ((member :up)
332            (when (string= head (host-unparse-directory-separator host))
333              (error 'simple-file-error
334                     :pathname pathname
335                     :format-control "~@<invalid use of :UP after :ABSOLUTE.~@:>"))
336            (with-directory-node-removed (head)
337              (let ((head (concatenate 'string head "..")))
338                (with-directory-node-noted (head)
339                  (%enumerate-directories (concatenate 'string head (host-unparse-directory-separator host))
340                                          (rest tail) pathname
341                                          verify-existence follow-links
342                                          nodes function)))))
343           ((member :back)
344            ;; :WILD-INFERIORS is handled above, so the only case here
345            ;; should be (:ABSOLUTE :BACK)
346            (aver (string= head (host-unparse-directory-separator host)))
347            (error 'simple-file-error
348                   :pathname pathname
349                   :format-control "~@<invalid use of :BACK after :ABSOLUTE.~@:>"))))
350         (%enumerate-files head pathname verify-existence function))))
351
352 ;;; Call FUNCTION on files.
353 (defun %enumerate-files (directory pathname verify-existence function)
354   (declare (simple-string directory))
355   (/noshow0 "entering %ENUMERATE-FILES")
356   (let ((name (%pathname-name pathname))
357         (type (%pathname-type pathname))
358         (version (%pathname-version pathname)))
359     (/noshow0 "computed NAME, TYPE, and VERSION")
360     (cond ((member name '(nil :unspecific))
361            (/noshow0 "UNSPECIFIC, more or less")
362            (let ((directory (coerce directory 'string)))
363              (when (or (not verify-existence)
364                        (sb!unix:unix-file-kind directory))
365                (funcall function directory))))
366           ((or (pattern-p name)
367                (pattern-p type)
368                (eq name :wild)
369                (eq type :wild))
370            (/noshow0 "WILD, more or less")
371            ;; I IGNORE-ERRORS here just because the original CMU CL
372            ;; code did. I think the intent is that it's not an error
373            ;; to request matches to a wild pattern when no matches
374            ;; exist, but I haven't tried to figure out whether
375            ;; everything is kosher. (E.g. what if we try to match a
376            ;; wildcard but we don't have permission to read one of the
377            ;; relevant directories?) -- WHN 2001-04-17
378            (dolist (complete-filename (ignore-errors
379                                         (directory-lispy-filenames directory)))
380              (multiple-value-bind
381                  (file-name file-type file-version)
382                  (let ((*ignore-wildcards* t))
383                    (extract-name-type-and-version
384                     complete-filename 0 (length complete-filename)))
385                (when (and (components-match file-name name)
386                           (components-match file-type type)
387                           (components-match file-version version))
388                  (funcall function
389                           (concatenate 'string
390                                        directory
391                                        complete-filename))))))
392           (t
393            (/noshow0 "default case")
394            (let ((file (concatenate 'string directory name)))
395              (/noshow "computed basic FILE")
396              (unless (or (null type) (eq type :unspecific))
397                (/noshow0 "tweaking FILE for more-or-less-:UNSPECIFIC case")
398                (setf file (concatenate 'string file "." type)))
399              (unless (member version '(nil :newest :wild :unspecific))
400                (/noshow0 "tweaking FILE for more-or-less-:WILD case")
401                (setf file (concatenate 'string file "."
402                                        (quick-integer-to-string version))))
403              (/noshow0 "finished possibly tweaking FILE")
404              (when (or (not verify-existence)
405                        (sb!unix:unix-file-kind file t))
406                (/noshow0 "calling FUNCTION on FILE")
407                (funcall function file)))))))
408
409 (/noshow0 "filesys.lisp 603")
410
411 ;;; FIXME: Why do we need this?
412 (defun quick-integer-to-string (n)
413   (declare (type integer n))
414   (cond ((not (fixnump n))
415          (write-to-string n :base 10 :radix nil))
416         ((zerop n) "0")
417         ((eql n 1) "1")
418         ((minusp n)
419          (concatenate 'simple-base-string "-"
420                       (the simple-base-string (quick-integer-to-string (- n)))))
421         (t
422          (do* ((len (1+ (truncate (integer-length n) 3)))
423                (res (make-string len :element-type 'base-char))
424                (i (1- len) (1- i))
425                (q n)
426                (r 0))
427               ((zerop q)
428                (incf i)
429                (replace res res :start2 i :end2 len)
430                (%shrink-vector res (- len i)))
431            (declare (simple-string res)
432                     (fixnum len i r q))
433            (multiple-value-setq (q r) (truncate q 10))
434            (setf (schar res i) (schar "0123456789" r))))))
435 \f
436 ;;;; UNIX-NAMESTRING
437
438 (defun empty-relative-pathname-spec-p (x)
439   (or (equal x "")
440       (and (pathnamep x)
441            (or (equal (pathname-directory x) '(:relative))
442                ;; KLUDGE: I'm not sure this second check should really
443                ;; have to be here. But on sbcl-0.6.12.7,
444                ;; (PATHNAME-DIRECTORY (PATHNAME "")) is NIL, and
445                ;; (PATHNAME "") seems to act like an empty relative
446                ;; pathname, so in order to work with that, I test
447                ;; for NIL here. -- WHN 2001-05-18
448                (null (pathname-directory x)))
449            (null (pathname-name x))
450            (null (pathname-type x)))
451       ;; (The ANSI definition of "pathname specifier" has
452       ;; other cases, but none of them seem to admit the possibility
453       ;; of being empty and relative.)
454       ))
455
456 ;;; Convert PATHNAME into a string that can be used with UNIX system
457 ;;; calls, or return NIL if no match is found. Wild-cards are expanded.
458 ;;;
459 ;;; FIXME: apart from the error checking (for wildness and for
460 ;;; existence) and conversion to physical pathanme, this is redundant
461 ;;; with UNPARSE-NATIVE-UNIX-NAMESTRING; one should probably be
462 ;;; written in terms of the other.
463 ;;;
464 ;;; FIXME: actually this (I think) works not just for Unix.
465 (defun unix-namestring (pathname-spec &optional (for-input t))
466   (let* ((namestring (physicalize-pathname (merge-pathnames pathname-spec)))
467          (matches nil)) ; an accumulator for actual matches
468     (when (wild-pathname-p namestring)
469       (error 'simple-file-error
470              :pathname namestring
471              :format-control "bad place for a wild pathname"))
472     (!enumerate-matches (match namestring nil :verify-existence for-input)
473                         (push match matches))
474     (case (length matches)
475       (0 nil)
476       (1 (first matches))
477       (t (bug "!ENUMERATE-MATCHES returned more than one match on a non-wild pathname")))))
478 \f
479 ;;;; TRUENAME, PROBE-FILE, FILE-AUTHOR, FILE-WRITE-DATE.
480
481 ;;; Rewritten in 12/2007 by RMK, replacing 13+ year old CMU code that
482 ;;; made a mess of things in order to support search lists (which SBCL
483 ;;; has never had).  These are now all relatively straightforward
484 ;;; wrappers around stat(2) and realpath(2), with the same basic logic
485 ;;; in all cases.  The wrinkles to be aware of:
486 ;;;
487 ;;; * SBCL defines the truename of an existing, dangling or
488 ;;;   self-referring symlink to be the symlink itself.
489 ;;; * The old version of PROBE-FILE merged the pathspec against
490 ;;;   *DEFAULT-PATHNAME-DEFAULTS* twice, and so lost when *D-P-D*
491 ;;;   was a relative pathname.  Even if the case where *D-P-D* is a
492 ;;;   relative pathname is problematic, there's no particular reason
493 ;;;   to get that wrong, so let's try not to.
494 ;;; * Note that while stat(2) is probably atomic, getting the truename
495 ;;;   for a filename involves poking all over the place, and so is
496 ;;;   subject to race conditions if other programs mutate the file
497 ;;;   system while we're resolving symlinks.  So it's not implausible for
498 ;;;   realpath(3) to fail even if stat(2) succeeded.  There's nothing
499 ;;;   obvious we can do about this, however.
500 ;;; * Windows' apparent analogue of realpath(3) is called
501 ;;;   GetFullPathName, and it's a bit less useful than realpath(3).
502 ;;;   In particular, while realpath(3) errors in case the file doesn't
503 ;;;   exist, GetFullPathName seems to return a filename in all cases.
504 ;;;   As realpath(3) is not atomic anyway, we only ever call it when
505 ;;;   we think a file exists, so just be careful when rewriting this
506 ;;;   routine.
507 (defun query-file-system (pathspec query-for)
508   (let ((pathname (translate-logical-pathname
509                    (merge-pathnames
510                     (pathname pathspec)
511                     (sane-default-pathname-defaults)))))
512     (when (wild-pathname-p pathname)
513       (error 'simple-file-error
514              :pathname pathname
515              :format-control "~@<can't find the ~A of wild pathname ~A~
516                               (physicalized from ~A).~:>"
517              :format-arguments (list query-for pathname pathspec)))
518     (let ((filename (native-namestring pathname :as-file t)))
519       (multiple-value-bind (existsp errno ino mode nlink uid gid rdev size
520                                     atime mtime)
521           (sb!unix:unix-stat filename)
522         (declare (ignore ino nlink gid rdev size atime))
523         (if existsp
524             (case query-for
525               (:truename (nth-value
526                           0
527                           (parse-native-namestring
528                            ;; Note: in case the file is stat'able, POSIX
529                            ;; realpath(3) gets us a canonical absolute
530                            ;; filename, even if the post-merge PATHNAME
531                            ;; is not absolute...
532                            (multiple-value-bind (realpath errno)
533                                (sb!unix:unix-realpath filename)
534                              (if realpath
535                                  realpath
536                                  (simple-file-perror "couldn't resolve ~A"
537                                                      filename errno)))
538                            (pathname-host pathname)
539                            (sane-default-pathname-defaults)
540                            ;; ... but without any trailing slash.
541                            :as-directory (eql (logand  mode sb!unix:s-ifmt)
542                                               sb!unix:s-ifdir))))
543               (:author (sb!unix:uid-username uid))
544               (:write-date (+ unix-to-universal-time mtime)))
545             (progn
546               ;; SBCL has for many years had a policy that a pathname
547               ;; that names an existing, dangling or self-referential
548               ;; symlink denotes the symlink itself.  stat(2) fails
549               ;; and sets errno to ELOOP in this case, but we must
550               ;; distinguish cases where the symlink exists from ones
551               ;; where there's a loop in the apparent containing
552               ;; directory.
553               #!-win32
554               (multiple-value-bind (linkp ignore ino mode nlink uid gid rdev
555                                           size atime mtime)
556                   (sb!unix:unix-lstat filename)
557                 (declare (ignore ignore ino mode nlink gid rdev size atime))
558                 (when (and (or (= errno sb!unix:enoent)
559                                (= errno sb!unix:eloop))
560                            linkp)
561                   (return-from query-file-system
562                     (case query-for
563                       (:truename
564                        ;; So here's a trick: since lstat succeded,
565                        ;; FILENAME exists, so its directory exists and
566                        ;; only the non-directory part is loopy.  So
567                        ;; let's resolve FILENAME's directory part with
568                        ;; realpath(3), in order to get a canonical
569                        ;; absolute name for the directory, and then
570                        ;; return a pathname having PATHNAME's name,
571                        ;; type, and version, but the rest from the
572                        ;; truename of the directory.  Since we turned
573                        ;; PATHNAME into FILENAME "as a file", FILENAME
574                        ;; does not end in a slash, and so we get the
575                        ;; directory part of FILENAME by reparsing
576                        ;; FILENAME and masking off its name, type, and
577                        ;; version bits.  But note not to call ourselves
578                        ;; recursively, because we don't want to
579                        ;; re-merge against *DEFAULT-PATHNAME-DEFAULTS*,
580                        ;; since PATHNAME may be a relative pathname.
581                        (merge-pathnames
582                         (nth-value
583                          0
584                          (parse-native-namestring
585                           (multiple-value-bind (realpath errno)
586                               (sb!unix:unix-realpath
587                                (native-namestring
588                                 (make-pathname
589                                  :name :unspecific
590                                  :type :unspecific
591                                  :version :unspecific
592                                  :defaults (parse-native-namestring
593                                             filename
594                                             (pathname-host pathname)
595                                             (sane-default-pathname-defaults)))))
596                             (if realpath
597                                 realpath
598                                 (simple-file-perror "couldn't resolve ~A"
599                                                     filename errno)))
600                           (pathname-host pathname)
601                           (sane-default-pathname-defaults)
602                           :as-directory t))
603                         pathname))
604                       (:author (sb!unix:uid-username uid))
605                       (:write-date (+ unix-to-universal-time mtime))))))
606               ;; If we're still here, the file doesn't exist; error.
607               (simple-file-perror
608                (format nil "failed to find the ~A of ~~A" query-for)
609                pathspec errno)))))))
610
611
612 (defun probe-file (pathspec)
613   #!+sb-doc
614   "Return the truename of PATHSPEC if the truename can be found,
615 or NIL otherwise.  See TRUENAME for more information."
616   (handler-case (truename pathspec) (file-error () nil)))
617
618 (defun truename (pathspec)
619   #!+sb-doc
620   "If PATHSPEC is a pathname that names an existing file, return
621 a pathname that denotes a canonicalized name for the file.  If
622 pathspec is a stream associated with a file, return a pathname
623 that denotes a canonicalized name for the file associated with
624 the stream.
625
626 An error of type FILE-ERROR is signalled if no such file exists
627 or if the file system is such that a canonicalized file name
628 cannot be determined or if the pathname is wild.
629
630 Under Unix, the TRUENAME of a symlink that links to itself or to
631 a file that doesn't exist is considered to be the name of the
632 broken symlink itself."
633   ;; Note that eventually this routine might be different for streams
634   ;; than for other pathname designators.
635   (if (streamp pathspec)
636       (query-file-system pathspec :truename)
637       (query-file-system pathspec :truename)))
638
639 (defun file-author (pathspec)
640   #!+sb-doc
641   "Return the author of the file specified by PATHSPEC. Signal an
642 error of type FILE-ERROR if no such file exists, or if PATHSPEC
643 is a wild pathname."
644   (query-file-system pathspec :author))
645
646 (defun file-write-date (pathspec)
647   #!+sb-doc
648   "Return the write date of the file specified by PATHSPEC.
649 An error of type FILE-ERROR is signaled if no such file exists,
650 or if PATHSPEC is a wild pathname."
651   (query-file-system pathspec :write-date))
652 \f
653 ;;;; miscellaneous other operations
654
655 (/show0 "filesys.lisp 700")
656
657 (defun rename-file (file new-name)
658   #!+sb-doc
659   "Rename FILE to have the specified NEW-NAME. If FILE is a stream open to a
660   file, then the associated file is renamed."
661   (let* ((original (truename file))
662          (original-namestring (unix-namestring original t))
663          (new-name (merge-pathnames new-name original))
664          (new-namestring (unix-namestring new-name nil)))
665     (unless new-namestring
666       (error 'simple-file-error
667              :pathname new-name
668              :format-control "~S can't be created."
669              :format-arguments (list new-name)))
670     (multiple-value-bind (res error)
671         (sb!unix:unix-rename original-namestring new-namestring)
672       (unless res
673         (error 'simple-file-error
674                :pathname new-name
675                :format-control "~@<couldn't rename ~2I~_~A ~I~_to ~2I~_~A: ~
676                                 ~I~_~A~:>"
677                :format-arguments (list original new-name (strerror error))))
678       (when (streamp file)
679         (file-name file new-name))
680       (values new-name original (truename new-name)))))
681
682 (defun delete-file (file)
683   #!+sb-doc
684   "Delete the specified FILE."
685   (let ((namestring (unix-namestring file t)))
686     (when (streamp file)
687       (close file :abort t))
688     (unless namestring
689       (error 'simple-file-error
690              :pathname file
691              :format-control "~S doesn't exist."
692              :format-arguments (list file)))
693     (multiple-value-bind (res err) (sb!unix:unix-unlink namestring)
694       (unless res
695         (simple-file-perror "couldn't delete ~A" namestring err))))
696   t)
697 \f
698 (defun sbcl-homedir-pathname ()
699   (let ((sbcl-home (posix-getenv "SBCL_HOME")))
700     ;; SBCL_HOME isn't set for :EXECUTABLE T embedded cores
701     (when (and sbcl-home (not (string= sbcl-home "")))
702       (parse-native-namestring sbcl-home
703                                #-win32 sb!impl::*unix-host*
704                                #+win32 sb!impl::*win32-host*
705                                *default-pathname-defaults*
706                                :as-directory t))))
707
708 ;;; (This is an ANSI Common Lisp function.)
709 (defun user-homedir-pathname (&optional host)
710   #!+sb-doc
711   "Return the home directory of the user as a pathname. If the HOME
712 environment variable has been specified, the directory it designates
713 is returned; otherwise obtains the home directory from the operating
714 system."
715   (declare (ignore host))
716   (let ((env-home (posix-getenv "HOME")))
717     (values
718      (parse-native-namestring
719       (if (and env-home (not (string= env-home "")))
720           env-home
721           #!-win32
722           (sb!unix:uid-homedir (sb!unix:unix-getuid))
723           #!+win32
724           ;; Needs to bypass PARSE-NATIVE-NAMESTRING & ENSURE-TRAILING-SLASH
725           ;; What?! -- RMK, 2007-12-31
726           (return-from user-homedir-pathname
727             (sb!win32::get-folder-pathname sb!win32::csidl_profile)))
728       #-win32 sb!impl::*unix-host*
729       #+win32 sb!impl::*win32-host*
730       *default-pathname-defaults*
731       :as-directory t))))
732
733 \f
734 ;;;; DIRECTORY
735
736 (/show0 "filesys.lisp 800")
737
738 ;;; NOTE: There is a fair amount of hair below that is probably not
739 ;;; strictly necessary.
740 ;;;
741 ;;; The issue is the following: what does (DIRECTORY "SYS:*;") mean?
742 ;;; Until 2004-01, SBCL's behaviour was unquestionably wrong, as it
743 ;;; did not translate the logical pathname at all, but instead treated
744 ;;; it as a physical one.  Other Lisps seem to to treat this call as
745 ;;; equivalent to (DIRECTORY (TRANSLATE-LOGICAL-PATHNAME "SYS:*;")),
746 ;;; which is fine as far as it goes, but not very interesting, and
747 ;;; arguably counterintuitive.  (PATHNAME-MATCH-P "SYS:SRC;" "SYS:*;")
748 ;;; is true, so why should "SYS:SRC;" not show up in the call to
749 ;;; DIRECTORY?  (assuming the physical pathname corresponding to it
750 ;;; exists, of course).
751 ;;;
752 ;;; So, the interpretation that I am pushing is for all pathnames
753 ;;; matching the input pathname to be queried.  This means that we
754 ;;; need to compute the intersection of the input pathname and the
755 ;;; logical host FROM translations, and then translate the resulting
756 ;;; pathname using the host to the TO translation; this treatment is
757 ;;; recursively invoked until we get a physical pathname, whereupon
758 ;;; our physical DIRECTORY implementation takes over.
759
760 ;;; FIXME: this is an incomplete implementation.  It only works when
761 ;;; both are logical pathnames (which is OK, because that's the only
762 ;;; case when we call it), but there are other pitfalls as well: see
763 ;;; the DIRECTORY-HELPER below for some, but others include a lack of
764 ;;; pattern handling.
765
766 ;;; The above was written by CSR, I (RMK) believe.  The argument that
767 ;;; motivates the interpretation is faulty, however: PATHNAME-MATCH-P
768 ;;; returns true for (PATHNAME-MATCH-P #P"/tmp/*/" #P"/tmp/../"), but
769 ;;; the latter pathname is not in the result of DIRECTORY on the
770 ;;; former.  Indeed, if DIRECTORY were constrained to return the
771 ;;; truename for every pathname for which PATHNAME-MATCH-P returned
772 ;;; true and which denoted a filename that named an existing file,
773 ;;; (DIRECTORY #P"/tmp/**/") would be required to list every file on a
774 ;;; Unix system, since any file can be named as though it were "below"
775 ;;; /tmp, given the dotdot entries.  So I think the strongest
776 ;;; "consistency" we can define between PATHNAME-MATCH-P and DIRECTORY
777 ;;; is that PATHNAME-MATCH-P returns true of everything DIRECTORY
778 ;;; returns, but not vice versa.
779
780 ;;; In any case, even if the motivation were sound, DIRECTORY on a
781 ;;; wild logical pathname has no portable semantics.  I see nothing in
782 ;;; ANSI that requires implementations to support wild physical
783 ;;; pathnames, and so there need not be any translation of a wild
784 ;;; logical pathname to a phyiscal pathname.  So a program that calls
785 ;;; DIRECTORY on a wild logical pathname is doing something
786 ;;; non-portable at best.  And if the only sensible semantics for
787 ;;; DIRECTORY on a wild logical pathname is something like the
788 ;;; following, it would be just as well if it signaled an error, since
789 ;;; a program can't possibly rely on the result of an intersection of
790 ;;; user-defined translations with a file system probe.  (Potentially
791 ;;; useful kinds of "pathname" that might not support wildcards could
792 ;;; include pathname hosts that model unqueryable namespaces like HTTP
793 ;;; URIs, or that model namespaces that it's not convenient to
794 ;;; investigate, such as the namespace of TCP ports that some network
795 ;;; host listens on.  I happen to think it a bad idea to try to
796 ;;; shoehorn such namespaces into a pathnames system, but people
797 ;;; sometimes claim to want pathnames for these things.)  -- RMK
798 ;;; 2007-12-31.
799
800 (defun pathname-intersections (one two)
801   (aver (logical-pathname-p one))
802   (aver (logical-pathname-p two))
803   (labels
804       ((intersect-version (one two)
805          (aver (typep one '(or null (member :newest :wild :unspecific)
806                             integer)))
807          (aver (typep two '(or null (member :newest :wild :unspecific)
808                             integer)))
809          (cond
810            ((eq one :wild) two)
811            ((eq two :wild) one)
812            ((or (null one) (eq one :unspecific)) two)
813            ((or (null two) (eq two :unspecific)) one)
814            ((eql one two) one)
815            (t nil)))
816        (intersect-name/type (one two)
817          (aver (typep one '(or null (member :wild :unspecific) string)))
818          (aver (typep two '(or null (member :wild :unspecific) string)))
819          (cond
820            ((eq one :wild) two)
821            ((eq two :wild) one)
822            ((or (null one) (eq one :unspecific)) two)
823            ((or (null two) (eq two :unspecific)) one)
824            ((string= one two) one)
825            (t nil)))
826        (intersect-directory (one two)
827          (aver (typep one '(or null (member :wild :unspecific) list)))
828          (aver (typep two '(or null (member :wild :unspecific) list)))
829          (cond
830            ((eq one :wild) two)
831            ((eq two :wild) one)
832            ((or (null one) (eq one :unspecific)) two)
833            ((or (null two) (eq two :unspecific)) one)
834            (t (aver (eq (car one) (car two)))
835               (mapcar
836                (lambda (x) (cons (car one) x))
837                (intersect-directory-helper (cdr one) (cdr two)))))))
838     (let ((version (intersect-version
839                     (pathname-version one) (pathname-version two)))
840           (name (intersect-name/type
841                  (pathname-name one) (pathname-name two)))
842           (type (intersect-name/type
843                  (pathname-type one) (pathname-type two)))
844           (host (pathname-host one)))
845       (mapcar (lambda (d)
846                 (make-pathname :host host :name name :type type
847                                :version version :directory d))
848               (intersect-directory
849                (pathname-directory one) (pathname-directory two))))))
850
851 ;;; FIXME: written as its own function because I (CSR) don't
852 ;;; understand it, so helping both debuggability and modularity.  In
853 ;;; case anyone is motivated to rewrite it, it returns a list of
854 ;;; sublists representing the intersection of the two input directory
855 ;;; paths (excluding the initial :ABSOLUTE or :RELATIVE).
856 ;;;
857 ;;; FIXME: Does not work with :UP or :BACK
858 ;;; FIXME: Does not work with patterns
859 ;;;
860 ;;; FIXME: PFD suggests replacing this implementation with a DFA
861 ;;; conversion of a NDFA.  Find out (a) what this means and (b) if it
862 ;;; turns out to be worth it.
863 (defun intersect-directory-helper (one two)
864   (flet ((simple-intersection (cone ctwo)
865            (cond
866              ((eq cone :wild) ctwo)
867              ((eq ctwo :wild) cone)
868              (t (aver (typep cone 'string))
869                 (aver (typep ctwo 'string))
870                 (if (string= cone ctwo) cone nil)))))
871     (macrolet
872         ((loop-possible-wild-inferiors-matches
873              (lower-bound bounding-sequence order)
874            (let ((index (gensym)) (g2 (gensym)) (g3 (gensym)) (l (gensym)))
875              `(let ((,l (length ,bounding-sequence)))
876                (loop for ,index from ,lower-bound to ,l
877                 append (mapcar (lambda (,g2)
878                                  (append
879                                   (butlast ,bounding-sequence (- ,l ,index))
880                                   ,g2))
881                         (mapcar
882                          (lambda (,g3)
883                            (append
884                             (if (eq (car (nthcdr ,index ,bounding-sequence))
885                                     :wild-inferiors)
886                                 '(:wild-inferiors)
887                                 nil) ,g3))
888                          (intersect-directory-helper
889                           ,@(if order
890                                 `((nthcdr ,index one) (cdr two))
891                                 `((cdr one) (nthcdr ,index two)))))))))))
892       (cond
893         ((and (eq (car one) :wild-inferiors)
894               (eq (car two) :wild-inferiors))
895          (delete-duplicates
896           (append (mapcar (lambda (x) (cons :wild-inferiors x))
897                           (intersect-directory-helper (cdr one) (cdr two)))
898                   (loop-possible-wild-inferiors-matches 2 one t)
899                   (loop-possible-wild-inferiors-matches 2 two nil))
900           :test 'equal))
901         ((eq (car one) :wild-inferiors)
902          (delete-duplicates (loop-possible-wild-inferiors-matches 0 two nil)
903                             :test 'equal))
904         ((eq (car two) :wild-inferiors)
905          (delete-duplicates (loop-possible-wild-inferiors-matches 0 one t)
906                             :test 'equal))
907         ((and (null one) (null two)) (list nil))
908         ((null one) nil)
909         ((null two) nil)
910         (t (and (simple-intersection (car one) (car two))
911                 (mapcar (lambda (x) (cons (simple-intersection
912                                            (car one) (car two)) x))
913                         (intersect-directory-helper (cdr one) (cdr two)))))))))
914
915 (defun directory (pathname &key)
916   #!+sb-doc
917   "Return a list of PATHNAMEs, each the TRUENAME of a file that matched the
918    given pathname. Note that the interaction between this ANSI-specified
919    TRUENAMEing and the semantics of the Unix filesystem (symbolic links..)
920    means this function can sometimes return files which don't have the same
921    directory as PATHNAME."
922   (let (;; We create one entry in this hash table for each truename,
923         ;; as an asymptotically efficient way of removing duplicates
924         ;; (which can arise when e.g. multiple symlinks map to the
925         ;; same truename).
926         (truenames (make-hash-table :test #'equal))
927         ;; FIXME: Possibly this MERGE-PATHNAMES call should only
928         ;; happen once we get a physical pathname.
929         (merged-pathname (merge-pathnames pathname)))
930     (labels ((do-physical-directory (pathname)
931                (aver (not (logical-pathname-p pathname)))
932                (!enumerate-matches (match pathname)
933                  (let* ((*ignore-wildcards* t)
934                         ;; FIXME: Why not TRUENAME?  As reported by
935                         ;; Milan Zamazal sbcl-devel 2003-10-05, using
936                         ;; TRUENAME causes a race condition whereby
937                         ;; removal of a file during the directory
938                         ;; operation causes an error.  It's not clear
939                         ;; what the right thing to do is, though.  --
940                         ;; CSR, 2003-10-13
941                         (truename (probe-file match)))
942                    (when truename
943                      (setf (gethash (namestring truename) truenames)
944                            truename)))))
945              (do-directory (pathname)
946                (if (logical-pathname-p pathname)
947                    (let ((host (intern-logical-host (pathname-host pathname))))
948                      (dolist (x (logical-host-canon-transls host))
949                        (destructuring-bind (from to) x
950                          (let ((intersections
951                                 (pathname-intersections pathname from)))
952                            (dolist (p intersections)
953                              (do-directory (translate-pathname p from to)))))))
954                    (do-physical-directory pathname))))
955       (do-directory merged-pathname))
956     (mapcar #'cdr
957             ;; Sorting isn't required by the ANSI spec, but sorting
958             ;; into some canonical order seems good just on the
959             ;; grounds that the implementation should have repeatable
960             ;; behavior when possible.
961             (sort (loop for name being each hash-key in truenames
962                      using (hash-value truename)
963                      collect (cons name truename))
964                   #'string<
965                   :key #'car))))
966 \f
967 (/show0 "filesys.lisp 899")
968
969 ;;; predicate to order pathnames by; goes by name
970 ;; FIXME: Does anything use this?  It's not exported, and I don't find
971 ;; the name anywhere else.
972 (defun pathname-order (x y)
973   (let ((xn (%pathname-name x))
974         (yn (%pathname-name y)))
975     (if (and xn yn)
976         (let ((res (string-lessp xn yn)))
977           (cond ((not res) nil)
978                 ((= res (length (the simple-string xn))) t)
979                 ((= res (length (the simple-string yn))) nil)
980                 (t t)))
981         xn)))
982 \f
983 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
984   #!+sb-doc
985   "Test whether the directories containing the specified file
986   actually exist, and attempt to create them if they do not.
987   The MODE argument is a CMUCL/SBCL-specific extension to control
988   the Unix permission bits."
989   (let ((pathname (physicalize-pathname (merge-pathnames (pathname pathspec))))
990         (created-p nil))
991     (when (wild-pathname-p pathname)
992       (error 'simple-file-error
993              :format-control "bad place for a wild pathname"
994              :pathname pathspec))
995     (let ((dir (pathname-directory pathname)))
996       (loop for i from 1 upto (length dir)
997             do (let ((newpath (make-pathname
998                                :host (pathname-host pathname)
999                                :device (pathname-device pathname)
1000                                :directory (subseq dir 0 i))))
1001                  (unless (probe-file newpath)
1002                    (let ((namestring (coerce (native-namestring newpath)
1003                                              'string)))
1004                      (when verbose
1005                        (format *standard-output*
1006                                "~&creating directory: ~A~%"
1007                                namestring))
1008                      (sb!unix:unix-mkdir namestring mode)
1009                      (unless (probe-file newpath)
1010                        (restart-case (error
1011                                       'simple-file-error
1012                                       :pathname pathspec
1013                                       :format-control
1014                                       "can't create directory ~A"
1015                                       :format-arguments (list namestring))
1016                          (retry ()
1017                            :report "Retry directory creation."
1018                            (ensure-directories-exist
1019                             pathspec
1020                             :verbose verbose :mode mode))
1021                          (continue ()
1022                            :report
1023                            "Continue as if directory creation was successful."
1024                            nil)))
1025                      (setf created-p t)))))
1026       (values pathspec created-p))))
1027
1028 (/show0 "filesys.lisp 1000")