• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * nghttp2 - HTTP/2 C Library
3  *
4  * Copyright (c) 2016 Tatsuhiro Tsujikawa
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining
7  * a copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sublicense, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be
15  * included in all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24  */
25 #include "shrpx_api_downstream_connection.h"
26 
27 #include <sys/mman.h>
28 #include <fcntl.h>
29 #include <unistd.h>
30 #include <cstdlib>
31 
32 #include "shrpx_client_handler.h"
33 #include "shrpx_upstream.h"
34 #include "shrpx_downstream.h"
35 #include "shrpx_worker.h"
36 #include "shrpx_connection_handler.h"
37 #include "shrpx_log.h"
38 
39 namespace shrpx {
40 
41 namespace {
42 const auto backendconfig_endpoint = APIEndpoint{
43     "/api/v1beta1/backendconfig"_sr,
44     true,
45     (1 << API_METHOD_POST) | (1 << API_METHOD_PUT),
46     &APIDownstreamConnection::handle_backendconfig,
47 };
48 
49 const auto configrevision_endpoint = APIEndpoint{
50     "/api/v1beta1/configrevision"_sr,
51     true,
52     (1 << API_METHOD_GET),
53     &APIDownstreamConnection::handle_configrevision,
54 };
55 } // namespace
56 
57 namespace {
58 // The method string.  This must be same order of APIMethod.
59 constexpr StringRef API_METHOD_STRING[] = {
60     "GET"_sr,
61     "POST"_sr,
62     "PUT"_sr,
63 };
64 } // namespace
65 
APIDownstreamConnection(Worker * worker)66 APIDownstreamConnection::APIDownstreamConnection(Worker *worker)
67     : worker_(worker), api_(nullptr), fd_(-1), shutdown_read_(false) {}
68 
~APIDownstreamConnection()69 APIDownstreamConnection::~APIDownstreamConnection() {
70   if (fd_ != -1) {
71     close(fd_);
72   }
73 }
74 
attach_downstream(Downstream * downstream)75 int APIDownstreamConnection::attach_downstream(Downstream *downstream) {
76   if (LOG_ENABLED(INFO)) {
77     DCLOG(INFO, this) << "Attaching to DOWNSTREAM:" << downstream;
78   }
79 
80   downstream_ = downstream;
81 
82   return 0;
83 }
84 
detach_downstream(Downstream * downstream)85 void APIDownstreamConnection::detach_downstream(Downstream *downstream) {
86   if (LOG_ENABLED(INFO)) {
87     DCLOG(INFO, this) << "Detaching from DOWNSTREAM:" << downstream;
88   }
89   downstream_ = nullptr;
90 }
91 
send_reply(unsigned int http_status,APIStatusCode api_status,const StringRef & data)92 int APIDownstreamConnection::send_reply(unsigned int http_status,
93                                         APIStatusCode api_status,
94                                         const StringRef &data) {
95   shutdown_read_ = true;
96 
97   auto upstream = downstream_->get_upstream();
98 
99   auto &resp = downstream_->response();
100 
101   resp.http_status = http_status;
102 
103   auto &balloc = downstream_->get_block_allocator();
104 
105   StringRef api_status_str;
106 
107   switch (api_status) {
108   case APIStatusCode::SUCCESS:
109     api_status_str = "Success"_sr;
110     break;
111   case APIStatusCode::FAILURE:
112     api_status_str = "Failure"_sr;
113     break;
114   default:
115     assert(0);
116   }
117 
118   constexpr auto M1 = "{\"status\":\""_sr;
119   constexpr auto M2 = "\",\"code\":"_sr;
120   constexpr auto M3 = "}"_sr;
121 
122   // 3 is the number of digits in http_status, assuming it is 3 digits
123   // number.
124   auto buflen = M1.size() + M2.size() + M3.size() + data.size() +
125                 api_status_str.size() + 3;
126 
127   auto buf = make_byte_ref(balloc, buflen);
128   auto p = std::begin(buf);
129 
130   p = std::copy(std::begin(M1), std::end(M1), p);
131   p = std::copy(std::begin(api_status_str), std::end(api_status_str), p);
132   p = std::copy(std::begin(M2), std::end(M2), p);
133   p = util::utos(p, http_status);
134   p = std::copy(std::begin(data), std::end(data), p);
135   p = std::copy(std::begin(M3), std::end(M3), p);
136 
137   buf = buf.subspan(0, p - std::begin(buf));
138 
139   auto content_length = util::make_string_ref_uint(balloc, buf.size());
140 
141   resp.fs.add_header_token("content-length"_sr, content_length, false,
142                            http2::HD_CONTENT_LENGTH);
143 
144   switch (http_status) {
145   case 400:
146   case 405:
147   case 413:
148     resp.fs.add_header_token("connection"_sr, "close"_sr, false,
149                              http2::HD_CONNECTION);
150     break;
151   }
152 
153   if (upstream->send_reply(downstream_, buf.data(), buf.size()) != 0) {
154     return -1;
155   }
156 
157   return 0;
158 }
159 
160 namespace {
lookup_api(const StringRef & path)161 const APIEndpoint *lookup_api(const StringRef &path) {
162   switch (path.size()) {
163   case 26:
164     switch (path[25]) {
165     case 'g':
166       if (util::streq("/api/v1beta1/backendconfi"_sr, path, 25)) {
167         return &backendconfig_endpoint;
168       }
169       break;
170     }
171     break;
172   case 27:
173     switch (path[26]) {
174     case 'n':
175       if (util::streq("/api/v1beta1/configrevisio"_sr, path, 26)) {
176         return &configrevision_endpoint;
177       }
178       break;
179     }
180     break;
181   }
182   return nullptr;
183 }
184 } // namespace
185 
push_request_headers()186 int APIDownstreamConnection::push_request_headers() {
187   auto &req = downstream_->request();
188 
189   auto path =
190       StringRef{std::begin(req.path),
191                 std::find(std::begin(req.path), std::end(req.path), '?')};
192 
193   api_ = lookup_api(path);
194 
195   if (!api_) {
196     send_reply(404, APIStatusCode::FAILURE);
197 
198     return 0;
199   }
200 
201   switch (req.method) {
202   case HTTP_GET:
203     if (!(api_->allowed_methods & (1 << API_METHOD_GET))) {
204       error_method_not_allowed();
205       return 0;
206     }
207     break;
208   case HTTP_POST:
209     if (!(api_->allowed_methods & (1 << API_METHOD_POST))) {
210       error_method_not_allowed();
211       return 0;
212     }
213     break;
214   case HTTP_PUT:
215     if (!(api_->allowed_methods & (1 << API_METHOD_PUT))) {
216       error_method_not_allowed();
217       return 0;
218     }
219     break;
220   default:
221     error_method_not_allowed();
222     return 0;
223   }
224 
225   // This works with req.fs.content_length == -1
226   if (req.fs.content_length >
227       static_cast<int64_t>(get_config()->api.max_request_body)) {
228     send_reply(413, APIStatusCode::FAILURE);
229 
230     return 0;
231   }
232 
233   switch (req.method) {
234   case HTTP_POST:
235   case HTTP_PUT: {
236     char tempname[] = "/tmp/nghttpx-api.XXXXXX";
237 #ifdef HAVE_MKOSTEMP
238     fd_ = mkostemp(tempname, O_CLOEXEC);
239 #else  // !HAVE_MKOSTEMP
240     fd_ = mkstemp(tempname);
241 #endif // !HAVE_MKOSTEMP
242     if (fd_ == -1) {
243       send_reply(500, APIStatusCode::FAILURE);
244 
245       return 0;
246     }
247 #ifndef HAVE_MKOSTEMP
248     util::make_socket_closeonexec(fd_);
249 #endif // HAVE_MKOSTEMP
250     unlink(tempname);
251     break;
252   }
253   }
254 
255   downstream_->set_request_header_sent(true);
256   auto src = downstream_->get_blocked_request_buf();
257   auto dest = downstream_->get_request_buf();
258   src->remove(*dest);
259 
260   return 0;
261 }
262 
error_method_not_allowed()263 int APIDownstreamConnection::error_method_not_allowed() {
264   auto &resp = downstream_->response();
265 
266   size_t len = 0;
267   for (uint8_t i = 0; i < API_METHOD_MAX; ++i) {
268     if (api_->allowed_methods & (1 << i)) {
269       // The length of method + ", "
270       len += API_METHOD_STRING[i].size() + 2;
271     }
272   }
273 
274   assert(len > 0);
275 
276   auto &balloc = downstream_->get_block_allocator();
277 
278   auto iov = make_byte_ref(balloc, len + 1);
279   auto p = std::begin(iov);
280   for (uint8_t i = 0; i < API_METHOD_MAX; ++i) {
281     if (api_->allowed_methods & (1 << i)) {
282       auto &s = API_METHOD_STRING[i];
283       p = std::copy(std::begin(s), std::end(s), p);
284       p = std::copy_n(", ", 2, p);
285     }
286   }
287 
288   p -= 2;
289   *p = '\0';
290 
291   resp.fs.add_header_token("allow"_sr, StringRef{std::span{std::begin(iov), p}},
292                            false, -1);
293   return send_reply(405, APIStatusCode::FAILURE);
294 }
295 
push_upload_data_chunk(const uint8_t * data,size_t datalen)296 int APIDownstreamConnection::push_upload_data_chunk(const uint8_t *data,
297                                                     size_t datalen) {
298   if (shutdown_read_ || !api_->require_body) {
299     return 0;
300   }
301 
302   auto &req = downstream_->request();
303   auto &apiconf = get_config()->api;
304 
305   if (static_cast<size_t>(req.recv_body_length) > apiconf.max_request_body) {
306     send_reply(413, APIStatusCode::FAILURE);
307 
308     return 0;
309   }
310 
311   ssize_t nwrite;
312   while ((nwrite = write(fd_, data, datalen)) == -1 && errno == EINTR)
313     ;
314   if (nwrite == -1) {
315     auto error = errno;
316     LOG(ERROR) << "Could not write API request body: errno=" << error;
317     send_reply(500, APIStatusCode::FAILURE);
318 
319     return 0;
320   }
321 
322   // We don't have to call Upstream::resume_read() here, because
323   // request buffer is effectively unlimited.  Actually, we cannot
324   // call it here since it could recursively call this function again.
325 
326   return 0;
327 }
328 
end_upload_data()329 int APIDownstreamConnection::end_upload_data() {
330   if (shutdown_read_) {
331     return 0;
332   }
333 
334   return api_->handler(*this);
335 }
336 
handle_backendconfig()337 int APIDownstreamConnection::handle_backendconfig() {
338   auto &req = downstream_->request();
339 
340   if (req.recv_body_length == 0) {
341     send_reply(200, APIStatusCode::SUCCESS);
342 
343     return 0;
344   }
345 
346   auto rp = mmap(nullptr, req.recv_body_length, PROT_READ, MAP_SHARED, fd_, 0);
347   if (rp == reinterpret_cast<void *>(-1)) {
348     send_reply(500, APIStatusCode::FAILURE);
349     return 0;
350   }
351 
352   auto unmapper = defer(munmap, rp, req.recv_body_length);
353 
354   Config new_config{};
355   new_config.conn.downstream = std::make_shared<DownstreamConfig>();
356   const auto &downstreamconf = new_config.conn.downstream;
357 
358   auto config = get_config();
359   auto &src = config->conn.downstream;
360 
361   downstreamconf->timeout = src->timeout;
362   downstreamconf->connections_per_host = src->connections_per_host;
363   downstreamconf->connections_per_frontend = src->connections_per_frontend;
364   downstreamconf->request_buffer_size = src->request_buffer_size;
365   downstreamconf->response_buffer_size = src->response_buffer_size;
366   downstreamconf->family = src->family;
367 
368   std::set<StringRef> include_set;
369   std::map<StringRef, size_t> pattern_addr_indexer;
370 
371   for (auto first = reinterpret_cast<const uint8_t *>(rp),
372             last = first + req.recv_body_length;
373        first != last;) {
374     auto eol = std::find(first, last, '\n');
375     if (eol == last) {
376       break;
377     }
378 
379     if (first == eol || *first == '#') {
380       first = ++eol;
381       continue;
382     }
383 
384     auto eq = std::find(first, eol, '=');
385     if (eq == eol) {
386       send_reply(400, APIStatusCode::FAILURE);
387       return 0;
388     }
389 
390     auto opt = StringRef{std::span{first, eq}};
391     auto optval = StringRef{std::span{eq + 1, eol}};
392 
393     auto optid = option_lookup_token(opt);
394 
395     switch (optid) {
396     case SHRPX_OPTID_BACKEND:
397       break;
398     default:
399       first = ++eol;
400       continue;
401     }
402 
403     if (parse_config(&new_config, optid, opt, optval, include_set,
404                      pattern_addr_indexer) != 0) {
405       send_reply(400, APIStatusCode::FAILURE);
406       return 0;
407     }
408 
409     first = ++eol;
410   }
411 
412   auto &tlsconf = config->tls;
413   if (configure_downstream_group(&new_config, config->http2_proxy, true,
414                                  tlsconf) != 0) {
415     send_reply(400, APIStatusCode::FAILURE);
416     return 0;
417   }
418 
419   auto conn_handler = worker_->get_connection_handler();
420 
421   conn_handler->send_replace_downstream(downstreamconf);
422 
423   send_reply(200, APIStatusCode::SUCCESS);
424 
425   return 0;
426 }
427 
handle_configrevision()428 int APIDownstreamConnection::handle_configrevision() {
429   auto config = get_config();
430   auto &balloc = downstream_->get_block_allocator();
431 
432   // Construct the following string:
433   //   ,
434   //   "data":{
435   //     "configRevision": N
436   //   }
437   auto data = concat_string_ref(
438       balloc, R"(,"data":{"configRevision":)"_sr,
439       util::make_string_ref_uint(balloc, config->config_revision), "}"_sr);
440 
441   send_reply(200, APIStatusCode::SUCCESS, data);
442 
443   return 0;
444 }
445 
pause_read(IOCtrlReason reason)446 void APIDownstreamConnection::pause_read(IOCtrlReason reason) {}
447 
resume_read(IOCtrlReason reason,size_t consumed)448 int APIDownstreamConnection::resume_read(IOCtrlReason reason, size_t consumed) {
449   return 0;
450 }
451 
force_resume_read()452 void APIDownstreamConnection::force_resume_read() {}
453 
on_read()454 int APIDownstreamConnection::on_read() { return 0; }
455 
on_write()456 int APIDownstreamConnection::on_write() { return 0; }
457 
on_upstream_change(Upstream * upstream)458 void APIDownstreamConnection::on_upstream_change(Upstream *upstream) {}
459 
poolable() const460 bool APIDownstreamConnection::poolable() const { return false; }
461 
462 const std::shared_ptr<DownstreamAddrGroup> &
get_downstream_addr_group() const463 APIDownstreamConnection::get_downstream_addr_group() const {
464   static std::shared_ptr<DownstreamAddrGroup> s;
465   return s;
466 }
467 
get_addr() const468 DownstreamAddr *APIDownstreamConnection::get_addr() const { return nullptr; }
469 
470 } // namespace shrpx
471