aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/utils/http_util/http_util.cpp
blob: f5f9c021329f4975c833e1b520f5fc4628e38146 (plain)
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/*
* Sketchy HTTP client
* (C) 2013,2016 Jack Lloyd
*     2017 René Korthaus, Rohde & Schwarz Cybersecurity
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/http_util.h>
#include <botan/parsing.h>
#include <botan/hex.h>
#include <botan/internal/os_utils.h>
#include <botan/internal/socket.h>
#include <botan/internal/stl_util.h>
#include <sstream>

namespace Botan {

namespace HTTP {

namespace {

/*
* Connect to a host, write some bytes, then read until the server
* closes the socket.
*/
std::string http_transact(const std::string& hostname,
                          const std::string& message,
                          std::chrono::milliseconds timeout)
   {
   std::unique_ptr<OS::Socket> socket;

   const std::chrono::system_clock::time_point start_time = std::chrono::system_clock::now();

   try
      {
      socket = OS::open_socket(hostname, "http", timeout);
      if(!socket)
         throw Exception("No socket support enabled in build");
      }
   catch(std::exception& e)
      {
      throw HTTP_Error("HTTP connection to " + hostname + " failed: " + e.what());
      }

   // Blocks until entire message has been written
   socket->write(cast_char_ptr_to_uint8(message.data()),
                 message.size());

   if(std::chrono::system_clock::now() - start_time > timeout)
      throw HTTP_Error("Timeout during writing message body");

   std::ostringstream oss;
   std::vector<uint8_t> buf(BOTAN_DEFAULT_BUFFER_SIZE);
   while(true)
      {
      const size_t got = socket->read(buf.data(), buf.size());
      if(got == 0) // EOF
         break;

      if(std::chrono::system_clock::now() - start_time > timeout)
         throw HTTP_Error("Timeout while reading message body");

      oss.write(cast_uint8_ptr_to_char(buf.data()),
                static_cast<std::streamsize>(got));
      }

   return oss.str();
   }

}

std::string url_encode(const std::string& in)
   {
   std::ostringstream out;

   for(auto c : in)
      {
      if(c >= 'A' && c <= 'Z')
         out << c;
      else if(c >= 'a' && c <= 'z')
         out << c;
      else if(c >= '0' && c <= '9')
         out << c;
      else if(c == '-' || c == '_' || c == '.' || c == '~')
         out << c;
      else
         out << '%' << hex_encode(cast_char_ptr_to_uint8(&c), 1);
      }

   return out.str();
   }

std::ostream& operator<<(std::ostream& o, const Response& resp)
   {
   o << "HTTP " << resp.status_code() << " " << resp.status_message() << "\n";
   for(auto h : resp.headers())
      o << "Header '" << h.first << "' = '" << h.second << "'\n";
   o << "Body " << std::to_string(resp.body().size()) << " bytes:\n";
   o.write(cast_uint8_ptr_to_char(resp.body().data()), resp.body().size());
   return o;
   }

Response http_sync(http_exch_fn http_transact,
                   const std::string& verb,
                   const std::string& url,
                   const std::string& content_type,
                   const std::vector<uint8_t>& body,
                   size_t allowable_redirects)
   {
   if(url.empty())
      throw HTTP_Error("URL empty");

   const auto protocol_host_sep = url.find("://");
   if(protocol_host_sep == std::string::npos)
      throw HTTP_Error("Invalid URL '" + url + "'");

   const auto host_loc_sep = url.find('/', protocol_host_sep + 3);

   std::string hostname, loc;

   if(host_loc_sep == std::string::npos)
      {
      hostname = url.substr(protocol_host_sep + 3, std::string::npos);
      loc = "/";
      }
   else
      {
      hostname = url.substr(protocol_host_sep + 3, host_loc_sep-protocol_host_sep-3);
      loc = url.substr(host_loc_sep, std::string::npos);
      }

   std::ostringstream outbuf;

   outbuf << verb << " " << loc << " HTTP/1.0\r\n";
   outbuf << "Host: " << hostname << "\r\n";

   if(verb == "GET")
      {
      outbuf << "Accept: */*\r\n";
      outbuf << "Cache-Control: no-cache\r\n";
      }
   else if(verb == "POST")
      outbuf << "Content-Length: " << body.size() << "\r\n";

   if(!content_type.empty())
      outbuf << "Content-Type: " << content_type << "\r\n";
   outbuf << "Connection: close\r\n\r\n";
   outbuf.write(cast_uint8_ptr_to_char(body.data()), body.size());

   std::istringstream io(http_transact(hostname, outbuf.str()));

   std::string line1;
   std::getline(io, line1);
   if(!io || line1.empty())
      throw HTTP_Error("No response");

   std::stringstream response_stream(line1);
   std::string http_version;
   unsigned int status_code;
   std::string status_message;

   response_stream >> http_version >> status_code;

   std::getline(response_stream, status_message);

   if(!response_stream || http_version.substr(0,5) != "HTTP/")
      throw HTTP_Error("Not an HTTP response");

   std::map<std::string, std::string> headers;
   std::string header_line;
   while (std::getline(io, header_line) && header_line != "\r")
      {
      auto sep = header_line.find(": ");
      if(sep == std::string::npos || sep > header_line.size() - 2)
         throw HTTP_Error("Invalid HTTP header " + header_line);
      const std::string key = header_line.substr(0, sep);

      if(sep + 2 < header_line.size() - 1)
         {
         const std::string val = header_line.substr(sep + 2, (header_line.size() - 1) - (sep + 2));
         headers[key] = val;
         }
      }

   if(status_code == 301 && headers.count("Location"))
      {
      if(allowable_redirects == 0)
         throw HTTP_Error("HTTP redirection count exceeded");
      return GET_sync(headers["Location"], allowable_redirects - 1);
      }

   std::vector<uint8_t> resp_body;
   std::vector<uint8_t> buf(4096);
   while(io.good())
      {
      io.read(cast_uint8_ptr_to_char(buf.data()), buf.size());
      resp_body.insert(resp_body.end(), buf.data(), &buf[io.gcount()]);
      }

   const std::string header_size = search_map(headers, std::string("Content-Length"));

   if(!header_size.empty())
      {
      if(resp_body.size() != to_u32bit(header_size))
         throw HTTP_Error("Content-Length disagreement, header says " +
                          header_size + " got " + std::to_string(resp_body.size()));
      }

   return Response(status_code, status_message, resp_body, headers);
   }

Response http_sync(const std::string& verb,
                   const std::string& url,
                   const std::string& content_type,
                   const std::vector<uint8_t>& body,
                   size_t allowable_redirects,
                   std::chrono::milliseconds timeout)
   {
   auto transact_with_timeout =
      [timeout](const std::string& hostname, const std::string& service)
      {
      return http_transact(hostname, service, timeout);
      };

   return http_sync(
      transact_with_timeout,
      verb,
      url,
      content_type,
      body,
      allowable_redirects);
   }

Response GET_sync(const std::string& url,
                  size_t allowable_redirects,
                  std::chrono::milliseconds timeout)
   {
   return http_sync("GET", url, "", std::vector<uint8_t>(), allowable_redirects, timeout);
   }

Response POST_sync(const std::string& url,
                   const std::string& content_type,
                   const std::vector<uint8_t>& body,
                   size_t allowable_redirects,
                   std::chrono::milliseconds timeout)
   {
   return http_sync("POST", url, content_type, body, allowable_redirects, timeout);
   }

}

}