PlainConnection.cpp 5.2 KB

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