Ton

Форк
0
/
adnl-pong.cpp 
202 строки · 7.2 Кб
1
/*
2
    This file is part of TON Blockchain source code.
3

4
    TON Blockchain is free software; you can redistribute it and/or
5
    modify it under the terms of the GNU General Public License
6
    as published by the Free Software Foundation; either version 2
7
    of the License, or (at your option) any later version.
8

9
    TON Blockchain is distributed in the hope that it will be useful,
10
    but WITHOUT ANY WARRANTY; without even the implied warranty of
11
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
    GNU General Public License for more details.
13

14
    You should have received a copy of the GNU General Public License
15
    along with TON Blockchain.  If not, see <http://www.gnu.org/licenses/>.
16

17
    In addition, as a special exception, the copyright holders give permission
18
    to link the code of portions of this program with the OpenSSL library.
19
    You must obey the GNU General Public License in all respects for all
20
    of the code used other than OpenSSL. If you modify file(s) with this
21
    exception, you may extend this exception to your version of the file(s),
22
    but you are not obligated to do so. If you do not wish to do so, delete this
23
    exception statement from your version. If you delete this exception statement
24
    from all source files in the program, then also delete it here.
25

26
    Copyright 2017-2020 Telegram Systems LLP
27
*/
28
#include "td/actor/actor.h"
29
#include "td/utils/buffer.h"
30
#include "td/utils/port/IPAddress.h"
31
#include "td/net/UdpServer.h"
32
#include "td/utils/port/signals.h"
33
#include "td/utils/OptionParser.h"
34
#include "td/utils/FileLog.h"
35
#include "td/utils/port/path.h"
36
#include "td/utils/port/user.h"
37
#include "td/utils/filesystem.h"
38
#include "common/checksum.h"
39
#include "common/errorcode.h"
40
#include "tl-utils/tl-utils.hpp"
41
#include "auto/tl/ton_api_json.h"
42
#include "adnl/adnl.h"
43
#include <map>
44
#include "git.h"
45

46
#if TD_DARWIN || TD_LINUX
47
#include <unistd.h>
48
#endif
49

50
namespace ton {
51

52
namespace adnl {
53

54
class Callback : public adnl::Adnl::Callback {
55
 public:
56
  void receive_message(AdnlNodeIdShort src, AdnlNodeIdShort dst, td::BufferSlice data) override {
57
  }
58
  void receive_query(AdnlNodeIdShort src, AdnlNodeIdShort dst, td::BufferSlice data,
59
                     td::Promise<td::BufferSlice> promise) override {
60
    TRY_RESULT_PROMISE_PREFIX(promise, f, fetch_tl_object<ton_api::adnl_ping>(std::move(data), true),
61
                              "adnl.ping expected");
62
    promise.set_value(create_serialize_tl_object<ton_api::adnl_pong>(f->value_));
63
  }
64

65
  Callback() {
66
  }
67

68
 private:
69
};
70

71
}  // namespace adnl
72

73
}  // namespace ton
74

75
std::atomic<bool> rotate_logs_flags{false};
76
void force_rotate_logs(int sig) {
77
  rotate_logs_flags.store(true);
78
}
79

80
int main(int argc, char *argv[]) {
81
  SET_VERBOSITY_LEVEL(verbosity_INFO);
82

83
  ton::PrivateKey pk;
84
  td::IPAddress addr;
85

86
  td::set_default_failure_signal_handler().ensure();
87

88
  std::unique_ptr<td::LogInterface> logger_;
89
  SCOPE_EXIT {
90
    td::log_interface = td::default_log_interface;
91
  };
92

93
  std::string config = "/var/ton-work/etc/adnl-proxy.conf.json";
94

95
  td::OptionParser p;
96
  p.set_description("adnl pinger");
97
  p.add_option('v', "verbosity", "set verbosity level", [&](td::Slice arg) {
98
    int v = VERBOSITY_NAME(FATAL) + (td::to_integer<int>(arg));
99
    SET_VERBOSITY_LEVEL(v);
100
  });
101
  p.add_option('V', "version", "shows adnl-pong build information", [&]() {
102
    std::cout << "adnl-pong build information: [ Commit: " << GitMetadata::CommitSHA1() << ", Date: " << GitMetadata::CommitDate() << "]\n";
103
    std::exit(0);
104
  });
105
  p.add_option('h', "help", "prints_help", [&]() {
106
    char b[10240];
107
    td::StringBuilder sb(td::MutableSlice{b, 10000});
108
    sb << p;
109
    std::cout << sb.as_cslice().c_str();
110
    std::exit(2);
111
  });
112
  p.add_option('d', "daemonize", "set SIGHUP", [&]() {
113
#if TD_DARWIN || TD_LINUX
114
    close(0);
115
    setsid();
116
#endif
117
    td::set_signal_handler(td::SignalType::HangUp, force_rotate_logs).ensure();
118
  });
119
  p.add_checked_option('l', "logname", "log to file", [&](td::Slice fname) {
120
    auto F = std::make_unique<td::FileLog>();
121
    TRY_STATUS(F->init(fname.str(), std::numeric_limits<td::uint64>::max(), true));
122
    logger_ = std::move(F);
123
    td::log_interface = logger_.get();
124
    return td::Status::OK();
125
  });
126
  td::uint32 threads = 7;
127
  p.add_checked_option(
128
      't', "threads", PSTRING() << "number of threads (default=" << threads << ")", [&](td::Slice fname) {
129
        td::int32 v;
130
        try {
131
          v = std::stoi(fname.str());
132
        } catch (...) {
133
          return td::Status::Error(ton::ErrorCode::error, "bad value for --threads: not a number");
134
        }
135
        if (v < 1 || v > 256) {
136
          return td::Status::Error(ton::ErrorCode::error, "bad value for --threads: should be in range [1..256]");
137
        }
138
        threads = v;
139
        return td::Status::OK();
140
      });
141
  p.add_checked_option('u', "user", "change user", [&](td::Slice user) { return td::change_user(user.str()); });
142
  p.add_checked_option('k', "key", "private key", [&](td::Slice key) {
143
    TRY_RESULT_ASSIGN(pk, ton::PrivateKey::import(key));
144
    return td::Status::OK();
145
  });
146
  p.add_checked_option('a', "addr", "ip:port of instance", [&](td::Slice key) {
147
    TRY_STATUS(addr.init_host_port(key.str()));
148
    return td::Status::OK();
149
  });
150

151
  p.run(argc, argv).ensure();
152

153
  if (pk.empty()) {
154
    LOG(FATAL) << "no --key given";
155
  }
156
  if (!addr.is_valid()) {
157
    LOG(FATAL) << "no --addr given";
158
  }
159

160
  td::actor::Scheduler scheduler({threads});
161

162
  td::actor::ActorOwn<ton::keyring::Keyring> keyring;
163
  td::actor::ActorOwn<ton::adnl::Adnl> adnl;
164
  td::actor::ActorOwn<ton::adnl::AdnlNetworkManager> network_manager;
165

166
  auto pub = pk.compute_public_key();
167

168
  scheduler.run_in_context([&]() {
169
    keyring = ton::keyring::Keyring::create("");
170
    td::actor::send_closure(keyring, &ton::keyring::Keyring::add_key, std::move(pk), true, [](td::Unit) {});
171

172
    adnl = ton::adnl::Adnl::create("", keyring.get());
173

174
    network_manager = ton::adnl::AdnlNetworkManager::create(static_cast<td::uint16>(addr.get_port()));
175

176
    ton::adnl::AdnlCategoryMask cat_mask;
177
    cat_mask[0] = true;
178
    td::actor::send_closure(network_manager, &ton::adnl::AdnlNetworkManager::add_self_addr, addr, std::move(cat_mask),
179
                            0);
180

181
    auto tladdr = ton::create_tl_object<ton::ton_api::adnl_address_udp>(addr.get_ipv4(), addr.get_port());
182
    auto addr_vec = std::vector<ton::tl_object_ptr<ton::ton_api::adnl_Address>>();
183
    addr_vec.push_back(std::move(tladdr));
184
    auto tladdrlist = ton::create_tl_object<ton::ton_api::adnl_addressList>(
185
        std::move(addr_vec), ton::adnl::Adnl::adnl_start_time(), ton::adnl::Adnl::adnl_start_time(), 0, 2000000000);
186
    auto addrlist = ton::adnl::AdnlAddressList::create(tladdrlist).move_as_ok();
187

188
    td::actor::send_closure(adnl, &ton::adnl::Adnl::add_id, ton::adnl::AdnlNodeIdFull{pub}, std::move(addrlist),
189
                            static_cast<td::uint8>(0));
190
    td::actor::send_closure(adnl, &ton::adnl::Adnl::subscribe, ton::adnl::AdnlNodeIdShort{pub.compute_short_id()},
191
                            ton::adnl::Adnl::int_to_bytestring(ton::ton_api::adnl_ping::ID),
192
                            std::make_unique<ton::adnl::Callback>());
193
  });
194

195
  while (scheduler.run(1)) {
196
    if (rotate_logs_flags.exchange(false)) {
197
      if (td::log_interface) {
198
        td::log_interface->rotate();
199
      }
200
    }
201
  }
202
}
203

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.