]>
git.ipfire.org Git - thirdparty/util-linux.git/blob - lib/canonicalize.c
2 * canonicalize.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.
18 * This routine is part of libc. We include it nevertheless,
19 * since the libc version has some security flaws.
21 * TODO: use canonicalize_file_name() when exist in glibc
28 #include "canonicalize.h"
31 # define MAXSYMLINKS 256
35 myrealpath(const char *path
, char *resolved_path
, int maxreslth
) {
38 char link_path
[PATH_MAX
+1];
42 npath
= resolved_path
;
44 /* If it's a relative pathname use getcwd for starters. */
46 if (!getcwd(npath
, maxreslth
-2))
48 npath
+= strlen(npath
);
56 /* Expand each slash-separated pathname component. */
57 while (*path
!= '\0') {
58 /* Ignore stray "/" */
63 if (*path
== '.' && (path
[1] == '\0' || path
[1] == '/')) {
68 if (*path
== '.' && path
[1] == '.' &&
69 (path
[2] == '\0' || path
[2] == '/')) {
72 while (npath
> resolved_path
+1 &&
77 /* Safely copy the next pathname component. */
78 while (*path
!= '\0' && *path
!= '/') {
79 if (npath
-resolved_path
> maxreslth
-2) {
86 /* Protect against infinite loops. */
87 if (readlinks
++ > MAXSYMLINKS
) {
92 /* See if last pathname component is a symlink. */
94 n
= readlink(resolved_path
, link_path
, PATH_MAX
);
96 /* EINVAL means the file exists but isn't a symlink. */
103 /* Note: readlink doesn't add the null byte. */
105 if (*link_path
== '/')
106 /* Start over for an absolute symlink. */
107 npath
= resolved_path
;
109 /* Otherwise back up over this component. */
110 while (*(--npath
) != '/')
113 /* Insert symlink contents into path. */
115 newbuf
= malloc(m
+ n
+ 1);
118 memcpy(newbuf
, link_path
, n
);
119 memcpy(newbuf
+ n
, path
, m
+ 1);
125 /* Delete trailing slash but don't whomp a lone slash. */
126 if (npath
!= resolved_path
+1 && npath
[-1] == '/')
128 /* Make sure it's null terminated. */
132 return resolved_path
;
140 canonicalize_path(const char *path
) {
141 char canonical
[PATH_MAX
+2];
146 if (myrealpath (path
, canonical
, PATH_MAX
+1))
147 return strdup(canonical
);