-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
94 lines (75 loc) · 2.76 KB
/
main.cpp
File metadata and controls
94 lines (75 loc) · 2.76 KB
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
88
89
90
91
92
93
94
#include <iostream>
#include <sstream>
#include <cstdint>
#include <cstring>
#include <cerrno>
#include <curl/curl.h>
#include "version.h"
// TODO: improve performance, see: https://ec.haxx.se/libcurl/performance.html
// TODO: set buffer size according to the given file
// see: CURLOPT_BUFFERSIZE, CURL_MAX_READ_SIZE
// TODO: add arg to enable verbosity, see: CURLOPT_VERBOSE
// TODO: provide a way to add user certs: https://ec.haxx.se/transfers/options/tls.html
// TODO: make out-file optional, use file name in url instead
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cerr << "Missing arguments!\n";
std::cout << "Usage: " << argv[0] << " <url> <out-file>\n\n"
<< " <url> url of file to download\n\n"
<< " <out-file> path to save the file to\n";
return 1;
}
std::string url{argv[1]};
std::string outFile{argv[2]};
CURL* curl = curl_easy_init();
char errbuf[CURL_ERROR_SIZE];
errbuf[0] = 0;
CURLcode ret = CURLE_OK;
bool isOK = true;
FILE* outFileFp = NULL;
curl_version_info_data *curlVersionInfo = curl_version_info(CURLVERSION_NOW);
std::stringstream agent;
agent << argv[0] << '/'
<< VERSION_MAJOR << '.'
<< VERSION_MINOR << '.'
<< VERSION_PATCH;
std::cout << "user agent: " << agent.str() << '\n';
std::cout << "using curl version: " << curlVersionInfo->version << '\n'
<< "attempt to download " << url << '\n';
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
curl_easy_setopt(curl, CURLOPT_USERAGENT, agent.str().c_str());
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 50L);
curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
outFileFp = std::fopen(outFile.c_str(), "wb");
if (outFileFp == NULL) {
std::cerr << "failed to open file: " << std::strerror(errno) << '\n';
isOK = false;
goto cleanup;
}
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, outFileFp);
ret = curl_easy_perform(curl);
isOK = ret == CURLE_OK;
if (isOK) {
std::cout << "written file to " << outFile << '\n';
} else {
if (errbuf[0] != 0) {
std::cerr << "error: " << errbuf << '\n';
} else {
std::cerr << "error: " << curl_easy_strerror(ret) << '\n';
}
}
cleanup:
if (outFileFp != NULL) {
std::fclose(outFileFp);
outFileFp = NULL;
}
if (curl != NULL) {
curl_easy_cleanup(curl);
curl = NULL;
}
return isOK ? 0 : 1;
}