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_child(const char *child, const char *parent, size_t parent_len)
154 if (parent_len == 0 || got_path_is_root_dir(parent))
155 return 1;
157 if (strncmp(parent, child, parent_len) != 0)
158 return 0;
159 if (child[parent_len] != '/')
160 return 0;
162 return 1;
165 int
166 got_path_cmp(const char *path1, const char *path2, size_t len1, size_t len2)
168 size_t min_len;
169 size_t i = 0;
171 /* Leading directory separators are insignificant. */
172 while (path1[0] == '/') {
173 path1++;
174 len1--;
176 while (path2[0] == '/') {
177 path2++;
178 len2--;
181 min_len = MIN(len1, len2);
183 /* Skip over common prefix. */
184 while (i < min_len && path1[i] == path2[i])
185 i++;
187 /* Are the paths exactly equal (besides path separators)? */
188 if (len1 == len2 && i >= min_len)
189 return 0;
191 /* Skip over redundant trailing path seperators. */
192 while (path1[i] == '/' && path1[i + 1] == '/')
193 path1++;
194 while (path2[i] == '/' && path2[i + 1] == '/')
195 path2++;
197 /* Trailing path separators are insignificant. */
198 if (path1[i] == '/' && path1[i + 1] == '\0' && path2[i] == '\0')
199 return 0;
200 if (path2[i] == '/' && path2[i + 1] == '\0' && path1[i] == '\0')
201 return 0;
203 /* Order children in subdirectories directly after their parents. */
204 if (path1[i] == '/' && path2[i] == '\0')
205 return 1;
206 if (path2[i] == '/' && path1[i] == '\0')
207 return -1;
208 if (path1[i] == '/' && path2[i] != '\0')
209 return -1;
210 if (path2[i] == '/' && path1[i] != '\0')
211 return 1;
213 /* Next character following the common prefix determines order. */
214 return (unsigned char)path1[i] < (unsigned char)path2[i] ? -1 : 1;
217 const struct got_error *
218 got_pathlist_insert(struct got_pathlist_entry **inserted,
219 struct got_pathlist_head *pathlist, const char *path, void *data)
221 struct got_pathlist_entry *new, *pe;
222 size_t path_len = strlen(path);
224 if (inserted)
225 *inserted = NULL;
227 /*
228 * Many callers will provide paths in a somewhat sorted order while
229 * constructing a path list from inputs such as tree objects or
230 * dirents. Iterating backwards from the tail of the list should
231 * be more efficient than traversing through the entire list each
232 * time an element is inserted.
233 */
234 pe = TAILQ_LAST(pathlist, got_pathlist_head);
235 while (pe) {
236 int cmp = got_path_cmp(pe->path, path, pe->path_len, path_len);
237 if (cmp == 0)
238 return NULL; /* duplicate */
239 else if (cmp < 0)
240 break;
241 pe = TAILQ_PREV(pe, got_pathlist_head, entry);
244 new = malloc(sizeof(*new));
245 if (new == NULL)
246 return got_error_from_errno("malloc");
247 new->path = path;
248 new->path_len = path_len;
249 new->data = data;
250 if (pe)
251 TAILQ_INSERT_AFTER(pathlist, pe, new, entry);
252 else
253 TAILQ_INSERT_HEAD(pathlist, new, entry);
254 if (inserted)
255 *inserted = new;
256 return NULL;
259 const struct got_error *
260 got_pathlist_append(struct got_pathlist_head *pathlist,
261 const char *path, void *data)
263 struct got_pathlist_entry *new;
265 new = malloc(sizeof(*new));
266 if (new == NULL)
267 return got_error_from_errno("malloc");
268 new->path = path;
269 new->path_len = strlen(path);
270 new->data = data;
271 TAILQ_INSERT_TAIL(pathlist, new, entry);
272 return NULL;
275 void
276 got_pathlist_free(struct got_pathlist_head *pathlist)
278 struct got_pathlist_entry *pe;
280 while ((pe = TAILQ_FIRST(pathlist)) != NULL) {
281 TAILQ_REMOVE(pathlist, pe, entry);
282 free(pe);
286 static const struct got_error *
287 make_parent_dirs(const char *abspath)
289 const struct got_error *err = NULL;
290 char *parent;
292 err = got_path_dirname(&parent, abspath);
293 if (err)
294 return err;
296 if (mkdir(parent, GOT_DEFAULT_DIR_MODE) == -1) {
297 if (errno == ENOENT) {
298 err = make_parent_dirs(parent);
299 if (err)
300 goto done;
301 if (mkdir(parent, GOT_DEFAULT_DIR_MODE) == -1) {
302 err = got_error_from_errno2("mkdir", parent);
303 goto done;
305 } else
306 err = got_error_from_errno2("mkdir", parent);
308 done:
309 free(parent);
310 return err;
313 const struct got_error *
314 got_path_mkdir(const char *abspath)
316 const struct got_error *err = NULL;
318 if (mkdir(abspath, GOT_DEFAULT_DIR_MODE) == -1) {
319 if (errno == ENOENT) {
320 err = make_parent_dirs(abspath);
321 if (err)
322 goto done;
323 if (mkdir(abspath, GOT_DEFAULT_DIR_MODE) == -1)
324 err = got_error_from_errno2("mkdir", abspath);
325 } else
326 err = got_error_from_errno2("mkdir", abspath);
329 done:
330 return err;
333 int
334 got_path_dir_is_empty(const char *dir)
336 DIR *d;
337 struct dirent *dent;
338 int empty = 1;
340 d = opendir(dir);
341 if (d == NULL)
342 return 1;
344 while ((dent = readdir(d)) != NULL) {
345 if (strcmp(dent->d_name, ".") == 0 ||
346 strcmp(dent->d_name, "..") == 0)
347 continue;
349 empty = 0;
350 break;
353 closedir(d);
354 return empty;
357 const struct got_error *
358 got_path_dirname(char **parent, const char *path)
360 char buf[PATH_MAX];
361 char *p;
363 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf))
364 return got_error(GOT_ERR_NO_SPACE);
366 p = dirname(buf);
367 if (p == NULL)
368 return got_error_from_errno2("dirname", path);
370 if (p[0] == '.' && p[1] == '\0')
371 return got_error_path(path, GOT_ERR_BAD_PATH);
373 *parent = strdup(p);
374 if (*parent == NULL)
375 return got_error_from_errno("strdup");
377 return NULL;
380 const struct got_error *
381 got_path_dirent_type(int *type, const char *path_parent, struct dirent *dent)
383 const struct got_error *err = NULL;
384 char *path_child;
385 struct stat sb;
387 if (dent->d_type != DT_UNKNOWN) {
388 *type = dent->d_type;
389 return NULL;
392 *type = DT_UNKNOWN;
394 /*
395 * This is a fallback to accommodate filesystems which do not
396 * provide directory entry type information. DT_UNKNOWN directory
397 * entries occur on NFS mounts without "readdir plus" RPC.
398 */
400 if (asprintf(&path_child, "%s/%s", path_parent, dent->d_name) == -1)
401 return got_error_from_errno("asprintf");
403 if (lstat(path_child, &sb) == -1) {
404 err = got_error_from_errno2("lstat", path_child);
405 goto done;
408 if (S_ISFIFO(sb.st_mode))
409 *type = DT_FIFO;
410 else if (S_ISCHR(sb.st_mode))
411 *type = DT_CHR;
412 else if (S_ISDIR(sb.st_mode))
413 *type = DT_DIR;
414 else if (S_ISBLK(sb.st_mode))
415 *type = DT_BLK;
416 else if (S_ISLNK(sb.st_mode))
417 *type = DT_LNK;
418 else if (S_ISREG(sb.st_mode))
419 *type = DT_REG;
420 else if (S_ISSOCK(sb.st_mode))
421 *type = DT_SOCK;
422 done:
423 free(path_child);
424 return err;
427 const struct got_error *
428 got_path_basename(char **s, const char *path)
430 char buf[PATH_MAX];
431 char *base;
433 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf))
434 return got_error(GOT_ERR_NO_SPACE);
436 base = basename(buf);
437 if (base == NULL)
438 return got_error_from_errno2("basename", path);
440 *s = strdup(base);
441 if (*s == NULL)
442 return got_error_from_errno("strdup");
444 return NULL;
447 void
448 got_path_strip_trailing_slashes(char *path)
450 size_t x;
452 x = strlen(path);
453 while (x-- > 0 && path[x] == '/')
454 path[x] = '\0';
457 /* based on findprog() from usr.bin/which/which.c */
458 const struct got_error *
459 got_path_find_prog(char **filename, const char *prog)
461 const struct got_error *err = NULL;
462 const char *path;
463 char *p;
464 int len;
465 struct stat sbuf;
466 char *pathcpy, *dup = NULL;
468 *filename = NULL;
470 path = getenv("PATH");
471 if (path == NULL)
472 path = _PATH_DEFPATH;
474 /* Special case if prog contains '/' */
475 if (strchr(prog, '/')) {
476 if ((stat(prog, &sbuf) == 0) && S_ISREG(sbuf.st_mode) &&
477 access(prog, X_OK) == 0) {
478 *filename = strdup(prog);
479 if (*filename == NULL)
480 return got_error_from_errno("strdup");
482 return NULL;
485 if ((dup = strdup(path)) == NULL)
486 return got_error_from_errno("strdup");
487 pathcpy = dup;
489 while ((p = strsep(&pathcpy, ":")) != NULL) {
490 const char *d;
492 len = strlen(p);
493 while (len > 0 && p[len-1] == '/')
494 p[--len] = '\0'; /* strip trailing '/' */
496 d = p;
497 if (*d == '\0')
498 d = ".";
500 if (asprintf(filename, "%s/%s", d, prog) == -1) {
501 err = got_error_from_errno("asprintf");
502 break;
504 if ((stat(*filename, &sbuf) == 0) && S_ISREG(sbuf.st_mode) &&
505 access(*filename, X_OK) == 0)
506 break;
507 free(*filename);
508 *filename = NULL;
509 continue;
511 free(dup);
512 return err;
515 const struct got_error *
516 got_path_create_file(const char *path, const char *content)
518 const struct got_error *err = NULL;
519 int fd = -1;
521 fd = open(path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC,
522 GOT_DEFAULT_FILE_MODE);
523 if (fd == -1) {
524 err = got_error_from_errno2("open", path);
525 goto done;
528 if (content) {
529 int len = dprintf(fd, "%s\n", content);
530 if (len != strlen(content) + 1) {
531 err = got_error_from_errno("dprintf");
532 goto done;
536 done:
537 if (fd != -1 && close(fd) == -1 && err == NULL)
538 err = got_error_from_errno("close");
539 return err;