3 /* We allow "recursive" symbolic links. Only within reason, though. */
6 const char *make_absolute_path(const char *path
)
8 static char bufs
[2][PATH_MAX
+ 1], *buf
= bufs
[0], *next_buf
= bufs
[1];
10 int buf_index
= 1, len
;
13 char *last_elem
= NULL
;
16 if (strlcpy(buf
, path
, PATH_MAX
) >= PATH_MAX
)
17 die ("Too long path: %.*s", 60, path
);
20 if (stat(buf
, &st
) || !S_ISDIR(st
.st_mode
)) {
21 char *last_slash
= strrchr(buf
, '/');
24 last_elem
= xstrdup(last_slash
+ 1);
26 last_elem
= xstrdup(buf
);
32 if (!*cwd
&& !getcwd(cwd
, sizeof(cwd
)))
33 die ("Could not get current working directory");
36 die ("Could not switch to '%s'", buf
);
38 if (!getcwd(buf
, PATH_MAX
))
39 die ("Could not get current working directory");
42 int len
= strlen(buf
);
43 if (len
+ strlen(last_elem
) + 2 > PATH_MAX
)
44 die ("Too long path name: '%s/%s'",
47 strcpy(buf
+ len
+ 1, last_elem
);
52 if (!lstat(buf
, &st
) && S_ISLNK(st
.st_mode
)) {
53 len
= readlink(buf
, next_buf
, PATH_MAX
);
55 die ("Invalid symlink: %s", buf
);
58 buf_index
= 1 - buf_index
;
59 next_buf
= bufs
[buf_index
];
64 if (*cwd
&& chdir(cwd
))
65 die ("Could not change back to '%s'", cwd
);
70 static const char *get_pwd_cwd(void)
72 static char cwd
[PATH_MAX
+ 1];
74 struct stat cwd_stat
, pwd_stat
;
75 if (getcwd(cwd
, PATH_MAX
) == NULL
)
78 if (pwd
&& strcmp(pwd
, cwd
)) {
80 if (!stat(pwd
, &pwd_stat
) &&
81 pwd_stat
.st_dev
== cwd_stat
.st_dev
&&
82 pwd_stat
.st_ino
== cwd_stat
.st_ino
) {
83 strlcpy(cwd
, pwd
, PATH_MAX
);
89 const char *make_nonrelative_path(const char *path
)
91 static char buf
[PATH_MAX
+ 1];
93 if (is_absolute_path(path
)) {
94 if (strlcpy(buf
, path
, PATH_MAX
) >= PATH_MAX
)
95 die("Too long path: %.*s", 60, path
);
97 const char *cwd
= get_pwd_cwd();
99 die("Cannot determine the current working directory");
100 if (snprintf(buf
, PATH_MAX
, "%s/%s", cwd
, path
) >= PATH_MAX
)
101 die("Too long path: %.*s", 60, path
);