blob: b714c66b6c586e96636c9b352d6df7e0efffd150 [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 {
Matt Kraai0a685902001-08-14 17:10:08 +000019 s = xgetcwd(NULL);
20 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;
29 } else if (*s == '.') {
30 if (s[1] == '/' || s[1] == 0) { /* remove extra '.' */
31 continue;
32 } else if ((s[1] == '.') && (s[2] == '/' || s[2] == 0)) {
33 ++s;
34 if (p > start) {
35 while (*--p != '/'); /* omit previous dir */
36 }
37 continue;
38 }
Matt Kraaia7cecbc2001-08-10 15:05:27 +000039 }
40 }
Matt Kraai0a685902001-08-14 17:10:08 +000041 *++p = *s;
42 } while (*++s);
43
44 if ((p == start) || (*p != '/')) { /* not a trailing slash */
45 ++p; /* so keep last character */
Matt Kraaia7cecbc2001-08-10 15:05:27 +000046 }
Matt Kraai0a685902001-08-14 17:10:08 +000047 *p = 0;
48
Matt Kraaia7cecbc2001-08-10 15:05:27 +000049 return start;
50}