test_http_server.cc revision 790e62e2d8114647b0785574bea361cf931c482b
1// Copyright (c) 2009 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// This file implements a simple HTTP server. It can exhibit odd behavior
6// that's useful for testing. For example, it's useful to test that
7// the updater can continue a connection if it's dropped, or that it
8// handles very slow data transfers.
9
10// To use this, simply make an HTTP connection to localhost:port and
11// GET a url.
12
13#include <netinet/in.h>
14#include <sys/socket.h>
15#include <sys/types.h>
16#include <errno.h>
17#include <inttypes.h>
18#include <stdio.h>
19#include <stdlib.h>
20#include <string.h>
21#include <unistd.h>
22#include <algorithm>
23#include <string>
24#include <vector>
25#include "base/logging.h"
26
27using std::min;
28using std::string;
29using std::vector;
30
31namespace chromeos_update_engine {
32
33struct HttpRequest {
34  HttpRequest() : offset(0), return_code(200) {}
35  string url;
36  off_t offset;
37  int return_code;
38};
39
40namespace {
41const int kPort = 8080;  // hardcoded to 8080 for now
42const int kBigLength = 100000;
43}
44
45bool ParseRequest(int fd, HttpRequest* request) {
46  string headers;
47  while(headers.find("\r\n\r\n") == string::npos) {
48    vector<char> buf(1024);
49    memset(&buf[0], 0, buf.size());
50    ssize_t r = read(fd, &buf[0], buf.size() - 1);
51    if (r < 0) {
52      perror("read");
53      exit(1);
54    }
55    buf.resize(r);
56
57    headers.insert(headers.end(), buf.begin(), buf.end());
58  }
59  LOG(INFO) << "got headers: " << headers;
60
61  string::size_type url_start, url_end;
62  CHECK_NE(headers.find("GET "), string::npos);
63  url_start = headers.find("GET ") + strlen("GET ");
64  url_end = headers.find(' ', url_start);
65  CHECK_NE(string::npos, url_end);
66  string url = headers.substr(url_start, url_end - url_start);
67  LOG(INFO) << "URL: " << url;
68
69  string::size_type range_start, range_end;
70  if (headers.find("\r\nRange: ") == string::npos) {
71    request->offset = 0;
72  } else {
73    range_start = headers.find("\r\nRange: ") + strlen("\r\nRange: ");
74    range_end = headers.find('\r', range_start);
75    CHECK_NE(string::npos, range_end);
76    string range_header = headers.substr(range_start, range_end - range_start);
77
78    LOG(INFO) << "Range: " << range_header;
79    CHECK(*range_header.rbegin() == '-');
80    request->offset = atoll(range_header.c_str() + strlen("bytes="));
81    request->return_code = 206;  // Success for Range: request
82    LOG(INFO) << "Offset: " << request->offset;
83  }
84  request->url = url;
85  return true;
86}
87
88void WriteString(int fd, const string& str) {
89  unsigned int bytes_written = 0;
90  while (bytes_written < str.size()) {
91    ssize_t r = write(fd, str.c_str() + bytes_written,
92                      str.size() - bytes_written);
93    LOG(INFO) << "write() wrote " << r << " bytes";
94    if (r < 0) {
95      perror("write");
96      return;
97    }
98    bytes_written += r;
99  }
100  LOG(INFO) << "WriteString wrote " << bytes_written << " bytes";
101}
102
103string Itoa(off_t num) {
104  char buf[100] = {0};
105  snprintf(buf, sizeof(buf), "%" PRIi64, num);
106  return buf;
107}
108
109void WriteHeaders(int fd, bool support_range, off_t full_size,
110                  off_t start_offset, int return_code) {
111  LOG(INFO) << "writing headers";
112  WriteString(fd, string("HTTP/1.1 ") + Itoa(return_code) + " OK\r\n");
113  WriteString(fd, "Content-Type: application/octet-stream\r\n");
114  if (support_range) {
115    WriteString(fd, "Accept-Ranges: bytes\r\n");
116    WriteString(fd, string("Content-Range: bytes ") + Itoa(start_offset) +
117                "-" + Itoa(full_size - 1) + "/" + Itoa(full_size) + "\r\n");
118  }
119  off_t content_length = full_size;
120  if (support_range)
121    content_length -= start_offset;
122  WriteString(fd, string("Content-Length: ") + Itoa(content_length) + "\r\n");
123  WriteString(fd, "\r\n");
124}
125
126void HandleQuitQuitQuit(int fd) {
127  WriteHeaders(fd, true, 0, 0, 200);
128  exit(0);
129}
130
131void HandleBig(int fd, const HttpRequest& request) {
132  const off_t full_length = kBigLength;
133  WriteHeaders(fd, true, full_length, request.offset, request.return_code);
134  const off_t content_length = full_length - request.offset;
135  int i = request.offset;
136  for (; i % 10; i++)
137    WriteString(fd, string(1, 'a' + (i % 10)));
138  CHECK_EQ(i % 10, 0);
139  for (; i < content_length; i += 10)
140    WriteString(fd, "abcdefghij");
141  CHECK_EQ(i, full_length);
142}
143
144// This is like /big, but it writes at most 9000 bytes. Also,
145// half way through it sleeps for 70 seconds
146// (technically, when (offset % (9000 * 7)) == 0).
147void HandleFlaky(int fd, const HttpRequest& request) {
148  const off_t full_length = kBigLength;
149  WriteHeaders(fd, true, full_length, request.offset, request.return_code);
150  const off_t content_length =
151      min(static_cast<off_t>(9000), full_length - request.offset);
152  const bool should_sleep = (request.offset % (9000 * 7)) == 0;
153
154  string buf;
155
156  for (int i = request.offset; i % 10; i++)
157    buf.append(1, 'a' + (i % 10));
158  while (static_cast<off_t>(buf.size()) < content_length)
159    buf.append("abcdefghij");
160  buf.resize(content_length);
161
162  if (!should_sleep) {
163    LOG(INFO) << "writing data blob of size " << buf.size();
164    WriteString(fd, buf);
165  } else {
166    string::size_type half_way_point = buf.size() / 2;
167    LOG(INFO) << "writing small data blob of size " << half_way_point;
168    WriteString(fd, buf.substr(0, half_way_point));
169    sleep(10);
170    LOG(INFO) << "writing small data blob of size "
171              << (buf.size() - half_way_point);
172    WriteString(fd, buf.substr(half_way_point, buf.size() - half_way_point));
173  }
174}
175
176void HandleDefault(int fd, const HttpRequest& request) {
177  const string data("unhandled path");
178  WriteHeaders(fd, true, data.size(), request.offset, request.return_code);
179  const string data_to_write(data.substr(request.offset,
180                                         data.size() - request.offset));
181  WriteString(fd, data_to_write);
182}
183
184void HandleConnection(int fd) {
185  HttpRequest request;
186  ParseRequest(fd, &request);
187
188  if (request.url == "/quitquitquit")
189    HandleQuitQuitQuit(fd);
190  else if (request.url == "/big")
191    HandleBig(fd, request);
192  else if (request.url == "/flaky")
193    HandleFlaky(fd, request);
194  else
195    HandleDefault(fd, request);
196
197  close(fd);
198}
199
200}  // namespace chromeos_update_engine
201
202using namespace chromeos_update_engine;
203
204int main(int argc, char** argv) {
205  socklen_t clilen;
206  struct sockaddr_in server_addr;
207  struct sockaddr_in client_addr;
208  memset(&server_addr, 0, sizeof(server_addr));
209  memset(&client_addr, 0, sizeof(client_addr));
210
211  int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
212  if (listen_fd < 0)
213    LOG(FATAL) << "socket() failed";
214
215  server_addr.sin_family = AF_INET;
216  server_addr.sin_addr.s_addr = INADDR_ANY;
217  server_addr.sin_port = htons(kPort);
218
219  {
220    // Get rid of "Address in use" error
221    int tr = 1;
222    if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &tr,
223                   sizeof(int)) == -1) {
224      perror("setsockopt");
225      exit(1);
226    }
227  }
228
229  if (bind(listen_fd, reinterpret_cast<struct sockaddr *>(&server_addr),
230           sizeof(server_addr)) < 0) {
231    perror("bind");
232    exit(1);
233  }
234  CHECK_EQ(listen(listen_fd,5), 0);
235  while (1) {
236    clilen = sizeof(client_addr);
237    int client_fd = accept(listen_fd,
238                           (struct sockaddr *) &client_addr,
239                           &clilen);
240    LOG(INFO) << "got past accept";
241    if (client_fd < 0)
242      LOG(FATAL) << "ERROR on accept";
243    HandleConnection(client_fd);
244  }
245  return 0;
246}
247