summaryrefslogtreecommitdiff
path: root/src/uTPCore.cc
blob: a983676c7cf647d986945c726cdcbc738837a166 (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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#include "common.h"

#include <chrono>
#include <array>

#include "a2netcompat.h"
#include "a2io.h"
#include "a2functional.h"
#include "a2time.h"
#include "message.h"
#include "DlRetryEx.h"
#include "DlAbortEx.h"
#include "fmt.h"
#include "util.h"
#include "TimeA2.h"
#include "Peer.h"
#include "Logger.h"
#include "LogFactory.h"
#include "Option.h"
#include "DownloadEngine.h"
#include "SocketCore.h"
#include "uTPCore.h"
#include "RequestGroupMan.h"
#include "ReceiverMSEHandshakeCommand.h"

namespace aria2 {

utp_context* uTPCore::ctx_;
utp_context* uTPCore::ctx6_;
std::shared_ptr<SocketCore> uTPCore::sock_;
std::shared_ptr<SocketCore> uTPCore::sock6_;
Timer uTPCore::start_;

uint64 uTPCore::getMilliseconds(utp_callback_arguments* arg)
{
  auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
      start_.difference());
  return (uint64)ms.count();
}

uint64 uTPCore::getMicroseconds(utp_callback_arguments* arg)
{
  auto us = std::chrono::duration_cast<std::chrono::microseconds>(
      start_.difference());
  return (uint64)us.count();
}

uint64 uTPCore::getReadBufferSize(utp_callback_arguments* arg)
{
  uTPCore* utp = (uTPCore*)utp_get_userdata(arg->socket);
  if (utp == nullptr) {
    return 0;
  }
  return utp->end_ - utp->pos_;
}

uint64 uTPCore::writeLogCallback(utp_callback_arguments* arg)
{
  A2_LOG_DEBUG(fmt("uTP: %s", arg->buf));
  return 0;
}

uint64 uTPCore::sendtoCallback(utp_callback_arguments* arg)
{
  if (arg->address->sa_family == AF_INET) {
    sock_->writeData(arg->buf, arg->len, arg->address, arg->address_len,
                     arg->flags);
  }
  else {
    sock6_->writeData(arg->buf, arg->len, arg->address, arg->address_len,
                      arg->flags);
  }
  return 0;
}

uint64 uTPCore::acceptCallback(utp_callback_arguments* arg)
{
  std::shared_ptr<uTPCore> utp = std::make_shared<uTPCore>(arg->socket);
  utp_set_userdata(arg->socket, utp.get());
  utp->isWritable_ = true;
  Endpoint endpoint = util::getNumericNameInfo(arg->address, arg->address_len);
  DownloadEngine* e = (DownloadEngine*)utp_context_get_userdata(arg->context);
  std::shared_ptr<Peer> peer =
      std::make_shared<Peer>(endpoint.addr, endpoint.port, true);
  cuid_t cuid = e->newCUID();
  e->addCommand(make_unique<ReceiverMSEHandshakeCommand>(cuid, peer, e, utp));
  A2_LOG_DEBUG(fmt("Accepted the connection from %s:%u.",
                   peer->getIPAddress().c_str(), peer->getPort()));
  A2_LOG_DEBUG(
      fmt("Added CUID#%" PRId64 " to receive BitTorrent/MSE handshake.", cuid));
  return 0;
}

uint64 uTPCore::stateChangeCallback(utp_callback_arguments* arg)
{
  uTPCore* utp = (uTPCore*)utp_get_userdata(arg->socket);
  if (arg->state == UTP_STATE_CONNECT || arg->state == UTP_STATE_WRITABLE) {
    utp->isWritable_ = true;
    if (utp->command_ != nullptr && utp->writeCheck_ == true) {
      utp->command_->setStatusActive();
    }
  }
  return 0;
}

uint64 uTPCore::readCallback(utp_callback_arguments* arg)
{
  uTPCore* utp = (uTPCore*)utp_get_userdata(arg->socket);
  size_t bufLen = utp->buf_.size() - utp->end_;
  if (arg->len > bufLen) {
    utp->buf_.resize(utp->end_ + arg->len);
  }
  std::memcpy(utp->buf_.data() + utp->end_, arg->buf, arg->len);
  utp->end_ += arg->len;
  if (utp->end_ == utp->buf_.size()) {
    utp->needDrainRead_ = true;
  }
  else {
    utp_read_drained(utp->s_);
  }
  if (utp->command_ != nullptr && utp->readCheck_ == true) {
    utp->command_->setStatusActive();
  }
  return 0;
}

uint64 uTPCore::errorCallback(utp_callback_arguments* arg)
{
  uTPCore* utp = (uTPCore*)utp_get_userdata(arg->socket);
  utp->errNum_ = arg->error_code;
  if (utp->command_ != nullptr) {
    utp->command_->setStatusActive();
  }
  return 0;
}

namespace {
void setupContextAndSock(utp_context*& ctx, std::shared_ptr<SocketCore>& sock,
                         int family, uint16_t port, DownloadEngine* e)
{
  sock = std::make_shared<SocketCore>(SOCK_DGRAM);
  sock->bind("", port, family);
  sock->setNonBlockingMode();
  ctx = utp_init(2);
  utp_context_set_userdata(ctx, (void*)e);
  utp_set_callback(ctx, UTP_GET_MILLISECONDS, uTPCore::getMilliseconds);
  utp_set_callback(ctx, UTP_GET_MICROSECONDS, uTPCore::getMicroseconds);
  utp_set_callback(ctx, UTP_GET_READ_BUFFER_SIZE, uTPCore::getReadBufferSize);
  if (A2_LOG_DEBUG_ENABLED) {
    utp_context_set_option(ctx, UTP_LOG_DEBUG, 1);
    utp_context_set_option(ctx, UTP_LOG_NORMAL, 1);
    utp_context_set_option(ctx, UTP_LOG_MTU, 1);
  }
  utp_set_callback(ctx, UTP_LOG, uTPCore::writeLogCallback);
  utp_set_callback(ctx, UTP_SENDTO, uTPCore::sendtoCallback);
  utp_set_callback(ctx, UTP_ON_ACCEPT, uTPCore::acceptCallback);
  utp_set_callback(ctx, UTP_ON_STATE_CHANGE, uTPCore::stateChangeCallback);
  utp_set_callback(ctx, UTP_ON_READ, uTPCore::readCallback);

  e->addRoutineCommand(
      make_unique<uTPListenCommand>(e->newCUID(), e, ctx, sock));
}
} // namespace

void uTPCore::initContext(uint16_t port, DownloadEngine* e)
{
  start_ = global::wallclock();
  setupContextAndSock(ctx_, sock_, AF_INET, port, e);
  if (e->getOption()->getAsBool(PREF_DISABLE_IPV6) == false) {
    setupContextAndSock(ctx6_, sock6_, AF_INET6, port, e);
  }
}

void uTPCore::destroyContext()
{
  if (ctx_ != nullptr) {
    utp_destroy(ctx_);
    ctx_ = nullptr;
  }
  if (ctx6_ != nullptr) {
    utp_destroy(ctx6_);
    ctx6_ = nullptr;
  }
}

uTPCore::uTPCore(utp_socket* s)
    : s_(s),
      isWritable_(false),
      needDrainRead_(false),
      pos_(0),
      end_(0),
      errNum_(0),
      readCheck_(false),
      writeCheck_(false),
      command_(nullptr),
      SocketCore(SOCK_DGRAM)
{
  buf_.resize(16_k);
}

uTPCore::~uTPCore() { closeConnection(); }

void uTPCore::establishConnection(const std::string& host, uint16_t port,
                                  bool tcpNodelay)
{
  addrinfo* res;
  int rv;
  rv = callGetaddrinfo(&res, host.c_str(), util::uitos(port).c_str(),
                       protocolFamily_, SOCK_DGRAM, 0, 0);
  if (rv != 0) {
    throw DL_ABORT_EX(fmt(EX_RESOLVE_HOSTNAME, host.c_str(), gai_strerror(rv)));
  }
  std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> resDeleter(res,
                                                                freeaddrinfo);
  struct addrinfo* rp;
  for (rp = res; rp; rp = rp->ai_next) {
    s_ = utp_create_socket(rp->ai_family == AF_INET ? ctx_ : ctx6_);
    utp_set_userdata(s_, (void*)this);
    if (utp_connect(s_, rp->ai_addr, rp->ai_addrlen) != 0) {
      utp_close(s_);
      s_ = nullptr;
      continue;
    }
    return;
  }
  throw DL_ABORT_EX(
      fmt("Failed to create uTP connection to %s.", host.c_str()));
}

bool uTPCore::isWritable(time_t timeout) { return isWritable_; }

bool uTPCore::isReadable(time_t timeout) { return pos_ < end_; }

ssize_t uTPCore::writeData(const void* data, size_t len)
{
  a2iovec iov = {(void*)data, len};
  return writeData(&iov, 1);
}

ssize_t uTPCore::writeVector(a2iovec* iov, size_t iovcnt)
{
  if (errNum_ != 0) {
    throw DL_RETRY_EX(
        fmt("Failed to send data, cause: %s.", utp_error_code_names[errNum_]));
  }
  ssize_t ret = 0;
  wantRead_ = false;
  wantWrite_ = false;
  size_t len =
      std::accumulate(iov, iov + iovcnt, (size_t)0,
                      [](size_t s, a2iovec& elem) { return s + elem.iov_len; });
  ret = utp_writev(s_, (utp_iovec*)iov, iovcnt);
  if (ret == -1) {
    throw DL_RETRY_EX("Failed to send data over uTP.");
  }
  if ((size_t)ret < len) {
    wantWrite_ = true;
    isWritable_ = false;
  }
  return ret;
}

void uTPCore::readData(void* data, size_t& len)
{
  if (errNum_ != 0) {
    throw DL_RETRY_EX(
        fmt("Failed to read data, cause: %s.", utp_error_code_names[errNum_]));
  }
  wantRead_ = false;
  wantWrite_ = false;
  size_t dataLen = end_ - pos_;
  if (dataLen == 0) {
    len = 0;
    wantRead_ = true;
    return;
  }
  if (len > dataLen) {
    len = dataLen;
  }
  std::memcpy(data, buf_.data() + pos_, len);
  pos_ += len;
  if (pos_ > buf_.size() / 2) {
    dataLen = end_ - pos_;
    std::memmove(buf_.data(), buf_.data() + pos_, dataLen);
    pos_ = 0;
    end_ = dataLen;
    if (needDrainRead_ == true) {
      utp_read_drained(s_);
      needDrainRead_ = false;
    }
  }
}

void uTPCore::closeConnection()
{
  if (s_ != nullptr) {
    utp_set_userdata(s_, nullptr);
    utp_close(s_);
  }
  s_ = nullptr;
  command_ = nullptr;
}

void uTPCore::setRWCheck(Command* command, int is_add, int is_read)
{
  if (is_add == true) {
    command_ = command;
    if (is_read == true) {
      readCheck_ = true;
      if (isReadable(0)) {
        command_->setStatusActive();
      }
    }
    else {
      writeCheck_ = true;
      if (isWritable(0)) {
        command_->setStatusActive();
      }
    }
  }
  else {
    command_ = command;
    if (is_read == true) {
      readCheck_ = false;
    }
    else {
      writeCheck_ = false;
    }
  }
}

uTPListenCommand::uTPListenCommand(cuid_t cuid, DownloadEngine* e,
                                   utp_context* ctx,
                                   std::shared_ptr<SocketCore> sock)
    : e_(e), ctx_(ctx), sock_(sock), Command(cuid)
{
  e_->addSocketForReadCheck(sock_, this);
}

uTPListenCommand::~uTPListenCommand()
{
  if (sock_ != nullptr) {
    e_->deleteSocketForReadCheck(sock_, this);
  }
};

bool uTPListenCommand::execute()
{
  if (e_->isHaltRequested() || e_->getRequestGroupMan()->downloadFinished()) {
    return true;
  }
  std::array<char, 2_k> data;
  try {
    while (1) {
      sockaddr_union sockaddr;
      socklen_t socklen = sizeof(sockaddr);
      ssize_t length =
          sock_->readDataFrom(data.data(), data.size(), sockaddr, socklen);
      if (length == 0) {
        utp_issue_deferred_acks(ctx_);
        break;
      }
      utp_process_udp(ctx_, (byte*)data.data(), (size_t)length, &sockaddr.sa,
                      socklen);
    }
  }
  catch (RecoverableException& e) {
    A2_LOG_INFO_EX("Exception thrown while receiving UDP message.", e);
  }
  utp_check_timeouts(ctx_);
  e_->addRoutineCommand(std::unique_ptr<Command>(this));
  return false;
}

} // namespace aria2