-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathfile.c
73 lines (58 loc) · 1.31 KB
/
file.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <myst/eraise.h>
#include <myst/file.h>
#include <myst/strings.h>
int myst_write_file(const char* path, const void* data, size_t size)
{
int ret = 0;
int fd;
const uint8_t* p = (const uint8_t*)data;
size_t r = size;
ssize_t n;
if ((fd = open(path, O_CREAT | O_WRONLY | O_TRUNC, 0640)) < 0)
ERAISE(-errno);
while ((n = write(fd, p, r)) > 0)
{
p += n;
r -= n;
}
if (r != 0)
ERAISE(-EIO);
close(fd);
done:
return ret;
}
/* change owner to ${SUDO_UID}.${SUDO_GID} if possible */
int myst_chown_sudo_user(const char* path)
{
int ret = 0;
const char* sudo_uid;
const char* sudo_gid;
int uid = getuid();
int gid = getgid();
size_t found = 0;
if ((sudo_uid = getenv("SUDO_UID")))
{
ECHECK(myst_str2int(sudo_uid, &uid));
found++;
}
if ((sudo_gid = getenv("SUDO_GID")))
{
ECHECK(myst_str2int(sudo_gid, &gid));
found++;
}
if (found != 2)
goto done;
if (uid == 0 || gid == 0)
goto done;
if (chown(path, uid, gid) != 0)
ERAISE(-errno);
done:
return ret;
}