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;
228 if (inserted)
229 *inserted = NULL;
231 new = malloc(sizeof(*new));
232 if (new == NULL)
233 return got_error_from_errno("malloc");
234 new->path = path;
235 new->path_len = strlen(path);
236 new->data = data;
238 /*
239 * Many callers will provide paths in a somewhat sorted order while
240 * constructing a path list from inputs such as tree objects or
241 * dirents. Iterating backwards from the tail of the list should
242 * be more efficient than traversing through the entire list each
243 * time an element is inserted.
244 */
245 pe = TAILQ_LAST(pathlist, got_pathlist_head);
246 while (pe) {
247 int cmp = got_path_cmp(pe->path, new->path,
248 pe->path_len, new->path_len);
249 if (cmp == 0) {
250 free(new); /* duplicate */
251 return NULL;
252 } else if (cmp < 0) {
253 TAILQ_INSERT_AFTER(pathlist, pe, new, entry);
254 if (inserted)
255 *inserted = new;
256 return NULL;
258 pe = TAILQ_PREV(pe, got_pathlist_head, entry);
261 TAILQ_INSERT_HEAD(pathlist, new, entry);
262 if (inserted)
263 *inserted = new;
264 return NULL;
267 const struct got_error *
268 got_pathlist_append(struct got_pathlist_head *pathlist,
269 const char *path, void *data)
271 struct got_pathlist_entry *new;
273 new = malloc(sizeof(*new));
274 if (new == NULL)
275 return got_error_from_errno("malloc");
276 new->path = path;
277 new->path_len = strlen(path);
278 new->data = data;
279 TAILQ_INSERT_TAIL(pathlist, new, entry);
280 return NULL;
283 void
284 got_pathlist_free(struct got_pathlist_head *pathlist)
286 struct got_pathlist_entry *pe;
288 while ((pe = TAILQ_FIRST(pathlist)) != NULL) {
289 TAILQ_REMOVE(pathlist, pe, entry);
290 free(pe);
294 static const struct got_error *
295 make_parent_dirs(const char *abspath)
297 const struct got_error *err = NULL;
298 char *parent;
300 err = got_path_dirname(&parent, abspath);
301 if (err)
302 return err;
304 if (mkdir(parent, GOT_DEFAULT_DIR_MODE) == -1) {
305 if (errno == ENOENT) {
306 err = make_parent_dirs(parent);
307 if (err)
308 goto done;
309 if (mkdir(parent, GOT_DEFAULT_DIR_MODE) == -1) {
310 err = got_error_from_errno2("mkdir", parent);
311 goto done;
313 } else
314 err = got_error_from_errno2("mkdir", parent);
316 done:
317 free(parent);
318 return err;
321 const struct got_error *
322 got_path_mkdir(const char *abspath)
324 const struct got_error *err = NULL;
326 if (mkdir(abspath, GOT_DEFAULT_DIR_MODE) == -1) {
327 if (errno == ENOENT) {
328 err = make_parent_dirs(abspath);
329 if (err)
330 goto done;
331 if (mkdir(abspath, GOT_DEFAULT_DIR_MODE) == -1)
332 err = got_error_from_errno2("mkdir", abspath);
333 } else
334 err = got_error_from_errno2("mkdir", abspath);
337 done:
338 return err;
341 int
342 got_path_dir_is_empty(const char *dir)
344 DIR *d;
345 struct dirent *dent;
346 int empty = 1;
348 d = opendir(dir);
349 if (d == NULL)
350 return 1;
352 while ((dent = readdir(d)) != NULL) {
353 if (strcmp(dent->d_name, ".") == 0 ||
354 strcmp(dent->d_name, "..") == 0)
355 continue;
357 empty = 0;
358 break;
361 closedir(d);
362 return empty;
365 const struct got_error *
366 got_path_dirname(char **parent, const char *path)
368 char buf[PATH_MAX];
369 char *p;
371 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf))
372 return got_error(GOT_ERR_NO_SPACE);
374 p = dirname(buf);
375 if (p == NULL)
376 return got_error_from_errno2("dirname", path);
378 if (p[0] == '.' && p[1] == '\0')
379 return got_error_path(path, GOT_ERR_BAD_PATH);
381 *parent = strdup(p);
382 if (*parent == NULL)
383 return got_error_from_errno("strdup");
385 return NULL;
388 const struct got_error *
389 got_path_dirent_type(int *type, const char *path_parent, struct dirent *dent)
391 const struct got_error *err = NULL;
392 char *path_child;
393 struct stat sb;
395 if (dent->d_type != DT_UNKNOWN) {
396 *type = dent->d_type;
397 return NULL;
400 *type = DT_UNKNOWN;
402 /*
403 * This is a fallback to accommodate filesystems which do not
404 * provide directory entry type information. DT_UNKNOWN directory
405 * entries occur on NFS mounts without "readdir plus" RPC.
406 */
408 if (asprintf(&path_child, "%s/%s", path_parent, dent->d_name) == -1)
409 return got_error_from_errno("asprintf");
411 if (lstat(path_child, &sb) == -1) {
412 err = got_error_from_errno2("lstat", path_child);
413 goto done;
416 if (S_ISFIFO(sb.st_mode))
417 *type = DT_FIFO;
418 else if (S_ISCHR(sb.st_mode))
419 *type = DT_CHR;
420 else if (S_ISDIR(sb.st_mode))
421 *type = DT_DIR;
422 else if (S_ISBLK(sb.st_mode))
423 *type = DT_BLK;
424 else if (S_ISLNK(sb.st_mode))
425 *type = DT_LNK;
426 else if (S_ISREG(sb.st_mode))
427 *type = DT_REG;
428 else if (S_ISSOCK(sb.st_mode))
429 *type = DT_SOCK;
430 done:
431 free(path_child);
432 return err;
435 const struct got_error *
436 got_path_basename(char **s, const char *path)
438 char buf[PATH_MAX];
439 char *base;
441 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf))
442 return got_error(GOT_ERR_NO_SPACE);
444 base = basename(buf);
445 if (base == NULL)
446 return got_error_from_errno2("basename", path);
448 *s = strdup(base);
449 if (*s == NULL)
450 return got_error_from_errno("strdup");
452 return NULL;
455 void
456 got_path_strip_trailing_slashes(char *path)
458 size_t x;
460 x = strlen(path);
461 while (x-- > 0 && path[x] == '/')
462 path[x] = '\0';
465 /* based on findprog() from usr.bin/which/which.c */
466 const struct got_error *
467 got_path_find_prog(char **filename, const char *prog)
469 const struct got_error *err = NULL;
470 char *p;
471 int len;
472 struct stat sbuf;
473 char *path, *pathcpy;
475 *filename = NULL;
477 path = getenv("PATH");
478 if (path == NULL)
479 path = _PATH_DEFPATH;
481 /* Special case if prog contains '/' */
482 if (strchr(prog, '/')) {
483 if ((stat(prog, &sbuf) == 0) && S_ISREG(sbuf.st_mode) &&
484 access(prog, X_OK) == 0) {
485 *filename = strdup(prog);
486 if (*filename == NULL)
487 return got_error_from_errno("strdup");
489 return NULL;
492 if ((path = strdup(path)) == NULL)
493 return got_error_from_errno("strdup");
494 pathcpy = path;
496 while ((p = strsep(&pathcpy, ":")) != NULL) {
497 if (*p == '\0')
498 p = ".";
500 len = strlen(p);
501 while (len > 0 && p[len-1] == '/')
502 p[--len] = '\0'; /* strip trailing '/' */
504 if (asprintf(filename, "%s/%s", p, prog) == -1) {
505 err = got_error_from_errno("asprintf");
506 break;
508 if ((stat(*filename, &sbuf) == 0) && S_ISREG(sbuf.st_mode) &&
509 access(*filename, X_OK) == 0)
510 break;
511 free(*filename);
512 *filename = NULL;
513 continue;
515 free(path);
516 return err;
519 const struct got_error *
520 got_path_create_file(const char *path, const char *content)
522 const struct got_error *err = NULL;
523 int fd = -1;
525 fd = open(path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC,
526 GOT_DEFAULT_FILE_MODE);
527 if (fd == -1) {
528 err = got_error_from_errno2("open", path);
529 goto done;
532 if (content) {
533 int len = dprintf(fd, "%s\n", content);
534 if (len != strlen(content) + 1) {
535 err = got_error_from_errno("dprintf");
536 goto done;
540 done:
541 if (fd != -1 && close(fd) == -1 && err == NULL)
542 err = got_error_from_errno("close");
543 return err;