blob: f80e3e8a5eef53ddeba2cd365bbd39506cfea8f9 [file] [log] [blame]
Matt Kraaia7cecbc2001-08-10 15:05:27 +00001/* vi: set sw=4 ts=4: */
2/*
Manuel Novoa III cad53642003-03-19 09:13:01 +00003 * bb_simplify_path implementation for busybox
Matt Kraaia7cecbc2001-08-10 15:05:27 +00004 *
Manuel Novoa III cad53642003-03-19 09:13:01 +00005 * Copyright (C) 2001 Manuel Novoa III <mjn3@codepoet.org>
Matt Kraaia7cecbc2001-08-10 15:05:27 +00006 *
"Robert P. J. Day"5d8843e2006-07-10 11:41:19 +00007 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
Matt Kraaia7cecbc2001-08-10 15:05:27 +00008 */
Matt Kraaia7cecbc2001-08-10 15:05:27 +00009#include "libbb.h"
10
Denis Vlasenko1cf4a0e2009-04-22 13:49:16 +000011char* FAST_FUNC bb_simplify_abs_path_inplace(char *start)
Matt Kraaia7cecbc2001-08-10 15:05:27 +000012{
Denis Vlasenko1cf4a0e2009-04-22 13:49:16 +000013 char *s, *p;
Matt Kraaia7cecbc2001-08-10 15:05:27 +000014
Matt Kraai0a685902001-08-14 17:10:08 +000015 p = s = start;
Matt Kraai0a685902001-08-14 17:10:08 +000016 do {
17 if (*p == '/') {
18 if (*s == '/') { /* skip duplicate (or initial) slash */
19 continue;
Denis Vlasenko16abcd92007-04-13 23:59:52 +000020 }
21 if (*s == '.') {
22 if (s[1] == '/' || !s[1]) { /* remove extra '.' */
Matt Kraai0a685902001-08-14 17:10:08 +000023 continue;
Denis Vlasenko16abcd92007-04-13 23:59:52 +000024 }
25 if ((s[1] == '.') && (s[2] == '/' || !s[2])) {
Matt Kraai0a685902001-08-14 17:10:08 +000026 ++s;
27 if (p > start) {
Denis Vlasenko16abcd92007-04-13 23:59:52 +000028 while (*--p != '/') /* omit previous dir */
29 continue;
Matt Kraai0a685902001-08-14 17:10:08 +000030 }
31 continue;
32 }
Matt Kraaia7cecbc2001-08-10 15:05:27 +000033 }
34 }
Matt Kraai0a685902001-08-14 17:10:08 +000035 *++p = *s;
36 } while (*++s);
37
38 if ((p == start) || (*p != '/')) { /* not a trailing slash */
39 ++p; /* so keep last character */
Matt Kraaia7cecbc2001-08-10 15:05:27 +000040 }
Denis Vlasenko1cf4a0e2009-04-22 13:49:16 +000041 *p = '\0';
42 return p;
43}
Matt Kraai0a685902001-08-14 17:10:08 +000044
Denis Vlasenko1cf4a0e2009-04-22 13:49:16 +000045char* FAST_FUNC bb_simplify_path(const char *path)
46{
47 char *s, *p;
48
49 if (path[0] == '/')
50 s = xstrdup(path);
51 else {
52 p = xrealloc_getcwd_or_warn(NULL);
53 s = concat_path_file(p, path);
54 free(p);
55 }
56
57 bb_simplify_abs_path_inplace(s);
58 return s;
Matt Kraaia7cecbc2001-08-10 15:05:27 +000059}