Matt Kraai | a7cecbc | 2001-08-10 15:05:27 +0000 | [diff] [blame] | 1 | /* vi: set sw=4 ts=4: */ |
| 2 | /* |
Manuel Novoa III | cad5364 | 2003-03-19 09:13:01 +0000 | [diff] [blame] | 3 | * bb_simplify_path implementation for busybox |
Matt Kraai | a7cecbc | 2001-08-10 15:05:27 +0000 | [diff] [blame] | 4 | * |
Manuel Novoa III | cad5364 | 2003-03-19 09:13:01 +0000 | [diff] [blame] | 5 | * Copyright (C) 2001 Manuel Novoa III <mjn3@codepoet.org> |
Matt Kraai | a7cecbc | 2001-08-10 15:05:27 +0000 | [diff] [blame] | 6 | * |
"Robert P. J. Day" | 5d8843e | 2006-07-10 11:41:19 +0000 | [diff] [blame^] | 7 | * Licensed under GPLv2 or later, see file LICENSE in this tarball for details. |
Matt Kraai | a7cecbc | 2001-08-10 15:05:27 +0000 | [diff] [blame] | 8 | */ |
| 9 | |
| 10 | #include <stdlib.h> |
Matt Kraai | a7cecbc | 2001-08-10 15:05:27 +0000 | [diff] [blame] | 11 | #include "libbb.h" |
| 12 | |
Manuel Novoa III | cad5364 | 2003-03-19 09:13:01 +0000 | [diff] [blame] | 13 | char *bb_simplify_path(const char *path) |
Matt Kraai | a7cecbc | 2001-08-10 15:05:27 +0000 | [diff] [blame] | 14 | { |
Matt Kraai | 0a68590 | 2001-08-14 17:10:08 +0000 | [diff] [blame] | 15 | char *s, *start, *p; |
Matt Kraai | a7cecbc | 2001-08-10 15:05:27 +0000 | [diff] [blame] | 16 | |
| 17 | if (path[0] == '/') |
Manuel Novoa III | cad5364 | 2003-03-19 09:13:01 +0000 | [diff] [blame] | 18 | start = bb_xstrdup(path); |
Matt Kraai | a7cecbc | 2001-08-10 15:05:27 +0000 | [diff] [blame] | 19 | else { |
Matt Kraai | 0a68590 | 2001-08-14 17:10:08 +0000 | [diff] [blame] | 20 | s = xgetcwd(NULL); |
| 21 | start = concat_path_file(s, path); |
| 22 | free(s); |
Matt Kraai | a7cecbc | 2001-08-10 15:05:27 +0000 | [diff] [blame] | 23 | } |
Matt Kraai | 0a68590 | 2001-08-14 17:10:08 +0000 | [diff] [blame] | 24 | p = s = start; |
Matt Kraai | a7cecbc | 2001-08-10 15:05:27 +0000 | [diff] [blame] | 25 | |
Matt Kraai | 0a68590 | 2001-08-14 17:10:08 +0000 | [diff] [blame] | 26 | 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 Kraai | a7cecbc | 2001-08-10 15:05:27 +0000 | [diff] [blame] | 40 | } |
| 41 | } |
Matt Kraai | 0a68590 | 2001-08-14 17:10:08 +0000 | [diff] [blame] | 42 | *++p = *s; |
| 43 | } while (*++s); |
| 44 | |
| 45 | if ((p == start) || (*p != '/')) { /* not a trailing slash */ |
| 46 | ++p; /* so keep last character */ |
Matt Kraai | a7cecbc | 2001-08-10 15:05:27 +0000 | [diff] [blame] | 47 | } |
Matt Kraai | 0a68590 | 2001-08-14 17:10:08 +0000 | [diff] [blame] | 48 | *p = 0; |
| 49 | |
Matt Kraai | a7cecbc | 2001-08-10 15:05:27 +0000 | [diff] [blame] | 50 | return start; |
| 51 | } |