blob: 171798e6048cccf517dfc001171a5e30a063b7be [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
10#include <stdlib.h>
Matt Kraaia7cecbc2001-08-10 15:05:27 +000011#include "libbb.h"
12
Manuel Novoa III cad53642003-03-19 09:13:01 +000013char *bb_simplify_path(const char *path)
Matt Kraaia7cecbc2001-08-10 15:05:27 +000014{
Matt Kraai0a685902001-08-14 17:10:08 +000015 char *s, *start, *p;
Matt Kraaia7cecbc2001-08-10 15:05:27 +000016
17 if (path[0] == '/')
Manuel Novoa III cad53642003-03-19 09:13:01 +000018 start = bb_xstrdup(path);
Matt Kraaia7cecbc2001-08-10 15:05:27 +000019 else {
Matt Kraai0a685902001-08-14 17:10:08 +000020 s = xgetcwd(NULL);
21 start = concat_path_file(s, path);
22 free(s);
Matt Kraaia7cecbc2001-08-10 15:05:27 +000023 }
Matt Kraai0a685902001-08-14 17:10:08 +000024 p = s = start;
Matt Kraaia7cecbc2001-08-10 15:05:27 +000025
Matt Kraai0a685902001-08-14 17:10:08 +000026 do {
27 if (*p == '/') {
28 if (*s == '/') { /* skip duplicate (or initial) slash */
29 continue;
30 } else if (*s == '.') {
31 if (s[1] == '/' || s[1] == 0) { /* remove extra '.' */
32 continue;
33 } else if ((s[1] == '.') && (s[2] == '/' || s[2] == 0)) {
34 ++s;
35 if (p > start) {
36 while (*--p != '/'); /* omit previous dir */
37 }
38 continue;
39 }
Matt Kraaia7cecbc2001-08-10 15:05:27 +000040 }
41 }
Matt Kraai0a685902001-08-14 17:10:08 +000042 *++p = *s;
43 } while (*++s);
44
45 if ((p == start) || (*p != '/')) { /* not a trailing slash */
46 ++p; /* so keep last character */
Matt Kraaia7cecbc2001-08-10 15:05:27 +000047 }
Matt Kraai0a685902001-08-14 17:10:08 +000048 *p = 0;
49
Matt Kraaia7cecbc2001-08-10 15:05:27 +000050 return start;
51}