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