attempt to make cmdline tests involing http-server more reliable
[got-portable.git] / lib / path.c
blobd765b120f985effa9c40e2b704d993df3a0e64cc
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>
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.
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.
19 #include "got_compat.h"
21 #include <sys/queue.h>
22 #include <sys/stat.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <limits.h>
27 #include <libgen.h>
28 #include <stdlib.h>
29 #include <unistd.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <dirent.h>
33 #include <paths.h>
35 #include "got_error.h"
36 #include "got_path.h"
38 #ifndef MIN
39 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
40 #endif
42 int
43 got_path_is_absolute(const char *path)
45 return path[0] == '/';
48 /* based on canonpath() from kern_pledge.c */
49 const struct got_error *
50 got_canonpath(const char *input, char *buf, size_t bufsize)
52 const char *p;
53 char *q;
55 /* can't canon relative paths, don't bother */
56 if (!got_path_is_absolute(input)) {
57 if (strlcpy(buf, input, bufsize) >= bufsize)
58 return got_error(GOT_ERR_NO_SPACE);
59 return NULL;
62 p = input;
63 q = buf;
64 while (*p && (q - buf < bufsize)) {
65 if (p[0] == '/' && (p[1] == '/' || p[1] == '\0')) {
66 p += 1;
68 } else if (p[0] == '/' && p[1] == '.' &&
69 (p[2] == '/' || p[2] == '\0')) {
70 p += 2;
72 } else if (p[0] == '/' && p[1] == '.' && p[2] == '.' &&
73 (p[3] == '/' || p[3] == '\0')) {
74 p += 3;
75 if (q != buf) /* "/../" at start of buf */
76 while (*--q != '/')
77 continue;
79 } else {
80 *q++ = *p++;
83 if ((*p == '\0') && (q - buf < bufsize)) {
84 *q = 0;
85 return NULL;
86 } else
87 return got_error(GOT_ERR_NO_SPACE);
90 const struct got_error *
91 got_path_skip_common_ancestor(char **child, const char *parent_abspath,
92 const char *abspath)
94 const struct got_error *err = NULL;
95 size_t len_parent, len, bufsize;
97 *child = NULL;
99 len_parent = strlen(parent_abspath);
100 len = strlen(abspath);
101 if (len_parent >= len)
102 return got_error_path(abspath, GOT_ERR_BAD_PATH);
103 if (strncmp(parent_abspath, abspath, len_parent) != 0)
104 return got_error_path(abspath, GOT_ERR_BAD_PATH);
105 if (!got_path_is_root_dir(parent_abspath) && abspath[len_parent] != '/')
106 return got_error_path(abspath, GOT_ERR_BAD_PATH);
107 while (abspath[len_parent] == '/')
108 abspath++;
109 bufsize = len - len_parent + 1;
110 *child = malloc(bufsize);
111 if (*child == NULL)
112 return got_error_from_errno("malloc");
113 if (strlcpy(*child, abspath + len_parent, bufsize) >= bufsize) {
114 err = got_error_from_errno("strlcpy");
115 free(*child);
116 *child = NULL;
117 return err;
119 return NULL;
122 const struct got_error *
123 got_path_strip(char **out, const char *path, int n)
125 const char *p, *c;
127 p = path;
128 *out = NULL;
130 while (n > 0 && (c = strchr(p, '/')) != NULL) {
131 p = c + 1;
132 n--;
135 if (n > 0)
136 return got_error_fmt(GOT_ERR_BAD_PATH,
137 "can't strip %d path-components from %s", n, path);
139 if ((*out = strdup(p)) == NULL)
140 return got_error_from_errno("strdup");
141 return NULL;
145 got_path_is_root_dir(const char *path)
147 while (*path == '/')
148 path++;
149 return (*path == '\0');
153 got_path_is_child(const char *child, const char *parent, size_t parent_len)
155 if (parent_len == 0 || got_path_is_root_dir(parent))
156 return 1;
158 if (strncmp(parent, child, parent_len) != 0)
159 return 0;
160 if (child[parent_len] != '/')
161 return 0;
163 return 1;
167 got_path_cmp(const char *path1, const char *path2, size_t len1, size_t len2)
169 size_t min_len;
170 size_t i = 0;
172 /* Leading directory separators are insignificant. */
173 while (path1[0] == '/') {
174 path1++;
175 len1--;
177 while (path2[0] == '/') {
178 path2++;
179 len2--;
182 min_len = MIN(len1, len2);
184 /* Skip over common prefix. */
185 while (i < min_len && path1[i] == path2[i])
186 i++;
188 /* Are the paths exactly equal (besides path separators)? */
189 if (len1 == len2 && i >= min_len)
190 return 0;
192 /* Skip over redundant trailing path separators. */
193 while (path1[i] == '/' && path1[i + 1] == '/')
194 path1++;
195 while (path2[i] == '/' && path2[i + 1] == '/')
196 path2++;
198 /* Trailing path separators are insignificant. */
199 if (path1[i] == '/' && path1[i + 1] == '\0' && path2[i] == '\0')
200 return 0;
201 if (path2[i] == '/' && path2[i + 1] == '\0' && path1[i] == '\0')
202 return 0;
204 /* Order children in subdirectories directly after their parents. */
205 if (path1[i] == '/' && path2[i] == '\0')
206 return 1;
207 if (path2[i] == '/' && path1[i] == '\0')
208 return -1;
209 if (path1[i] == '/' && path2[i] != '\0')
210 return -1;
211 if (path2[i] == '/' && path1[i] != '\0')
212 return 1;
214 /* Next character following the common prefix determines order. */
215 return (unsigned char)path1[i] < (unsigned char)path2[i] ? -1 : 1;
218 const struct got_error *
219 got_pathlist_insert(struct got_pathlist_entry **inserted,
220 struct got_pathlist_head *pathlist, const char *path, void *data)
222 struct got_pathlist_entry *new, *pe;
223 size_t path_len = strlen(path);
225 if (inserted)
226 *inserted = NULL;
229 * Many callers will provide paths in a somewhat sorted order while
230 * constructing a path list from inputs such as tree objects or
231 * dirents. Iterating backwards from the tail of the list should
232 * be more efficient than traversing through the entire list each
233 * time an element is inserted.
235 pe = TAILQ_LAST(pathlist, got_pathlist_head);
236 while (pe) {
237 int cmp = got_path_cmp(pe->path, path, pe->path_len, path_len);
238 if (cmp == 0)
239 return NULL; /* duplicate */
240 else if (cmp < 0)
241 break;
242 pe = TAILQ_PREV(pe, got_pathlist_head, entry);
245 new = malloc(sizeof(*new));
246 if (new == NULL)
247 return got_error_from_errno("malloc");
248 new->path = path;
249 new->path_len = path_len;
250 new->data = data;
251 if (pe)
252 TAILQ_INSERT_AFTER(pathlist, pe, new, entry);
253 else
254 TAILQ_INSERT_HEAD(pathlist, new, entry);
255 if (inserted)
256 *inserted = new;
257 return NULL;
260 void
261 got_pathlist_free(struct got_pathlist_head *pathlist, int freemask)
263 struct got_pathlist_entry *pe;
265 while ((pe = TAILQ_FIRST(pathlist)) != NULL) {
266 if (freemask & GOT_PATHLIST_FREE_PATH) {
267 free((char *)pe->path);
268 pe->path = NULL;
270 if (freemask & GOT_PATHLIST_FREE_DATA) {
271 free(pe->data);
272 pe->data = NULL;
274 TAILQ_REMOVE(pathlist, pe, entry);
275 free(pe);
279 static const struct got_error *
280 make_parent_dirs(const char *abspath)
282 const struct got_error *err = NULL;
283 char *parent;
285 err = got_path_dirname(&parent, abspath);
286 if (err)
287 return err;
289 if (mkdir(parent, GOT_DEFAULT_DIR_MODE) == -1) {
290 if (errno == ENOENT) {
291 err = make_parent_dirs(parent);
292 if (err)
293 goto done;
294 if (mkdir(parent, GOT_DEFAULT_DIR_MODE) == -1) {
295 err = got_error_from_errno2("mkdir", parent);
296 goto done;
298 } else
299 err = got_error_from_errno2("mkdir", parent);
301 done:
302 free(parent);
303 return err;
306 const struct got_error *
307 got_path_mkdir(const char *abspath)
309 const struct got_error *err = NULL;
311 if (mkdir(abspath, GOT_DEFAULT_DIR_MODE) == -1) {
312 if (errno == ENOENT) {
313 err = make_parent_dirs(abspath);
314 if (err)
315 goto done;
316 if (mkdir(abspath, GOT_DEFAULT_DIR_MODE) == -1)
317 err = got_error_from_errno2("mkdir", abspath);
318 } else
319 err = got_error_from_errno2("mkdir", abspath);
322 done:
323 return err;
327 got_path_dir_is_empty(const char *dir)
329 DIR *d;
330 struct dirent *dent;
331 int empty = 1;
333 d = opendir(dir);
334 if (d == NULL)
335 return 1;
337 while ((dent = readdir(d)) != NULL) {
338 if (strcmp(dent->d_name, ".") == 0 ||
339 strcmp(dent->d_name, "..") == 0)
340 continue;
342 empty = 0;
343 break;
346 closedir(d);
347 return empty;
350 const struct got_error *
351 got_path_dirname(char **parent, const char *path)
353 char buf[PATH_MAX];
354 char *p;
356 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf))
357 return got_error(GOT_ERR_NO_SPACE);
359 p = dirname(buf);
360 if (p == NULL)
361 return got_error_from_errno2("dirname", path);
363 if (p[0] == '.' && p[1] == '\0')
364 return got_error_path(path, GOT_ERR_BAD_PATH);
366 *parent = strdup(p);
367 if (*parent == NULL)
368 return got_error_from_errno("strdup");
370 return NULL;
373 const struct got_error *
374 got_path_dirent_type(int *type, const char *path_parent, struct dirent *dent)
376 const struct got_error *err = NULL;
377 char *path_child;
378 struct stat sb;
380 if (dent->d_type != DT_UNKNOWN) {
381 *type = dent->d_type;
382 return NULL;
385 *type = DT_UNKNOWN;
388 * This is a fallback to accommodate filesystems which do not
389 * provide directory entry type information. DT_UNKNOWN directory
390 * entries occur on NFS mounts without "readdir plus" RPC.
393 if (asprintf(&path_child, "%s/%s", path_parent, dent->d_name) == -1)
394 return got_error_from_errno("asprintf");
396 if (lstat(path_child, &sb) == -1) {
397 err = got_error_from_errno2("lstat", path_child);
398 goto done;
401 if (S_ISFIFO(sb.st_mode))
402 *type = DT_FIFO;
403 else if (S_ISCHR(sb.st_mode))
404 *type = DT_CHR;
405 else if (S_ISDIR(sb.st_mode))
406 *type = DT_DIR;
407 else if (S_ISBLK(sb.st_mode))
408 *type = DT_BLK;
409 else if (S_ISLNK(sb.st_mode))
410 *type = DT_LNK;
411 else if (S_ISREG(sb.st_mode))
412 *type = DT_REG;
413 else if (S_ISSOCK(sb.st_mode))
414 *type = DT_SOCK;
415 done:
416 free(path_child);
417 return err;
420 const struct got_error *
421 got_path_basename(char **s, const char *path)
423 char buf[PATH_MAX];
424 char *base;
426 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf))
427 return got_error(GOT_ERR_NO_SPACE);
429 base = basename(buf);
430 if (base == NULL)
431 return got_error_from_errno2("basename", path);
433 *s = strdup(base);
434 if (*s == NULL)
435 return got_error_from_errno("strdup");
437 return NULL;
440 void
441 got_path_strip_trailing_slashes(char *path)
443 size_t x;
445 x = strlen(path);
446 while (x-- > 0 && path[x] == '/')
447 path[x] = '\0';
450 /* based on findprog() from usr.bin/which/which.c */
451 const struct got_error *
452 got_path_find_prog(char **filename, const char *prog)
454 const struct got_error *err = NULL;
455 const char *path;
456 char *p;
457 int len;
458 struct stat sbuf;
459 char *pathcpy, *dup = NULL;
461 *filename = NULL;
463 path = getenv("PATH");
464 if (path == NULL)
465 path = _PATH_DEFPATH;
467 /* Special case if prog contains '/' */
468 if (strchr(prog, '/')) {
469 if ((stat(prog, &sbuf) == 0) && S_ISREG(sbuf.st_mode) &&
470 access(prog, X_OK) == 0) {
471 *filename = strdup(prog);
472 if (*filename == NULL)
473 return got_error_from_errno("strdup");
475 return NULL;
478 if ((dup = strdup(path)) == NULL)
479 return got_error_from_errno("strdup");
480 pathcpy = dup;
482 while ((p = strsep(&pathcpy, ":")) != NULL) {
483 const char *d;
485 len = strlen(p);
486 while (len > 0 && p[len-1] == '/')
487 p[--len] = '\0'; /* strip trailing '/' */
489 d = p;
490 if (*d == '\0')
491 d = ".";
493 if (asprintf(filename, "%s/%s", d, prog) == -1) {
494 err = got_error_from_errno("asprintf");
495 break;
497 if ((stat(*filename, &sbuf) == 0) && S_ISREG(sbuf.st_mode) &&
498 access(*filename, X_OK) == 0)
499 break;
500 free(*filename);
501 *filename = NULL;
503 free(dup);
504 return err;
507 const struct got_error *
508 got_path_create_file(const char *path, const char *content)
510 const struct got_error *err = NULL;
511 int fd = -1;
513 fd = open(path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC,
514 GOT_DEFAULT_FILE_MODE);
515 if (fd == -1) {
516 err = got_error_from_errno2("open", path);
517 goto done;
520 if (content) {
521 int len = dprintf(fd, "%s\n", content);
522 if (len != strlen(content) + 1) {
523 err = got_error_from_errno("dprintf");
524 goto done;
528 done:
529 if (fd != -1 && close(fd) == -1 && err == NULL)
530 err = got_error_from_errno("close");
531 return err;
534 const struct got_error *
535 got_path_move_file(const char *oldpath, const char *newpath)
537 const struct got_error *err;
539 if (rename(oldpath, newpath) != -1)
540 return NULL;
542 if (errno != ENOENT)
543 return got_error_from_errno3("rename", oldpath, newpath);
545 err = make_parent_dirs(newpath);
546 if (err)
547 return err;
549 if (rename(oldpath, newpath) == -1)
550 return got_error_from_errno3("rename", oldpath, newpath);
552 return NULL;