Tuesday, December 28, 2004

Infinitly Recursive Directories

Raymond Chen explains how you can create infinitly recursive directory trees on Windows NT.

You can do the same thing on a UNIX machine in the following manner:

ln -s foo foo
Innocent programs can get into infinite loops if they encounter infinitly recursive directory trees like this.

SOLARIS defines a constant called MAXSYMLINKS in sys/param.h and the kernel routines that chase down symbolic links, compare the number of symbolic links in the path against this constant and raise an error if the number of symbolic links in the path exceeds this constant.

From /usr/include/sys/param.h:

154 * MAXPATHLEN defines the longest permissible path length,
155 * including the terminating null, after expanding symbolic links.
156 * MAXSYMLINKS defines the maximum number of symbolic links
157 * that may be expanded in a path name. It should be set high
158 * enough to allow all legitimate uses, but halt infinite loops
159 * reasonably quickly.
160 * MAXNAMELEN is the length (including the terminating null) of
161 * the longest permissible file (component) name.
162 */
163 #define MAXPATHLEN 1024
164 #define MAXSYMLINKS 20

Not performing this check, or a high value for MAXSYMLINKS can cause a stack overflow in the kernel routines that process contents of a directory recursively.

I'm not sure if MAXSYMLINKS, or a similar constant is part of the POSIX specification though. If it is, we do not need to worry about infinitly recursive directories, even when we write portable UNIX programs.

No comments: