network_emulation.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. /*
  2. * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef TEST_NETWORK_NETWORK_EMULATION_H_
  11. #define TEST_NETWORK_NETWORK_EMULATION_H_
  12. #include <cstdint>
  13. #include <deque>
  14. #include <map>
  15. #include <memory>
  16. #include <string>
  17. #include <utility>
  18. #include <vector>
  19. #include "absl/types/optional.h"
  20. #include "api/array_view.h"
  21. #include "api/numerics/samples_stats_counter.h"
  22. #include "api/test/network_emulation_manager.h"
  23. #include "api/test/simulated_network.h"
  24. #include "api/units/timestamp.h"
  25. #include "rtc_base/copy_on_write_buffer.h"
  26. #include "rtc_base/network.h"
  27. #include "rtc_base/network_constants.h"
  28. #include "rtc_base/socket_address.h"
  29. #include "rtc_base/synchronization/sequence_checker.h"
  30. #include "rtc_base/task_queue_for_test.h"
  31. #include "rtc_base/task_utils/repeating_task.h"
  32. #include "rtc_base/thread_annotations.h"
  33. #include "rtc_base/thread_checker.h"
  34. #include "system_wrappers/include/clock.h"
  35. namespace webrtc {
  36. // This class is immutable and so thread safe.
  37. class EmulatedNetworkOutgoingStatsImpl final
  38. : public EmulatedNetworkOutgoingStats {
  39. public:
  40. EmulatedNetworkOutgoingStatsImpl(
  41. int64_t packets_sent,
  42. DataSize bytes_sent,
  43. SamplesStatsCounter sent_packets_size_counter,
  44. DataSize first_sent_packet_size,
  45. Timestamp first_packet_sent_time,
  46. Timestamp last_packet_sent_time)
  47. : packets_sent_(packets_sent),
  48. bytes_sent_(bytes_sent),
  49. sent_packets_size_counter_(std::move(sent_packets_size_counter)),
  50. first_sent_packet_size_(first_sent_packet_size),
  51. first_packet_sent_time_(first_packet_sent_time),
  52. last_packet_sent_time_(last_packet_sent_time) {}
  53. explicit EmulatedNetworkOutgoingStatsImpl(
  54. const EmulatedNetworkOutgoingStats& stats)
  55. : packets_sent_(stats.PacketsSent()),
  56. bytes_sent_(stats.BytesSent()),
  57. sent_packets_size_counter_(stats.SentPacketsSizeCounter()),
  58. first_sent_packet_size_(stats.FirstSentPacketSize()),
  59. first_packet_sent_time_(stats.FirstPacketSentTime()),
  60. last_packet_sent_time_(stats.LastPacketSentTime()) {}
  61. ~EmulatedNetworkOutgoingStatsImpl() override = default;
  62. int64_t PacketsSent() const override { return packets_sent_; }
  63. DataSize BytesSent() const override { return bytes_sent_; }
  64. const SamplesStatsCounter& SentPacketsSizeCounter() const override {
  65. return sent_packets_size_counter_;
  66. }
  67. DataSize FirstSentPacketSize() const override {
  68. return first_sent_packet_size_;
  69. }
  70. Timestamp FirstPacketSentTime() const override {
  71. return first_packet_sent_time_;
  72. }
  73. Timestamp LastPacketSentTime() const override {
  74. return last_packet_sent_time_;
  75. }
  76. DataRate AverageSendRate() const override;
  77. private:
  78. const int64_t packets_sent_;
  79. const DataSize bytes_sent_;
  80. const SamplesStatsCounter sent_packets_size_counter_;
  81. const DataSize first_sent_packet_size_;
  82. const Timestamp first_packet_sent_time_;
  83. const Timestamp last_packet_sent_time_;
  84. };
  85. // This class is immutable and so thread safe.
  86. class EmulatedNetworkIncomingStatsImpl final
  87. : public EmulatedNetworkIncomingStats {
  88. public:
  89. EmulatedNetworkIncomingStatsImpl(
  90. int64_t packets_received,
  91. DataSize bytes_received,
  92. SamplesStatsCounter received_packets_size_counter,
  93. int64_t packets_dropped,
  94. DataSize bytes_dropped,
  95. SamplesStatsCounter dropped_packets_size_counter,
  96. DataSize first_received_packet_size,
  97. Timestamp first_packet_received_time,
  98. Timestamp last_packet_received_time)
  99. : packets_received_(packets_received),
  100. bytes_received_(bytes_received),
  101. received_packets_size_counter_(received_packets_size_counter),
  102. packets_dropped_(packets_dropped),
  103. bytes_dropped_(bytes_dropped),
  104. dropped_packets_size_counter_(dropped_packets_size_counter),
  105. first_received_packet_size_(first_received_packet_size),
  106. first_packet_received_time_(first_packet_received_time),
  107. last_packet_received_time_(last_packet_received_time) {}
  108. explicit EmulatedNetworkIncomingStatsImpl(
  109. const EmulatedNetworkIncomingStats& stats)
  110. : packets_received_(stats.PacketsReceived()),
  111. bytes_received_(stats.BytesReceived()),
  112. received_packets_size_counter_(stats.ReceivedPacketsSizeCounter()),
  113. packets_dropped_(stats.PacketsDropped()),
  114. bytes_dropped_(stats.BytesDropped()),
  115. dropped_packets_size_counter_(stats.DroppedPacketsSizeCounter()),
  116. first_received_packet_size_(stats.FirstReceivedPacketSize()),
  117. first_packet_received_time_(stats.FirstPacketReceivedTime()),
  118. last_packet_received_time_(stats.LastPacketReceivedTime()) {}
  119. ~EmulatedNetworkIncomingStatsImpl() override = default;
  120. int64_t PacketsReceived() const override { return packets_received_; }
  121. DataSize BytesReceived() const override { return bytes_received_; }
  122. const SamplesStatsCounter& ReceivedPacketsSizeCounter() const override {
  123. return received_packets_size_counter_;
  124. }
  125. int64_t PacketsDropped() const override { return packets_dropped_; }
  126. DataSize BytesDropped() const override { return bytes_dropped_; }
  127. const SamplesStatsCounter& DroppedPacketsSizeCounter() const override {
  128. return dropped_packets_size_counter_;
  129. }
  130. DataSize FirstReceivedPacketSize() const override {
  131. return first_received_packet_size_;
  132. }
  133. Timestamp FirstPacketReceivedTime() const override {
  134. return first_packet_received_time_;
  135. }
  136. Timestamp LastPacketReceivedTime() const override {
  137. return last_packet_received_time_;
  138. }
  139. DataRate AverageReceiveRate() const override;
  140. private:
  141. const int64_t packets_received_;
  142. const DataSize bytes_received_;
  143. const SamplesStatsCounter received_packets_size_counter_;
  144. const int64_t packets_dropped_;
  145. const DataSize bytes_dropped_;
  146. const SamplesStatsCounter dropped_packets_size_counter_;
  147. const DataSize first_received_packet_size_;
  148. const Timestamp first_packet_received_time_;
  149. const Timestamp last_packet_received_time_;
  150. };
  151. // This class is immutable and so is thread safe.
  152. class EmulatedNetworkStatsImpl final : public EmulatedNetworkStats {
  153. public:
  154. EmulatedNetworkStatsImpl(
  155. std::vector<rtc::IPAddress> local_addresses,
  156. SamplesStatsCounter sent_packets_queue_wait_time_us,
  157. std::map<rtc::IPAddress, std::unique_ptr<EmulatedNetworkOutgoingStats>>
  158. outgoing_stats_per_destination,
  159. std::map<rtc::IPAddress, std::unique_ptr<EmulatedNetworkIncomingStats>>
  160. incoming_stats_per_source)
  161. : local_addresses_(std::move(local_addresses)),
  162. sent_packets_queue_wait_time_us_(sent_packets_queue_wait_time_us),
  163. outgoing_stats_per_destination_(
  164. std::move(outgoing_stats_per_destination)),
  165. incoming_stats_per_source_(std::move(incoming_stats_per_source)),
  166. overall_outgoing_stats_(GetOverallOutgoingStats()),
  167. overall_incoming_stats_(GetOverallIncomingStats()) {}
  168. ~EmulatedNetworkStatsImpl() override = default;
  169. std::vector<rtc::IPAddress> LocalAddresses() const override {
  170. return local_addresses_;
  171. }
  172. int64_t PacketsSent() const override {
  173. return overall_outgoing_stats_->PacketsSent();
  174. }
  175. DataSize BytesSent() const override {
  176. return overall_outgoing_stats_->BytesSent();
  177. }
  178. const SamplesStatsCounter& SentPacketsSizeCounter() const override {
  179. return overall_outgoing_stats_->SentPacketsSizeCounter();
  180. }
  181. const SamplesStatsCounter& SentPacketsQueueWaitTimeUs() const override {
  182. return sent_packets_queue_wait_time_us_;
  183. }
  184. DataSize FirstSentPacketSize() const override {
  185. return overall_outgoing_stats_->FirstSentPacketSize();
  186. }
  187. Timestamp FirstPacketSentTime() const override {
  188. return overall_outgoing_stats_->FirstPacketSentTime();
  189. }
  190. Timestamp LastPacketSentTime() const override {
  191. return overall_outgoing_stats_->LastPacketSentTime();
  192. }
  193. DataRate AverageSendRate() const override {
  194. return overall_outgoing_stats_->AverageSendRate();
  195. }
  196. int64_t PacketsReceived() const override {
  197. return overall_incoming_stats_->PacketsReceived();
  198. }
  199. DataSize BytesReceived() const override {
  200. return overall_incoming_stats_->BytesReceived();
  201. }
  202. const SamplesStatsCounter& ReceivedPacketsSizeCounter() const override {
  203. return overall_incoming_stats_->ReceivedPacketsSizeCounter();
  204. }
  205. int64_t PacketsDropped() const override {
  206. return overall_incoming_stats_->PacketsDropped();
  207. }
  208. DataSize BytesDropped() const override {
  209. return overall_incoming_stats_->BytesDropped();
  210. }
  211. const SamplesStatsCounter& DroppedPacketsSizeCounter() const override {
  212. return overall_incoming_stats_->DroppedPacketsSizeCounter();
  213. }
  214. DataSize FirstReceivedPacketSize() const override {
  215. return overall_incoming_stats_->FirstReceivedPacketSize();
  216. }
  217. Timestamp FirstPacketReceivedTime() const override {
  218. return overall_incoming_stats_->FirstPacketReceivedTime();
  219. }
  220. Timestamp LastPacketReceivedTime() const override {
  221. return overall_incoming_stats_->LastPacketReceivedTime();
  222. }
  223. DataRate AverageReceiveRate() const override {
  224. return overall_incoming_stats_->AverageReceiveRate();
  225. }
  226. std::map<rtc::IPAddress, std::unique_ptr<EmulatedNetworkOutgoingStats>>
  227. OutgoingStatsPerDestination() const override;
  228. std::map<rtc::IPAddress, std::unique_ptr<EmulatedNetworkIncomingStats>>
  229. IncomingStatsPerSource() const override;
  230. private:
  231. std::unique_ptr<EmulatedNetworkOutgoingStats> GetOverallOutgoingStats() const;
  232. std::unique_ptr<EmulatedNetworkIncomingStats> GetOverallIncomingStats() const;
  233. const std::vector<rtc::IPAddress> local_addresses_;
  234. const SamplesStatsCounter sent_packets_queue_wait_time_us_;
  235. const std::map<rtc::IPAddress, std::unique_ptr<EmulatedNetworkOutgoingStats>>
  236. outgoing_stats_per_destination_;
  237. const std::map<rtc::IPAddress, std::unique_ptr<EmulatedNetworkIncomingStats>>
  238. incoming_stats_per_source_;
  239. const std::unique_ptr<EmulatedNetworkOutgoingStats> overall_outgoing_stats_;
  240. const std::unique_ptr<EmulatedNetworkIncomingStats> overall_incoming_stats_;
  241. };
  242. class EmulatedNetworkOutgoingStatsBuilder {
  243. public:
  244. EmulatedNetworkOutgoingStatsBuilder();
  245. void OnPacketSent(Timestamp sent_time,
  246. DataSize packet_size,
  247. EmulatedEndpointConfig::StatsGatheringMode mode);
  248. void AddOutgoingStats(const EmulatedNetworkOutgoingStats& stats);
  249. std::unique_ptr<EmulatedNetworkOutgoingStats> Build() const;
  250. private:
  251. SequenceChecker sequence_checker_;
  252. int64_t packets_sent_ RTC_GUARDED_BY(sequence_checker_) = 0;
  253. DataSize bytes_sent_ RTC_GUARDED_BY(sequence_checker_) = DataSize::Zero();
  254. SamplesStatsCounter sent_packets_size_counter_
  255. RTC_GUARDED_BY(sequence_checker_);
  256. DataSize first_sent_packet_size_ RTC_GUARDED_BY(sequence_checker_) =
  257. DataSize::Zero();
  258. Timestamp first_packet_sent_time_ RTC_GUARDED_BY(sequence_checker_) =
  259. Timestamp::PlusInfinity();
  260. Timestamp last_packet_sent_time_ RTC_GUARDED_BY(sequence_checker_) =
  261. Timestamp::MinusInfinity();
  262. };
  263. class EmulatedNetworkIncomingStatsBuilder {
  264. public:
  265. EmulatedNetworkIncomingStatsBuilder();
  266. void OnPacketDropped(DataSize packet_size,
  267. EmulatedEndpointConfig::StatsGatheringMode mode);
  268. void OnPacketReceived(Timestamp received_time,
  269. DataSize packet_size,
  270. EmulatedEndpointConfig::StatsGatheringMode mode);
  271. // Adds stats collected from another endpoints to the builder.
  272. void AddIncomingStats(const EmulatedNetworkIncomingStats& stats);
  273. std::unique_ptr<EmulatedNetworkIncomingStats> Build() const;
  274. private:
  275. SequenceChecker sequence_checker_;
  276. int64_t packets_received_ RTC_GUARDED_BY(sequence_checker_) = 0;
  277. DataSize bytes_received_ RTC_GUARDED_BY(sequence_checker_) = DataSize::Zero();
  278. SamplesStatsCounter received_packets_size_counter_
  279. RTC_GUARDED_BY(sequence_checker_);
  280. int64_t packets_dropped_ RTC_GUARDED_BY(sequence_checker_) = 0;
  281. DataSize bytes_dropped_ RTC_GUARDED_BY(sequence_checker_) = DataSize::Zero();
  282. SamplesStatsCounter dropped_packets_size_counter_
  283. RTC_GUARDED_BY(sequence_checker_);
  284. DataSize first_received_packet_size_ RTC_GUARDED_BY(sequence_checker_) =
  285. DataSize::Zero();
  286. Timestamp first_packet_received_time_ RTC_GUARDED_BY(sequence_checker_) =
  287. Timestamp::PlusInfinity();
  288. Timestamp last_packet_received_time_ RTC_GUARDED_BY(sequence_checker_) =
  289. Timestamp::MinusInfinity();
  290. };
  291. // All methods of EmulatedNetworkStatsBuilder have to be used on a single
  292. // thread. It may be created on another thread.
  293. class EmulatedNetworkStatsBuilder {
  294. public:
  295. EmulatedNetworkStatsBuilder();
  296. explicit EmulatedNetworkStatsBuilder(rtc::IPAddress local_ip);
  297. void OnPacketSent(Timestamp queued_time,
  298. Timestamp sent_time,
  299. rtc::IPAddress destination_ip,
  300. DataSize packet_size,
  301. EmulatedEndpointConfig::StatsGatheringMode mode);
  302. void OnPacketDropped(rtc::IPAddress source_ip,
  303. DataSize packet_size,
  304. EmulatedEndpointConfig::StatsGatheringMode mode);
  305. void OnPacketReceived(Timestamp received_time,
  306. rtc::IPAddress source_ip,
  307. DataSize packet_size,
  308. EmulatedEndpointConfig::StatsGatheringMode mode);
  309. void AddEmulatedNetworkStats(const EmulatedNetworkStats& stats);
  310. std::unique_ptr<EmulatedNetworkStats> Build() const;
  311. private:
  312. SequenceChecker sequence_checker_;
  313. std::vector<rtc::IPAddress> local_addresses_
  314. RTC_GUARDED_BY(sequence_checker_);
  315. SamplesStatsCounter sent_packets_queue_wait_time_us_;
  316. std::map<rtc::IPAddress, EmulatedNetworkOutgoingStatsBuilder>
  317. outgoing_stats_per_destination_ RTC_GUARDED_BY(sequence_checker_);
  318. std::map<rtc::IPAddress, EmulatedNetworkIncomingStatsBuilder>
  319. incoming_stats_per_source_ RTC_GUARDED_BY(sequence_checker_);
  320. };
  321. class LinkEmulation : public EmulatedNetworkReceiverInterface {
  322. public:
  323. LinkEmulation(Clock* clock,
  324. rtc::TaskQueue* task_queue,
  325. std::unique_ptr<NetworkBehaviorInterface> network_behavior,
  326. EmulatedNetworkReceiverInterface* receiver)
  327. : clock_(clock),
  328. task_queue_(task_queue),
  329. network_behavior_(std::move(network_behavior)),
  330. receiver_(receiver) {}
  331. void OnPacketReceived(EmulatedIpPacket packet) override;
  332. private:
  333. struct StoredPacket {
  334. uint64_t id;
  335. EmulatedIpPacket packet;
  336. bool removed;
  337. };
  338. void Process(Timestamp at_time) RTC_RUN_ON(task_queue_);
  339. Clock* const clock_;
  340. rtc::TaskQueue* const task_queue_;
  341. const std::unique_ptr<NetworkBehaviorInterface> network_behavior_
  342. RTC_GUARDED_BY(task_queue_);
  343. EmulatedNetworkReceiverInterface* const receiver_;
  344. RepeatingTaskHandle process_task_ RTC_GUARDED_BY(task_queue_);
  345. std::deque<StoredPacket> packets_ RTC_GUARDED_BY(task_queue_);
  346. uint64_t next_packet_id_ RTC_GUARDED_BY(task_queue_) = 1;
  347. };
  348. class NetworkRouterNode : public EmulatedNetworkReceiverInterface {
  349. public:
  350. explicit NetworkRouterNode(rtc::TaskQueue* task_queue);
  351. void OnPacketReceived(EmulatedIpPacket packet) override;
  352. void SetReceiver(const rtc::IPAddress& dest_ip,
  353. EmulatedNetworkReceiverInterface* receiver);
  354. void RemoveReceiver(const rtc::IPAddress& dest_ip);
  355. void SetWatcher(std::function<void(const EmulatedIpPacket&)> watcher);
  356. void SetFilter(std::function<bool(const EmulatedIpPacket&)> filter);
  357. private:
  358. rtc::TaskQueue* const task_queue_;
  359. std::map<rtc::IPAddress, EmulatedNetworkReceiverInterface*> routing_
  360. RTC_GUARDED_BY(task_queue_);
  361. std::function<void(const EmulatedIpPacket&)> watcher_
  362. RTC_GUARDED_BY(task_queue_);
  363. std::function<bool(const EmulatedIpPacket&)> filter_
  364. RTC_GUARDED_BY(task_queue_);
  365. };
  366. // Represents node in the emulated network. Nodes can be connected with each
  367. // other to form different networks with different behavior. The behavior of
  368. // the node itself is determined by a concrete implementation of
  369. // NetworkBehaviorInterface that is provided on construction.
  370. class EmulatedNetworkNode : public EmulatedNetworkReceiverInterface {
  371. public:
  372. // Creates node based on |network_behavior|. The specified |packet_overhead|
  373. // is added to the size of each packet in the information provided to
  374. // |network_behavior|.
  375. // |task_queue| is used to process packets and to forward the packets when
  376. // they are ready.
  377. EmulatedNetworkNode(
  378. Clock* clock,
  379. rtc::TaskQueue* task_queue,
  380. std::unique_ptr<NetworkBehaviorInterface> network_behavior);
  381. ~EmulatedNetworkNode() override;
  382. RTC_DISALLOW_COPY_AND_ASSIGN(EmulatedNetworkNode);
  383. void OnPacketReceived(EmulatedIpPacket packet) override;
  384. LinkEmulation* link() { return &link_; }
  385. NetworkRouterNode* router() { return &router_; }
  386. // Creates a route for the given receiver_ip over all the given nodes to the
  387. // given receiver.
  388. static void CreateRoute(const rtc::IPAddress& receiver_ip,
  389. std::vector<EmulatedNetworkNode*> nodes,
  390. EmulatedNetworkReceiverInterface* receiver);
  391. static void ClearRoute(const rtc::IPAddress& receiver_ip,
  392. std::vector<EmulatedNetworkNode*> nodes);
  393. private:
  394. NetworkRouterNode router_;
  395. LinkEmulation link_;
  396. };
  397. // Represents single network interface on the device.
  398. // It will be used as sender from socket side to send data to the network and
  399. // will act as packet receiver from emulated network side to receive packets
  400. // from other EmulatedNetworkNodes.
  401. class EmulatedEndpointImpl : public EmulatedEndpoint {
  402. public:
  403. EmulatedEndpointImpl(
  404. uint64_t id,
  405. const rtc::IPAddress& ip,
  406. EmulatedEndpointConfig::StatsGatheringMode stats_gathering_mode,
  407. bool is_enabled,
  408. rtc::AdapterType type,
  409. rtc::TaskQueue* task_queue,
  410. Clock* clock);
  411. ~EmulatedEndpointImpl() override;
  412. uint64_t GetId() const;
  413. NetworkRouterNode* router() { return &router_; }
  414. void SendPacket(const rtc::SocketAddress& from,
  415. const rtc::SocketAddress& to,
  416. rtc::CopyOnWriteBuffer packet_data,
  417. uint16_t application_overhead = 0) override;
  418. absl::optional<uint16_t> BindReceiver(
  419. uint16_t desired_port,
  420. EmulatedNetworkReceiverInterface* receiver) override;
  421. void UnbindReceiver(uint16_t port) override;
  422. rtc::IPAddress GetPeerLocalAddress() const override;
  423. // Will be called to deliver packet into endpoint from network node.
  424. void OnPacketReceived(EmulatedIpPacket packet) override;
  425. void Enable();
  426. void Disable();
  427. bool Enabled() const;
  428. const rtc::Network& network() const { return *network_.get(); }
  429. std::unique_ptr<EmulatedNetworkStats> stats() const;
  430. private:
  431. static constexpr uint16_t kFirstEphemeralPort = 49152;
  432. uint16_t NextPort() RTC_EXCLUSIVE_LOCKS_REQUIRED(receiver_lock_);
  433. rtc::RecursiveCriticalSection receiver_lock_;
  434. rtc::ThreadChecker enabled_state_checker_;
  435. const uint64_t id_;
  436. // Peer's local IP address for this endpoint network interface.
  437. const rtc::IPAddress peer_local_addr_;
  438. const EmulatedEndpointConfig::StatsGatheringMode stats_gathering_mode_;
  439. bool is_enabled_ RTC_GUARDED_BY(enabled_state_checker_);
  440. const rtc::AdapterType type_;
  441. Clock* const clock_;
  442. rtc::TaskQueue* const task_queue_;
  443. std::unique_ptr<rtc::Network> network_;
  444. NetworkRouterNode router_;
  445. uint16_t next_port_ RTC_GUARDED_BY(receiver_lock_);
  446. std::map<uint16_t, EmulatedNetworkReceiverInterface*> port_to_receiver_
  447. RTC_GUARDED_BY(receiver_lock_);
  448. EmulatedNetworkStatsBuilder stats_builder_ RTC_GUARDED_BY(task_queue_);
  449. };
  450. class EmulatedRoute {
  451. public:
  452. EmulatedRoute(EmulatedEndpointImpl* from,
  453. std::vector<EmulatedNetworkNode*> via_nodes,
  454. EmulatedEndpointImpl* to)
  455. : from(from), via_nodes(std::move(via_nodes)), to(to), active(true) {}
  456. EmulatedEndpointImpl* from;
  457. std::vector<EmulatedNetworkNode*> via_nodes;
  458. EmulatedEndpointImpl* to;
  459. bool active;
  460. };
  461. // This object is immutable and so thread safe.
  462. class EndpointsContainer {
  463. public:
  464. explicit EndpointsContainer(
  465. const std::vector<EmulatedEndpointImpl*>& endpoints);
  466. EmulatedEndpointImpl* LookupByLocalAddress(
  467. const rtc::IPAddress& local_ip) const;
  468. bool HasEndpoint(EmulatedEndpointImpl* endpoint) const;
  469. // Returns list of networks for enabled endpoints. Caller takes ownership of
  470. // returned rtc::Network objects.
  471. std::vector<std::unique_ptr<rtc::Network>> GetEnabledNetworks() const;
  472. std::vector<EmulatedEndpoint*> GetEndpoints() const;
  473. std::unique_ptr<EmulatedNetworkStats> GetStats() const;
  474. private:
  475. const std::vector<EmulatedEndpointImpl*> endpoints_;
  476. };
  477. template <typename FakePacketType>
  478. class FakePacketRoute : public EmulatedNetworkReceiverInterface {
  479. public:
  480. FakePacketRoute(EmulatedRoute* route,
  481. std::function<void(FakePacketType, Timestamp)> action)
  482. : route_(route),
  483. action_(std::move(action)),
  484. send_addr_(route_->from->GetPeerLocalAddress(), 0),
  485. recv_addr_(route_->to->GetPeerLocalAddress(),
  486. *route_->to->BindReceiver(0, this)) {}
  487. ~FakePacketRoute() { route_->to->UnbindReceiver(recv_addr_.port()); }
  488. void SendPacket(size_t size, FakePacketType packet) {
  489. RTC_CHECK_GE(size, sizeof(int));
  490. sent_.emplace(next_packet_id_, packet);
  491. rtc::CopyOnWriteBuffer buf(size);
  492. reinterpret_cast<int*>(buf.data())[0] = next_packet_id_++;
  493. route_->from->SendPacket(send_addr_, recv_addr_, buf);
  494. }
  495. void OnPacketReceived(EmulatedIpPacket packet) override {
  496. int packet_id = reinterpret_cast<int*>(packet.data.data())[0];
  497. action_(std::move(sent_[packet_id]), packet.arrival_time);
  498. sent_.erase(packet_id);
  499. }
  500. private:
  501. EmulatedRoute* const route_;
  502. const std::function<void(FakePacketType, Timestamp)> action_;
  503. const rtc::SocketAddress send_addr_;
  504. const rtc::SocketAddress recv_addr_;
  505. int next_packet_id_ = 0;
  506. std::map<int, FakePacketType> sent_;
  507. };
  508. template <typename RequestPacketType, typename ResponsePacketType>
  509. class TwoWayFakeTrafficRoute {
  510. public:
  511. class TrafficHandlerInterface {
  512. public:
  513. virtual void OnRequest(RequestPacketType, Timestamp) = 0;
  514. virtual void OnResponse(ResponsePacketType, Timestamp) = 0;
  515. virtual ~TrafficHandlerInterface() = default;
  516. };
  517. TwoWayFakeTrafficRoute(TrafficHandlerInterface* handler,
  518. EmulatedRoute* send_route,
  519. EmulatedRoute* ret_route)
  520. : handler_(handler),
  521. request_handler_{send_route,
  522. [&](RequestPacketType packet, Timestamp arrival_time) {
  523. handler_->OnRequest(std::move(packet), arrival_time);
  524. }},
  525. response_handler_{
  526. ret_route, [&](ResponsePacketType packet, Timestamp arrival_time) {
  527. handler_->OnResponse(std::move(packet), arrival_time);
  528. }} {}
  529. void SendRequest(size_t size, RequestPacketType packet) {
  530. request_handler_.SendPacket(size, std::move(packet));
  531. }
  532. void SendResponse(size_t size, ResponsePacketType packet) {
  533. response_handler_.SendPacket(size, std::move(packet));
  534. }
  535. private:
  536. TrafficHandlerInterface* handler_;
  537. FakePacketRoute<RequestPacketType> request_handler_;
  538. FakePacketRoute<ResponsePacketType> response_handler_;
  539. };
  540. } // namespace webrtc
  541. #endif // TEST_NETWORK_NETWORK_EMULATION_H_