2 * realpath.c -- canonicalize pathname by removing symlinks
3 * Copyright (C) 1993 Rick Sladkey <jrs@world.std.com>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Library Public License as published by
7 * the Free Software Foundation; either version 2, or (at your option)
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Library Public License for more details.
22 #define MAX_READLINKS 32
25 char *realpath(const char *path, char resolved_path [])
27 char *realpath(path, resolved_path)
29 char resolved_path [];
32 char copy_path[PATH_MAX];
33 char link_path[PATH_MAX];
34 char *new_path = resolved_path;
39 /* Make a copy of the source path since we may need to modify it. */
40 strcpy(copy_path, path);
42 max_path = copy_path + PATH_MAX - 2;
43 /* If it's a relative pathname use getwd for starters. */
46 getcwd(new_path, PATH_MAX - 1);
50 new_path += strlen(new_path);
51 if (new_path[-1] != '/')
58 /* Expand each slash-separated pathname component. */
59 while (*path != '\0') {
60 /* Ignore stray "/". */
67 if (path[1] == '\0' || path[1] == '/') {
72 if (path[2] == '\0' || path[2] == '/') {
74 /* Ignore ".." at root. */
75 if (new_path == resolved_path + 1)
77 /* Handle ".." by backing up. */
78 while ((--new_path)[-1] != '/');
83 /* Safely copy the next pathname component. */
84 while (*path != '\0' && *path != '/') {
85 if (path > max_path) {
89 *new_path++ = *path++;
92 /* Protect against infinite loops. */
93 if (readlinks++ > MAX_READLINKS) {
97 /* See if latest pathname component is a symlink. */
99 n = readlink(resolved_path, link_path, PATH_MAX - 1);
101 /* EINVAL means the file exists but isn't a symlink. */
106 /* Note: readlink doesn't add the null byte. */
108 if (*link_path == '/')
109 /* Start over for an absolute symlink. */
110 new_path = resolved_path;
112 /* Otherwise back up over this component. */
113 while (*(--new_path) != '/');
114 /* Safe sex check. */
115 if (strlen(path) + n >= PATH_MAX) {
116 errno = ENAMETOOLONG;
119 /* Insert symlink contents into path. */
120 strcat(link_path, path);
121 strcpy(copy_path, link_path);
127 /* Delete trailing slash but don't whomp a lone slash. */
128 if (new_path != resolved_path + 1 && new_path[-1] == '/')
130 /* Make sure it's null terminated. */
132 return resolved_path;