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/stat.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <limits.h>
24 #include <libgen.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <dirent.h>
30 #include <paths.h>
32 #include "got_compat.h"
34 #include "got_error.h"
35 #include "got_path.h"
37 #ifndef MIN
38 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
39 #endif
41 int
42 got_path_is_absolute(const char *path)
43 {
44 return path[0] == '/';
45 }
47 /* based on canonpath() from kern_pledge.c */
48 const struct got_error *
49 got_canonpath(const char *input, char *buf, size_t bufsize)
50 {
51 const char *p;
52 char *q;
54 /* can't canon relative paths, don't bother */
55 if (!got_path_is_absolute(input)) {
56 if (strlcpy(buf, input, bufsize) >= bufsize)
57 return got_error(GOT_ERR_NO_SPACE);
58 return NULL;
59 }
61 p = input;
62 q = buf;
63 while (*p && (q - buf < bufsize)) {
64 if (p[0] == '/' && (p[1] == '/' || p[1] == '\0')) {
65 p += 1;
67 } else if (p[0] == '/' && p[1] == '.' &&
68 (p[2] == '/' || p[2] == '\0')) {
69 p += 2;
71 } else if (p[0] == '/' && p[1] == '.' && p[2] == '.' &&
72 (p[3] == '/' || p[3] == '\0')) {
73 p += 3;
74 if (q != buf) /* "/../" at start of buf */
75 while (*--q != '/')
76 continue;
78 } else {
79 *q++ = *p++;
80 }
81 }
82 if ((*p == '\0') && (q - buf < bufsize)) {
83 *q = 0;
84 return NULL;
85 } else
86 return got_error(GOT_ERR_NO_SPACE);
87 }
89 const struct got_error *
90 got_path_skip_common_ancestor(char **child, const char *parent_abspath,
91 const char *abspath)
92 {
93 const struct got_error *err = NULL;
94 size_t len_parent, len, bufsize;
96 *child = NULL;
98 len_parent = strlen(parent_abspath);
99 len = strlen(abspath);
100 if (len_parent >= len)
101 return got_error_path(abspath, GOT_ERR_BAD_PATH);
102 if (strncmp(parent_abspath, abspath, len_parent) != 0)
103 return got_error_path(abspath, GOT_ERR_BAD_PATH);
104 if (!got_path_is_root_dir(parent_abspath) && abspath[len_parent] != '/')
105 return got_error_path(abspath, GOT_ERR_BAD_PATH);
106 while (abspath[len_parent] == '/')
107 abspath++;
108 bufsize = len - len_parent + 1;
109 *child = malloc(bufsize);
110 if (*child == NULL)
111 return got_error_from_errno("malloc");
112 if (strlcpy(*child, abspath + len_parent, bufsize) >= bufsize) {
113 err = got_error_from_errno("strlcpy");
114 free(*child);
115 *child = NULL;
116 return err;
118 return NULL;
121 const struct got_error *
122 got_path_strip(char **out, const char *path, int n)
124 const char *p, *c;
126 p = path;
127 *out = NULL;
129 while (n > 0 && (c = strchr(p, '/')) != NULL) {
130 p = c + 1;
131 n--;
134 if (n > 0)
135 return got_error_fmt(GOT_ERR_BAD_PATH,
136 "can't strip %d path-components from %s", n, path);
138 if ((*out = strdup(p)) == NULL)
139 return got_error_from_errno("strdup");
140 return NULL;
143 int
144 got_path_is_root_dir(const char *path)
146 while (*path == '/')
147 path++;
148 return (*path == '\0');
151 int
152 got_path_is_current_dir(const char *path)
154 return (path[0] == '.' && path[1] == '\0');
157 int
158 got_path_is_child(const char *child, const char *parent, size_t parent_len)
160 if (parent_len == 0 || got_path_is_root_dir(parent))
161 return 1;
163 if (strncmp(parent, child, parent_len) != 0)
164 return 0;
165 if (child[parent_len] != '/')
166 return 0;
168 return 1;
171 int
172 got_path_cmp(const char *path1, const char *path2, size_t len1, size_t len2)
174 size_t min_len;
175 size_t i = 0;
177 /* Leading directory separators are insignificant. */
178 while (path1[0] == '/') {
179 path1++;
180 len1--;
182 while (path2[0] == '/') {
183 path2++;
184 len2--;
187 min_len = MIN(len1, len2);
189 /* Skip over common prefix. */
190 while (i < min_len && path1[i] == path2[i])
191 i++;
193 /* Are the paths exactly equal (besides path separators)? */
194 if (len1 == len2 && i >= min_len)
195 return 0;
197 /* Skip over redundant trailing path seperators. */
198 while (path1[i] == '/' && path1[i + 1] == '/')
199 path1++;
200 while (path2[i] == '/' && path2[i + 1] == '/')
201 path2++;
203 /* Trailing path separators are insignificant. */
204 if (path1[i] == '/' && path1[i + 1] == '\0' && path2[i] == '\0')
205 return 0;
206 if (path2[i] == '/' && path2[i + 1] == '\0' && path1[i] == '\0')
207 return 0;
209 /* Order children in subdirectories directly after their parents. */
210 if (path1[i] == '/' && path2[i] == '\0')
211 return 1;
212 if (path2[i] == '/' && path1[i] == '\0')
213 return -1;
214 if (path1[i] == '/' && path2[i] != '\0')
215 return -1;
216 if (path2[i] == '/' && path1[i] != '\0')
217 return 1;
219 /* Next character following the common prefix determines order. */
220 return (unsigned char)path1[i] < (unsigned char)path2[i] ? -1 : 1;
223 const struct got_error *
224 got_pathlist_insert(struct got_pathlist_entry **inserted,
225 struct got_pathlist_head *pathlist, const char *path, void *data)
227 struct got_pathlist_entry *new, *pe;
229 if (inserted)
230 *inserted = NULL;
232 new = malloc(sizeof(*new));
233 if (new == NULL)
234 return got_error_from_errno("malloc");
235 new->path = path;
236 new->path_len = strlen(path);
237 new->data = data;
239 /*
240 * Many callers will provide paths in a somewhat sorted order while
241 * constructing a path list from inputs such as tree objects or
242 * dirents. Iterating backwards from the tail of the list should
243 * be more efficient than traversing through the entire list each
244 * time an element is inserted.
245 */
246 pe = TAILQ_LAST(pathlist, got_pathlist_head);
247 while (pe) {
248 int cmp = got_path_cmp(pe->path, new->path,
249 pe->path_len, new->path_len);
250 if (cmp == 0) {
251 free(new); /* duplicate */
252 return NULL;
253 } else if (cmp < 0) {
254 TAILQ_INSERT_AFTER(pathlist, pe, new, entry);
255 if (inserted)
256 *inserted = new;
257 return NULL;
259 pe = TAILQ_PREV(pe, got_pathlist_head, entry);
262 TAILQ_INSERT_HEAD(pathlist, new, entry);
263 if (inserted)
264 *inserted = new;
265 return NULL;
268 const struct got_error *
269 got_pathlist_append(struct got_pathlist_head *pathlist,
270 const char *path, void *data)
272 struct got_pathlist_entry *new;
274 new = malloc(sizeof(*new));
275 if (new == NULL)
276 return got_error_from_errno("malloc");
277 new->path = path;
278 new->path_len = strlen(path);
279 new->data = data;
280 TAILQ_INSERT_TAIL(pathlist, new, entry);
281 return NULL;
284 void
285 got_pathlist_free(struct got_pathlist_head *pathlist)
287 struct got_pathlist_entry *pe;
289 while ((pe = TAILQ_FIRST(pathlist)) != NULL) {
290 TAILQ_REMOVE(pathlist, pe, entry);
291 free(pe);
295 static const struct got_error *
296 make_parent_dirs(const char *abspath)
298 const struct got_error *err = NULL;
299 char *parent;
301 err = got_path_dirname(&parent, abspath);
302 if (err)
303 return err;
305 if (mkdir(parent, GOT_DEFAULT_DIR_MODE) == -1) {
306 if (errno == ENOENT) {
307 err = make_parent_dirs(parent);
308 if (err)
309 goto done;
310 if (mkdir(parent, GOT_DEFAULT_DIR_MODE) == -1) {
311 err = got_error_from_errno2("mkdir", parent);
312 goto done;
314 } else
315 err = got_error_from_errno2("mkdir", parent);
317 done:
318 free(parent);
319 return err;
322 const struct got_error *
323 got_path_mkdir(const char *abspath)
325 const struct got_error *err = NULL;
327 if (mkdir(abspath, GOT_DEFAULT_DIR_MODE) == -1) {
328 if (errno == ENOENT) {
329 err = make_parent_dirs(abspath);
330 if (err)
331 goto done;
332 if (mkdir(abspath, GOT_DEFAULT_DIR_MODE) == -1)
333 err = got_error_from_errno2("mkdir", abspath);
334 } else
335 err = got_error_from_errno2("mkdir", abspath);
338 done:
339 return err;
342 int
343 got_path_dir_is_empty(const char *dir)
345 DIR *d;
346 struct dirent *dent;
347 int empty = 1;
349 d = opendir(dir);
350 if (d == NULL)
351 return 1;
353 while ((dent = readdir(d)) != NULL) {
354 if (strcmp(dent->d_name, ".") == 0 ||
355 strcmp(dent->d_name, "..") == 0)
356 continue;
358 empty = 0;
359 break;
362 closedir(d);
363 return empty;
366 const struct got_error *
367 got_path_dirname(char **parent, const char *path)
369 char buf[PATH_MAX];
370 char *p;
372 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf))
373 return got_error(GOT_ERR_NO_SPACE);
375 p = dirname(buf);
376 if (p == NULL)
377 return got_error_from_errno2("dirname", path);
379 if (p[0] == '.' && p[1] == '\0')
380 return got_error_path(path, GOT_ERR_BAD_PATH);
382 *parent = strdup(p);
383 if (*parent == NULL)
384 return got_error_from_errno("strdup");
386 return NULL;
389 const struct got_error *
390 got_path_dirent_type(int *type, const char *path_parent, struct dirent *dent)
392 const struct got_error *err = NULL;
393 char *path_child;
394 struct stat sb;
396 if (dent->d_type != DT_UNKNOWN) {
397 *type = dent->d_type;
398 return NULL;
401 *type = DT_UNKNOWN;
403 /*
404 * This is a fallback to accommodate filesystems which do not
405 * provide directory entry type information. DT_UNKNOWN directory
406 * entries occur on NFS mounts without "readdir plus" RPC.
407 */
409 if (asprintf(&path_child, "%s/%s", path_parent, dent->d_name) == -1)
410 return got_error_from_errno("asprintf");
412 if (lstat(path_child, &sb) == -1) {
413 err = got_error_from_errno2("lstat", path_child);
414 goto done;
417 if (S_ISFIFO(sb.st_mode))
418 *type = DT_FIFO;
419 else if (S_ISCHR(sb.st_mode))
420 *type = DT_CHR;
421 else if (S_ISDIR(sb.st_mode))
422 *type = DT_DIR;
423 else if (S_ISBLK(sb.st_mode))
424 *type = DT_BLK;
425 else if (S_ISLNK(sb.st_mode))
426 *type = DT_LNK;
427 else if (S_ISREG(sb.st_mode))
428 *type = DT_REG;
429 else if (S_ISSOCK(sb.st_mode))
430 *type = DT_SOCK;
431 done:
432 free(path_child);
433 return err;
436 const struct got_error *
437 got_path_basename(char **s, const char *path)
439 char buf[PATH_MAX];
440 char *base;
442 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf))
443 return got_error(GOT_ERR_NO_SPACE);
445 base = basename(buf);
446 if (base == NULL)
447 return got_error_from_errno2("basename", path);
449 *s = strdup(base);
450 if (*s == NULL)
451 return got_error_from_errno("strdup");
453 return NULL;
456 void
457 got_path_strip_trailing_slashes(char *path)
459 size_t x;
461 x = strlen(path);
462 while (x-- > 0 && path[x] == '/')
463 path[x] = '\0';
466 /* based on findprog() from usr.bin/which/which.c */
467 const struct got_error *
468 got_path_find_prog(char **filename, const char *prog)
470 const struct got_error *err = NULL;
471 char *p;
472 int len;
473 struct stat sbuf;
474 char *path, *pathcpy;
476 *filename = NULL;
478 path = getenv("PATH");
479 if (path == NULL)
480 path = _PATH_DEFPATH;
482 /* Special case if prog contains '/' */
483 if (strchr(prog, '/')) {
484 if ((stat(prog, &sbuf) == 0) && S_ISREG(sbuf.st_mode) &&
485 access(prog, X_OK) == 0) {
486 *filename = strdup(prog);
487 if (*filename == NULL)
488 return got_error_from_errno("strdup");
490 return NULL;
493 if ((path = strdup(path)) == NULL)
494 return got_error_from_errno("strdup");
495 pathcpy = path;
497 while ((p = strsep(&pathcpy, ":")) != NULL) {
498 if (*p == '\0')
499 p = ".";
501 len = strlen(p);
502 while (len > 0 && p[len-1] == '/')
503 p[--len] = '\0'; /* strip trailing '/' */
505 if (asprintf(filename, "%s/%s", p, prog) == -1) {
506 err = got_error_from_errno("asprintf");
507 break;
509 if ((stat(*filename, &sbuf) == 0) && S_ISREG(sbuf.st_mode) &&
510 access(*filename, X_OK) == 0)
511 break;
512 free(*filename);
513 *filename = NULL;
514 continue;
516 free(path);
517 return err;
520 const struct got_error *
521 got_path_create_file(const char *path, const char *content)
523 const struct got_error *err = NULL;
524 int fd = -1;
526 fd = open(path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC,
527 GOT_DEFAULT_FILE_MODE);
528 if (fd == -1) {
529 err = got_error_from_errno2("open", path);
530 goto done;
533 if (content) {
534 int len = dprintf(fd, "%s\n", content);
535 if (len != strlen(content) + 1) {
536 err = got_error_from_errno("dprintf");
537 goto done;
541 done:
542 if (fd != -1 && close(fd) == -1 && err == NULL)
543 err = got_error_from_errno("close");
544 return err;