2
0

candidate.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. /**
  2. * Copyright (c) 2019 Paul-Louis Ageneau
  3. *
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * This library 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 GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with this library; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include "candidate.hpp"
  19. #include "impl/internals.hpp"
  20. #include <algorithm>
  21. #include <array>
  22. #include <cctype>
  23. #include <sstream>
  24. #include <unordered_map>
  25. #ifdef _WIN32
  26. #include <winsock2.h>
  27. #include <ws2tcpip.h>
  28. #else
  29. #include <netdb.h>
  30. #include <netinet/in.h>
  31. #include <sys/socket.h>
  32. #endif
  33. #include <sys/types.h>
  34. using std::array;
  35. using std::string;
  36. namespace {
  37. inline bool match_prefix(const string &str, const string &prefix) {
  38. return str.size() >= prefix.size() &&
  39. std::mismatch(prefix.begin(), prefix.end(), str.begin()).first == prefix.end();
  40. }
  41. inline void trim_begin(string &str) {
  42. str.erase(str.begin(),
  43. std::find_if(str.begin(), str.end(), [](char c) { return !std::isspace(c); }));
  44. }
  45. inline void trim_end(string &str) {
  46. str.erase(
  47. std::find_if(str.rbegin(), str.rend(), [](char c) { return !std::isspace(c); }).base(),
  48. str.end());
  49. }
  50. } // namespace
  51. namespace rtc {
  52. Candidate::Candidate()
  53. : mFoundation("none"), mComponent(0), mPriority(0), mTypeString("unknown"),
  54. mTransportString("unknown"), mType(Type::Unknown), mTransportType(TransportType::Unknown),
  55. mNode("0.0.0.0"), mService("9"), mFamily(Family::Unresolved), mPort(0) {}
  56. Candidate::Candidate(string candidate) : Candidate() {
  57. if (!candidate.empty())
  58. parse(std::move(candidate));
  59. }
  60. Candidate::Candidate(string candidate, string mid) : Candidate() {
  61. if (!candidate.empty())
  62. parse(std::move(candidate));
  63. if (!mid.empty())
  64. mMid.emplace(std::move(mid));
  65. }
  66. void Candidate::parse(string candidate) {
  67. using TypeMap_t = std::unordered_map<string, Type>;
  68. using TcpTypeMap_t = std::unordered_map<string, TransportType>;
  69. static const TypeMap_t TypeMap = {{"host", Type::Host},
  70. {"srflx", Type::ServerReflexive},
  71. {"prflx", Type::PeerReflexive},
  72. {"relay", Type::Relayed}};
  73. static const TcpTypeMap_t TcpTypeMap = {{"active", TransportType::TcpActive},
  74. {"passive", TransportType::TcpPassive},
  75. {"so", TransportType::TcpSo}};
  76. const std::array prefixes{"a=", "candidate:"};
  77. for (string prefix : prefixes)
  78. if (match_prefix(candidate, prefix))
  79. candidate.erase(0, prefix.size());
  80. PLOG_VERBOSE << "Parsing candidate: " << candidate;
  81. // See RFC 8445 for format
  82. std::istringstream iss(candidate);
  83. string typ_;
  84. if (!(iss >> mFoundation >> mComponent >> mTransportString >> mPriority &&
  85. iss >> mNode >> mService >> typ_ >> mTypeString && typ_ == "typ"))
  86. throw std::invalid_argument("Invalid candidate format");
  87. std::getline(iss, mTail);
  88. trim_begin(mTail);
  89. trim_end(mTail);
  90. if (auto it = TypeMap.find(mTypeString); it != TypeMap.end())
  91. mType = it->second;
  92. else
  93. mType = Type::Unknown;
  94. if (mTransportString == "UDP" || mTransportString == "udp") {
  95. mTransportType = TransportType::Udp;
  96. } else if (mTransportString == "TCP" || mTransportString == "tcp") {
  97. // Peek tail to find TCP type
  98. std::istringstream tiss(mTail);
  99. string tcptype_, tcptype;
  100. if (tiss >> tcptype_ >> tcptype && tcptype_ == "tcptype") {
  101. if (auto it = TcpTypeMap.find(tcptype); it != TcpTypeMap.end())
  102. mTransportType = it->second;
  103. else
  104. mTransportType = TransportType::TcpUnknown;
  105. } else {
  106. mTransportType = TransportType::TcpUnknown;
  107. }
  108. } else {
  109. mTransportType = TransportType::Unknown;
  110. }
  111. }
  112. void Candidate::hintMid(string mid) {
  113. if (!mMid)
  114. mMid.emplace(std::move(mid));
  115. }
  116. bool Candidate::resolve(ResolveMode mode) {
  117. PLOG_VERBOSE << "Resolving candidate (mode="
  118. << (mode == ResolveMode::Simple ? "simple" : "lookup") << "): " << mNode << ' '
  119. << mService;
  120. // Try to resolve the node and service
  121. struct addrinfo hints = {};
  122. hints.ai_family = AF_UNSPEC;
  123. hints.ai_flags = AI_ADDRCONFIG;
  124. if (mTransportType == TransportType::Udp) {
  125. hints.ai_socktype = SOCK_DGRAM;
  126. hints.ai_protocol = IPPROTO_UDP;
  127. } else if (mTransportType != TransportType::Unknown) {
  128. hints.ai_socktype = SOCK_STREAM;
  129. hints.ai_protocol = IPPROTO_TCP;
  130. }
  131. if (mode == ResolveMode::Simple)
  132. hints.ai_flags |= AI_NUMERICHOST;
  133. struct addrinfo *result = nullptr;
  134. if (getaddrinfo(mNode.c_str(), mService.c_str(), &hints, &result) == 0) {
  135. for (auto p = result; p; p = p->ai_next) {
  136. if (p->ai_family == AF_INET || p->ai_family == AF_INET6) {
  137. char nodebuffer[MAX_NUMERICNODE_LEN];
  138. char servbuffer[MAX_NUMERICSERV_LEN];
  139. if (getnameinfo(p->ai_addr, socklen_t(p->ai_addrlen), nodebuffer,
  140. MAX_NUMERICNODE_LEN, servbuffer, MAX_NUMERICSERV_LEN,
  141. NI_NUMERICHOST | NI_NUMERICSERV) == 0) {
  142. try {
  143. mPort = uint16_t(std::stoul(servbuffer));
  144. } catch (...) {
  145. return false;
  146. }
  147. mAddress = nodebuffer;
  148. mFamily = p->ai_family == AF_INET6 ? Family::Ipv6 : Family::Ipv4;
  149. PLOG_VERBOSE << "Resolved candidate: " << mAddress << ' ' << mPort;
  150. break;
  151. }
  152. }
  153. }
  154. freeaddrinfo(result);
  155. }
  156. return mFamily != Family::Unresolved;
  157. }
  158. Candidate::Type Candidate::type() const { return mType; }
  159. Candidate::TransportType Candidate::transportType() const { return mTransportType; }
  160. uint32_t Candidate::priority() const { return mPriority; }
  161. string Candidate::candidate() const {
  162. const char sp{' '};
  163. std::ostringstream oss;
  164. oss << "candidate:";
  165. oss << mFoundation << sp << mComponent << sp << mTransportString << sp << mPriority << sp;
  166. if (isResolved())
  167. oss << mAddress << sp << mPort;
  168. else
  169. oss << mNode << sp << mService;
  170. oss << sp << "typ" << sp << mTypeString;
  171. if (!mTail.empty())
  172. oss << sp << mTail;
  173. return oss.str();
  174. }
  175. string Candidate::mid() const { return mMid.value_or("0"); }
  176. Candidate::operator string() const {
  177. std::ostringstream line;
  178. line << "a=" << candidate();
  179. return line.str();
  180. }
  181. bool Candidate::operator==(const Candidate &other) const {
  182. return (mFoundation == other.mFoundation && mService == other.mService && mNode == other.mNode);
  183. }
  184. bool Candidate::operator!=(const Candidate &other) const {
  185. return mFoundation != other.mFoundation;
  186. }
  187. bool Candidate::isResolved() const { return mFamily != Family::Unresolved; }
  188. Candidate::Family Candidate::family() const { return mFamily; }
  189. optional<string> Candidate::address() const {
  190. return isResolved() ? std::make_optional(mAddress) : nullopt;
  191. }
  192. optional<uint16_t> Candidate::port() const {
  193. return isResolved() ? std::make_optional(mPort) : nullopt;
  194. }
  195. } // namespace rtc
  196. std::ostream &operator<<(std::ostream &out, const rtc::Candidate &candidate) {
  197. return out << std::string(candidate);
  198. }
  199. std::ostream &operator<<(std::ostream &out, const rtc::Candidate::Type &type) {
  200. switch (type) {
  201. case rtc::Candidate::Type::Host:
  202. return out << "host";
  203. case rtc::Candidate::Type::PeerReflexive:
  204. return out << "prflx";
  205. case rtc::Candidate::Type::ServerReflexive:
  206. return out << "srflx";
  207. case rtc::Candidate::Type::Relayed:
  208. return out << "relay";
  209. default:
  210. return out << "unknown";
  211. }
  212. }
  213. std::ostream &operator<<(std::ostream &out, const rtc::Candidate::TransportType &transportType) {
  214. switch (transportType) {
  215. case rtc::Candidate::TransportType::Udp:
  216. return out << "UDP";
  217. case rtc::Candidate::TransportType::TcpActive:
  218. return out << "TCP_active";
  219. case rtc::Candidate::TransportType::TcpPassive:
  220. return out << "TCP_passive";
  221. case rtc::Candidate::TransportType::TcpSo:
  222. return out << "TCP_so";
  223. case rtc::Candidate::TransportType::TcpUnknown:
  224. return out << "TCP_unknown";
  225. default:
  226. return out << "unknown";
  227. }
  228. }