connectivity.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /**
  2. * Copyright (c) 2019 Paul-Louis Ageneau
  3. *
  4. * This Source Code Form is subject to the terms of the Mozilla Public
  5. * License, v. 2.0. If a copy of the MPL was not distributed with this
  6. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  7. */
  8. #include "rtc/rtc.hpp"
  9. #include "test.hpp"
  10. #include <atomic>
  11. #include <chrono>
  12. #include <iostream>
  13. #include <memory>
  14. #include <thread>
  15. #define CUSTOM_MAX_MESSAGE_SIZE 1048576
  16. using namespace rtc;
  17. using namespace std;
  18. template <class T> weak_ptr<T> make_weak_ptr(shared_ptr<T> ptr) { return ptr; }
  19. TestResult test_connectivity(bool);
  20. TestResult test_connectivity() { return test_connectivity(false); }
  21. TestResult test_connectivity_fail_on_wrong_fingerprint() { return test_connectivity(true); }
  22. TestResult test_connectivity(bool signal_wrong_fingerprint) {
  23. InitLogger(LogLevel::Debug);
  24. Configuration config1;
  25. // STUN server example (not necessary to connect locally)
  26. config1.iceServers.emplace_back("stun:stun.l.google.com:19302");
  27. // Custom MTU example
  28. config1.mtu = 1500;
  29. // Custom max message size
  30. config1.maxMessageSize = CUSTOM_MAX_MESSAGE_SIZE;
  31. PeerConnection pc1(config1);
  32. Configuration config2;
  33. // STUN server example (not necessary to connect locally)
  34. config2.iceServers.emplace_back("stun:stun.l.google.com:19302");
  35. // Custom MTU example
  36. config2.mtu = 1500;
  37. // Custom max message size
  38. config2.maxMessageSize = CUSTOM_MAX_MESSAGE_SIZE;
  39. // Port range example
  40. config2.portRangeBegin = 5000;
  41. config2.portRangeEnd = 6000;
  42. PeerConnection pc2(config2);
  43. pc1.onLocalDescription([&pc2, signal_wrong_fingerprint](Description sdp) {
  44. cout << "Description 1: " << sdp << endl;
  45. if (signal_wrong_fingerprint) {
  46. auto f = sdp.fingerprint();
  47. if (f.has_value()) {
  48. auto& c = f.value().value[0];
  49. if (c == 'F' || c == 'f') c = '0'; else c++;
  50. sdp.setFingerprint(f.value());
  51. }
  52. }
  53. pc2.setRemoteDescription(string(sdp));
  54. });
  55. pc1.onLocalCandidate([&pc2](Candidate candidate) {
  56. cout << "Candidate 1: " << candidate << endl;
  57. pc2.addRemoteCandidate(string(candidate));
  58. });
  59. pc1.onStateChange([](PeerConnection::State state) { cout << "State 1: " << state << endl; });
  60. pc1.onIceStateChange([](PeerConnection::IceState state) {
  61. cout << "ICE state 1: " << state << endl;
  62. });
  63. pc1.onGatheringStateChange([](PeerConnection::GatheringState state) {
  64. cout << "Gathering state 1: " << state << endl;
  65. });
  66. pc1.onSignalingStateChange([](PeerConnection::SignalingState state) {
  67. cout << "Signaling state 1: " << state << endl;
  68. });
  69. pc2.onLocalDescription([&pc1](Description sdp) {
  70. cout << "Description 2: " << sdp << endl;
  71. pc1.setRemoteDescription(string(sdp));
  72. });
  73. pc2.onLocalCandidate([&pc1](Candidate candidate) {
  74. cout << "Candidate 2: " << candidate << endl;
  75. pc1.addRemoteCandidate(string(candidate));
  76. });
  77. pc2.onStateChange([](PeerConnection::State state) { cout << "State 2: " << state << endl; });
  78. pc2.onIceStateChange([](PeerConnection::IceState state) {
  79. cout << "ICE state 2: " << state << endl;
  80. });
  81. pc2.onGatheringStateChange([](PeerConnection::GatheringState state) {
  82. cout << "Gathering state 2: " << state << endl;
  83. });
  84. pc2.onSignalingStateChange([](PeerConnection::SignalingState state) {
  85. cout << "Signaling state 2: " << state << endl;
  86. });
  87. shared_ptr<DataChannel> dc2;
  88. pc2.onDataChannel([&dc2](shared_ptr<DataChannel> dc) {
  89. cout << "DataChannel 2: Received with label \"" << dc->label() << "\"" << endl;
  90. dc->onOpen([wdc = make_weak_ptr(dc)]() {
  91. if (auto dc = wdc.lock()) {
  92. cout << "DataChannel 2: Open" << endl;
  93. dc->send("Hello from 2");
  94. }
  95. });
  96. dc->onClosed([]() { cout << "DataChannel 2: Closed" << endl; });
  97. dc->onMessage([](variant<binary, string> message) {
  98. if (holds_alternative<string>(message)) {
  99. cout << "Message 2: " << get<string>(message) << endl;
  100. }
  101. });
  102. std::atomic_store(&dc2, dc);
  103. });
  104. auto dc1 = pc1.createDataChannel("test");
  105. if (dc1->id().has_value())
  106. return TestResult(false, "DataChannel stream id assigned before connection");
  107. dc1->onOpen([wdc1 = make_weak_ptr(dc1)]() {
  108. if (auto dc1 = wdc1.lock()) {
  109. cout << "DataChannel 1: Open" << endl;
  110. dc1->send("Hello from 1");
  111. }
  112. });
  113. dc1->onClosed([]() { cout << "DataChannel 1: Closed" << endl; });
  114. dc1->onMessage([](const variant<binary, string> &message) {
  115. if (holds_alternative<string>(message)) {
  116. cout << "Message 1: " << get<string>(message) << endl;
  117. }
  118. });
  119. // Wait a bit
  120. int attempts = 10;
  121. shared_ptr<DataChannel> adc2;
  122. while ((!(adc2 = std::atomic_load(&dc2)) || !adc2->isOpen() || !dc1->isOpen()) && attempts--)
  123. this_thread::sleep_for(1s);
  124. if (pc1.state() != PeerConnection::State::Connected ||
  125. pc2.state() != PeerConnection::State::Connected) {
  126. if (signal_wrong_fingerprint) {
  127. return TestResult(true);
  128. } else {
  129. return TestResult(false, "PeerConnection is not connected");
  130. }
  131. }
  132. if ((pc1.iceState() != PeerConnection::IceState::Connected &&
  133. pc1.iceState() != PeerConnection::IceState::Completed) ||
  134. (pc2.iceState() != PeerConnection::IceState::Connected &&
  135. pc2.iceState() != PeerConnection::IceState::Completed))
  136. return TestResult(false, "ICE is not connected");
  137. if (!adc2 || !adc2->isOpen() || !dc1->isOpen())
  138. return TestResult(false, "DataChannel is not open");
  139. if (adc2->label() != "test")
  140. return TestResult(false, "Wrong DataChannel label");
  141. if (dc1->maxMessageSize() != CUSTOM_MAX_MESSAGE_SIZE ||
  142. dc2->maxMessageSize() != CUSTOM_MAX_MESSAGE_SIZE)
  143. return TestResult(false, "DataChannel max message size is incorrect");
  144. if (!dc1->id().has_value())
  145. return TestResult(false, "DataChannel stream id is not assigned");
  146. if (dc1->id().value() != adc2->id().value())
  147. return TestResult(false, "DataChannel stream ids do not match");
  148. if (auto addr = pc1.localAddress())
  149. cout << "Local address 1: " << *addr << endl;
  150. if (auto addr = pc1.remoteAddress())
  151. cout << "Remote address 1: " << *addr << endl;
  152. if (auto addr = pc2.localAddress())
  153. cout << "Local address 2: " << *addr << endl;
  154. if (auto addr = pc2.remoteAddress())
  155. cout << "Remote address 2: " << *addr << endl;
  156. Candidate local, remote;
  157. if (pc1.getSelectedCandidatePair(&local, &remote)) {
  158. cout << "Local candidate 1: " << local << endl;
  159. cout << "Remote candidate 1: " << remote << endl;
  160. }
  161. if (pc2.getSelectedCandidatePair(&local, &remote)) {
  162. cout << "Local candidate 2: " << local << endl;
  163. cout << "Remote candidate 2: " << remote << endl;
  164. }
  165. // Try to open a second data channel with another label
  166. shared_ptr<DataChannel> second2;
  167. pc2.onDataChannel([&second2](shared_ptr<DataChannel> dc) {
  168. cout << "Second DataChannel 2: Received with label \"" << dc->label() << "\"" << endl;
  169. dc->onOpen([wdc = make_weak_ptr(dc)]() {
  170. if (auto dc = wdc.lock())
  171. dc->send("Second hello from 2");
  172. });
  173. dc->onMessage([](variant<binary, string> message) {
  174. if (holds_alternative<string>(message)) {
  175. cout << "Second Message 2: " << get<string>(message) << endl;
  176. }
  177. });
  178. std::atomic_store(&second2, dc);
  179. });
  180. auto second1 = pc1.createDataChannel("second");
  181. if (!second1->id().has_value())
  182. throw std::runtime_error("Second DataChannel stream id is not assigned");
  183. second1->onOpen([wsecond1 = make_weak_ptr(second1)]() {
  184. if (auto second1 = wsecond1.lock()) {
  185. cout << "Second DataChannel 1: Open" << endl;
  186. second1->send("Second hello from 1");
  187. }
  188. });
  189. second1->onClosed([]() { cout << "Second DataChannel 1: Closed" << endl; });
  190. second1->onMessage([](const variant<binary, string> &message) {
  191. if (holds_alternative<string>(message)) {
  192. cout << "Second Message 1: " << get<string>(message) << endl;
  193. }
  194. });
  195. // Wait a bit
  196. attempts = 10;
  197. shared_ptr<DataChannel> asecond2;
  198. while (
  199. (!(asecond2 = std::atomic_load(&second2)) || !asecond2->isOpen() || !second1->isOpen()) &&
  200. attempts--)
  201. this_thread::sleep_for(1s);
  202. if (!asecond2 || !asecond2->isOpen() || !second1->isOpen())
  203. return TestResult(false, "Second DataChannel is not open");
  204. if (asecond2->label() != "second")
  205. return TestResult(false, "Wrong second DataChannel label");
  206. if (!second2->id().has_value() || !asecond2->id().has_value())
  207. return TestResult(false, "Second DataChannel stream id is not assigned");
  208. if (second2->id().value() != asecond2->id().value())
  209. return TestResult(false, "Second DataChannel stream ids do not match");
  210. // Delay close of peer 2 to check closing works properly
  211. pc1.close();
  212. this_thread::sleep_for(1s);
  213. pc2.close();
  214. this_thread::sleep_for(1s);
  215. return TestResult(true);
  216. }
  217. const char* key_pem =
  218. "-----BEGIN PRIVATE KEY-----\n"
  219. "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg3bbuT2SjSlMZH/J1\n"
  220. "vHwmF0Blb/DBc/v7f1Za9GPUXHmhRANCAATDpmYxZozjVw6xlERNjJJGgfY3bEmj\n"
  221. "xAKFRq3nbxbDHvMEs34u9HntMZWJ0hp3GUC+Ax7JHTv3cYqSaAg2SpR4\n"
  222. "-----END PRIVATE KEY-----\n";
  223. const char* cert_pem =
  224. "-----BEGIN CERTIFICATE-----\n"
  225. "MIIBgjCCASigAwIBAgIJAPMXEoZXOaDEMAoGCCqGSM49BAMCMEoxDzANBgNVBAMM\n"
  226. "BmNhLmNvbTELMAkGA1UEBhMCVVMxCzAJBgNVBAcMAkNBMRAwDgYDVQQKDAdleGFt\n"
  227. "cGxlMQswCQYDVQQIDAJDQTAeFw0yNDA1MDUxNjAzMjFaFw0yNDA4MTMxNjAzMjFa\n"
  228. "MDExCzAJBgNVBAYTAkNOMRAwDgYDVQQKDAdiYW96LmNuMRAwDgYDVQQDDAdiYW96\n"
  229. "Lm1lMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEw6ZmMWaM41cOsZRETYySRoH2\n"
  230. "N2xJo8QChUat528Wwx7zBLN+LvR57TGVidIadxlAvgMeyR0793GKkmgINkqUeKMQ\n"
  231. "MA4wDAYDVR0TAQH/BAIwADAKBggqhkjOPQQDAgNIADBFAiAPNldqGJHryfjPFyX3\n"
  232. "zfHHWlO7xSDTzdyoxzroFdwy+gIhAKmZizEVvDlBiIe+3ptCArU3dbp+bzLynTcr\n"
  233. "Ma9ayzQy\n"
  234. "-----END CERTIFICATE-----\n";
  235. TestResult test_pem() {
  236. InitLogger(LogLevel::Debug);
  237. Configuration config1;
  238. config1.certificatePemFile = cert_pem;
  239. config1.keyPemFile = key_pem;
  240. PeerConnection pc1(config1);
  241. atomic_bool done;
  242. string f;
  243. pc1.onLocalDescription([&done, &f](Description sdp) {
  244. f = sdp.fingerprint().value().value;
  245. done = true;
  246. });
  247. auto dc1 = pc1.createDataChannel("test");
  248. // Wait a bit
  249. int attempts = 10;
  250. while (!done && attempts--)
  251. this_thread::sleep_for(1s);
  252. cout << "Fingerprint: " << f << endl;
  253. if (f != "07:E5:6F:2A:1A:0C:2C:32:0E:C1:C3:9C:34:5A:78:4E:A5:8B:32:05:D1:57:D6:F4:E7:02:41:12:"
  254. "E6:01:C6:8F")
  255. return TestResult(false, "The fingerprint of the specified certificate do not match");
  256. return TestResult(true);
  257. }