candidate.cpp 8.0 KB

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