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_child(const char *child, const char *parent, size_t parent_len)
153 if (parent_len == 0 || got_path_is_root_dir(parent))
154 return 1;
156 if (strncmp(parent, child, parent_len) != 0)
157 return 0;
158 if (child[parent_len] != '/')
159 return 0;
161 return 1;
164 int
165 got_path_cmp(const char *path1, const char *path2, size_t len1, size_t len2)
167 size_t min_len;
168 size_t i = 0;
170 /* Leading directory separators are insignificant. */
171 while (path1[0] == '/') {
172 path1++;
173 len1--;
175 while (path2[0] == '/') {
176 path2++;
177 len2--;
180 min_len = MIN(len1, len2);
182 /* Skip over common prefix. */
183 while (i < min_len && path1[i] == path2[i])
184 i++;
186 /* Are the paths exactly equal (besides path separators)? */
187 if (len1 == len2 && i >= min_len)
188 return 0;
190 /* Skip over redundant trailing path seperators. */
191 while (path1[i] == '/' && path1[i + 1] == '/')
192 path1++;
193 while (path2[i] == '/' && path2[i + 1] == '/')
194 path2++;
196 /* Trailing path separators are insignificant. */
197 if (path1[i] == '/' && path1[i + 1] == '\0' && path2[i] == '\0')
198 return 0;
199 if (path2[i] == '/' && path2[i + 1] == '\0' && path1[i] == '\0')
200 return 0;
202 /* Order children in subdirectories directly after their parents. */
203 if (path1[i] == '/' && path2[i] == '\0')
204 return 1;
205 if (path2[i] == '/' && path1[i] == '\0')
206 return -1;
207 if (path1[i] == '/' && path2[i] != '\0')
208 return -1;
209 if (path2[i] == '/' && path1[i] != '\0')
210 return 1;
212 /* Next character following the common prefix determines order. */
213 return (unsigned char)path1[i] < (unsigned char)path2[i] ? -1 : 1;
216 const struct got_error *
217 got_pathlist_insert(struct got_pathlist_entry **inserted,
218 struct got_pathlist_head *pathlist, const char *path, void *data)
220 struct got_pathlist_entry *new, *pe;
221 size_t path_len = strlen(path);
223 if (inserted)
224 *inserted = NULL;
226 /*
227 * Many callers will provide paths in a somewhat sorted order while
228 * constructing a path list from inputs such as tree objects or
229 * dirents. Iterating backwards from the tail of the list should
230 * be more efficient than traversing through the entire list each
231 * time an element is inserted.
232 */
233 pe = TAILQ_LAST(pathlist, got_pathlist_head);
234 while (pe) {
235 int cmp = got_path_cmp(pe->path, path, pe->path_len, path_len);
236 if (cmp == 0)
237 return NULL; /* duplicate */
238 else if (cmp < 0)
239 break;
240 pe = TAILQ_PREV(pe, got_pathlist_head, entry);
243 new = malloc(sizeof(*new));
244 if (new == NULL)
245 return got_error_from_errno("malloc");
246 new->path = path;
247 new->path_len = path_len;
248 new->data = data;
249 if (pe)
250 TAILQ_INSERT_AFTER(pathlist, pe, new, entry);
251 else
252 TAILQ_INSERT_HEAD(pathlist, new, entry);
253 if (inserted)
254 *inserted = new;
255 return NULL;
258 const struct got_error *
259 got_pathlist_append(struct got_pathlist_head *pathlist,
260 const char *path, void *data)
262 struct got_pathlist_entry *new;
264 new = malloc(sizeof(*new));
265 if (new == NULL)
266 return got_error_from_errno("malloc");
267 new->path = path;
268 new->path_len = strlen(path);
269 new->data = data;
270 TAILQ_INSERT_TAIL(pathlist, new, entry);
271 return NULL;
274 void
275 got_pathlist_free(struct got_pathlist_head *pathlist, int freemask)
277 struct got_pathlist_entry *pe;
279 while ((pe = TAILQ_FIRST(pathlist)) != NULL) {
280 if (freemask & GOT_PATHLIST_FREE_PATH) {
281 free((char *)pe->path);
282 pe->path = NULL;
284 if (freemask & GOT_PATHLIST_FREE_DATA) {
285 free(pe->data);
286 pe->data = NULL;
288 TAILQ_REMOVE(pathlist, pe, entry);
289 free(pe);
293 static const struct got_error *
294 make_parent_dirs(const char *abspath)
296 const struct got_error *err = NULL;
297 char *parent;
299 err = got_path_dirname(&parent, abspath);
300 if (err)
301 return err;
303 if (mkdir(parent, GOT_DEFAULT_DIR_MODE) == -1) {
304 if (errno == ENOENT) {
305 err = make_parent_dirs(parent);
306 if (err)
307 goto done;
308 if (mkdir(parent, GOT_DEFAULT_DIR_MODE) == -1) {
309 err = got_error_from_errno2("mkdir", parent);
310 goto done;
312 } else
313 err = got_error_from_errno2("mkdir", parent);
315 done:
316 free(parent);
317 return err;
320 const struct got_error *
321 got_path_mkdir(const char *abspath)
323 const struct got_error *err = NULL;
325 if (mkdir(abspath, GOT_DEFAULT_DIR_MODE) == -1) {
326 if (errno == ENOENT) {
327 err = make_parent_dirs(abspath);
328 if (err)
329 goto done;
330 if (mkdir(abspath, GOT_DEFAULT_DIR_MODE) == -1)
331 err = got_error_from_errno2("mkdir", abspath);
332 } else
333 err = got_error_from_errno2("mkdir", abspath);
336 done:
337 return err;
340 int
341 got_path_dir_is_empty(const char *dir)
343 DIR *d;
344 struct dirent *dent;
345 int empty = 1;
347 d = opendir(dir);
348 if (d == NULL)
349 return 1;
351 while ((dent = readdir(d)) != NULL) {
352 if (strcmp(dent->d_name, ".") == 0 ||
353 strcmp(dent->d_name, "..") == 0)
354 continue;
356 empty = 0;
357 break;
360 closedir(d);
361 return empty;
364 const struct got_error *
365 got_path_dirname(char **parent, const char *path)
367 char buf[PATH_MAX];
368 char *p;
370 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf))
371 return got_error(GOT_ERR_NO_SPACE);
373 p = dirname(buf);
374 if (p == NULL)
375 return got_error_from_errno2("dirname", path);
377 if (p[0] == '.' && p[1] == '\0')
378 return got_error_path(path, GOT_ERR_BAD_PATH);
380 *parent = strdup(p);
381 if (*parent == NULL)
382 return got_error_from_errno("strdup");
384 return NULL;
387 const struct got_error *
388 got_path_dirent_type(int *type, const char *path_parent, struct dirent *dent)
390 const struct got_error *err = NULL;
391 char *path_child;
392 struct stat sb;
394 if (dent->d_type != DT_UNKNOWN) {
395 *type = dent->d_type;
396 return NULL;
399 *type = DT_UNKNOWN;
401 /*
402 * This is a fallback to accommodate filesystems which do not
403 * provide directory entry type information. DT_UNKNOWN directory
404 * entries occur on NFS mounts without "readdir plus" RPC.
405 */
407 if (asprintf(&path_child, "%s/%s", path_parent, dent->d_name) == -1)
408 return got_error_from_errno("asprintf");
410 if (lstat(path_child, &sb) == -1) {
411 err = got_error_from_errno2("lstat", path_child);
412 goto done;
415 if (S_ISFIFO(sb.st_mode))
416 *type = DT_FIFO;
417 else if (S_ISCHR(sb.st_mode))
418 *type = DT_CHR;
419 else if (S_ISDIR(sb.st_mode))
420 *type = DT_DIR;
421 else if (S_ISBLK(sb.st_mode))
422 *type = DT_BLK;
423 else if (S_ISLNK(sb.st_mode))
424 *type = DT_LNK;
425 else if (S_ISREG(sb.st_mode))
426 *type = DT_REG;
427 else if (S_ISSOCK(sb.st_mode))
428 *type = DT_SOCK;
429 done:
430 free(path_child);
431 return err;
434 const struct got_error *
435 got_path_basename(char **s, const char *path)
437 char buf[PATH_MAX];
438 char *base;
440 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf))
441 return got_error(GOT_ERR_NO_SPACE);
443 base = basename(buf);
444 if (base == NULL)
445 return got_error_from_errno2("basename", path);
447 *s = strdup(base);
448 if (*s == NULL)
449 return got_error_from_errno("strdup");
451 return NULL;
454 void
455 got_path_strip_trailing_slashes(char *path)
457 size_t x;
459 x = strlen(path);
460 while (x-- > 0 && path[x] == '/')
461 path[x] = '\0';
464 /* based on findprog() from usr.bin/which/which.c */
465 const struct got_error *
466 got_path_find_prog(char **filename, const char *prog)
468 const struct got_error *err = NULL;
469 const char *path;
470 char *p;
471 int len;
472 struct stat sbuf;
473 char *pathcpy, *dup = NULL;
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 ((dup = strdup(path)) == NULL)
493 return got_error_from_errno("strdup");
494 pathcpy = dup;
496 while ((p = strsep(&pathcpy, ":")) != NULL) {
497 const char *d;
499 len = strlen(p);
500 while (len > 0 && p[len-1] == '/')
501 p[--len] = '\0'; /* strip trailing '/' */
503 d = p;
504 if (*d == '\0')
505 d = ".";
507 if (asprintf(filename, "%s/%s", d, prog) == -1) {
508 err = got_error_from_errno("asprintf");
509 break;
511 if ((stat(*filename, &sbuf) == 0) && S_ISREG(sbuf.st_mode) &&
512 access(*filename, X_OK) == 0)
513 break;
514 free(*filename);
515 *filename = NULL;
517 free(dup);
518 return err;
521 const struct got_error *
522 got_path_create_file(const char *path, const char *content)
524 const struct got_error *err = NULL;
525 int fd = -1;
527 fd = open(path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC,
528 GOT_DEFAULT_FILE_MODE);
529 if (fd == -1) {
530 err = got_error_from_errno2("open", path);
531 goto done;
534 if (content) {
535 int len = dprintf(fd, "%s\n", content);
536 if (len != strlen(content) + 1) {
537 err = got_error_from_errno("dprintf");
538 goto done;
542 done:
543 if (fd != -1 && close(fd) == -1 && err == NULL)
544 err = got_error_from_errno("close");
545 return err;
548 const struct got_error *
549 got_path_move_file(const char *oldpath, const char *newpath)
551 const struct got_error *err;
553 if (rename(oldpath, newpath) != -1)
554 return NULL;
556 if (errno != ENOENT)
557 return got_error_from_errno3("rename", oldpath, newpath);
559 err = make_parent_dirs(newpath);
560 if (err)
561 return err;
563 if (rename(oldpath, newpath) == -1)
564 return got_error_from_errno3("rename", oldpath, newpath);
566 return NULL;