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.

306 lines
8.7 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2011, 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/examples/peerconnection/server/data_socket.h"
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #if defined(POSIX)
  32. #include <unistd.h>
  33. #endif
  34. #include "talk/examples/peerconnection/server/utils.h"
  35. static const char kHeaderTerminator[] = "\r\n\r\n";
  36. static const int kHeaderTerminatorLength = sizeof(kHeaderTerminator) - 1;
  37. // static
  38. const char DataSocket::kCrossOriginAllowHeaders[] =
  39. "Access-Control-Allow-Origin: *\r\n"
  40. "Access-Control-Allow-Credentials: true\r\n"
  41. "Access-Control-Allow-Methods: POST, GET, OPTIONS\r\n"
  42. "Access-Control-Allow-Headers: Content-Type, "
  43. "Content-Length, Connection, Cache-Control\r\n"
  44. "Access-Control-Expose-Headers: Content-Length, X-Peer-Id\r\n";
  45. #if defined(WIN32)
  46. class WinsockInitializer {
  47. static WinsockInitializer singleton;
  48. WinsockInitializer() {
  49. WSADATA data;
  50. WSAStartup(MAKEWORD(1, 0), &data);
  51. }
  52. public:
  53. ~WinsockInitializer() { WSACleanup(); }
  54. };
  55. WinsockInitializer WinsockInitializer::singleton;
  56. #endif
  57. //
  58. // SocketBase
  59. //
  60. bool SocketBase::Create() {
  61. assert(!valid());
  62. socket_ = ::socket(AF_INET, SOCK_STREAM, 0);
  63. return valid();
  64. }
  65. void SocketBase::Close() {
  66. if (socket_ != INVALID_SOCKET) {
  67. closesocket(socket_);
  68. socket_ = INVALID_SOCKET;
  69. }
  70. }
  71. //
  72. // DataSocket
  73. //
  74. std::string DataSocket::request_arguments() const {
  75. size_t args = request_path_.find('?');
  76. if (args != std::string::npos)
  77. return request_path_.substr(args + 1);
  78. return "";
  79. }
  80. bool DataSocket::PathEquals(const char* path) const {
  81. assert(path);
  82. size_t args = request_path_.find('?');
  83. if (args != std::string::npos)
  84. return request_path_.substr(0, args).compare(path) == 0;
  85. return request_path_.compare(path) == 0;
  86. }
  87. bool DataSocket::OnDataAvailable(bool* close_socket) {
  88. assert(valid());
  89. char buffer[0xfff] = {0};
  90. int bytes = recv(socket_, buffer, sizeof(buffer), 0);
  91. if (bytes == SOCKET_ERROR || bytes == 0) {
  92. *close_socket = true;
  93. return false;
  94. }
  95. *close_socket = false;
  96. bool ret = true;
  97. if (headers_received()) {
  98. if (method_ != POST) {
  99. // unexpectedly received data.
  100. ret = false;
  101. } else {
  102. data_.append(buffer, bytes);
  103. }
  104. } else {
  105. request_headers_.append(buffer, bytes);
  106. size_t found = request_headers_.find(kHeaderTerminator);
  107. if (found != std::string::npos) {
  108. data_ = request_headers_.substr(found + kHeaderTerminatorLength);
  109. request_headers_.resize(found + kHeaderTerminatorLength);
  110. ret = ParseHeaders();
  111. }
  112. }
  113. return ret;
  114. }
  115. bool DataSocket::Send(const std::string& data) const {
  116. return send(socket_, data.data(), data.length(), 0) != SOCKET_ERROR;
  117. }
  118. bool DataSocket::Send(const std::string& status, bool connection_close,
  119. const std::string& content_type,
  120. const std::string& extra_headers,
  121. const std::string& data) const {
  122. assert(valid());
  123. assert(!status.empty());
  124. std::string buffer("HTTP/1.1 " + status + "\r\n");
  125. buffer += "Server: PeerConnectionTestServer/0.1\r\n"
  126. "Cache-Control: no-cache\r\n";
  127. if (connection_close)
  128. buffer += "Connection: close\r\n";
  129. if (!content_type.empty())
  130. buffer += "Content-Type: " + content_type + "\r\n";
  131. buffer += "Content-Length: " + int2str(data.size()) + "\r\n";
  132. if (!extra_headers.empty()) {
  133. buffer += extra_headers;
  134. // Extra headers are assumed to have a separator per header.
  135. }
  136. buffer += kCrossOriginAllowHeaders;
  137. buffer += "\r\n";
  138. buffer += data;
  139. return Send(buffer);
  140. }
  141. void DataSocket::Clear() {
  142. method_ = INVALID;
  143. content_length_ = 0;
  144. content_type_.clear();
  145. request_path_.clear();
  146. request_headers_.clear();
  147. data_.clear();
  148. }
  149. bool DataSocket::ParseHeaders() {
  150. assert(!request_headers_.empty());
  151. assert(method_ == INVALID);
  152. size_t i = request_headers_.find("\r\n");
  153. if (i == std::string::npos)
  154. return false;
  155. if (!ParseMethodAndPath(request_headers_.data(), i))
  156. return false;
  157. assert(method_ != INVALID);
  158. assert(!request_path_.empty());
  159. if (method_ == POST) {
  160. const char* headers = request_headers_.data() + i + 2;
  161. size_t len = request_headers_.length() - i - 2;
  162. if (!ParseContentLengthAndType(headers, len))
  163. return false;
  164. }
  165. return true;
  166. }
  167. bool DataSocket::ParseMethodAndPath(const char* begin, size_t len) {
  168. struct {
  169. const char* method_name;
  170. size_t method_name_len;
  171. RequestMethod id;
  172. } supported_methods[] = {
  173. { "GET", 3, GET },
  174. { "POST", 4, POST },
  175. { "OPTIONS", 7, OPTIONS },
  176. };
  177. const char* path = NULL;
  178. for (size_t i = 0; i < ARRAYSIZE(supported_methods); ++i) {
  179. if (len > supported_methods[i].method_name_len &&
  180. isspace(begin[supported_methods[i].method_name_len]) &&
  181. strncmp(begin, supported_methods[i].method_name,
  182. supported_methods[i].method_name_len) == 0) {
  183. method_ = supported_methods[i].id;
  184. path = begin + supported_methods[i].method_name_len;
  185. break;
  186. }
  187. }
  188. const char* end = begin + len;
  189. if (!path || path >= end)
  190. return false;
  191. ++path;
  192. begin = path;
  193. while (!isspace(*path) && path < end)
  194. ++path;
  195. request_path_.assign(begin, path - begin);
  196. return true;
  197. }
  198. bool DataSocket::ParseContentLengthAndType(const char* headers, size_t length) {
  199. assert(content_length_ == 0);
  200. assert(content_type_.empty());
  201. const char* end = headers + length;
  202. while (headers && headers < end) {
  203. if (!isspace(headers[0])) {
  204. static const char kContentLength[] = "Content-Length:";
  205. static const char kContentType[] = "Content-Type:";
  206. if ((headers + ARRAYSIZE(kContentLength)) < end &&
  207. strncmp(headers, kContentLength,
  208. ARRAYSIZE(kContentLength) - 1) == 0) {
  209. headers += ARRAYSIZE(kContentLength) - 1;
  210. while (headers[0] == ' ')
  211. ++headers;
  212. content_length_ = atoi(headers);
  213. } else if ((headers + ARRAYSIZE(kContentType)) < end &&
  214. strncmp(headers, kContentType,
  215. ARRAYSIZE(kContentType) - 1) == 0) {
  216. headers += ARRAYSIZE(kContentType) - 1;
  217. while (headers[0] == ' ')
  218. ++headers;
  219. const char* type_end = strstr(headers, "\r\n");
  220. if (type_end == NULL)
  221. type_end = end;
  222. content_type_.assign(headers, type_end);
  223. }
  224. } else {
  225. ++headers;
  226. }
  227. headers = strstr(headers, "\r\n");
  228. if (headers)
  229. headers += 2;
  230. }
  231. return !content_type_.empty() && content_length_ != 0;
  232. }
  233. //
  234. // ListeningSocket
  235. //
  236. bool ListeningSocket::Listen(unsigned short port) {
  237. assert(valid());
  238. int enabled = 1;
  239. setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR,
  240. reinterpret_cast<const char*>(&enabled), sizeof(enabled));
  241. struct sockaddr_in addr = {0};
  242. addr.sin_family = AF_INET;
  243. addr.sin_addr.s_addr = htonl(INADDR_ANY);
  244. addr.sin_port = htons(port);
  245. if (bind(socket_, reinterpret_cast<const sockaddr*>(&addr),
  246. sizeof(addr)) == SOCKET_ERROR) {
  247. printf("bind failed\n");
  248. return false;
  249. }
  250. return listen(socket_, 5) != SOCKET_ERROR;
  251. }
  252. DataSocket* ListeningSocket::Accept() const {
  253. assert(valid());
  254. struct sockaddr_in addr = {0};
  255. socklen_t size = sizeof(addr);
  256. int client = accept(socket_, reinterpret_cast<sockaddr*>(&addr), &size);
  257. if (client == INVALID_SOCKET)
  258. return NULL;
  259. return new DataSocket(client);
  260. }