You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

334 lines
12 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2004--2008, Google Inc.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  17. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  19. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  22. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  23. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  24. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  25. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "talk/p2p/client/httpportallocator.h"
  28. #include <algorithm>
  29. #include <map>
  30. #include "talk/base/asynchttprequest.h"
  31. #include "talk/base/basicdefs.h"
  32. #include "talk/base/common.h"
  33. #include "talk/base/helpers.h"
  34. #include "talk/base/logging.h"
  35. #include "talk/base/nethelpers.h"
  36. #include "talk/base/signalthread.h"
  37. #include "talk/base/stringencode.h"
  38. namespace {
  39. const uint32 MSG_TIMEOUT = 100; // must not conflict
  40. // with BasicPortAllocator.cpp
  41. // Helper routine to remove whitespace from the ends of a string.
  42. void Trim(std::string& str) {
  43. size_t first = str.find_first_not_of(" \t\r\n");
  44. if (first == std::string::npos) {
  45. str.clear();
  46. return;
  47. }
  48. ASSERT(str.find_last_not_of(" \t\r\n") != std::string::npos);
  49. }
  50. // Parses the lines in the result of the HTTP request that are of the form
  51. // 'a=b' and returns them in a map.
  52. typedef std::map<std::string, std::string> StringMap;
  53. void ParseMap(const std::string& string, StringMap& map) {
  54. size_t start_of_line = 0;
  55. size_t end_of_line = 0;
  56. for (;;) { // for each line
  57. start_of_line = string.find_first_not_of("\r\n", end_of_line);
  58. if (start_of_line == std::string::npos)
  59. break;
  60. end_of_line = string.find_first_of("\r\n", start_of_line);
  61. if (end_of_line == std::string::npos) {
  62. end_of_line = string.length();
  63. }
  64. size_t equals = string.find('=', start_of_line);
  65. if ((equals >= end_of_line) || (equals == std::string::npos))
  66. continue;
  67. std::string key(string, start_of_line, equals - start_of_line);
  68. std::string value(string, equals + 1, end_of_line - equals - 1);
  69. Trim(key);
  70. Trim(value);
  71. if ((key.size() > 0) && (value.size() > 0))
  72. map[key] = value;
  73. }
  74. }
  75. } // namespace
  76. namespace cricket {
  77. // HttpPortAllocatorBase
  78. const int HttpPortAllocatorBase::kNumRetries = 5;
  79. const char HttpPortAllocatorBase::kCreateSessionURL[] = "/create_session";
  80. HttpPortAllocatorBase::HttpPortAllocatorBase(
  81. talk_base::NetworkManager* network_manager,
  82. talk_base::PacketSocketFactory* socket_factory,
  83. const std::string &user_agent)
  84. : BasicPortAllocator(network_manager, socket_factory), agent_(user_agent) {
  85. relay_hosts_.push_back("relay.google.com");
  86. stun_hosts_.push_back(
  87. talk_base::SocketAddress("stun.l.google.com", 19302));
  88. }
  89. HttpPortAllocatorBase::HttpPortAllocatorBase(
  90. talk_base::NetworkManager* network_manager,
  91. const std::string &user_agent)
  92. : BasicPortAllocator(network_manager), agent_(user_agent) {
  93. relay_hosts_.push_back("relay.google.com");
  94. stun_hosts_.push_back(
  95. talk_base::SocketAddress("stun.l.google.com", 19302));
  96. }
  97. HttpPortAllocatorBase::~HttpPortAllocatorBase() {
  98. }
  99. // HttpPortAllocatorSessionBase
  100. HttpPortAllocatorSessionBase::HttpPortAllocatorSessionBase(
  101. HttpPortAllocatorBase* allocator,
  102. const std::string& content_name,
  103. int component,
  104. const std::string& ice_ufrag,
  105. const std::string& ice_pwd,
  106. const std::vector<talk_base::SocketAddress>& stun_hosts,
  107. const std::vector<std::string>& relay_hosts,
  108. const std::string& relay_token,
  109. const std::string& user_agent)
  110. : BasicPortAllocatorSession(allocator, content_name, component,
  111. ice_ufrag, ice_pwd),
  112. relay_hosts_(relay_hosts), stun_hosts_(stun_hosts),
  113. relay_token_(relay_token), agent_(user_agent), attempts_(0) {
  114. }
  115. HttpPortAllocatorSessionBase::~HttpPortAllocatorSessionBase() {}
  116. void HttpPortAllocatorSessionBase::GetPortConfigurations() {
  117. // Creating relay sessions can take time and is done asynchronously.
  118. // Creating stun sessions could also take time and could be done aysnc also,
  119. // but for now is done here and added to the initial config. Note any later
  120. // configs will have unresolved stun ips and will be discarded by the
  121. // AllocationSequence.
  122. PortConfiguration* config = new PortConfiguration(stun_hosts_[0],
  123. username(),
  124. password());
  125. ConfigReady(config);
  126. TryCreateRelaySession();
  127. }
  128. void HttpPortAllocatorSessionBase::TryCreateRelaySession() {
  129. if (allocator()->flags() & PORTALLOCATOR_DISABLE_RELAY) {
  130. LOG(LS_VERBOSE) << "HttpPortAllocator: Relay ports disabled, skipping.";
  131. return;
  132. }
  133. if (attempts_ == HttpPortAllocator::kNumRetries) {
  134. LOG(LS_ERROR) << "HttpPortAllocator: maximum number of requests reached; "
  135. << "giving up on relay.";
  136. return;
  137. }
  138. if (relay_hosts_.size() == 0) {
  139. LOG(LS_ERROR) << "HttpPortAllocator: no relay hosts configured.";
  140. return;
  141. }
  142. // Choose the next host to try.
  143. std::string host = relay_hosts_[attempts_ % relay_hosts_.size()];
  144. attempts_++;
  145. LOG(LS_INFO) << "HTTPPortAllocator: sending to relay host " << host;
  146. if (relay_token_.empty()) {
  147. LOG(LS_WARNING) << "No relay auth token found.";
  148. }
  149. SendSessionRequest(host, talk_base::HTTP_SECURE_PORT);
  150. }
  151. std::string HttpPortAllocatorSessionBase::GetSessionRequestUrl() {
  152. std::string url = std::string(HttpPortAllocator::kCreateSessionURL);
  153. if (allocator()->flags() & PORTALLOCATOR_ENABLE_SHARED_UFRAG) {
  154. ASSERT(!username().empty());
  155. ASSERT(!password().empty());
  156. url = url + "?username=" + talk_base::s_url_encode(username()) +
  157. "&password=" + talk_base::s_url_encode(password());
  158. }
  159. return url;
  160. }
  161. void HttpPortAllocatorSessionBase::ReceiveSessionResponse(
  162. const std::string& response) {
  163. StringMap map;
  164. ParseMap(response, map);
  165. if (!username().empty() && map["username"] != username()) {
  166. LOG(LS_WARNING) << "Received unexpected username value from relay server.";
  167. }
  168. if (!password().empty() && map["password"] != password()) {
  169. LOG(LS_WARNING) << "Received unexpected password value from relay server.";
  170. }
  171. std::string relay_ip = map["relay.ip"];
  172. std::string relay_udp_port = map["relay.udp_port"];
  173. std::string relay_tcp_port = map["relay.tcp_port"];
  174. std::string relay_ssltcp_port = map["relay.ssltcp_port"];
  175. PortConfiguration* config = new PortConfiguration(stun_hosts_[0],
  176. map["username"],
  177. map["password"]);
  178. RelayServerConfig relay_config(RELAY_GTURN);
  179. if (!relay_udp_port.empty()) {
  180. talk_base::SocketAddress address(relay_ip, atoi(relay_udp_port.c_str()));
  181. relay_config.ports.push_back(ProtocolAddress(address, PROTO_UDP));
  182. }
  183. if (!relay_tcp_port.empty()) {
  184. talk_base::SocketAddress address(relay_ip, atoi(relay_tcp_port.c_str()));
  185. relay_config.ports.push_back(ProtocolAddress(address, PROTO_TCP));
  186. }
  187. if (!relay_ssltcp_port.empty()) {
  188. talk_base::SocketAddress address(relay_ip, atoi(relay_ssltcp_port.c_str()));
  189. relay_config.ports.push_back(ProtocolAddress(address, PROTO_SSLTCP));
  190. }
  191. config->AddRelay(relay_config);
  192. ConfigReady(config);
  193. }
  194. // HttpPortAllocator
  195. HttpPortAllocator::HttpPortAllocator(
  196. talk_base::NetworkManager* network_manager,
  197. talk_base::PacketSocketFactory* socket_factory,
  198. const std::string &user_agent)
  199. : HttpPortAllocatorBase(network_manager, socket_factory, user_agent) {
  200. }
  201. HttpPortAllocator::HttpPortAllocator(
  202. talk_base::NetworkManager* network_manager,
  203. const std::string &user_agent)
  204. : HttpPortAllocatorBase(network_manager, user_agent) {
  205. }
  206. HttpPortAllocator::~HttpPortAllocator() {}
  207. PortAllocatorSession* HttpPortAllocator::CreateSessionInternal(
  208. const std::string& content_name,
  209. int component,
  210. const std::string& ice_ufrag, const std::string& ice_pwd) {
  211. return new HttpPortAllocatorSession(this, content_name, component,
  212. ice_ufrag, ice_pwd, stun_hosts(),
  213. relay_hosts(), relay_token(),
  214. user_agent());
  215. }
  216. // HttpPortAllocatorSession
  217. HttpPortAllocatorSession::HttpPortAllocatorSession(
  218. HttpPortAllocator* allocator,
  219. const std::string& content_name,
  220. int component,
  221. const std::string& ice_ufrag,
  222. const std::string& ice_pwd,
  223. const std::vector<talk_base::SocketAddress>& stun_hosts,
  224. const std::vector<std::string>& relay_hosts,
  225. const std::string& relay,
  226. const std::string& agent)
  227. : HttpPortAllocatorSessionBase(allocator, content_name, component,
  228. ice_ufrag, ice_pwd, stun_hosts,
  229. relay_hosts, relay, agent) {
  230. }
  231. HttpPortAllocatorSession::~HttpPortAllocatorSession() {
  232. for (std::list<talk_base::AsyncHttpRequest*>::iterator it = requests_.begin();
  233. it != requests_.end(); ++it) {
  234. (*it)->Destroy(true);
  235. }
  236. }
  237. void HttpPortAllocatorSession::SendSessionRequest(const std::string& host,
  238. int port) {
  239. // Initiate an HTTP request to create a session through the chosen host.
  240. talk_base::AsyncHttpRequest* request =
  241. new talk_base::AsyncHttpRequest(user_agent());
  242. request->SignalWorkDone.connect(this,
  243. &HttpPortAllocatorSession::OnRequestDone);
  244. request->set_secure(port == talk_base::HTTP_SECURE_PORT);
  245. request->set_proxy(allocator()->proxy());
  246. request->response().document.reset(new talk_base::MemoryStream);
  247. request->request().verb = talk_base::HV_GET;
  248. request->request().path = GetSessionRequestUrl();
  249. request->request().addHeader("X-Talk-Google-Relay-Auth", relay_token(), true);
  250. request->request().addHeader("X-Stream-Type", "video_rtp", true);
  251. request->set_host(host);
  252. request->set_port(port);
  253. request->Start();
  254. request->Release();
  255. requests_.push_back(request);
  256. }
  257. void HttpPortAllocatorSession::OnRequestDone(talk_base::SignalThread* data) {
  258. talk_base::AsyncHttpRequest* request =
  259. static_cast<talk_base::AsyncHttpRequest*>(data);
  260. // Remove the request from the list of active requests.
  261. std::list<talk_base::AsyncHttpRequest*>::iterator it =
  262. std::find(requests_.begin(), requests_.end(), request);
  263. if (it != requests_.end()) {
  264. requests_.erase(it);
  265. }
  266. if (request->response().scode != 200) {
  267. LOG(LS_WARNING) << "HTTPPortAllocator: request "
  268. << " received error " << request->response().scode;
  269. TryCreateRelaySession();
  270. return;
  271. }
  272. LOG(LS_INFO) << "HTTPPortAllocator: request succeeded";
  273. talk_base::MemoryStream* stream =
  274. static_cast<talk_base::MemoryStream*>(request->response().document.get());
  275. stream->Rewind();
  276. size_t length;
  277. stream->GetSize(&length);
  278. std::string resp = std::string(stream->GetBuffer(), length);
  279. ReceiveSessionResponse(resp);
  280. }
  281. } // namespace cricket