Blob


1 /*
2 * Copyright (c) 2018 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <limits.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <stdio.h>
21 #include <string.h>
23 #include "got_path_priv.h"
25 int
26 got_path_is_absolute(const char *path)
27 {
28 return path[0] == '/';
29 }
31 char *
32 got_path_get_absolute(const char *relpath)
33 {
34 char cwd[PATH_MAX];
35 char *abspath;
37 if (getcwd(cwd, sizeof(cwd)) == NULL)
38 return NULL;
40 if (asprintf(&abspath, "%s/%s/", cwd, relpath) == -1)
41 return NULL;
43 return abspath;
44 }
46 char *
47 got_path_normalize(const char *path)
48 {
49 char *resolved;
51 resolved = realpath(path, NULL);
52 if (resolved == NULL)
53 return NULL;
55 if (!got_path_is_absolute(resolved)) {
56 char *abspath = got_path_get_absolute(resolved);
57 free(resolved);
58 resolved = abspath;
59 }
61 return resolved;
62 }
64 FILE *
65 got_opentemp(void)
66 {
67 char name[PATH_MAX];
68 int fd;
69 FILE *f;
71 if (strlcpy(name, "/tmp/got.XXXXXXXX", sizeof(name)) >= sizeof(name))
72 return NULL;
74 fd = mkstemp(name);
75 if (fd < 0)
76 return NULL;
78 unlink(name);
79 f = fdopen(fd, "w+");
80 if (f == NULL) {
81 close(fd);
82 return NULL;
83 }
85 return f;
86 }