gaigepr
gaigepr

Reputation: 965

Common Lisp determine is a directory is a subdir or another directory

I am using hunchentoot to build a simple web app to expose a directory tree to the web. The problem I am having is finding a reliable and safe way to determine if the directory requested is actually a child directory of the *share-root* which is /srv/share.

I have spent time the cl-fad but it is not exactly what I need (or I am not using it in such a way as to solve my problem).

My goal is to be able to receive a path like: /srv/share/media/../../../ and realize the request should be ignored because it is asking for something outside of the share.

Upvotes: 3

Views: 210

Answers (1)

sds
sds

Reputation: 60004

I suggest enough-namestring combined with truename: if

(enough-namestring foo bar)

is a relative pathname, then foo is under bar. In other words:

(defun pathname-under-p (under top)
  (case (car (pathname-directory (enough-namestring (truename under)
                                                    (truename top))))
    ((nil :relative) t)
    (t nil)))

or just

(defun pathname-under-p (under top)
  (not (eq :absolute (car (pathname-directory (enough-namestring (truename under)
                                                                 (truename top)))))))

If your implementation does not support truename on a directory, you will have to use an implementation-specific function or directory.

Many thanks to @Svante for debugging.

Upvotes: 3

Related Questions