summaryrefslogtreecommitdiffstats
path: root/apps/hiperf/src/forwarder_interface.cc
blob: e87a5953d20c90499ac8cd20a9f62d4bbaf20cb9 (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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
/*
 * Copyright (c) 2021 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 <arpa/inet.h>
#include <forwarder_interface.h>
#include <hicn/transport/utils/log.h>

#include <chrono>
#include <iostream>
#include <thread>
#include <unordered_set>

extern "C" {
#include <hicn/error.h>
#include <hicn/util/ip_address.h>
#include <hicn/util/sstrncpy.h>
}

// XXX the main listener should be retrieve in this class at initialization, aka
// when hICN becomes avialable
//
// XXX the main listener port will be retrieved in the forwarder
// interface... everything else will be delayed until we have this
// information

namespace hiperf {

ForwarderInterface::ForwarderInterface(asio::io_service &io_service)
    : external_ioservice_(io_service), timer_(io_service) {}

ForwarderInterface::ForwarderInterface(asio::io_service &io_service,
                                       ICallback *callback,
                                       forwarder_type_t fwd_type)
    : external_ioservice_(io_service), timer_(io_service) {
  initForwarderInterface(callback, fwd_type);
}

ForwarderInterface::~ForwarderInterface() {
  if (thread_ && thread_->joinable()) {
    internal_ioservice_.dispatch([this]() {
      if (sock_) {
        hc_sock_free(sock_);
        sock_ = nullptr;
      }

      work_.reset();
    });

    thread_->join();
  }
}

void ForwarderInterface::initForwarderInterface(ICallback *callback,
                                                forwarder_type_t fwd_type) {
  forwarder_interface_callback_ = callback;
  work_ = std::make_unique<asio::io_service::work>(internal_ioservice_);
  sock_ = nullptr;
  thread_ = std::make_unique<std::thread>([this]() {
    std::cout << "Starting Forwarder Interface thread" << std::endl;
    internal_ioservice_.run();
    std::cout << "Stopping Forwarder Interface thread" << std::endl;
  });
  check_routes_timer_ = nullptr;
  pending_add_route_counter_ = 0;
  hicn_listen_port_ = 9695;
  /* We start in disabled state even when a forwarder is always available */
  state_ = State::Disabled;
  fwd_type_ = fwd_type;
  num_reattempts = 0;
  std::cout << "Forwarder interface created... connecting to forwarder...\n";
  internal_ioservice_.post([this]() { onHicnServiceAvailable(true); });
}

void ForwarderInterface::onHicnServiceAvailable(bool flag) {
  if (flag) {
    switch (state_) {
      case State::Disabled:
      case State::Requested:
        state_ = State::Available;
      case State::Available:
        connectToForwarder();
        /* Synchronous */
        if (state_ != State::Connected) {
          std::cout << "ConnectToForwarder failed" << std::endl;
          goto REATTEMPT;
        }
        state_ = State::Ready;

        std::cout << "Connected to forwarder... cancelling reconnection timer"
                  << std::endl;

        timer_.cancel();
        num_reattempts = 0;

        std::cout << "Forwarder interface is ready... communicate to controller"
                  << std::endl;

        forwarder_interface_callback_->onHicnServiceReady();
      case State::Connected:
      case State::Ready:
        break;
    }
  } else {
    if (sock_) {
      hc_sock_free(sock_);
      sock_ = nullptr;
    }
    state_ = State::Disabled;  // XXX to be checked upon callback to prevent the
                               // state from going forward (used to manage
                               // concurrency)
  }
  return;

REATTEMPT:
  /* Schedule reattempt */
  std::cout << "Failed to connect, scheduling reattempt" << std::endl;
  num_reattempts++;

  timer_.expires_from_now(
      std::chrono::milliseconds(ForwarderInterface::REATTEMPT_DELAY_MS));
  // timer_.async_wait(std::bind(&ForwarderInterface::onHicnServiceAvailable,
  // this, flag, std::placeholders::_1));
  timer_.async_wait([this, flag](const std::error_code &ec) {
    if (ec) return;
    onHicnServiceAvailable(flag);
  });
}

int ForwarderInterface::connectToForwarder() {
  sock_ = hc_sock_create_forwarder(fwd_type_);
  if (!sock_) {
    std::cout << "Could not create socket" << std::endl;
    goto ERR_SOCK;
  }

  if (hc_sock_connect(sock_) < 0) {
    std::cout << "Could not connect to forwarder" << std::endl;
    goto ERR;
  }

  std::cout << "Forwarder interface connected" << std::endl;
  state_ = State::Connected;
  return 0;

ERR:
  hc_sock_free(sock_);
  sock_ = nullptr;
ERR_SOCK:
  return -1;
}

int ForwarderInterface::checkListener() {
  if (!sock_) return -1;

  hc_data_t *data;
  if (hc_listener_list(sock_, &data) < 0) return -1;

  int ret = -1;
  foreach_listener(l, data) {
    std::string interface = std::string(l->interface_name);
    if (interface.compare("lo") != 0) {
      hicn_listen_port_ = l->local_port;
      state_ = State::Ready;
      ret = 0;
      std::cout << "Got listener port" << std::endl;
      break;
    }
  }

  hc_data_free(data);
  return ret;
}

void ForwarderInterface::close() {
  std::cout << "ForwarderInterface::close" << std::endl;

  state_ = State::Disabled;
  /* Cancelling eventual reattempts */
  timer_.cancel();

  if (sock_) {
    hc_sock_free(sock_);
    sock_ = nullptr;
  }

  internal_ioservice_.post([this]() { work_.reset(); });

  if (thread_->joinable()) {
    thread_->join();
  }
}

#if 0
void ForwarderInterface::enableCheckRoutesTimer() {
  if (check_routes_timer_ != nullptr) return;

  check_routes_timer_ =
      std::make_unique<asio::steady_timer>(internal_ioservice_);
  checkRoutesLoop();
}

void ForwarderInterface::removeConnectedUserNow(ProtocolPtr protocol) {
  internalRemoveConnectedUser(protocol);
}

void ForwarderInterface::scheduleRemoveConnectedUser(ProtocolPtr protocol) {
  internal_ioservice_.post(
      [this, protocol]() { internalRemoveConnectedUser(protocol); });
}
#endif

void ForwarderInterface::createFaceAndRoute(const RouteInfoPtr &route_info) {
  std::vector<RouteInfoPtr> routes;
  routes.push_back(std::move(route_info));
  createFaceAndRoutes(routes);
}

void ForwarderInterface::createFaceAndRoutes(
    const std::vector<RouteInfoPtr> &routes_info) {
  pending_add_route_counter_++;
  auto timer = new asio::steady_timer(internal_ioservice_);
  internal_ioservice_.post([this, routes_info, timer]() {
    internalCreateFaceAndRoutes(routes_info, ForwarderInterface::MAX_REATTEMPT,
                                timer);
  });
}

void ForwarderInterface::deleteFaceAndRoute(const RouteInfoPtr &route_info) {
  std::vector<RouteInfoPtr> routes;
  routes.push_back(std::move(route_info));
  deleteFaceAndRoutes(routes);
}

void ForwarderInterface::deleteFaceAndRoutes(
    const std::vector<RouteInfoPtr> &routes_info) {
  internal_ioservice_.post([this, routes_info]() {
    for (auto &route : routes_info) {
      internalDeleteFaceAndRoute(route);
    }
  });
}

void ForwarderInterface::setStrategy(std::string prefix, uint32_t prefix_len,
                                     std::string strategy) {
  if (!sock_) return;

  ip_address_t ip_prefix;
  if (ip_address_pton(prefix.c_str(), &ip_prefix) < 0) {
    return;
  }

  strategy_type_t strategy_type = strategy_type_from_str(strategy.c_str());
  if (strategy_type == STRATEGY_TYPE_UNDEFINED) return;

  hc_strategy_t strategy_conf;
  strategy_conf.address = ip_prefix;
  strategy_conf.len = prefix_len;
  strategy_conf.family = AF_INET6;
  strategy_conf.type = strategy_type;

  hc_strategy_set(sock_, &strategy_conf);
}

void ForwarderInterface::internalDeleteFaceAndRoute(
    const RouteInfoPtr &route_info) {
  if (!sock_) return;

  hc_data_t *data;
  if (hc_route_list(sock_, &data) < 0) return;

  std::vector<hc_route_t *> routes_to_remove;
  foreach_route(r, data) {
    char remote_addr[INET6_ADDRSTRLEN];
    int ret = ip_address_ntop(&r->remote_addr, remote_addr, r->len, r->family);
    if (ret < 0) continue;

    std::string route_addr(remote_addr);
    if (route_addr.compare(route_info->route_addr) == 0 &&
        r->len == route_info->route_len) {
      // route found
      routes_to_remove.push_back(r);
    }
  }

  if (routes_to_remove.size() == 0) {
    // nothing to do here
    hc_data_free(data);
    return;
  }

  std::unordered_set<uint32_t> connids_to_remove;
  for (unsigned i = 0; i < routes_to_remove.size(); i++) {
    connids_to_remove.insert(routes_to_remove[i]->face_id);
    if (hc_route_delete(sock_, routes_to_remove[i]) < 0) {
      std::cout << "Error removing route from forwarder." << std::endl;
    }
  }

  // remove connection
  if (hc_connection_list(sock_, &data) < 0) {
    hc_data_free(data);
    return;
  }

  // collects pointerst to the connections using the conn IDs
  std::vector<hc_connection_t *> conns_to_remove;
  foreach_connection(c, data) {
    if (connids_to_remove.find(c->id) != connids_to_remove.end()) {
      // conn found
      conns_to_remove.push_back(c);
    }
  }

  if (conns_to_remove.size() == 0) {
    // nothing else to do here
    hc_data_free(data);
    return;
  }

  for (unsigned i = 0; i < conns_to_remove.size(); i++) {
    if (hc_connection_delete(sock_, conns_to_remove[i]) < 0) {
      std::cout << "Error removing connection from forwarder." << std::endl;
    }
  }

  hc_data_free(data);
}

void ForwarderInterface::internalCreateFaceAndRoutes(
    const std::vector<RouteInfoPtr> &route_info, uint8_t max_try,
    asio::steady_timer *timer) {
  uint32_t face_id;

  std::vector<RouteInfoPtr> failed;
  for (auto &route : route_info) {
    int ret = tryToCreateFace(route.get(), &face_id);
    if (ret >= 0) {
      auto ret = tryToCreateRoute(route.get(), face_id);
      if (ret < 0) {
        failed.push_back(route);
        std::cerr << "Error creating route and face" << std::endl;
        continue;
      }
    }
  }

  if (failed.size() > 0) {
    if (max_try == 0) {
      /* All attempts failed */
      goto RESULT;
    }
    max_try--;
    timer->expires_from_now(std::chrono::milliseconds(500));
    timer->async_wait(
        [this, failed, max_try, timer](const std::error_code &ec) {
          if (ec) return;
          internalCreateFaceAndRoutes(failed, max_try, timer);
        });
    return;
  }

#if 0
  // route_status_[protocol] = std::move(route_info);
  for (size_t i = 0; i < route_info.size(); i++) {
    route_status_.insert(
        std::pair<ClientId, RouteInfoPtr>(protocol, std::move(route_info[i])));
  }
#endif

RESULT:
  std::cout << "Face / Route create ok, now calling back protocol" << std::endl;
  pending_add_route_counter_--;
  external_ioservice_.post([this, r = std::move(route_info)]() mutable {
    forwarder_interface_callback_->onRouteConfigured(r);
  });
  delete timer;
}

int ForwarderInterface::tryToCreateFace(RouteInfo *route_info,
                                        uint32_t *face_id) {
  bool found = false;

  // check connection with the forwarder
  if (!sock_) {
    std::cout << "[ForwarderInterface::tryToCreateFace] socket error"
              << std::endl;
    goto ERR_SOCK;
  }

  // get listeners list
  hc_data_t *data;
  if (hc_listener_list(sock_, &data) < 0) {
    std::cout << "[ForwarderInterface::tryToCreateFace] cannot list listeners";
    goto ERR_LIST;
  }

  char _local_address[128];
  foreach_listener(l, data) {
    std::cout << "Processing " << l->interface_name << std::endl;
    std::string interface = std::string(l->interface_name);
    int ret = ip_address_ntop(&l->local_addr, _local_address, 128, AF_INET);
    if (ret < 0) {
      std::cerr << "Error in ip_address_ntop" << std::endl;
      goto ERR;
    }

    std::string local_address = std::string(_local_address);
    uint16_t local_port = l->local_port;

    if (interface.compare(route_info->interface) == 0 &&
        local_address.compare(route_info->local_addr) == 0 &&
        local_port == route_info->local_port) {
      found = true;
      break;
    }
  }

  std::cout << route_info->remote_addr << std::endl;

  ip_address_t local_address, remote_address;
  ip_address_pton(route_info->local_addr.c_str(), &local_address);
  ip_address_pton(route_info->remote_addr.c_str(), &remote_address);

  if (!found) {
    // Create listener
    hc_listener_t listener;
    memset(&listener, 0, sizeof(hc_listener_t));

    std::string name = "l_" + route_info->name;
    listener.local_addr = local_address;
    listener.type = FACE_TYPE_UDP;
    listener.family = AF_INET;
    listener.local_port = route_info->local_port;
    int ret = strcpy_s(listener.name, SYMBOLIC_NAME_LEN - 1, name.c_str());
    if (ret < EOK) goto ERR;
    ret = strcpy_s(listener.interface_name, INTERFACE_LEN - 1,
                   route_info->interface.c_str());
    if (ret < EOK) goto ERR;

    std::cout << "------------> " << route_info->interface << std::endl;

    ret = hc_listener_create(sock_, &listener);

    if (ret < 0) {
      std::cerr << "Error creating listener." << std::endl;
      return -1;
    } else {
      std::cout << "Listener " << listener.id << " created." << std::endl;
    }
  }

  // Create face
  hc_face_t face;
  memset(&face, 0, sizeof(hc_face_t));

  // crate face with the local interest
  face.face.type = FACE_TYPE_UDP;
  face.face.family = route_info->family;
  face.face.local_addr = local_address;
  face.face.remote_addr = remote_address;
  face.face.local_port = route_info->local_port;
  face.face.remote_port = route_info->remote_port;

  if (netdevice_set_name(&face.face.netdevice, route_info->interface.c_str()) <
      0) {
    std::cout << "[ForwarderInterface::tryToCreateFaceAndRoute] "
                 "netdevice_set_name "
                 "("
              << face.face.netdevice.name << ", "
              << route_info->interface << ") error" << std::endl;
    goto ERR;
  }

  // create face
  if (hc_face_create(sock_, &face) < 0) {
    std::cout << "[ForwarderInterface::tryToCreateFace] error creating face";
    goto ERR;
  }

  std::cout << "Face created successfully" << std::endl;

  // assing face to the return value
  *face_id = face.id;

  hc_data_free(data);
  return 0;

ERR:
  hc_data_free(data);
ERR_LIST:
ERR_SOCK:
  return -1;
}

int ForwarderInterface::tryToCreateRoute(RouteInfo *route_info,
                                         uint32_t face_id) {
  std::cout << "Trying to create route" << std::endl;

  // check connection with the forwarder
  if (!sock_) {
    std::cout << "[ForwarderInterface::tryToCreateRoute] socket error";
    return -1;
  }

  ip_address_t route_ip;
  hc_route_t route;

  if (ip_address_pton(route_info->route_addr.c_str(), &route_ip) < 0) {
    std::cout << "[ForwarderInterface::tryToCreateRoute] ip_address_pton error";
    return -1;
  }

  route.face_id = face_id;
  route.family = AF_INET6;
  route.remote_addr = route_ip;
  route.len = route_info->route_len;
  route.cost = 1;

  if (hc_route_create(sock_, &route) < 0) {
    std::cout << "[ForwarderInterface::tryToCreateRoute] error creating route";
    return -1;
  }

  std::cout << "[ForwarderInterface::tryToCreateRoute] OK" << std::endl;
  return 0;
}

#if 0  // not used
void ForwarderInterface::checkRoutesLoop() {
  check_routes_timer_->expires_from_now(std::chrono::milliseconds(1000));
  check_routes_timer_->async_wait([this](const std::error_code &ec) {
    if (ec) return;
    if (pending_add_route_counter_ == 0) checkRoutes();
  });
}

void ForwarderInterface::checkRoutes() {
  std::cout << "someone called the checkRoutes function" << std::endl;
  if (!sock_) return;

  hc_data_t *data;
  if (hc_route_list(sock_, &data) < 0) {
    return;
  }

  std::unordered_set<std::string> routes_set;
  foreach_route(r, data) {
    char remote_addr[INET6_ADDRSTRLEN];
    int ret = ip_address_ntop(&r->remote_addr, remote_addr, r->len, r->family);
    if (ret < 0) continue;
    std::string route(std::string(remote_addr) + "/" + std::to_string(r->len));
    routes_set.insert(route);
  }

  for (auto it = route_status_.begin(); it != route_status_.end(); it++) {
    std::string route(it->second->route_addr + "/" +
                      std::to_string(it->second->route_len));
    if (routes_set.find(route) == routes_set.end()) {
      // the route is missing
      createFaceAndRoute(it->second, it->first);
      break;
    }
  }

  hc_data_free(data);
}
#endif

#if 0
      using ListenerRetrievedCallback =
          std::function<void(std::error_code, uint32_t)>;

      ListenerRetrievedCallback listener_retrieved_callback_;

#ifdef __ANDROID__
            hicn_listen_port_(9695),
#else
            hicn_listen_port_(0),
#endif
            timer_(forward_engine_.getIoService()),

      void initConfigurationProtocol(void)
      {
        // We need the configuration, which is different for every protocol...
        // so we move this step down towards the protocol implementation itself.
        if (!permanent_hicn) {
          doInitConfigurationProtocol();
        } else {
          // XXX This should be moved somewhere else
          getMainListener(
              [this](const std::error_code &ec, uint32_t hicn_listen_port) {
                if (!ec)
                {
                  hicn_listen_port_ = hicn_listen_port;
                  doInitConfigurationProtocol();
                }
              });
          }
      }

      template <typename Callback>
      void getMainListener(Callback &&callback)
      {
        listener_retrieved_callback_ = std::forward<Callback &&>(callback);
        tryToConnectToForwarder();
      }
    private:
      void doGetMainListener(const std::error_code &ec)
      {
        if (!ec)
        {
          // ec == 0 --> timer expired
          int ret = forwarder_interface_.getMainListenerPort();
          if (ret <= 0)
          {
            // Since without the main listener of the forwarder the proxy cannot
            // work, we can stop the program here until we get the listener port.
            std::cout <<
                "Could not retrieve main listener port from the forwarder. "
                "Retrying.";

            timer_.expires_from_now(std::chrono::milliseconds(RETRY_INTERVAL));
            timer_.async_wait(std::bind(&Protocol::doGetMainListener, this,
                                        std::placeholders::_1));
          }
          else
          {
            timer_.cancel();
            retx_count_ = 0;
            hicn_listen_port_ = uint16_t(ret);
            listener_retrieved_callback_(
                make_error_code(configuration_error::success), hicn_listen_port_);
          }
        }
        else
        {
          std::cout <<  "Timer for retrieving main hicn listener canceled." << std::endl;
        }
      }

      void tryToConnectToForwarder()
      {
        doTryToConnectToForwarder(std::make_error_code(std::errc(0)));
      }

      void doTryToConnectToForwarder(const std::error_code &ec)
      {
        if (!ec)
        {
          // ec == 0 --> timer expired
          int ret = forwarder_interface_.connect();
          if (ret < 0)
          {
            // We were not able to connect to the local forwarder. Do not give up
            // and retry.
            std::cout <<  "Could not connect to local forwarder. Retrying." << std::endl;

            timer_.expires_from_now(std::chrono::milliseconds(RETRY_INTERVAL));
            timer_.async_wait(std::bind(&Protocol::doTryToConnectToForwarder, this,
                                        std::placeholders::_1));
          }
          else
          {
            timer_.cancel();
            retx_count_ = 0;
            doGetMainListener(std::make_error_code(std::errc(0)));
          }
        }
        else
        {
          std::cout <<  "Timer for re-trying forwarder connection canceled." << std::endl;
        }
      }


    template <typename ProtocolImplementation>
    constexpr uint32_t Protocol<ProtocolImplementation>::RETRY_INTERVAL;

#endif

constexpr uint32_t ForwarderInterface::REATTEMPT_DELAY_MS;
constexpr uint32_t ForwarderInterface::MAX_REATTEMPT;

}  // namespace hiperf