vfs: check userland buffers before reading them.
[haiku.git] / src / tools / fs_shell / path_util.cpp
blobac4fd6a559bb24991aa8c551d63d17e13dc38272
1 /*
2 * Copyright 2005-2007, Ingo Weinhold, bonefish@cs.tu-berlin.de.
3 * Distributed under the terms of the MIT License.
4 */
6 #include "path_util.h"
8 #include <stdlib.h>
9 #include <string.h>
11 #include "fssh_errors.h"
14 namespace FSShell {
17 fssh_status_t
18 get_last_path_component(const char *path, char *buffer, int bufferLen)
20 int len = strlen(path);
21 if (len == 0)
22 return FSSH_B_BAD_VALUE;
24 // eat trailing '/'
25 while (len > 0 && path[len - 1] == '/')
26 len--;
28 if (len == 0) {
29 // path is `/'
30 len = 1;
31 } else {
32 // find previous '/'
33 int pos = len - 1;
34 while (pos > 0 && path[pos] != '/')
35 pos--;
36 if (path[pos] == '/')
37 pos++;
39 path += pos;
40 len -= pos;
43 if (len >= bufferLen)
44 return FSSH_B_NAME_TOO_LONG;
46 memcpy(buffer, path, len);
47 buffer[len] = '\0';
48 return FSSH_B_OK;
51 char *
52 make_path(const char *dir, const char *entry)
54 // get the len
55 int dirLen = strlen(dir);
56 int entryLen = strlen(entry);
57 bool insertSeparator = (dir[dirLen - 1] != '/');
58 int pathLen = dirLen + entryLen + (insertSeparator ? 1 : 0) + 1;
60 // allocate the path
61 char *path = (char*)malloc(pathLen);
62 if (!path)
63 return NULL;
65 // compose the path
66 strcpy(path, dir);
67 if (insertSeparator)
68 strcat(path + dirLen, "/");
69 strcat(path + dirLen, entry);
71 return path;
75 } // namespace FSShell