blob: 29e371df60975f13a68bd97a35609d47ec59b2ab [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 */
9
Matt Kraaia7cecbc2001-08-10 15:05:27 +000010#include "libbb.h"
11
Manuel Novoa III cad53642003-03-19 09:13:01 +000012char *bb_simplify_path(const char *path)
Matt Kraaia7cecbc2001-08-10 15:05:27 +000013{
Matt Kraai0a685902001-08-14 17:10:08 +000014 char *s, *start, *p;
Matt Kraaia7cecbc2001-08-10 15:05:27 +000015
16 if (path[0] == '/')
Rob Landleyd921b2e2006-08-03 15:41:12 +000017 start = xstrdup(path);
Matt Kraaia7cecbc2001-08-10 15:05:27 +000018 else {
Denis Vlasenko6ca04442007-02-11 16:19:28 +000019 s = xrealloc_getcwd_or_warn(NULL);
Matt Kraai0a685902001-08-14 17:10:08 +000020 start = concat_path_file(s, path);
21 free(s);
Matt Kraaia7cecbc2001-08-10 15:05:27 +000022 }
Matt Kraai0a685902001-08-14 17:10:08 +000023 p = s = start;
Matt Kraaia7cecbc2001-08-10 15:05:27 +000024
Matt Kraai0a685902001-08-14 17:10:08 +000025 do {
26 if (*p == '/') {
27 if (*s == '/') { /* skip duplicate (or initial) slash */
28 continue;
Denis Vlasenko16abcd92007-04-13 23:59:52 +000029 }
30 if (*s == '.') {
31 if (s[1] == '/' || !s[1]) { /* remove extra '.' */
Matt Kraai0a685902001-08-14 17:10:08 +000032 continue;
Denis Vlasenko16abcd92007-04-13 23:59:52 +000033 }
34 if ((s[1] == '.') && (s[2] == '/' || !s[2])) {
Matt Kraai0a685902001-08-14 17:10:08 +000035 ++s;
36 if (p > start) {
Denis Vlasenko16abcd92007-04-13 23:59:52 +000037 while (*--p != '/') /* omit previous dir */
38 continue;
Matt Kraai0a685902001-08-14 17:10:08 +000039 }
40 continue;
41 }
Matt Kraaia7cecbc2001-08-10 15:05:27 +000042 }
43 }
Matt Kraai0a685902001-08-14 17:10:08 +000044 *++p = *s;
45 } while (*++s);
46
47 if ((p == start) || (*p != '/')) { /* not a trailing slash */
48 ++p; /* so keep last character */
Matt Kraaia7cecbc2001-08-10 15:05:27 +000049 }
Matt Kraai0a685902001-08-14 17:10:08 +000050 *p = 0;
51
Matt Kraaia7cecbc2001-08-10 15:05:27 +000052 return start;
53}