0.6.12.7.flaky1.2:
[sbcl.git] / src / code / filesys.lisp
1 ;;;; file system interface functions -- fairly Unix-specific
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!IMPL")
13 \f
14 ;;;; Unix pathname host support
15
16 ;;; Unix namestrings have the following format:
17 ;;;
18 ;;; namestring := [ directory ] [ file [ type [ version ]]]
19 ;;; directory := [ "/" | search-list ] { file "/" }*
20 ;;; search-list := [^:/]*:
21 ;;; file := [^/]*
22 ;;; type := "." [^/.]*
23 ;;; version := "." ([0-9]+ | "*")
24 ;;;
25 ;;; FIXME: Search lists are no longer supported.
26 ;;;
27 ;;; Note: this grammar is ambiguous. The string foo.bar.5 can be
28 ;;; parsed as either just the file specified or as specifying the
29 ;;; file, type, and version. Therefore, we use the following rules
30 ;;; when confronted with an ambiguous file.type.version string:
31 ;;;
32 ;;; - If the first character is a dot, it's part of the file. It is not
33 ;;; considered a dot in the following rules.
34 ;;;
35 ;;; - If there is only one dot, it separates the file and the type.
36 ;;;
37 ;;; - If there are multiple dots and the stuff following the last dot
38 ;;; is a valid version, then that is the version and the stuff between
39 ;;; the second to last dot and the last dot is the type.
40 ;;;
41 ;;; Wildcard characters:
42 ;;;
43 ;;; If the directory, file, type components contain any of the
44 ;;; following characters, it is considered part of a wildcard pattern
45 ;;; and has the following meaning.
46 ;;;
47 ;;; ? - matches any character
48 ;;; * - matches any zero or more characters.
49 ;;; [abc] - matches any of a, b, or c.
50 ;;; {str1,str2,...,strn} - matches any of str1, str2, ..., or strn.
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-base-string namestr)
59            (type index start end))
60   (let* ((result (make-string (- end start)))
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-base-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 (list :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-base-string namestr)
162            (type index start end))
163   (let* ((last-dot (position #\. namestr :start (1+ start) :end end
164                              :from-end t))
165          (second-to-last-dot (and last-dot
166                                   (position #\. namestr :start (1+ start)
167                                             :end last-dot :from-end t)))
168          (version :newest))
169     ;; If there is a second-to-last dot, check to see whether there is
170     ;; a valid version after the last dot.
171     (when second-to-last-dot
172       (cond ((and (= (+ last-dot 2) end)
173                   (char= (schar namestr (1+ last-dot)) #\*))
174              (setf version :wild))
175             ((and (< (1+ last-dot) end)
176                   (do ((index (1+ last-dot) (1+ index)))
177                       ((= index end) t)
178                     (unless (char<= #\0 (schar namestr index) #\9)
179                       (return nil))))
180              (setf version
181                    (parse-integer namestr :start (1+ last-dot) :end end)))
182             (t
183              (setf second-to-last-dot nil))))
184     (cond (second-to-last-dot
185            (values (maybe-make-pattern namestr start second-to-last-dot)
186                    (maybe-make-pattern namestr
187                                        (1+ second-to-last-dot)
188                                        last-dot)
189                    version))
190           (last-dot
191            (values (maybe-make-pattern namestr start last-dot)
192                    (maybe-make-pattern namestr (1+ last-dot) end)
193                    version))
194           (t
195            (values (maybe-make-pattern namestr start end)
196                    nil
197                    version)))))
198
199 (/show0 "filesys.lisp 200")
200
201 ;;; Take a string and return a list of cons cells that mark the char
202 ;;; separated subseq. The first value is true if absolute directories
203 ;;; location.
204 (defun split-at-slashes (namestr start end)
205   (declare (type simple-base-string namestr)
206            (type index start end))
207   (let ((absolute (and (/= start end)
208                        (char= (schar namestr start) #\/))))
209     (when absolute
210       (incf start))
211     ;; Next, split the remainder into slash-separated chunks.
212     (collect ((pieces))
213       (loop
214         (let ((slash (position #\/ namestr :start start :end end)))
215           (pieces (cons start (or slash end)))
216           (unless slash
217             (return))
218           (setf start (1+ slash))))
219       (values absolute (pieces)))))
220
221 (defun maybe-extract-search-list (namestr start end)
222   (declare (type simple-base-string namestr)
223            (type index start end))
224   (let ((quoted nil))
225     (do ((index start (1+ index)))
226         ((= index end)
227          (values nil start))
228       (if quoted
229           (setf quoted nil)
230           (case (schar namestr index)
231             (#\\
232              (setf quoted t))
233             (#\:
234              (return (values (remove-backslashes namestr start index)
235                              (1+ index)))))))))
236
237 (defun parse-unix-namestring (namestr start end)
238   (declare (type simple-base-string namestr)
239            (type index start end))
240   (multiple-value-bind (absolute pieces) (split-at-slashes namestr start end)
241     (let ((search-list (if absolute
242                            nil
243                            (let ((first (car pieces)))
244                              (multiple-value-bind (search-list new-start)
245                                  (maybe-extract-search-list namestr
246                                                             (car first)
247                                                             (cdr first))
248                                (when search-list
249                                  (setf absolute t)
250                                  (setf (car first) new-start))
251                                search-list)))))
252       (multiple-value-bind (name type version)
253           (let* ((tail (car (last pieces)))
254                  (tail-start (car tail))
255                  (tail-end (cdr tail)))
256             (unless (= tail-start tail-end)
257               (setf pieces (butlast pieces))
258               (extract-name-type-and-version namestr tail-start tail-end)))
259         ;; PVE: make sure there are no illegal characters in
260         ;; the name, illegal being (code-char 0) and #\/
261         #!+high-security
262         (when (and (stringp name)
263                    (find-if #'(lambda (x) (or (char= x (code-char 0))
264                                               (char= x #\/)))
265                             name))
266           (error 'parse-error))
267         
268         ;; Now we have everything we want. So return it.
269         (values nil ; no host for unix namestrings.
270                 nil ; no devices for unix namestrings.
271                 (collect ((dirs))
272                   (when search-list
273                     (dirs (intern-search-list search-list)))
274                   (dolist (piece pieces)
275                     (let ((piece-start (car piece))
276                           (piece-end (cdr piece)))
277                       (unless (= piece-start piece-end)
278                         (cond ((string= namestr ".." :start1 piece-start
279                                         :end1 piece-end)
280                                (dirs :up))
281                               ((string= namestr "**" :start1 piece-start
282                                         :end1 piece-end)
283                                (dirs :wild-inferiors))
284                               (t
285                                (dirs (maybe-make-pattern namestr
286                                                          piece-start
287                                                          piece-end)))))))
288                   (cond (absolute
289                          (cons :absolute (dirs)))
290                         ((dirs)
291                          (cons :relative (dirs)))
292                         (t
293                          nil)))
294                 name
295                 type
296                 version)))))
297
298 (/show0 "filesys.lisp 300")
299
300 (defun unparse-unix-host (pathname)
301   (declare (type pathname pathname)
302            (ignore pathname))
303   "Unix")
304
305 (defun unparse-unix-piece (thing)
306   (etypecase thing
307     ((member :wild) "*")
308     (simple-string
309      (let* ((srclen (length thing))
310             (dstlen srclen))
311        (dotimes (i srclen)
312          (case (schar thing i)
313            ((#\* #\? #\[)
314             (incf dstlen))))
315        (let ((result (make-string dstlen))
316              (dst 0))
317          (dotimes (src srclen)
318            (let ((char (schar thing src)))
319              (case char
320                ((#\* #\? #\[)
321                 (setf (schar result dst) #\\)
322                 (incf dst)))
323              (setf (schar result dst) char)
324              (incf dst)))
325          result)))
326     (pattern
327      (collect ((strings))
328        (dolist (piece (pattern-pieces thing))
329          (etypecase piece
330            (simple-string
331             (strings piece))
332            (symbol
333             (ecase piece
334               (:multi-char-wild
335                (strings "*"))
336               (:single-char-wild
337                (strings "?"))))
338            (cons
339             (case (car piece)
340               (:character-set
341                (strings "[")
342                (strings (cdr piece))
343                (strings "]"))
344               (t
345                (error "invalid pattern piece: ~S" piece))))))
346        (apply #'concatenate
347               'simple-string
348               (strings))))))
349
350 (defun unparse-unix-directory-list (directory)
351   (declare (type list directory))
352   (collect ((pieces))
353     (when directory
354       (ecase (pop directory)
355         (:absolute
356          (cond ((search-list-p (car directory))
357                 (pieces (search-list-name (pop directory)))
358                 (pieces ":"))
359                (t
360                 (pieces "/"))))
361         (:relative
362          ;; nothing special
363          ))
364       (dolist (dir directory)
365         (typecase dir
366           ((member :up)
367            (pieces "../"))
368           ((member :back)
369            (error ":BACK cannot be represented in namestrings."))
370           ((member :wild-inferiors)
371            (pieces "**/"))
372           ((or simple-string pattern)
373            (pieces (unparse-unix-piece dir))
374            (pieces "/"))
375           (t
376            (error "invalid directory component: ~S" dir)))))
377     (apply #'concatenate 'simple-string (pieces))))
378
379 (defun unparse-unix-directory (pathname)
380   (declare (type pathname pathname))
381   (unparse-unix-directory-list (%pathname-directory pathname)))
382
383 (defun unparse-unix-file (pathname)
384   (declare (type pathname pathname))
385   (collect ((strings))
386     (let* ((name (%pathname-name pathname))
387            (type (%pathname-type pathname))
388            (type-supplied (not (or (null type) (eq type :unspecific)))))
389       ;; Note: by ANSI 19.3.1.1.5, we ignore the version slot when
390       ;; translating logical pathnames to a filesystem without
391       ;; versions (like Unix).
392       (when name
393         (strings (unparse-unix-piece name)))
394       (when type-supplied
395         (unless name
396           (error "cannot specify the type without a file: ~S" pathname))
397         (strings ".")
398         (strings (unparse-unix-piece type))))
399     (apply #'concatenate 'simple-string (strings))))
400
401 (/show0 "filesys.lisp 406")
402
403 (defun unparse-unix-namestring (pathname)
404   (declare (type pathname pathname))
405   (concatenate 'simple-string
406                (unparse-unix-directory pathname)
407                (unparse-unix-file pathname)))
408
409 (defun unparse-unix-enough (pathname defaults)
410   (declare (type pathname pathname defaults))
411   (flet ((lose ()
412            (error "~S cannot be represented relative to ~S."
413                   pathname defaults)))
414     (collect ((strings))
415       (let* ((pathname-directory (%pathname-directory pathname))
416              (defaults-directory (%pathname-directory defaults))
417              (prefix-len (length defaults-directory))
418              (result-directory
419               (cond ((and (> prefix-len 1)
420                           (>= (length pathname-directory) prefix-len)
421                           (compare-component (subseq pathname-directory
422                                                      0 prefix-len)
423                                              defaults-directory))
424                      ;; Pathname starts with a prefix of default. So
425                      ;; just use a relative directory from then on out.
426                      (cons :relative (nthcdr prefix-len pathname-directory)))
427                     ((eq (car pathname-directory) :absolute)
428                      ;; We are an absolute pathname, so we can just use it.
429                      pathname-directory)
430                     (t
431                      ;; We are a relative directory. So we lose.
432                      (lose)))))
433         (strings (unparse-unix-directory-list result-directory)))
434       (let* ((pathname-version (%pathname-version pathname))
435              (version-needed (and pathname-version
436                                   (not (eq pathname-version :newest))))
437              (pathname-type (%pathname-type pathname))
438              (type-needed (or version-needed
439                               (and pathname-type
440                                    (not (eq pathname-type :unspecific)))))
441              (pathname-name (%pathname-name pathname))
442              (name-needed (or type-needed
443                               (and pathname-name
444                                    (not (compare-component pathname-name
445                                                            (%pathname-name
446                                                             defaults)))))))
447         (when name-needed
448           (unless pathname-name (lose))
449           (strings (unparse-unix-piece pathname-name)))
450         (when type-needed
451           (when (or (null pathname-type) (eq pathname-type :unspecific))
452             (lose))
453           (strings ".")
454           (strings (unparse-unix-piece pathname-type)))
455         (when version-needed
456           (typecase pathname-version
457             ((member :wild)
458              (strings ".*"))
459             (integer
460              (strings (format nil ".~D" pathname-version)))
461             (t
462              (lose)))))
463       (apply #'concatenate 'simple-string (strings)))))
464
465 (/show0 "filesys.lisp 471")
466
467 (def!struct (unix-host
468              (:make-load-form-fun make-unix-host-load-form)
469              (:include host
470                        (parse #'parse-unix-namestring)
471                        (unparse #'unparse-unix-namestring)
472                        (unparse-host #'unparse-unix-host)
473                        (unparse-directory #'unparse-unix-directory)
474                        (unparse-file #'unparse-unix-file)
475                        (unparse-enough #'unparse-unix-enough)
476                        (customary-case :lower))))
477
478 (/show0 "filesys.lisp 486")
479
480 (defvar *unix-host* (make-unix-host))
481
482 (/show0 "filesys.lisp 488")
483
484 (defun make-unix-host-load-form (host)
485   (declare (ignore host))
486   '*unix-host*)
487 \f
488 ;;;; wildcard matching stuff
489
490 ;;; Return a list of all the Lispy filenames (not including e.g. the
491 ;;; Unix magic "." and "..") in the directory named by DIRECTORY-NAME.
492 (defun directory-lispy-filenames (directory-name)
493   (with-alien ((adlf (* c-string)
494                      (alien-funcall (extern-alien
495                                      "alloc_directory_lispy_filenames"
496                                      (function (* c-string) c-string))
497                                     directory-name)))
498     (if (null-alien adlf)
499         (error 'simple-file-error
500                :pathname directory-name
501                :format-control "~@<couldn't read directory ~S: ~2I~_~A~:>"
502                :format-arguments (list directory-name (strerror)))
503         (unwind-protect
504             (c-strings->string-list adlf)
505           (alien-funcall (extern-alien "free_directory_lispy_filenames"
506                                        (function void (* c-string)))
507                          adlf)))))
508
509 (/show0 "filesys.lisp 498")
510
511 ;;; FIXME: could maybe be EVAL-WHEN (COMPILE EVAL)
512
513 (defmacro enumerate-matches ((var pathname &optional result
514                                   &key (verify-existence t)
515                                   (follow-links t))
516                              &body body)
517   (let ((body-name (gensym "ENUMERATE-MATCHES-BODY-FUN-")))
518     `(block nil
519        (flet ((,body-name (,var)
520                 ,@body))
521          (declare (dynamic-extent ,body-name))
522          (%enumerate-matches (pathname ,pathname)
523                              ,verify-existence
524                              ,follow-links
525                              #',body-name)
526          ,result))))
527
528 (/show0 "filesys.lisp 500")
529
530 ;;; Call FUNCTION on matches.
531 (defun %enumerate-matches (pathname verify-existence follow-links function)
532   (/show0 "entering %ENUMERATE-MATCHES")
533   (when (pathname-type pathname)
534     (unless (pathname-name pathname)
535       (error "cannot supply a type without a name:~%  ~S" pathname)))
536   (when (and (integerp (pathname-version pathname))
537              (member (pathname-type pathname) '(nil :unspecific)))
538     (error "cannot supply a version without a type:~%  ~S" pathname))
539   (let ((directory (pathname-directory pathname)))
540     (/show0 "computed DIRECTORY")
541     (if directory
542         (ecase (car directory)
543           (:absolute
544            (/show0 "absolute directory")
545            (%enumerate-directories "/" (cdr directory) pathname
546                                    verify-existence follow-links
547                                    nil function))
548           (:relative
549            (/show0 "relative directory")
550            (%enumerate-directories "" (cdr directory) pathname
551                                    verify-existence follow-links
552                                    nil function)))
553         (%enumerate-files "" pathname verify-existence function))))
554
555 ;;; Call FUNCTION on directories.
556 (defun %enumerate-directories (head tail pathname verify-existence
557                                follow-links nodes function)
558   (declare (simple-string head))
559   (macrolet ((unix-xstat (name)
560                `(if follow-links
561                     (sb!unix:unix-stat ,name)
562                     (sb!unix:unix-lstat ,name)))
563              (with-directory-node-noted ((head) &body body)
564                `(multiple-value-bind (res dev ino mode)
565                     (unix-xstat ,head)
566                   (when (and res (eql (logand mode sb!unix:s-ifmt)
567                                       sb!unix:s-ifdir))
568                     (let ((nodes (cons (cons dev ino) nodes)))
569                       ,@body)))))
570     (if tail
571         (let ((piece (car tail)))
572           (etypecase piece
573             (simple-string
574              (let ((head (concatenate 'string head piece)))
575                (with-directory-node-noted (head)
576                  (%enumerate-directories (concatenate 'string head "/")
577                                          (cdr tail) pathname
578                                          verify-existence follow-links
579                                          nodes function))))
580             ((member :wild-inferiors)
581              (%enumerate-directories head (rest tail) pathname
582                                      verify-existence follow-links
583                                      nodes function)
584              (dolist (name (ignore-errors (directory-lispy-filenames head)))
585                (let ((subdir (concatenate 'string head name)))
586                  (multiple-value-bind (res dev ino mode)
587                      (unix-xstat subdir)
588                    (declare (type (or fixnum null) mode))
589                    (when (and res (eql (logand mode sb!unix:s-ifmt)
590                                        sb!unix:s-ifdir))
591                      (unless (dolist (dir nodes nil)
592                                (when (and (eql (car dir) dev)
593                                           (eql (cdr dir) ino))
594                                  (return t)))
595                        (let ((nodes (cons (cons dev ino) nodes))
596                              (subdir (concatenate 'string subdir "/")))
597                          (%enumerate-directories subdir tail pathname
598                                                  verify-existence follow-links
599                                                  nodes function))))))))
600             ((or pattern (member :wild))
601              (dolist (name (directory-lispy-filenames head))
602                (when (or (eq piece :wild) (pattern-matches piece name))
603                  (let ((subdir (concatenate 'string head name)))
604                    (multiple-value-bind (res dev ino mode)
605                        (unix-xstat subdir)
606                      (declare (type (or fixnum null) mode))
607                      (when (and res
608                                 (eql (logand mode sb!unix:s-ifmt)
609                                      sb!unix:s-ifdir))
610                        (let ((nodes (cons (cons dev ino) nodes))
611                              (subdir (concatenate 'string subdir "/")))
612                          (%enumerate-directories subdir (rest tail) pathname
613                                                  verify-existence follow-links
614                                                  nodes function))))))))
615           ((member :up)
616              (let ((head (concatenate 'string head "..")))
617                (with-directory-node-noted (head)
618                  (%enumerate-directories (concatenate 'string head "/")
619                                          (rest tail) pathname
620                                          verify-existence follow-links
621                                          nodes function))))))
622         (%enumerate-files head pathname verify-existence function))))
623
624 ;;; Call FUNCTION on files.
625 (defun %enumerate-files (directory pathname verify-existence function)
626   (declare (simple-string directory))
627   (/show0 "entering %ENUMERATE-FILES")
628   (let ((name (%pathname-name pathname))
629         (type (%pathname-type pathname))
630         (version (%pathname-version pathname)))
631     (/show0 "computed NAME, TYPE, and VERSION")
632     (cond ((member name '(nil :unspecific))
633            (/show0 "UNSPECIFIC, more or less")
634            (when (or (not verify-existence)
635                      (sb!unix:unix-file-kind directory))
636              (funcall function directory)))
637           ((or (pattern-p name)
638                (pattern-p type)
639                (eq name :wild)
640                (eq type :wild))
641            (/show0 "WILD, more or less")
642            ;; I IGNORE-ERRORS here just because the original CMU CL
643            ;; code did. I think the intent is that it's not an error
644            ;; to request matches to a wild pattern when no matches
645            ;; exist, but I haven't tried to figure out whether
646            ;; everything is kosher. (E.g. what if we try to match a
647            ;; wildcard but we don't have permission to read one of the
648            ;; relevant directories?) -- WHN 2001-04-17
649            (dolist (complete-filename (ignore-errors
650                                         (directory-lispy-filenames directory)))
651              (multiple-value-bind
652                  (file-name file-type file-version)
653                  (let ((*ignore-wildcards* t))
654                    (extract-name-type-and-version
655                     complete-filename 0 (length complete-filename)))
656                (when (and (components-match file-name name)
657                           (components-match file-type type)
658                           (components-match file-version version))
659                  (funcall function
660                           (concatenate 'string
661                                        directory
662                                        complete-filename))))))
663           (t
664            (/show0 "default case")
665            (let ((file (concatenate 'string directory name)))
666              (/show0 "computed basic FILE=..")
667              (/primitive-print file)
668              (unless (or (null type) (eq type :unspecific))
669                (/show0 "tweaking FILE for more-or-less-:UNSPECIFIC case")
670                (setf file (concatenate 'string file "." type)))
671              (unless (member version '(nil :newest :wild))
672                (/show0 "tweaking FILE for more-or-less-:WILD case")
673                (setf file (concatenate 'string file "."
674                                        (quick-integer-to-string version))))
675              (/show0 "finished possibly tweaking FILE=..")
676              (/primitive-print file)
677              (when (or (not verify-existence)
678                        (sb!unix:unix-file-kind file t))
679                (/show0 "calling FUNCTION on FILE")
680                (funcall function file)))))))
681
682 (/show0 "filesys.lisp 603")
683
684 ;;; FIXME: Why do we need this?
685 (defun quick-integer-to-string (n)
686   (declare (type integer n))
687   (cond ((not (fixnump n))
688          (write-to-string n :base 10 :radix nil))
689         ((zerop n) "0")
690         ((eql n 1) "1")
691         ((minusp n)
692          (concatenate 'simple-string "-"
693                       (the simple-string (quick-integer-to-string (- n)))))
694         (t
695          (do* ((len (1+ (truncate (integer-length n) 3)))
696                (res (make-string len))
697                (i (1- len) (1- i))
698                (q n)
699                (r 0))
700               ((zerop q)
701                (incf i)
702                (replace res res :start2 i :end2 len)
703                (shrink-vector res (- len i)))
704            (declare (simple-string res)
705                     (fixnum len i r q))
706            (multiple-value-setq (q r) (truncate q 10))
707            (setf (schar res i) (schar "0123456789" r))))))
708 \f
709 ;;;; UNIX-NAMESTRING
710
711 (defun empty-relative-pathname-spec-p (x)
712   (or (equal x "")
713       (and (pathnamep x)
714            (or (equal (pathname-directory x) '(:relative))
715                ;; KLUDGE: I'm not sure this second check should really
716                ;; have to be here. But on sbcl-0.6.12.7,
717                ;; (PATHNAME-DIRECTORY (PATHNAME "")) is NIL, and
718                ;; (PATHNAME "") seems to act like an empty relative
719                ;; pathname, so in order to work with that, I test
720                ;; for NIL here. -- WHN 2001-05-18
721                (null (pathname-directory x)))
722            (null (pathname-name x))
723            (null (pathname-type x)))
724       ;; (The ANSI definition of "pathname specifier" has 
725       ;; other cases, but none of them seem to admit the possibility
726       ;; of being empty and relative.)
727       ))
728
729 ;;; Convert PATHNAME into a string that can be used with UNIX system
730 ;;; calls, or return NIL if no match is found. Search-lists and
731 ;;; wild-cards are expanded.
732 (defun unix-namestring (pathname-spec &optional (for-input t))
733   ;; The ordinary rules of converting Lispy paths to Unix paths break
734   ;; down for the current working directory, which Lisp thinks of as
735   ;; "" (more or less, and modulo ANSI's *DEFAULT-PATHNAME-DEFAULTS*,
736   ;; which unfortunately SBCL, as of sbcl-0.6.12.8, basically ignores)
737   ;; and Unix thinks of as ".". Since we're at the interface between
738   ;; Unix system calls and things like ENSURE-DIRECTORIES-EXIST which
739   ;; think the Lisp way, we perform the conversion.
740   ;;
741   ;; (FIXME: The *right* way to deal with this special case is to
742   ;; merge PATHNAME-SPEC with *DEFAULT-PATHNAME-DEFAULTS* here, after
743   ;; which it's not a relative pathname any more so the special case
744   ;; is no longer an issue. But until *DEFAULT-PATHNAME-DEFAULTS*
745   ;; works, we use this hack.)
746   (if (empty-relative-pathname-spec-p pathname-spec)
747       "."
748       ;; Otherwise, the ordinary rules apply.
749       (let* ((possibly-logical-pathname (pathname pathname-spec))
750              (physical-pathname (if (typep possibly-logical-pathname
751                                            'logical-pathname)
752                                     (namestring (translate-logical-pathname
753                                                  possibly-logical-pathname))
754                                     possibly-logical-pathname))
755              (matches nil)) ; an accumulator for actual matches
756         (enumerate-matches (match physical-pathname nil
757                                   :verify-existence for-input)
758           (push match matches))
759         (case (length matches)
760           (0 nil)
761           (1 (first matches))
762           (t (error 'simple-file-error
763                     :format-control "~S is ambiguous:~{~%  ~A~}"
764                     :format-arguments (list pathname-spec matches)))))))
765 \f
766 ;;;; TRUENAME and PROBE-FILE
767
768 ;;; This is only trivially different from PROBE-FILE, which is silly
769 ;;; but ANSI.
770 (defun truename (pathname)
771   #!+sb-doc
772   "Return the pathname for the actual file described by PATHNAME.
773   An error of type FILE-ERROR is signalled if no such file exists,
774   or the pathname is wild."
775   (if (wild-pathname-p pathname)
776       (error 'simple-file-error
777              :format-control "can't use a wild pathname here"
778              :pathname pathname)
779       (let ((result (probe-file pathname)))
780         (unless result
781           (error 'simple-file-error
782                  :pathname pathname
783                  :format-control "The file ~S does not exist."
784                  :format-arguments (list (namestring pathname))))
785         result)))
786
787 ;;; If PATHNAME exists, return its truename, otherwise NIL.
788 (defun probe-file (pathname)
789   #!+sb-doc
790   "Return a pathname which is the truename of the file if it exists, or NIL
791   otherwise. An error of type FILE-ERROR is signaled if pathname is wild."
792   (when (wild-pathname-p pathname)
793     (error 'simple-file-error
794            :pathname pathname
795            :format-control "can't use a wild pathname here"))
796   (let ((namestring (unix-namestring pathname t)))
797     (when (and namestring (sb!unix:unix-file-kind namestring))
798       (let ((truename (sb!unix:unix-resolve-links
799                        (sb!unix:unix-maybe-prepend-current-directory
800                         namestring))))
801         (when truename
802           (let ((*ignore-wildcards* t))
803             (pathname (sb!unix:unix-simplify-pathname truename))))))))
804 \f
805 ;;;; miscellaneous other operations
806
807 (/show0 "filesys.lisp 700")
808
809 (defun rename-file (file new-name)
810   #!+sb-doc
811   "Rename FILE to have the specified NEW-NAME. If FILE is a stream open to a
812   file, then the associated file is renamed."
813   (let* ((original (truename file))
814          (original-namestring (unix-namestring original t))
815          (new-name (merge-pathnames new-name original))
816          (new-namestring (unix-namestring new-name nil)))
817     (unless new-namestring
818       (error 'simple-file-error
819              :pathname new-name
820              :format-control "~S can't be created."
821              :format-arguments (list new-name)))
822     (multiple-value-bind (res error)
823         (sb!unix:unix-rename original-namestring new-namestring)
824       (unless res
825         (error 'simple-file-error
826                :pathname new-name
827                :format-control "~@<couldn't rename ~2I~_~A ~I~_to ~2I~_~A: ~
828                                 ~I~_~A~:>"
829                :format-arguments (list original new-name (strerror error))))
830       (when (streamp file)
831         (file-name file new-namestring))
832       (values new-name original (truename new-name)))))
833
834 (defun delete-file (file)
835   #!+sb-doc
836   "Delete the specified FILE."
837   (let ((namestring (unix-namestring file t)))
838     (when (streamp file)
839       (close file :abort t))
840     (unless namestring
841       (error 'simple-file-error
842              :pathname file
843              :format-control "~S doesn't exist."
844              :format-arguments (list file)))
845     (multiple-value-bind (res err) (sb!unix:unix-unlink namestring)
846       (unless res
847         (simple-file-perror "couldn't delete ~A" namestring err))))
848   t)
849 \f
850 ;;; (This is an ANSI Common Lisp function.) 
851 ;;;
852 ;;; This is obtained from the logical name \"home:\", which is set
853 ;;; up for us at initialization time.
854 (defun user-homedir-pathname (&optional host)
855   "Return the home directory of the user as a pathname."
856   (declare (ignore host))
857   ;; Note: CMU CL did #P"home:" here instead of using a call to
858   ;; PATHNAME. Delaying construction of the pathname until we're
859   ;; running in a target Lisp lets us avoid figuring out how to dump
860   ;; cross-compilation host Lisp PATHNAME objects into a target Lisp
861   ;; object file. It also might have a small positive effect on
862   ;; efficiency, in that we don't allocate a PATHNAME we don't need,
863   ;; but it it could also have a larger negative effect. Hopefully
864   ;; it'll be OK. -- WHN 19990714
865   (pathname "home:"))
866
867 (defun file-write-date (file)
868   #!+sb-doc
869   "Return file's creation date, or NIL if it doesn't exist.
870  An error of type file-error is signaled if file is a wild pathname"
871   (if (wild-pathname-p file)
872       ;; FIXME: This idiom appears many times in this file. Perhaps it
873       ;; should turn into (CANNOT-BE-WILD-PATHNAME FILE). (C-B-W-P
874       ;; should be a macro, not a function, so that the error message
875       ;; is reported as coming from e.g. FILE-WRITE-DATE instead of
876       ;; from CANNOT-BE-WILD-PATHNAME itself.)
877       (error 'simple-file-error
878              :pathname file
879              :format-control "bad place for a wild pathname")
880       (let ((name (unix-namestring file t)))
881         (when name
882           (multiple-value-bind
883               (res dev ino mode nlink uid gid rdev size atime mtime)
884               (sb!unix:unix-stat name)
885             (declare (ignore dev ino mode nlink uid gid rdev size atime))
886             (when res
887               (+ unix-to-universal-time mtime)))))))
888
889 (defun file-author (file)
890   #!+sb-doc
891   "Returns the file author as a string, or nil if the author cannot be
892  determined. Signals an error of type file-error if file doesn't exist,
893  or file is a wild pathname."
894   (if (wild-pathname-p file)
895       (error 'simple-file-error
896              :pathname file
897              "bad place for a wild pathname")
898       (let ((name (unix-namestring (pathname file) t)))
899         (unless name
900           (error 'simple-file-error
901                  :pathname file
902                  :format-control "~S doesn't exist."
903                  :format-arguments (list file)))
904         (multiple-value-bind (winp dev ino mode nlink uid)
905             (sb!unix:unix-stat name)
906           (declare (ignore dev ino mode nlink))
907           (if winp (lookup-login-name uid))))))
908 \f
909 ;;;; DIRECTORY
910
911 (/show0 "filesys.lisp 800")
912
913 (defun directory (pathname &key (all t) (check-for-subdirs t)
914                            (follow-links t))
915   #!+sb-doc
916   "Returns a list of pathnames, one for each file that matches the given
917    pathname. Supplying :ALL as NIL causes this to ignore Unix dot files. This
918    never includes Unix dot and dot-dot in the result. If :FOLLOW-LINKS is NIL,
919    then symbolic links in the result are not expanded. This is not the
920    default because TRUENAME does follow links, and the result pathnames are
921    defined to be the TRUENAME of the pathname (the truename of a link may well
922    be in another directory.)"
923   (let ((results nil))
924     (enumerate-search-list
925         (pathname (merge-pathnames pathname
926                                    (make-pathname :name :wild
927                                                   :type :wild
928                                                   :version :wild)))
929       (enumerate-matches (name pathname)
930         (when (or all
931                   (let ((slash (position #\/ name :from-end t)))
932                     (or (null slash)
933                         (= (1+ slash) (length name))
934                         (char/= (schar name (1+ slash)) #\.))))
935           (push name results))))
936     (let ((*ignore-wildcards* t))
937       (mapcar (lambda (name)
938                 (let ((name (if (and check-for-subdirs
939                                      (eq (sb!unix:unix-file-kind name)
940                                          :directory))
941                                 (concatenate 'string name "/")
942                                 name)))
943                   (if follow-links (truename name) (pathname name))))
944               (sort (delete-duplicates results :test #'string=) #'string<)))))
945 \f
946 ;;;; translating Unix uid's
947 ;;;;
948 ;;;; FIXME: should probably move into unix.lisp
949
950 (defvar *uid-hash-table* (make-hash-table)
951   #!+sb-doc
952   "hash table for keeping track of uid's and login names")
953
954 (/show0 "filesys.lisp 844")
955
956 ;;; LOOKUP-LOGIN-NAME translates a user id into a login name. Previous
957 ;;; lookups are cached in a hash table since groveling the passwd(s)
958 ;;; files is somewhat expensive. The table may hold NIL for id's that
959 ;;; cannot be looked up since this keeps the files from having to be
960 ;;; searched in their entirety each time this id is translated.
961 (defun lookup-login-name (uid)
962   (multiple-value-bind (login-name foundp) (gethash uid *uid-hash-table*)
963     (if foundp
964         login-name
965         (setf (gethash uid *uid-hash-table*)
966               (get-group-or-user-name :user uid)))))
967
968 ;;; GET-GROUP-OR-USER-NAME first tries "/etc/passwd" ("/etc/group")
969 ;;; since it is a much smaller file, contains all the local id's, and
970 ;;; most uses probably involve id's on machines one would login into.
971 ;;; Then if necessary, we look in "/etc/passwds" ("/etc/groups") which
972 ;;; is really long and has to be fetched over the net.
973 ;;;
974 ;;; FIXME: Now that we no longer have lookup-group-name, we no longer need
975 ;;; the GROUP-OR-USER argument.
976 (defun get-group-or-user-name (group-or-user id)
977   #!+sb-doc
978   "Returns the simple-string user or group name of the user whose uid or gid
979    is id, or NIL if no such user or group exists. Group-or-user is either
980    :group or :user."
981   (let ((id-string (let ((*print-base* 10)) (prin1-to-string id))))
982     (declare (simple-string id-string))
983     (multiple-value-bind (file1 file2)
984         (ecase group-or-user
985           (:group (values "/etc/group" "/etc/groups"))
986           (:user (values "/etc/passwd" "/etc/passwd")))
987       (or (get-group-or-user-name-aux id-string file1)
988           (get-group-or-user-name-aux id-string file2)))))
989
990 ;;; FIXME: Isn't there now a POSIX routine to parse the passwd file?
991 ;;; getpwent? getpwuid?
992 (defun get-group-or-user-name-aux (id-string passwd-file)
993   (with-open-file (stream passwd-file)
994     (loop
995       (let ((entry (read-line stream nil)))
996         (unless entry (return nil))
997         (let ((name-end (position #\: (the simple-string entry)
998                                   :test #'char=)))
999           (when name-end
1000             (let ((id-start (position #\: (the simple-string entry)
1001                                       :start (1+ name-end) :test #'char=)))
1002               (when id-start
1003                 (incf id-start)
1004                 (let ((id-end (position #\: (the simple-string entry)
1005                                         :start id-start :test #'char=)))
1006                   (when (and id-end
1007                              (string= id-string entry
1008                                       :start2 id-start :end2 id-end))
1009                     (return (subseq entry 0 name-end))))))))))))
1010 \f
1011 (/show0 "filesys.lisp 899")
1012
1013 ;;; predicate to order pathnames by; goes by name
1014 (defun pathname-order (x y)
1015   (let ((xn (%pathname-name x))
1016         (yn (%pathname-name y)))
1017     (if (and xn yn)
1018         (let ((res (string-lessp xn yn)))
1019           (cond ((not res) nil)
1020                 ((= res (length (the simple-string xn))) t)
1021                 ((= res (length (the simple-string yn))) nil)
1022                 (t t)))
1023         xn)))
1024 \f
1025 ;;;; DEFAULT-DIRECTORY stuff
1026 ;;;;
1027 ;;;; FIXME: *DEFAULT-DIRECTORY-DEFAULTS* seems to be the ANSI way to
1028 ;;;; deal with this, so we should beef up *DEFAULT-DIRECTORY-DEFAULTS*
1029 ;;;; and make all the old DEFAULT-DIRECTORY stuff go away. (At that
1030 ;;;; time the need for UNIX-CHDIR will go away too, I think.)
1031
1032 (defun default-directory ()
1033   #!+sb-doc
1034   "Returns the pathname for the default directory. This is the place where
1035   a file will be written if no directory is specified. This may be changed
1036   with setf."
1037   (multiple-value-bind (gr dir-or-error) (sb!unix:unix-current-directory)
1038     (if gr
1039         (let ((*ignore-wildcards* t))
1040           (pathname (concatenate 'simple-string dir-or-error "/")))
1041         (error dir-or-error))))
1042
1043 (defun %set-default-directory (new-val)
1044   (let ((namestring (unix-namestring new-val t)))
1045     (unless namestring
1046       (error "~S doesn't exist." new-val))
1047     (multiple-value-bind (gr error) (sb!unix:unix-chdir namestring)
1048       (if gr
1049           (setf (search-list "default:") (default-directory))
1050           (simple-file-perror "couldn't set default directory to ~S"
1051                               new-val
1052                               error)))
1053     new-val))
1054
1055 (/show0 "filesys.lisp 934")
1056
1057 (/show0 "entering what used to be !FILESYS-COLD-INIT")
1058 (defvar *default-pathname-defaults*
1059   (%make-pathname *unix-host* nil nil nil nil :newest))
1060 (setf (search-list "default:") (default-directory))
1061 (/show0 "leaving what used to be !FILESYS-COLD-INIT")
1062 \f
1063 (defun ensure-directories-exist (pathspec &key verbose (mode #o777))
1064   #!+sb-doc
1065   "Test whether the directories containing the specified file
1066   actually exist, and attempt to create them if they do not.
1067   The MODE argument is a CMUCL/SBCL-specific extension to control
1068   the Unix permission bits."
1069   (let* ((pathname (pathname pathspec))
1070          (pathname (if (typep pathname 'logical-pathname)
1071                        (translate-logical-pathname pathname)
1072                        pathname))
1073          (created-p nil))
1074     (when (wild-pathname-p pathname)
1075       (error 'simple-file-error
1076              :format-control "bad place for a wild pathname"
1077              :pathname pathspec))
1078     (enumerate-search-list (pathname pathname)
1079        (let ((dir (pathname-directory pathname)))
1080          (loop for i from 1 upto (length dir)
1081                do (let ((newpath (make-pathname
1082                                   :host (pathname-host pathname)
1083                                   :device (pathname-device pathname)
1084                                   :directory (subseq dir 0 i))))
1085                     (unless (probe-file newpath)
1086                       (let ((namestring (namestring newpath)))
1087                         (when verbose
1088                           (format *standard-output*
1089                                   "~&creating directory: ~A~%"
1090                                   namestring))
1091                         (sb!unix:unix-mkdir namestring mode)
1092                         (unless (probe-file namestring)
1093                           (error 'simple-file-error
1094                                  :pathname pathspec
1095                                  :format-control "can't create directory ~A"
1096                                  :format-arguments (list namestring)))
1097                         (setf created-p t)))))
1098          ;; Only the first path in a search-list is considered.
1099          (return (values pathname created-p))))))
1100
1101 (/show0 "filesys.lisp 1000")