connectivity.cpp 9.6 KB

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