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;
228 size_t path_len = strlen(path);
230 if (inserted)
231 *inserted = NULL;
233 /*
234 * Many callers will provide paths in a somewhat sorted order while
235 * constructing a path list from inputs such as tree objects or
236 * dirents. Iterating backwards from the tail of the list should
237 * be more efficient than traversing through the entire list each
238 * time an element is inserted.
239 */
240 pe = TAILQ_LAST(pathlist, got_pathlist_head);
241 while (pe) {
242 int cmp = got_path_cmp(pe->path, path, pe->path_len, path_len);
243 if (cmp == 0)
244 return NULL; /* duplicate */
245 else if (cmp < 0)
246 break;
247 pe = TAILQ_PREV(pe, got_pathlist_head, entry);
250 new = malloc(sizeof(*new));
251 if (new == NULL)
252 return got_error_from_errno("malloc");
253 new->path = path;
254 new->path_len = path_len;
255 new->data = data;
256 if (pe)
257 TAILQ_INSERT_AFTER(pathlist, pe, new, entry);
258 else
259 TAILQ_INSERT_HEAD(pathlist, new, entry);
260 if (inserted)
261 *inserted = new;
262 return NULL;
265 const struct got_error *
266 got_pathlist_append(struct got_pathlist_head *pathlist,
267 const char *path, void *data)
269 struct got_pathlist_entry *new;
271 new = malloc(sizeof(*new));
272 if (new == NULL)
273 return got_error_from_errno("malloc");
274 new->path = path;
275 new->path_len = strlen(path);
276 new->data = data;
277 TAILQ_INSERT_TAIL(pathlist, new, entry);
278 return NULL;
281 void
282 got_pathlist_free(struct got_pathlist_head *pathlist)
284 struct got_pathlist_entry *pe;
286 while ((pe = TAILQ_FIRST(pathlist)) != NULL) {
287 TAILQ_REMOVE(pathlist, pe, entry);
288 free(pe);
292 static const struct got_error *
293 make_parent_dirs(const char *abspath)
295 const struct got_error *err = NULL;
296 char *parent;
298 err = got_path_dirname(&parent, abspath);
299 if (err)
300 return err;
302 if (mkdir(parent, GOT_DEFAULT_DIR_MODE) == -1) {
303 if (errno == ENOENT) {
304 err = make_parent_dirs(parent);
305 if (err)
306 goto done;
307 if (mkdir(parent, GOT_DEFAULT_DIR_MODE) == -1) {
308 err = got_error_from_errno2("mkdir", parent);
309 goto done;
311 } else
312 err = got_error_from_errno2("mkdir", parent);
314 done:
315 free(parent);
316 return err;
319 const struct got_error *
320 got_path_mkdir(const char *abspath)
322 const struct got_error *err = NULL;
324 if (mkdir(abspath, GOT_DEFAULT_DIR_MODE) == -1) {
325 if (errno == ENOENT) {
326 err = make_parent_dirs(abspath);
327 if (err)
328 goto done;
329 if (mkdir(abspath, GOT_DEFAULT_DIR_MODE) == -1)
330 err = got_error_from_errno2("mkdir", abspath);
331 } else
332 err = got_error_from_errno2("mkdir", abspath);
335 done:
336 return err;
339 int
340 got_path_dir_is_empty(const char *dir)
342 DIR *d;
343 struct dirent *dent;
344 int empty = 1;
346 d = opendir(dir);
347 if (d == NULL)
348 return 1;
350 while ((dent = readdir(d)) != NULL) {
351 if (strcmp(dent->d_name, ".") == 0 ||
352 strcmp(dent->d_name, "..") == 0)
353 continue;
355 empty = 0;
356 break;
359 closedir(d);
360 return empty;
363 const struct got_error *
364 got_path_dirname(char **parent, const char *path)
366 char buf[PATH_MAX];
367 char *p;
369 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf))
370 return got_error(GOT_ERR_NO_SPACE);
372 p = dirname(buf);
373 if (p == NULL)
374 return got_error_from_errno2("dirname", path);
376 if (p[0] == '.' && p[1] == '\0')
377 return got_error_path(path, GOT_ERR_BAD_PATH);
379 *parent = strdup(p);
380 if (*parent == NULL)
381 return got_error_from_errno("strdup");
383 return NULL;
386 const struct got_error *
387 got_path_dirent_type(int *type, const char *path_parent, struct dirent *dent)
389 const struct got_error *err = NULL;
390 char *path_child;
391 struct stat sb;
393 if (dent->d_type != DT_UNKNOWN) {
394 *type = dent->d_type;
395 return NULL;
398 *type = DT_UNKNOWN;
400 /*
401 * This is a fallback to accommodate filesystems which do not
402 * provide directory entry type information. DT_UNKNOWN directory
403 * entries occur on NFS mounts without "readdir plus" RPC.
404 */
406 if (asprintf(&path_child, "%s/%s", path_parent, dent->d_name) == -1)
407 return got_error_from_errno("asprintf");
409 if (lstat(path_child, &sb) == -1) {
410 err = got_error_from_errno2("lstat", path_child);
411 goto done;
414 if (S_ISFIFO(sb.st_mode))
415 *type = DT_FIFO;
416 else if (S_ISCHR(sb.st_mode))
417 *type = DT_CHR;
418 else if (S_ISDIR(sb.st_mode))
419 *type = DT_DIR;
420 else if (S_ISBLK(sb.st_mode))
421 *type = DT_BLK;
422 else if (S_ISLNK(sb.st_mode))
423 *type = DT_LNK;
424 else if (S_ISREG(sb.st_mode))
425 *type = DT_REG;
426 else if (S_ISSOCK(sb.st_mode))
427 *type = DT_SOCK;
428 done:
429 free(path_child);
430 return err;
433 const struct got_error *
434 got_path_basename(char **s, const char *path)
436 char buf[PATH_MAX];
437 char *base;
439 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf))
440 return got_error(GOT_ERR_NO_SPACE);
442 base = basename(buf);
443 if (base == NULL)
444 return got_error_from_errno2("basename", path);
446 *s = strdup(base);
447 if (*s == NULL)
448 return got_error_from_errno("strdup");
450 return NULL;
453 void
454 got_path_strip_trailing_slashes(char *path)
456 size_t x;
458 x = strlen(path);
459 while (x-- > 0 && path[x] == '/')
460 path[x] = '\0';
463 /* based on findprog() from usr.bin/which/which.c */
464 const struct got_error *
465 got_path_find_prog(char **filename, const char *prog)
467 const struct got_error *err = NULL;
468 char *p;
469 int len;
470 struct stat sbuf;
471 char *path, *pathcpy;
473 *filename = NULL;
475 path = getenv("PATH");
476 if (path == NULL)
477 path = _PATH_DEFPATH;
479 /* Special case if prog contains '/' */
480 if (strchr(prog, '/')) {
481 if ((stat(prog, &sbuf) == 0) && S_ISREG(sbuf.st_mode) &&
482 access(prog, X_OK) == 0) {
483 *filename = strdup(prog);
484 if (*filename == NULL)
485 return got_error_from_errno("strdup");
487 return NULL;
490 if ((path = strdup(path)) == NULL)
491 return got_error_from_errno("strdup");
492 pathcpy = path;
494 while ((p = strsep(&pathcpy, ":")) != NULL) {
495 if (*p == '\0')
496 p = ".";
498 len = strlen(p);
499 while (len > 0 && p[len-1] == '/')
500 p[--len] = '\0'; /* strip trailing '/' */
502 if (asprintf(filename, "%s/%s", p, prog) == -1) {
503 err = got_error_from_errno("asprintf");
504 break;
506 if ((stat(*filename, &sbuf) == 0) && S_ISREG(sbuf.st_mode) &&
507 access(*filename, X_OK) == 0)
508 break;
509 free(*filename);
510 *filename = NULL;
511 continue;
513 free(path);
514 return err;
517 const struct got_error *
518 got_path_create_file(const char *path, const char *content)
520 const struct got_error *err = NULL;
521 int fd = -1;
523 fd = open(path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC,
524 GOT_DEFAULT_FILE_MODE);
525 if (fd == -1) {
526 err = got_error_from_errno2("open", path);
527 goto done;
530 if (content) {
531 int len = dprintf(fd, "%s\n", content);
532 if (len != strlen(content) + 1) {
533 err = got_error_from_errno("dprintf");
534 goto done;
538 done:
539 if (fd != -1 && close(fd) == -1 && err == NULL)
540 err = got_error_from_errno("close");
541 return err;