Rewritten by Manuel Novoa III.
[oweals/busybox.git] / libbb / simplify_path.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * simplify_path implementation for busybox
4  *
5  *
6  * Copyright (C) 2001  Manuel Novoa III  <mjn3@opensource.lineo.com>
7  *
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  * General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22  *
23  */
24
25 #include <stdlib.h>
26
27 #include "libbb.h"
28
29 char *simplify_path(const char *path)
30 {
31         char *s, *start, *p;
32
33         if (path[0] == '/')
34                 start = xstrdup(path);
35         else {
36                 s = xgetcwd(NULL);
37                 start = concat_path_file(s, path);
38                 free(s);
39         }
40         p = s = start;
41
42         do {
43                 if (*p == '/') {
44                         if (*s == '/') {        /* skip duplicate (or initial) slash */
45                                 continue;
46                         } else if (*s == '.') {
47                                 if (s[1] == '/' || s[1] == 0) { /* remove extra '.' */
48                                         continue;
49                                 } else if ((s[1] == '.') && (s[2] == '/' || s[2] == 0)) {
50                                         ++s;
51                                         if (p > start) {
52                                                 while (*--p != '/');    /* omit previous dir */
53                                         }
54                                         continue;
55                                 }
56                         }
57                 }
58                 *++p = *s;
59         } while (*++s);
60
61         if ((p == start) || (*p != '/')) {      /* not a trailing slash */
62                 ++p;                                    /* so keep last character */
63         }
64         *p = 0;
65
66         return start;
67 }