Blob


1 /*
2 * Copyright (c) 2018, 2019 Stefan Sperling <stsp@openbsd.org>
3 * Copyright (c) 2015 Theo de Raadt <deraadt@openbsd.org>
4 * Copyright (c) 1997 Todd C. Miller <millert@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/stat.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <limits.h>
25 #include <libgen.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <dirent.h>
31 #include <paths.h>
33 #include "got_error.h"
34 #include "got_path.h"
36 #ifndef MIN
37 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
38 #endif
40 int
41 got_path_is_absolute(const char *path)
42 {
43 return path[0] == '/';
44 }
46 /* based on canonpath() from kern_pledge.c */
47 const struct got_error *
48 got_canonpath(const char *input, char *buf, size_t bufsize)
49 {
50 const char *p;
51 char *q;
53 /* can't canon relative paths, don't bother */
54 if (!got_path_is_absolute(input)) {
55 if (strlcpy(buf, input, bufsize) >= bufsize)
56 return got_error(GOT_ERR_NO_SPACE);
57 return NULL;
58 }
60 p = input;
61 q = buf;
62 while (*p && (q - buf < bufsize)) {
63 if (p[0] == '/' && (p[1] == '/' || p[1] == '\0')) {
64 p += 1;
66 } else if (p[0] == '/' && p[1] == '.' &&
67 (p[2] == '/' || p[2] == '\0')) {
68 p += 2;
70 } else if (p[0] == '/' && p[1] == '.' && p[2] == '.' &&
71 (p[3] == '/' || p[3] == '\0')) {
72 p += 3;
73 if (q != buf) /* "/../" at start of buf */
74 while (*--q != '/')
75 continue;
77 } else {
78 *q++ = *p++;
79 }
80 }
81 if ((*p == '\0') && (q - buf < bufsize)) {
82 *q = 0;
83 return NULL;
84 } else
85 return got_error(GOT_ERR_NO_SPACE);
86 }
88 const struct got_error *
89 got_path_skip_common_ancestor(char **child, const char *parent_abspath,
90 const char *abspath)
91 {
92 const struct got_error *err = NULL;
93 size_t len_parent, len, bufsize;
95 *child = NULL;
97 len_parent = strlen(parent_abspath);
98 len = strlen(abspath);
99 if (len_parent >= len)
100 return got_error_path(abspath, GOT_ERR_BAD_PATH);
101 if (strncmp(parent_abspath, abspath, len_parent) != 0)
102 return got_error_path(abspath, GOT_ERR_BAD_PATH);
103 if (!got_path_is_root_dir(parent_abspath) && abspath[len_parent] != '/')
104 return got_error_path(abspath, GOT_ERR_BAD_PATH);
105 while (abspath[len_parent] == '/')
106 abspath++;
107 bufsize = len - len_parent + 1;
108 *child = malloc(bufsize);
109 if (*child == NULL)
110 return got_error_from_errno("malloc");
111 if (strlcpy(*child, abspath + len_parent, bufsize) >= bufsize) {
112 err = got_error_from_errno("strlcpy");
113 free(*child);
114 *child = NULL;
115 return err;
117 return NULL;
120 const struct got_error *
121 got_path_strip(char **out, const char *path, int n)
123 const char *p, *c;
125 p = path;
126 *out = NULL;
128 while (n > 0 && (c = strchr(p, '/')) != NULL) {
129 p = c + 1;
130 n--;
133 if (n > 0)
134 return got_error_fmt(GOT_ERR_BAD_PATH,
135 "can't strip %d path-components from %s", n, path);
137 if ((*out = strdup(p)) == NULL)
138 return got_error_from_errno("strdup");
139 return NULL;
142 int
143 got_path_is_root_dir(const char *path)
145 while (*path == '/')
146 path++;
147 return (*path == '\0');
150 int
151 got_path_is_current_dir(const char *path)
153 return (path[0] == '.' && path[1] == '\0');
156 int
157 got_path_is_child(const char *child, const char *parent, size_t parent_len)
159 if (parent_len == 0 || got_path_is_root_dir(parent))
160 return 1;
162 if (strncmp(parent, child, parent_len) != 0)
163 return 0;
164 if (child[parent_len] != '/')
165 return 0;
167 return 1;
170 int
171 got_path_cmp(const char *path1, const char *path2, size_t len1, size_t len2)
173 size_t min_len;
174 size_t i = 0;
176 /* Leading directory separators are insignificant. */
177 while (path1[0] == '/') {
178 path1++;
179 len1--;
181 while (path2[0] == '/') {
182 path2++;
183 len2--;
186 min_len = MIN(len1, len2);
188 /* Skip over common prefix. */
189 while (i < min_len && path1[i] == path2[i])
190 i++;
192 /* Are the paths exactly equal (besides path separators)? */
193 if (len1 == len2 && i >= min_len)
194 return 0;
196 /* Skip over redundant trailing path seperators. */
197 while (path1[i] == '/' && path1[i + 1] == '/')
198 path1++;
199 while (path2[i] == '/' && path2[i + 1] == '/')
200 path2++;
202 /* Trailing path separators are insignificant. */
203 if (path1[i] == '/' && path1[i + 1] == '\0' && path2[i] == '\0')
204 return 0;
205 if (path2[i] == '/' && path2[i + 1] == '\0' && path1[i] == '\0')
206 return 0;
208 /* Order children in subdirectories directly after their parents. */
209 if (path1[i] == '/' && path2[i] == '\0')
210 return 1;
211 if (path2[i] == '/' && path1[i] == '\0')
212 return -1;
213 if (path1[i] == '/' && path2[i] != '\0')
214 return -1;
215 if (path2[i] == '/' && path1[i] != '\0')
216 return 1;
218 /* Next character following the common prefix determines order. */
219 return (unsigned char)path1[i] < (unsigned char)path2[i] ? -1 : 1;
222 const struct got_error *
223 got_pathlist_insert(struct got_pathlist_entry **inserted,
224 struct got_pathlist_head *pathlist, const char *path, void *data)
226 struct got_pathlist_entry *new, *pe;
227 size_t path_len = strlen(path);
229 if (inserted)
230 *inserted = NULL;
232 /*
233 * Many callers will provide paths in a somewhat sorted order while
234 * constructing a path list from inputs such as tree objects or
235 * dirents. Iterating backwards from the tail of the list should
236 * be more efficient than traversing through the entire list each
237 * time an element is inserted.
238 */
239 pe = TAILQ_LAST(pathlist, got_pathlist_head);
240 while (pe) {
241 int cmp = got_path_cmp(pe->path, path, pe->path_len, path_len);
242 if (cmp == 0)
243 return NULL; /* duplicate */
244 else if (cmp < 0)
245 break;
246 pe = TAILQ_PREV(pe, got_pathlist_head, entry);
249 new = malloc(sizeof(*new));
250 if (new == NULL)
251 return got_error_from_errno("malloc");
252 new->path = path;
253 new->path_len = path_len;
254 new->data = data;
255 if (pe)
256 TAILQ_INSERT_AFTER(pathlist, pe, new, entry);
257 else
258 TAILQ_INSERT_HEAD(pathlist, new, entry);
259 if (inserted)
260 *inserted = new;
261 return NULL;
264 const struct got_error *
265 got_pathlist_append(struct got_pathlist_head *pathlist,
266 const char *path, void *data)
268 struct got_pathlist_entry *new;
270 new = malloc(sizeof(*new));
271 if (new == NULL)
272 return got_error_from_errno("malloc");
273 new->path = path;
274 new->path_len = strlen(path);
275 new->data = data;
276 TAILQ_INSERT_TAIL(pathlist, new, entry);
277 return NULL;
280 void
281 got_pathlist_free(struct got_pathlist_head *pathlist)
283 struct got_pathlist_entry *pe;
285 while ((pe = TAILQ_FIRST(pathlist)) != NULL) {
286 TAILQ_REMOVE(pathlist, pe, entry);
287 free(pe);
291 static const struct got_error *
292 make_parent_dirs(const char *abspath)
294 const struct got_error *err = NULL;
295 char *parent;
297 err = got_path_dirname(&parent, abspath);
298 if (err)
299 return err;
301 if (mkdir(parent, GOT_DEFAULT_DIR_MODE) == -1) {
302 if (errno == ENOENT) {
303 err = make_parent_dirs(parent);
304 if (err)
305 goto done;
306 if (mkdir(parent, GOT_DEFAULT_DIR_MODE) == -1) {
307 err = got_error_from_errno2("mkdir", parent);
308 goto done;
310 } else
311 err = got_error_from_errno2("mkdir", parent);
313 done:
314 free(parent);
315 return err;
318 const struct got_error *
319 got_path_mkdir(const char *abspath)
321 const struct got_error *err = NULL;
323 if (mkdir(abspath, GOT_DEFAULT_DIR_MODE) == -1) {
324 if (errno == ENOENT) {
325 err = make_parent_dirs(abspath);
326 if (err)
327 goto done;
328 if (mkdir(abspath, GOT_DEFAULT_DIR_MODE) == -1)
329 err = got_error_from_errno2("mkdir", abspath);
330 } else
331 err = got_error_from_errno2("mkdir", abspath);
334 done:
335 return err;
338 int
339 got_path_dir_is_empty(const char *dir)
341 DIR *d;
342 struct dirent *dent;
343 int empty = 1;
345 d = opendir(dir);
346 if (d == NULL)
347 return 1;
349 while ((dent = readdir(d)) != NULL) {
350 if (strcmp(dent->d_name, ".") == 0 ||
351 strcmp(dent->d_name, "..") == 0)
352 continue;
354 empty = 0;
355 break;
358 closedir(d);
359 return empty;
362 const struct got_error *
363 got_path_dirname(char **parent, const char *path)
365 char buf[PATH_MAX];
366 char *p;
368 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf))
369 return got_error(GOT_ERR_NO_SPACE);
371 p = dirname(buf);
372 if (p == NULL)
373 return got_error_from_errno2("dirname", path);
375 if (p[0] == '.' && p[1] == '\0')
376 return got_error_path(path, GOT_ERR_BAD_PATH);
378 *parent = strdup(p);
379 if (*parent == NULL)
380 return got_error_from_errno("strdup");
382 return NULL;
385 const struct got_error *
386 got_path_dirent_type(int *type, const char *path_parent, struct dirent *dent)
388 const struct got_error *err = NULL;
389 char *path_child;
390 struct stat sb;
392 if (dent->d_type != DT_UNKNOWN) {
393 *type = dent->d_type;
394 return NULL;
397 *type = DT_UNKNOWN;
399 /*
400 * This is a fallback to accommodate filesystems which do not
401 * provide directory entry type information. DT_UNKNOWN directory
402 * entries occur on NFS mounts without "readdir plus" RPC.
403 */
405 if (asprintf(&path_child, "%s/%s", path_parent, dent->d_name) == -1)
406 return got_error_from_errno("asprintf");
408 if (lstat(path_child, &sb) == -1) {
409 err = got_error_from_errno2("lstat", path_child);
410 goto done;
413 if (S_ISFIFO(sb.st_mode))
414 *type = DT_FIFO;
415 else if (S_ISCHR(sb.st_mode))
416 *type = DT_CHR;
417 else if (S_ISDIR(sb.st_mode))
418 *type = DT_DIR;
419 else if (S_ISBLK(sb.st_mode))
420 *type = DT_BLK;
421 else if (S_ISLNK(sb.st_mode))
422 *type = DT_LNK;
423 else if (S_ISREG(sb.st_mode))
424 *type = DT_REG;
425 else if (S_ISSOCK(sb.st_mode))
426 *type = DT_SOCK;
427 done:
428 free(path_child);
429 return err;
432 const struct got_error *
433 got_path_basename(char **s, const char *path)
435 char buf[PATH_MAX];
436 char *base;
438 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf))
439 return got_error(GOT_ERR_NO_SPACE);
441 base = basename(buf);
442 if (base == NULL)
443 return got_error_from_errno2("basename", path);
445 *s = strdup(base);
446 if (*s == NULL)
447 return got_error_from_errno("strdup");
449 return NULL;
452 void
453 got_path_strip_trailing_slashes(char *path)
455 size_t x;
457 x = strlen(path);
458 while (x-- > 0 && path[x] == '/')
459 path[x] = '\0';
462 /* based on findprog() from usr.bin/which/which.c */
463 const struct got_error *
464 got_path_find_prog(char **filename, const char *prog)
466 const struct got_error *err = NULL;
467 char *p;
468 int len;
469 struct stat sbuf;
470 char *path, *pathcpy;
472 *filename = NULL;
474 path = getenv("PATH");
475 if (path == NULL)
476 path = _PATH_DEFPATH;
478 /* Special case if prog contains '/' */
479 if (strchr(prog, '/')) {
480 if ((stat(prog, &sbuf) == 0) && S_ISREG(sbuf.st_mode) &&
481 access(prog, X_OK) == 0) {
482 *filename = strdup(prog);
483 if (*filename == NULL)
484 return got_error_from_errno("strdup");
486 return NULL;
489 if ((path = strdup(path)) == NULL)
490 return got_error_from_errno("strdup");
491 pathcpy = path;
493 while ((p = strsep(&pathcpy, ":")) != NULL) {
494 if (*p == '\0')
495 p = ".";
497 len = strlen(p);
498 while (len > 0 && p[len-1] == '/')
499 p[--len] = '\0'; /* strip trailing '/' */
501 if (asprintf(filename, "%s/%s", p, prog) == -1) {
502 err = got_error_from_errno("asprintf");
503 break;
505 if ((stat(*filename, &sbuf) == 0) && S_ISREG(sbuf.st_mode) &&
506 access(*filename, X_OK) == 0)
507 break;
508 free(*filename);
509 *filename = NULL;
510 continue;
512 free(path);
513 return err;
516 const struct got_error *
517 got_path_create_file(const char *path, const char *content)
519 const struct got_error *err = NULL;
520 int fd = -1;
522 fd = open(path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC,
523 GOT_DEFAULT_FILE_MODE);
524 if (fd == -1) {
525 err = got_error_from_errno2("open", path);
526 goto done;
529 if (content) {
530 int len = dprintf(fd, "%s\n", content);
531 if (len != strlen(content) + 1) {
532 err = got_error_from_errno("dprintf");
533 goto done;
537 done:
538 if (fd != -1 && close(fd) == -1 && err == NULL)
539 err = got_error_from_errno("close");
540 return err;