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.
24
#define PATH_MAX _POSIX_PATH_MAX
27
#define PATH_MAX MAXPATHLEN
34
#define MAX_READLINKS 32
37
char *realpath(const char *path, char resolved_path [])
39
char *realpath(path, resolved_path)
41
char resolved_path [];
44
char copy_path[PATH_MAX];
45
char link_path[PATH_MAX];
46
char *new_path = resolved_path;
51
/* Make a copy of the source path since we may need to modify it. */
52
strcpy(copy_path, path);
54
max_path = copy_path + PATH_MAX - 2;
55
/* If it's a relative pathname use getwd for starters. */
58
getcwd(new_path, PATH_MAX - 1);
62
new_path += strlen(new_path);
63
if (new_path[-1] != '/')
70
/* Expand each slash-separated pathname component. */
71
while (*path != '\0') {
72
/* Ignore stray "/". */
79
if (path[1] == '\0' || path[1] == '/') {
84
if (path[2] == '\0' || path[2] == '/') {
86
/* Ignore ".." at root. */
87
if (new_path == resolved_path + 1)
89
/* Handle ".." by backing up. */
90
while ((--new_path)[-1] != '/')
96
/* Safely copy the next pathname component. */
97
while (*path != '\0' && *path != '/') {
98
if (path > max_path) {
102
*new_path++ = *path++;
105
/* Protect against infinite loops. */
106
if (readlinks++ > MAX_READLINKS) {
110
/* See if latest pathname component is a symlink. */
112
n = readlink(resolved_path, link_path, PATH_MAX - 1);
114
/* EINVAL means the file exists but isn't a symlink. */
119
/* Note: readlink doesn't add the null byte. */
121
if (*link_path == '/')
122
/* Start over for an absolute symlink. */
123
new_path = resolved_path;
125
/* Otherwise back up over this component. */
126
while (*(--new_path) != '/')
128
/* Safe sex check. */
129
if (strlen(path) + n >= PATH_MAX) {
130
errno = ENAMETOOLONG;
133
/* Insert symlink contents into path. */
134
strcat(link_path, path);
135
strcpy(copy_path, link_path);
141
/* Delete trailing slash but don't whomp a lone slash. */
142
if (new_path != resolved_path + 1 && new_path[-1] == '/')
144
/* Make sure it's null terminated. */
146
return resolved_path;