summaryrefslogtreecommitdiffstats
path: root/apps/http-proxy/src/http_session.cc
blob: 760539fe041adb0851e6abbd58b4d81d34ebbdca (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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/*
 * Copyright (c) 2019 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "http_session.h"

#include <hicn/transport/utils/branch_prediction.h>
#include <hicn/transport/utils/log.h>

#include <iostream>

namespace transport {

HTTPSession::HTTPSession(asio::io_service &io_service, std::string &ip_address,
                         std::string &port,
                         ContentReceivedCallback receive_callback,
                         OnConnectionClosed on_connection_closed_callback,
                         bool client)
    : io_service_(io_service),
      socket_(io_service_),
      resolver_(io_service_),
      endpoint_iterator_(resolver_.resolve({ip_address, port})),
      timer_(io_service),
      reverse_(client),
      is_reconnection_(false),
      data_available_(false),
      content_length_(0),
      is_last_chunk_(false),
      chunked_(false),
      receive_callback_(receive_callback),
      on_connection_closed_callback_(on_connection_closed_callback) {
  input_buffer_.prepare(buffer_size + 2048);
  state_ = ConnectorState::CONNECTING;

  if (reverse_) {
    header_info_ = std::make_unique<RequestMetadata>();
  } else {
    header_info_ = std::make_unique<ResponseMetadata>();
  }

  doConnect();
}

HTTPSession::HTTPSession(asio::ip::tcp::socket socket,
                         ContentReceivedCallback receive_callback,
                         OnConnectionClosed on_connection_closed_callback,
                         bool client)
    :
#if ((ASIO_VERSION / 100 % 1000) < 12)
      io_service_(socket.get_io_service()),
#else
      io_service_((asio::io_context &)(socket.get_executor().context())),
#endif
      socket_(std::move(socket)),
      resolver_(io_service_),
      timer_(io_service_),
      reverse_(client),
      is_reconnection_(false),
      data_available_(false),
      content_length_(0),
      is_last_chunk_(false),
      chunked_(false),
      receive_callback_(receive_callback),
      on_connection_closed_callback_(on_connection_closed_callback) {
  input_buffer_.prepare(buffer_size + 2048);
  state_ = ConnectorState::CONNECTED;
  asio::ip::tcp::no_delay noDelayOption(true);
  socket_.set_option(noDelayOption);

  if (reverse_) {
    header_info_ = std::make_unique<RequestMetadata>();
  } else {
    header_info_ = std::make_unique<ResponseMetadata>();
  }
  doReadHeader();
}

HTTPSession::~HTTPSession() {}

void HTTPSession::send(const uint8_t *packet, std::size_t len,
                       ContentSentCallback &&content_sent) {
  io_service_.dispatch([this, packet, len, content_sent]() {
    asio::async_write(socket_, asio::buffer(packet, len),
                      [content_sent = std::move(content_sent)](
                          std::error_code ec, std::size_t /*length*/) {
                        if (!ec) {
                          content_sent();
                        }
                      });
  });
}

void HTTPSession::send(utils::MemBuf *buffer,
                       ContentSentCallback &&content_sent) {
  io_service_.dispatch([this, buffer, callback = std::move(content_sent)]() {
    bool write_in_progress = !write_msgs_.empty();
    write_msgs_.emplace_back(std::unique_ptr<utils::MemBuf>(buffer),
                             std::move(callback));
    if (TRANSPORT_EXPECT_TRUE(state_ == ConnectorState::CONNECTED)) {
      if (!write_in_progress) {
        doWrite();
      }
    } else {
      TRANSPORT_LOGD("Tell the handle connect it has data to write");
      data_available_ = true;
    }
  });
}

void HTTPSession::close() {
  if (state_ != ConnectorState::CLOSED) {
    state_ = ConnectorState::CLOSED;
    if (socket_.is_open()) {
      // socket_.shutdown(asio::ip::tcp::socket::shutdown_type::shutdown_both);
      socket_.close();
      // on_disconnect_callback_();
    }
  }
}

void HTTPSession::doWrite() {
  auto &buffer = write_msgs_.front().first;

  asio::async_write(socket_, asio::buffer(buffer->data(), buffer->length()),
                    [this](std::error_code ec, std::size_t length) {
                      if (TRANSPORT_EXPECT_FALSE(!ec)) {
                        TRANSPORT_LOGD("Content successfully sent! %zu",
                                       length);
                        write_msgs_.front().second();
                        write_msgs_.pop_front();
                        if (!write_msgs_.empty()) {
                          doWrite();
                        }
                      } else {
                        TRANSPORT_LOGD("Content NOT sent!");
                      }
                    });
}  // namespace transport

void HTTPSession::handleRead(std::error_code ec, std::size_t length) {
  if (TRANSPORT_EXPECT_TRUE(!ec)) {
    content_length_ -= length;
    const uint8_t *buffer =
        asio::buffer_cast<const uint8_t *>(input_buffer_.data());
    bool is_last = chunked_ ? (is_last_chunk_ ? !content_length_ : false)
                            : !content_length_;
    receive_callback_(buffer, input_buffer_.size(), is_last, false, nullptr);
    input_buffer_.consume(input_buffer_.size());

    if (!content_length_) {
      if (!chunked_ || is_last_chunk_) {
        doReadHeader();
      } else {
        doReadChunkedHeader();
      }
    } else {
      auto to_read =
          content_length_ >= buffer_size ? buffer_size : content_length_;
      asio::async_read(socket_, input_buffer_, asio::transfer_exactly(to_read),
                       std::bind(&HTTPSession::handleRead, this,
                                 std::placeholders::_1, std::placeholders::_2));
    }
  } else if (ec == asio::error::eof) {
    input_buffer_.consume(input_buffer_.size());
    tryReconnection();
  }
}

void HTTPSession::doReadBody(std::size_t body_size,
                             std::size_t additional_bytes) {
  auto bytes_to_read =
      body_size > additional_bytes ? (body_size - additional_bytes) : 0;

  auto to_read = bytes_to_read >= buffer_size
                     ? (buffer_size - input_buffer_.size())
                     : bytes_to_read;

  is_last_chunk_ = chunked_ && body_size == 5;

  if (to_read > 0) {
    content_length_ = bytes_to_read;
    asio::async_read(socket_, input_buffer_, asio::transfer_exactly(to_read),
                     std::bind(&HTTPSession::handleRead, this,
                               std::placeholders::_1, std::placeholders::_2));
  } else {
    if (body_size) {
      const uint8_t *buffer =
          asio::buffer_cast<const uint8_t *>(input_buffer_.data());
      receive_callback_(buffer, body_size, chunked_ ? is_last_chunk_ : !to_read,
                        false, nullptr);
      input_buffer_.consume(body_size);
    }

    if (!chunked_ || is_last_chunk_) {
      doReadHeader();
    } else {
      doReadChunkedHeader();
    }
  }
}

void HTTPSession::doReadChunkedHeader() {
  asio::async_read_until(
      socket_, input_buffer_, "\r\n",
      [this](std::error_code ec, std::size_t length) {
        if (TRANSPORT_EXPECT_TRUE(!ec)) {
          const uint8_t *buffer =
              asio::buffer_cast<const uint8_t *>(input_buffer_.data());
          std::size_t chunk_size =
              std::stoul(reinterpret_cast<const char *>(buffer), 0, 16) + 2 +
              length;
          auto additional_bytes = input_buffer_.size();
          doReadBody(chunk_size, additional_bytes);
        } else {
          input_buffer_.consume(input_buffer_.size());
          tryReconnection();
        }
      });
}

void HTTPSession::doReadHeader() {
  asio::async_read_until(
      socket_, input_buffer_, "\r\n\r\n",
      [this](std::error_code ec, std::size_t length) {
        if (TRANSPORT_EXPECT_TRUE(!ec)) {
          const uint8_t *buffer =
              asio::buffer_cast<const uint8_t *>(input_buffer_.data());
          HTTPMessageFastParser::getHeaders(buffer, length, reverse_,
                                            header_info_.get());

          auto &headers = header_info_->headers;

          // Try to get content length, if available
          auto it = headers.find(HTTPMessageFastParser::content_length);
          std::size_t size = 0;
          if (it != headers.end()) {
            size = std::stoull(it->second);
            chunked_ = false;
          } else {
            it = headers.find(HTTPMessageFastParser::transfer_encoding);
            if (it != headers.end() &&
                it->second.compare(HTTPMessageFastParser::chunked) == 0) {
              chunked_ = true;
            }
          }

          receive_callback_(buffer, length, !size && !chunked_, true,
                            header_info_.get());
          auto additional_bytes = input_buffer_.size() - length;
          input_buffer_.consume(length);

          if (!chunked_) {
            doReadBody(size, additional_bytes);
          } else {
            doReadChunkedHeader();
          }
        } else {
          input_buffer_.consume(input_buffer_.size());
          tryReconnection();
        }
      });
}

void HTTPSession::tryReconnection() {
  if (on_connection_closed_callback_(socket_)) {
    if (state_ == ConnectorState::CONNECTED) {
      TRANSPORT_LOGD("Connection lost. Trying to reconnect...\n");
      state_ = ConnectorState::CONNECTING;
      is_reconnection_ = true;
      io_service_.post([this]() {
        if (socket_.is_open()) {
          // socket_.shutdown(asio::ip::tcp::socket::shutdown_type::shutdown_both);
          socket_.close();
        }
        startConnectionTimer();
        doConnect();
      });
    }
  }
}

void HTTPSession::doConnect() {
  asio::async_connect(socket_, endpoint_iterator_,
                      [this](std::error_code ec, tcp::resolver::iterator) {
                        if (!ec) {
                          timer_.cancel();
                          state_ = ConnectorState::CONNECTED;

                          asio::ip::tcp::no_delay noDelayOption(true);
                          socket_.set_option(noDelayOption);

                          // on_reconnect_callback_();

                          doReadHeader();

                          if (data_available_ && !write_msgs_.empty()) {
                            data_available_ = false;
                            doWrite();
                          }

                          if (is_reconnection_) {
                            is_reconnection_ = false;
                            TRANSPORT_LOGD("Connection recovered!");
                          }

                        } else {
                          TRANSPORT_LOGE("Impossible to reconnect: %s",
                                         ec.message().c_str());
                          close();
                        }
                      });
}

bool HTTPSession::checkConnected() {
  return state_ == ConnectorState::CONNECTED;
}

void HTTPSession::startConnectionTimer() {
  timer_.expires_from_now(std::chrono::seconds(10));
  timer_.async_wait(
      std::bind(&HTTPSession::handleDeadline, this, std::placeholders::_1));
}

void HTTPSession::handleDeadline(const std::error_code &ec) {
  if (!ec) {
    io_service_.post([this]() {
      socket_.close();
      TRANSPORT_LOGE("Error connecting. Is the server running?\n");
      io_service_.stop();
    });
  }
}

}  // namespace transport