-
Notifications
You must be signed in to change notification settings - Fork 0
/
fexecve-from-url.c
82 lines (64 loc) · 1.79 KB
/
fexecve-from-url.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
/*
* example:
* fexecve-from-url http://host/ELF [args]
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/syscall.h>
#include <curl/curl.h>
#ifndef MFD_CLOEXEC
#define MFD_CLOEXEC 0x0001U
#endif
static inline int memfd_create(const char *name, unsigned int flags) {
return syscall(__NR_memfd_create, name, flags);
}
static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
size_t n = fwrite(ptr, size, nmemb, (FILE *)stream);
return n;
}
int main(int argc, char *argv[], char *envp[]) {
int memfd;
int result;
CURLcode curlres;
CURL *handle;
FILE *fp;
if (!argv[1]) {
fprintf(stderr, "usage: %s <url>\n", argv[0]);
return EXIT_FAILURE;
}
memfd = memfd_create("asdf", MFD_CLOEXEC);
fp = fdopen(memfd, "wb");
if (fp == NULL) {
fprintf(stderr, "fdopen(): %s\n", strerror(errno));
return EXIT_FAILURE;
}
curl_global_init(CURL_GLOBAL_ALL);
handle = curl_easy_init();
curl_easy_setopt(handle, CURLOPT_URL, argv[1]);
curl_easy_setopt(handle, CURLOPT_VERBOSE, 0L); // Set to 1L for debugging
curl_easy_setopt(handle, CURLOPT_NOPROGRESS, 1L);
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, fp);
curl_easy_setopt(handle, CURLOPT_FAILONERROR, 1L);
curlres = curl_easy_perform(handle);
if (curlres != CURLE_OK) {
fprintf(stderr, "Download failed.");
return EXIT_FAILURE;
}
curl_easy_cleanup(handle);
curl_global_cleanup();
// remove argv[1] so we can pass arguments after the URL
char *newargv[argc - 1];
int i;
newargv[0] = argv[0];
for(i = 2; i < argc; i++)
newargv[i - 1] = argv[i];
result = fexecve(memfd, newargv, envp);
close(memfd);
fclose(fp);
return result;
}