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.

296 lines
7.7 KiB

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