LLVM 23.0.0git
HTTPClient.cpp
Go to the documentation of this file.
1//===--- HTTPClient.cpp - HTTP client library -----------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file defines the implementation of the HTTPClient library for issuing
11/// HTTP requests and handling the responses.
12///
13//===----------------------------------------------------------------------===//
14
16
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/Support/Errc.h"
20#include "llvm/Support/Error.h"
23#ifdef LLVM_ENABLE_CURL
24#include <curl/curl.h>
25#endif
26
27using namespace llvm;
28
30
31bool operator==(const HTTPRequest &A, const HTTPRequest &B) {
32 return A.Url == B.Url && A.Method == B.Method &&
33 A.FollowRedirects == B.FollowRedirects;
34}
35
37
38bool HTTPClient::IsInitialized = false;
39
45
46#ifdef LLVM_ENABLE_CURL
47
48bool HTTPClient::isAvailable() { return true; }
49
51 if (!IsInitialized) {
52 curl_global_init(CURL_GLOBAL_ALL);
53 IsInitialized = true;
54 }
55}
56
58 if (IsInitialized) {
59 curl_global_cleanup();
60 IsInitialized = false;
61 }
62}
63
64void HTTPClient::setTimeout(std::chrono::milliseconds Timeout) {
65 if (Timeout < std::chrono::milliseconds(0))
66 Timeout = std::chrono::milliseconds(0);
67 curl_easy_setopt(Curl, CURLOPT_TIMEOUT_MS, Timeout.count());
68}
69
70/// CurlHTTPRequest and the curl{Header,Write}Function are implementation
71/// details used to work with Curl. Curl makes callbacks with a single
72/// customizable pointer parameter.
73struct CurlHTTPRequest {
74 CurlHTTPRequest(HTTPResponseHandler &Handler) : Handler(Handler) {}
75 void storeError(Error Err) {
76 ErrorState = joinErrors(std::move(Err), std::move(ErrorState));
77 }
78 HTTPResponseHandler &Handler;
79 llvm::Error ErrorState = Error::success();
80};
81
82static size_t curlWriteFunction(char *Contents, size_t Size, size_t NMemb,
83 CurlHTTPRequest *CurlRequest) {
84 Size *= NMemb;
85 if (Error Err =
86 CurlRequest->Handler.handleBodyChunk(StringRef(Contents, Size))) {
87 CurlRequest->storeError(std::move(Err));
88 return 0;
89 }
90 return Size;
91}
92
95 "Must call HTTPClient::initialize() at the beginning of main().");
96 if (Curl)
97 return;
98 Curl = curl_easy_init();
99 assert(Curl && "Curl could not be initialized");
100 // Set the callback hooks.
101 curl_easy_setopt(Curl, CURLOPT_WRITEFUNCTION, curlWriteFunction);
102 // Detect supported compressed encodings and accept all.
103 curl_easy_setopt(Curl, CURLOPT_ACCEPT_ENCODING, "");
104}
105
106HTTPClient::~HTTPClient() { curl_easy_cleanup(Curl); }
107
109 HTTPResponseHandler &Handler) {
110 if (Request.Method != HTTPMethod::GET)
112 "Unsupported CURL request method.");
113
114 SmallString<128> Url = Request.Url;
115 curl_easy_setopt(Curl, CURLOPT_URL, Url.c_str());
116 curl_easy_setopt(Curl, CURLOPT_FOLLOWLOCATION, Request.FollowRedirects);
117
118 curl_slist *Headers = nullptr;
119 for (const std::string &Header : Request.Headers)
120 Headers = curl_slist_append(Headers, Header.c_str());
121 curl_easy_setopt(Curl, CURLOPT_HTTPHEADER, Headers);
122
123 CurlHTTPRequest CurlRequest(Handler);
124 curl_easy_setopt(Curl, CURLOPT_WRITEDATA, &CurlRequest);
125 CURLcode CurlRes = curl_easy_perform(Curl);
126 curl_slist_free_all(Headers);
127 if (CurlRes != CURLE_OK)
128 return joinErrors(std::move(CurlRequest.ErrorState),
130 "curl_easy_perform() failed: %s\n",
131 curl_easy_strerror(CurlRes)));
132 return std::move(CurlRequest.ErrorState);
133}
134
135unsigned HTTPClient::responseCode() {
136 long Code = 0;
137 curl_easy_getinfo(Curl, CURLINFO_RESPONSE_CODE, &Code);
138 return Code;
139}
140
141#else
142
143HTTPClient::HTTPClient() = default;
144
145HTTPClient::~HTTPClient() = default;
146
147bool HTTPClient::isAvailable() { return false; }
148
150
152
153void HTTPClient::setTimeout(std::chrono::milliseconds Timeout) {}
154
156 HTTPResponseHandler &Handler) {
157 llvm_unreachable("No HTTP Client implementation available.");
158}
159
161 llvm_unreachable("No HTTP Client implementation available.");
162}
163
164#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
ManagedStatic< HTTPClientCleanup > Cleanup
This file contains the declarations of the HTTPClient library for issuing HTTP requests and handling ...
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
static bool isAvailable()
Returns true only if LLVM has been compiled with a working HTTPClient.
static bool IsInitialized
Definition HTTPClient.h:62
unsigned responseCode()
Returns the last received response code or zero if none.
static void initialize()
Must be called at the beginning of a program, while it is a single thread.
Error perform(const HTTPRequest &Request, HTTPResponseHandler &Handler)
Performs the Request, passing response data to the Handler.
void setTimeout(std::chrono::milliseconds Timeout)
Sets the timeout for the entire request, in milliseconds.
static void cleanup()
Must be called at the end of a program, while it is a single thread.
A handler for state updates occurring while an HTTPRequest is performed.
Definition HTTPClient.h:43
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
const char * c_str()
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
NodeAddr< CodeNode * > Code
Definition RDFGraph.h:388
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1305
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
@ io_error
Definition Errc.h:58
@ invalid_argument
Definition Errc.h:56
Error joinErrors(Error E1, Error E2)
Concatenate errors.
Definition Error.h:442
@ Timeout
Reached timeout while waiting for the owner to release the lock.
A stateless description of an outbound HTTP request.
Definition HTTPClient.h:30
SmallVector< std::string, 0 > Headers
Definition HTTPClient.h:32
HTTPRequest(StringRef Url)
SmallString< 128 > Url
Definition HTTPClient.h:31
HTTPMethod Method
Definition HTTPClient.h:33