blob: 89dc5bdf21c2c3e19295327ec03605456ab3a3fd [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 *
Denys Vlasenko0ef64bd2010-08-16 20:14:46 +02007 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
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 == '/') {
Denys Vlasenkofb132e42010-10-29 11:46:52 +020018 if (*s == '/') { /* skip duplicate (or initial) slash */
Matt Kraai0a685902001-08-14 17:10:08 +000019 continue;
Denis Vlasenko16abcd92007-04-13 23:59:52 +000020 }
21 if (*s == '.') {
Denys Vlasenkofb132e42010-10-29 11:46:52 +020022 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) {
Denys Vlasenkofb132e42010-10-29 11:46:52 +020028 while (*--p != '/') /* omit previous dir */
Denis Vlasenko16abcd92007-04-13 23:59:52 +000029 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
Denys Vlasenkofb132e42010-10-29 11:46:52 +020038 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}