13 #ifndef __STOUT_NET_HPP__
14 #define __STOUT_NET_HPP__
25 #include <arpa/inet.h>
30 #include <net/if_dl.h>
31 #include <net/if_types.h>
41 #include <sys/param.h>
44 #include <curl/curl.h>
90 curl_global_init(CURL_GLOBAL_ALL);
106 CURL* curl = curl_easy_init();
107 if (curl ==
nullptr) {
108 curl_easy_cleanup(curl);
109 return Error(
"Failed to initialize libcurl");
112 curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
113 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION,
true);
114 curl_easy_setopt(curl, CURLOPT_HEADER, 1);
115 curl_easy_setopt(curl, CURLOPT_NOBODY, 1);
117 CURLcode curlErrorCode = curl_easy_perform(curl);
118 if (curlErrorCode != 0) {
119 curl_easy_cleanup(curl);
120 return Error(curl_easy_strerror(curlErrorCode));
124 curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &result);
126 curl_easy_cleanup(curl);
129 return Error(
"No URL content-length available");
132 return Bytes(uint64_t(result));
152 CURL* curl = curl_easy_init();
154 if (curl ==
nullptr) {
155 curl_easy_cleanup(curl);
157 return Error(
"Failed to initialize libcurl");
160 curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
161 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
nullptr);
162 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION,
true);
168 FILE*
file = ::_fdopen(fd->crt(),
"wb");
170 FILE* file = ::fdopen(fd.
get(),
"w");
172 if (file ==
nullptr) {
173 curl_easy_cleanup(curl);
175 return ErrnoError(
"Failed to open file handle of '" + path +
"'");
177 curl_easy_setopt(curl, CURLOPT_WRITEDATA, file);
179 CURLcode curlErrorCode = curl_easy_perform(curl);
180 if (curlErrorCode != 0) {
181 curl_easy_cleanup(curl);
183 return Error(curl_easy_strerror(curlErrorCode));
187 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
188 curl_easy_cleanup(curl);
190 if (fclose(file) != 0) {
191 return ErrnoError(
"Failed to close file handle of '" + path +
"'");
199 #endif // __STOUT_NET_HPP__
#define O_WRONLY
Definition: fcntl.hpp:26
Definition: errorbase.hpp:35
const mode_t S_IRGRP
Definition: windows.hpp:319
#define O_CLOEXEC
Definition: fcntl.hpp:31
const mode_t S_IWUSR
Definition: windows.hpp:312
Definition: errorbase.hpp:49
#define O_CREAT
Definition: fcntl.hpp:28
const mode_t S_IRUSR
Definition: windows.hpp:311
void initialize()
Definition: net.hpp:74
URI file(const std::string &path)
Creates a file URI with the given path on the local host.
Definition: file.hpp:33
Try< Nothing > close(int fd)
Definition: close.hpp:24
Try< int > download(const std::string &url, const std::string &path)
Definition: net.hpp:139
static Try error(const E &e)
Definition: try.hpp:42
static Try some(const T &t)
Definition: try.hpp:41
bool isError() const
Definition: try.hpp:71
Try< int_fd > open(const std::string &path, int oflag, mode_t mode=0)
Definition: open.hpp:39
Try< Bytes > contentLength(const std::string &url)
Definition: net.hpp:102
const mode_t S_IROTH
Definition: windows.hpp:327
const T & get() const
Definition: try.hpp:73