-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfs.c
87 lines (77 loc) · 1.72 KB
/
fs.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include "fs.h"
#include "config.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h> /* PATH_MAX */
#include <string.h>
#include <unistd.h>
#include "libks/arena-buffer.h"
#include "libks/buffer.h"
/*
* Search for the given filename starting at the current working directory and
* traverse upwards. Returns a file descriptor to the file if found, -1 otherwise.
* The optional nlevels argument reflects the number of directories traversed
* upwards.
*/
int
searchpath(const char *filename, int *nlevels)
{
struct stat sb;
dev_t dev = 0;
ino_t ino = 0;
int fd = -1;
int flags = O_RDONLY | O_CLOEXEC;
int i = 0;
int dirfd;
dirfd = open(".", flags | O_DIRECTORY);
if (dirfd == -1)
return -1;
if (fstat(dirfd, &sb) == -1)
goto out;
dev = sb.st_dev;
ino = sb.st_ino;
for (;;) {
fd = openat(dirfd, filename, flags);
if (fd >= 0)
break;
fd = openat(dirfd, "..", flags | O_DIRECTORY);
close(dirfd);
dirfd = fd;
fd = -1;
if (dirfd == -1)
break;
if (fstat(dirfd, &sb) == -1)
break;
if (dev == sb.st_dev && ino == sb.st_ino)
break;
dev = sb.st_dev;
ino = sb.st_ino;
i++;
}
out:
if (dirfd != -1)
close(dirfd);
if (fd != -1 && nlevels != NULL)
*nlevels = i;
return fd;
}
/*
* Transform the given path into a mkstemp(3) compatible template.
* The temporary file will reside in the same directory as a "hidden" file.
*/
char *
tmptemplate(const char *path, struct arena_scope *s)
{
struct buffer *bf;
const char *basename, *p;
bf = arena_buffer_alloc(s, PATH_MAX);
p = strrchr(path, '/');
if (p != NULL) {
buffer_puts(bf, path, (size_t)(&p[1] - path));
basename = &p[1];
} else {
basename = path;
}
buffer_printf(bf, ".%s.XXXXXXXX", basename);
return buffer_str(bf);
}