This repository has been archived by the owner on Dec 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.c
79 lines (69 loc) · 1.55 KB
/
init.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
#include <sys/sendfile.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <error.h>
#include <string.h>
static const char installdir[] = "/usr/local/bin/";
#define EFAIL EXIT_FAILURE
int main(int argc, char *argv[])
{
if (argc < 2)
{
error(EFAIL, 0, "missing file operand");
}
int out = -1;
{
size_t pathlen = sizeof(installdir) + strlen(argv[1]); // sizeof accounts NULL so we have room for newpath NULL
char *newpath = (char *)calloc(pathlen, sizeof(char));
if (!newpath)
{
error(EFAIL, 0, "unable to allocate memory");
}
snprintf(newpath, pathlen, "%s%s", installdir, argv[1]);
newpath[pathlen - 1] = '\0'; // Ensure it ends with NULL
out = creat(newpath, 0777);
free(newpath);
newpath = NULL;
if (out == -1)
{
if (errno == EACCES)
{
error(EFAIL, errno, "not in root");
}
else
{
error(EFAIL, errno, "failed to create a file in %s", installdir);
}
}
}
int in = open(argv[1], O_RDONLY);
if (in == -1)
{
error(EFAIL, errno, "failed to access file \"%s\"", argv[1]);
}
{
struct stat statbuf;
if (fstat(in, &statbuf) == -1)
{
error(EFAIL, errno, "failed to read file size");
}
if (sendfile(out, in, NULL, statbuf.st_size) == -1)
{
error(EFAIL, errno, "failed to copy the file");
}
}
if (close(in) == -1)
{
error(EFAIL, errno, "failed to close the file");
}
if (close(out) == -1)
{
error(EFAIL, errno, "failed to close the file");
}
printf("globalize: installed %s\n", argv[1]);
return EXIT_SUCCESS;
}