Coverage Report

Created: 2022-06-23 06:44

/src/botan/src/lib/utils/http_util/http_util.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
* Sketchy HTTP client
3
* (C) 2013,2016 Jack Lloyd
4
*     2017 René Korthaus, Rohde & Schwarz Cybersecurity
5
*
6
* Botan is released under the Simplified BSD License (see license.txt)
7
*/
8
9
#include <botan/internal/http_util.h>
10
#include <botan/internal/parsing.h>
11
#include <botan/hex.h>
12
#include <botan/internal/os_utils.h>
13
#include <botan/internal/socket.h>
14
#include <botan/internal/stl_util.h>
15
#include <sstream>
16
17
namespace Botan::HTTP {
18
19
namespace {
20
21
/*
22
* Connect to a host, write some bytes, then read until the server
23
* closes the socket.
24
*/
25
std::string http_transact(const std::string& hostname,
26
                          const std::string& service,
27
                          const std::string& message,
28
                          std::chrono::milliseconds timeout)
29
0
   {
30
0
   std::unique_ptr<OS::Socket> socket;
31
32
0
   const std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now();
33
34
0
   try
35
0
      {
36
0
      socket = OS::open_socket(hostname, service, timeout);
37
0
      if(!socket)
38
0
         throw Not_Implemented("No socket support enabled in build");
39
0
      }
40
0
   catch(std::exception& e)
41
0
      {
42
0
      throw HTTP_Error("HTTP connection to " + hostname + " failed: " + e.what());
43
0
      }
44
45
   // Blocks until entire message has been written
46
0
   socket->write(cast_char_ptr_to_uint8(message.data()),
47
0
                 message.size());
48
49
0
   if(std::chrono::system_clock::now() - start_time > timeout)
50
0
      throw HTTP_Error("Timeout during writing message body");
51
52
0
   std::ostringstream oss;
53
0
   std::vector<uint8_t> buf(BOTAN_DEFAULT_BUFFER_SIZE);
54
0
   while(true)
55
0
      {
56
0
      const size_t got = socket->read(buf.data(), buf.size());
57
0
      if(got == 0) // EOF
58
0
         break;
59
60
0
      if(std::chrono::system_clock::now() - start_time > timeout)
61
0
         throw HTTP_Error("Timeout while reading message body");
62
63
0
      oss.write(cast_uint8_ptr_to_char(buf.data()),
64
0
                static_cast<std::streamsize>(got));
65
0
      }
66
67
0
   return oss.str();
68
0
   }
69
70
bool needs_url_encoding(char c)
71
0
   {
72
0
   if(c >= 'A' && c <= 'Z')
73
0
      return false;
74
0
   if(c >= 'a' && c <= 'z')
75
0
      return false;
76
0
   if(c >= '0' && c <= '9')
77
0
      return false;
78
0
   if(c == '-' || c == '_' || c == '.' || c == '~')
79
0
      return false;
80
0
   return true;
81
0
   }
82
83
}
84
85
std::string url_encode(const std::string& in)
86
0
   {
87
0
   std::ostringstream out;
88
89
0
   for(auto c : in)
90
0
      {
91
0
      if(needs_url_encoding(c))
92
0
         out << '%' << hex_encode(cast_char_ptr_to_uint8(&c), 1);
93
0
      else
94
0
         out << c;
95
0
      }
96
97
0
   return out.str();
98
0
   }
99
100
std::ostream& operator<<(std::ostream& o, const Response& resp)
101
0
   {
102
0
   o << "HTTP " << resp.status_code() << " " << resp.status_message() << "\n";
103
0
   for(const auto& h : resp.headers())
104
0
      o << "Header '" << h.first << "' = '" << h.second << "'\n";
105
0
   o << "Body " << std::to_string(resp.body().size()) << " bytes:\n";
106
0
   o.write(cast_uint8_ptr_to_char(resp.body().data()), resp.body().size());
107
0
   return o;
108
0
   }
109
110
Response http_sync(const http_exch_fn& http_transact,
111
                   const std::string& verb,
112
                   const std::string& url,
113
                   const std::string& content_type,
114
                   const std::vector<uint8_t>& body,
115
                   size_t allowable_redirects)
116
0
   {
117
0
   if(url.empty())
118
0
      throw HTTP_Error("URL empty");
119
120
0
   const auto protocol_host_sep = url.find("://");
121
0
   if(protocol_host_sep == std::string::npos)
122
0
      throw HTTP_Error("Invalid URL '" + url + "'");
123
124
0
   const auto host_loc_sep = url.find('/', protocol_host_sep + 3);
125
126
0
   std::string hostname, loc, service;
127
128
0
   if(host_loc_sep == std::string::npos)
129
0
      {
130
0
      hostname = url.substr(protocol_host_sep + 3, std::string::npos);
131
0
      loc = "/";
132
0
      }
133
0
   else
134
0
      {
135
0
      hostname = url.substr(protocol_host_sep + 3, host_loc_sep-protocol_host_sep-3);
136
0
      loc = url.substr(host_loc_sep, std::string::npos);
137
0
      }
138
139
0
   const auto port_sep = hostname.find(':');
140
0
   if(port_sep == std::string::npos)
141
0
      {
142
0
      service = "http";
143
      // hostname not modified
144
0
      }
145
0
   else
146
0
      {
147
0
      service = hostname.substr(port_sep + 1, std::string::npos);
148
0
      hostname = hostname.substr(0, port_sep);
149
0
      }
150
151
0
   std::ostringstream outbuf;
152
153
0
   outbuf << verb << " " << loc << " HTTP/1.0\r\n";
154
0
   outbuf << "Host: " << hostname << "\r\n";
155
156
0
   if(verb == "GET")
157
0
      {
158
0
      outbuf << "Accept: */*\r\n";
159
0
      outbuf << "Cache-Control: no-cache\r\n";
160
0
      }
161
0
   else if(verb == "POST")
162
0
      outbuf << "Content-Length: " << body.size() << "\r\n";
163
164
0
   if(!content_type.empty())
165
0
      outbuf << "Content-Type: " << content_type << "\r\n";
166
0
   outbuf << "Connection: close\r\n\r\n";
167
0
   outbuf.write(cast_uint8_ptr_to_char(body.data()), body.size());
168
169
0
   std::istringstream io(http_transact(hostname, service, outbuf.str()));
170
171
0
   std::string line1;
172
0
   std::getline(io, line1);
173
0
   if(!io || line1.empty())
174
0
      throw HTTP_Error("No response");
175
176
0
   std::stringstream response_stream(line1);
177
0
   std::string http_version;
178
0
   unsigned int status_code;
179
0
   std::string status_message;
180
181
0
   response_stream >> http_version >> status_code;
182
183
0
   std::getline(response_stream, status_message);
184
185
0
   if(!response_stream || http_version.substr(0,5) != "HTTP/")
186
0
      throw HTTP_Error("Not an HTTP response");
187
188
0
   std::map<std::string, std::string> headers;
189
0
   std::string header_line;
190
0
   while (std::getline(io, header_line) && header_line != "\r")
191
0
      {
192
0
      auto sep = header_line.find(": ");
193
0
      if(sep == std::string::npos || sep > header_line.size() - 2)
194
0
         throw HTTP_Error("Invalid HTTP header " + header_line);
195
0
      const std::string key = header_line.substr(0, sep);
196
197
0
      if(sep + 2 < header_line.size() - 1)
198
0
         {
199
0
         const std::string val = header_line.substr(sep + 2, (header_line.size() - 1) - (sep + 2));
200
0
         headers[key] = val;
201
0
         }
202
0
      }
203
204
0
   if(status_code == 301 && headers.count("Location"))
205
0
      {
206
0
      if(allowable_redirects == 0)
207
0
         throw HTTP_Error("HTTP redirection count exceeded");
208
0
      return GET_sync(headers["Location"], allowable_redirects - 1);
209
0
      }
210
211
0
   std::vector<uint8_t> resp_body;
212
0
   std::vector<uint8_t> buf(4096);
213
0
   while(io.good())
214
0
      {
215
0
      io.read(cast_uint8_ptr_to_char(buf.data()), buf.size());
216
0
      const size_t got = static_cast<size_t>(io.gcount());
217
0
      resp_body.insert(resp_body.end(), buf.data(), &buf[got]);
218
0
      }
219
220
0
   const std::string header_size = search_map(headers, std::string("Content-Length"));
221
222
0
   if(!header_size.empty())
223
0
      {
224
0
      if(resp_body.size() != to_u32bit(header_size))
225
0
         throw HTTP_Error("Content-Length disagreement, header says " +
226
0
                          header_size + " got " + std::to_string(resp_body.size()));
227
0
      }
228
229
0
   return Response(status_code, status_message, resp_body, headers);
230
0
   }
231
232
Response http_sync(const std::string& verb,
233
                   const std::string& url,
234
                   const std::string& content_type,
235
                   const std::vector<uint8_t>& body,
236
                   size_t allowable_redirects,
237
                   std::chrono::milliseconds timeout)
238
0
   {
239
0
   auto transact_with_timeout =
240
0
      [timeout](const std::string& hostname, const std::string& service, const std::string& message)
241
0
      {
242
0
      return http_transact(hostname, service, message, timeout);
243
0
      };
244
245
0
   return http_sync(
246
0
      transact_with_timeout,
247
0
      verb,
248
0
      url,
249
0
      content_type,
250
0
      body,
251
0
      allowable_redirects);
252
0
   }
253
254
Response GET_sync(const std::string& url,
255
                  size_t allowable_redirects,
256
                  std::chrono::milliseconds timeout)
257
0
   {
258
0
   return http_sync("GET", url, "", std::vector<uint8_t>(), allowable_redirects, timeout);
259
0
   }
260
261
Response POST_sync(const std::string& url,
262
                   const std::string& content_type,
263
                   const std::vector<uint8_t>& body,
264
                   size_t allowable_redirects,
265
                   std::chrono::milliseconds timeout)
266
0
   {
267
0
   return http_sync("POST", url, content_type, body, allowable_redirects, timeout);
268
0
   }
269
270
}