PlainConnection.cpp 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. #include "PlainConnection.h"
  2. #ifndef _WIN32
  3. #include <netdb.h> // for addrinfo, freeaddrinfo, getaddrinfo
  4. #include <netdb.h>
  5. #include <netinet/in.h> // for IPPROTO_IP, IPPROTO_TCP
  6. #include <netinet/tcp.h> // for TCP_NODELAY
  7. #include <sys/errno.h> // for EAGAIN, EINTR, ETIMEDOUT, errno
  8. #include <sys/socket.h> // for setsockopt, connect, recv, send, shutdown
  9. #include <sys/time.h> // for timeval
  10. #include <cstring> // for memset
  11. #include <stdexcept> // for runtime_error
  12. #else
  13. #include <ws2tcpip.h>
  14. #endif
  15. #include "BellLogger.h" // for AbstractLogger
  16. #include "Logger.h" // for CSPOT_LOG
  17. #include "Packet.h" // for cspot
  18. #include "Utils.h" // for extract, pack
  19. using namespace cspot;
  20. static int getErrno() {
  21. #ifdef _WIN32
  22. int code = WSAGetLastError();
  23. if (code == WSAETIMEDOUT)
  24. return ETIMEDOUT;
  25. if (code == WSAEINTR)
  26. return EINTR;
  27. return code;
  28. #else
  29. return errno;
  30. #endif
  31. }
  32. PlainConnection::PlainConnection() {
  33. this->apSock = -1;
  34. };
  35. PlainConnection::~PlainConnection() {
  36. this->close();
  37. };
  38. void PlainConnection::connect(const std::string& apAddress) {
  39. struct addrinfo h, *airoot, *ai;
  40. std::string hostname = apAddress.substr(0, apAddress.find(":"));
  41. std::string portStr =
  42. apAddress.substr(apAddress.find(":") + 1, apAddress.size());
  43. memset(&h, 0, sizeof(h));
  44. h.ai_family = AF_INET;
  45. h.ai_socktype = SOCK_STREAM;
  46. h.ai_protocol = IPPROTO_IP;
  47. // Lookup host
  48. if (getaddrinfo(hostname.c_str(), portStr.c_str(), &h, &airoot)) {
  49. CSPOT_LOG(error, "getaddrinfo failed");
  50. }
  51. // find the right ai, connect to server
  52. for (ai = airoot; ai; ai = ai->ai_next) {
  53. if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
  54. continue;
  55. this->apSock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  56. if (this->apSock < 0)
  57. continue;
  58. if (::connect(this->apSock, (struct sockaddr*)ai->ai_addr,
  59. ai->ai_addrlen) != -1) {
  60. #ifdef _WIN32
  61. uint32_t tv = 3000;
  62. #else
  63. struct timeval tv;
  64. tv.tv_sec = 3;
  65. tv.tv_usec = 0;
  66. #endif
  67. setsockopt(this->apSock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv,
  68. sizeof tv);
  69. setsockopt(this->apSock, SOL_SOCKET, SO_SNDTIMEO, (const char*)&tv,
  70. sizeof tv);
  71. int flag = 1;
  72. setsockopt(this->apSock, /* socket affected */
  73. IPPROTO_TCP, /* set option at TCP level */
  74. TCP_NODELAY, /* name of option */
  75. (char*)&flag, /* the cast is historical cruft */
  76. sizeof(int)); /* length of option value */
  77. break;
  78. }
  79. #ifdef _WIN32
  80. closesocket(this->apSock);
  81. #else
  82. ::close(this->apSock);
  83. #endif
  84. apSock = -1;
  85. throw std::runtime_error("Can't connect to spotify servers");
  86. }
  87. freeaddrinfo(airoot);
  88. CSPOT_LOG(debug, "Connected to spotify server");
  89. }
  90. std::vector<uint8_t> PlainConnection::recvPacket() {
  91. // Read packet size
  92. std::vector<uint8_t> packetBuffer(4);
  93. readBlock(packetBuffer.data(), 4);
  94. uint32_t packetSize = ntohl(extract<uint32_t>(packetBuffer, 0));
  95. packetBuffer.resize(packetSize, 0);
  96. // Read actual data
  97. readBlock(packetBuffer.data() + 4, packetSize - 4);
  98. return packetBuffer;
  99. }
  100. std::vector<uint8_t> PlainConnection::sendPrefixPacket(
  101. const std::vector<uint8_t>& prefix, const std::vector<uint8_t>& data) {
  102. // Calculate full packet length
  103. uint32_t actualSize = prefix.size() + data.size() + sizeof(uint32_t);
  104. // Packet structure [PREFIX] + [SIZE] + [DATA]
  105. auto sizeRaw = pack<uint32_t>(htonl(actualSize));
  106. sizeRaw.insert(sizeRaw.begin(), prefix.begin(), prefix.end());
  107. sizeRaw.insert(sizeRaw.end(), data.begin(), data.end());
  108. // Actually write it to the server
  109. writeBlock(sizeRaw);
  110. return sizeRaw;
  111. }
  112. void PlainConnection::readBlock(const uint8_t* dst, size_t size) {
  113. unsigned int idx = 0;
  114. ssize_t n;
  115. int retries = 0;
  116. while (idx < size) {
  117. READ:
  118. if ((n = recv(this->apSock, (char*)&dst[idx], size - idx, 0)) <= 0) {
  119. switch (getErrno()) {
  120. case EAGAIN:
  121. case ETIMEDOUT:
  122. if (timeoutHandler()) {
  123. CSPOT_LOG(error, "Connection lost, will need to reconnect...");
  124. throw std::runtime_error("Reconnection required");
  125. }
  126. goto READ;
  127. case EINTR:
  128. break;
  129. default:
  130. if (retries++ > 4)
  131. throw std::runtime_error("Error in read");
  132. goto READ;
  133. }
  134. }
  135. idx += n;
  136. }
  137. }
  138. size_t PlainConnection::writeBlock(const std::vector<uint8_t>& data) {
  139. unsigned int idx = 0;
  140. ssize_t n;
  141. int retries = 0;
  142. while (idx < data.size()) {
  143. WRITE:
  144. if ((n = send(this->apSock, (char*)&data[idx],
  145. data.size() - idx < 64 ? data.size() - idx : 64, 0)) <= 0) {
  146. switch (getErrno()) {
  147. case EAGAIN:
  148. case ETIMEDOUT:
  149. if (timeoutHandler()) {
  150. throw std::runtime_error("Reconnection required");
  151. }
  152. goto WRITE;
  153. case EINTR:
  154. break;
  155. default:
  156. if (retries++ > 4)
  157. throw std::runtime_error("Error in write");
  158. goto WRITE;
  159. }
  160. }
  161. idx += n;
  162. }
  163. return data.size();
  164. }
  165. void PlainConnection::close() {
  166. if (this->apSock < 0)
  167. return;
  168. CSPOT_LOG(info, "Closing socket...");
  169. shutdown(this->apSock, SHUT_RDWR);
  170. #ifdef _WIN32
  171. closesocket(this->apSock);
  172. #else
  173. ::close(this->apSock);
  174. #endif
  175. this->apSock = -1;
  176. }