blob: a2f1e0527598b98e62a1fa88aea967f89d04ec89 [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
adlr@google.com3defe6a2009-12-04 20:57:17 +000016
17// This file implements a simple HTTP server. It can exhibit odd behavior
18// that's useful for testing. For example, it's useful to test that
19// the updater can continue a connection if it's dropped, or that it
20// handles very slow data transfers.
21
22// To use this, simply make an HTTP connection to localhost:port and
23// GET a url.
24
Gilad Arnold97bdb3f2013-06-30 23:05:50 -070025#include <err.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000026#include <errno.h>
Gilad Arnoldb6c562a2013-07-01 02:19:26 -070027#include <fcntl.h>
Andrew de los Reyes08c4e272010-04-15 14:02:17 -070028#include <inttypes.h>
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -070029#include <netinet/in.h>
30#include <signal.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000031#include <stdio.h>
32#include <stdlib.h>
33#include <string.h>
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -070034#include <sys/socket.h>
Gilad Arnoldb6c562a2013-07-01 02:19:26 -070035#include <sys/stat.h>
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -070036#include <sys/types.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000037#include <unistd.h>
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -070038
adlr@google.com3defe6a2009-12-04 20:57:17 +000039#include <algorithm>
40#include <string>
41#include <vector>
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -070042
43#include <base/logging.h>
Alex Deymof123ae22015-09-24 14:59:43 -070044#include <base/posix/eintr_wrapper.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070045#include <base/strings/string_split.h>
46#include <base/strings/string_util.h>
47#include <base/strings/stringprintf.h>
Gilad Arnold9bedeb52011-11-17 16:19:57 -080048
Alex Deymo39910dc2015-11-09 17:04:30 -080049#include "update_engine/common/http_common.h"
Gilad Arnold9bedeb52011-11-17 16:19:57 -080050
Gilad Arnolde4ad2502011-12-29 17:08:54 -080051// HTTP end-of-line delimiter; sorry, this needs to be a macro.
52#define EOL "\r\n"
53
adlr@google.com3defe6a2009-12-04 20:57:17 +000054using std::string;
55using std::vector;
56
57namespace chromeos_update_engine {
58
Gilad Arnoldb6c562a2013-07-01 02:19:26 -070059static const char* kListeningMsgPrefix = "listening on port ";
Gilad Arnold97bdb3f2013-06-30 23:05:50 -070060
61enum {
62 RC_OK = 0,
63 RC_BAD_ARGS,
64 RC_ERR_READ,
65 RC_ERR_SETSOCKOPT,
66 RC_ERR_BIND,
Gilad Arnoldb6c562a2013-07-01 02:19:26 -070067 RC_ERR_LISTEN,
68 RC_ERR_GETSOCKNAME,
69 RC_ERR_REPORT,
Gilad Arnold97bdb3f2013-06-30 23:05:50 -070070};
71
adlr@google.com3defe6a2009-12-04 20:57:17 +000072struct HttpRequest {
Alex Deymo6f10c5f2016-03-03 22:35:43 -080073 string raw_headers;
Darin Petkov41c2fcf2010-08-25 13:14:48 -070074 string host;
adlr@google.com3defe6a2009-12-04 20:57:17 +000075 string url;
Alex Deymo6f10c5f2016-03-03 22:35:43 -080076 off_t start_offset{0};
77 off_t end_offset{0}; // non-inclusive, zero indicates unspecified.
78 HttpResponseCode return_code{kHttpResponseOk};
adlr@google.com3defe6a2009-12-04 20:57:17 +000079};
80
adlr@google.com3defe6a2009-12-04 20:57:17 +000081bool ParseRequest(int fd, HttpRequest* request) {
82 string headers;
Gilad Arnold9bedeb52011-11-17 16:19:57 -080083 do {
84 char buf[1024];
85 ssize_t r = read(fd, buf, sizeof(buf));
adlr@google.com3defe6a2009-12-04 20:57:17 +000086 if (r < 0) {
87 perror("read");
Gilad Arnold97bdb3f2013-06-30 23:05:50 -070088 exit(RC_ERR_READ);
adlr@google.com3defe6a2009-12-04 20:57:17 +000089 }
Gilad Arnold9bedeb52011-11-17 16:19:57 -080090 headers.append(buf, r);
Alex Vakulenkoa3cf75a2016-01-20 07:56:15 -080091 } while (!base::EndsWith(headers, EOL EOL, base::CompareCase::SENSITIVE));
adlr@google.com3defe6a2009-12-04 20:57:17 +000092
Gilad Arnold9bedeb52011-11-17 16:19:57 -080093 LOG(INFO) << "got headers:\n--8<------8<------8<------8<----\n"
Amin Hassani7cc8bb02019-01-14 16:29:47 -080094 << headers << "\n--8<------8<------8<------8<----";
Alex Deymo6f10c5f2016-03-03 22:35:43 -080095 request->raw_headers = headers;
adlr@google.com3defe6a2009-12-04 20:57:17 +000096
Gilad Arnold9bedeb52011-11-17 16:19:57 -080097 // Break header into lines.
Hidehiko Abeeab915e2018-09-23 16:54:06 +090098 vector<string> lines = base::SplitStringUsingSubstr(
99 headers.substr(0, headers.length() - strlen(EOL EOL)),
100 EOL,
101 base::TRIM_WHITESPACE,
102 base::SPLIT_WANT_ALL);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000103
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800104 // Decode URL line.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800105 vector<string> terms = base::SplitString(lines[0],
106 base::kWhitespaceASCII,
Alex Vakulenkoa3cf75a2016-01-20 07:56:15 -0800107 base::KEEP_WHITESPACE,
108 base::SPLIT_WANT_NONEMPTY);
Mike Frysinger0f9547d2012-02-16 12:11:37 -0500109 CHECK_EQ(terms.size(), static_cast<vector<string>::size_type>(3));
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800110 CHECK_EQ(terms[0], "GET");
111 request->url = terms[1];
112 LOG(INFO) << "URL: " << request->url;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000113
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800114 // Decode remaining lines.
115 size_t i;
116 for (i = 1; i < lines.size(); i++) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800117 terms = base::SplitString(lines[i],
118 base::kWhitespaceASCII,
119 base::KEEP_WHITESPACE,
120 base::SPLIT_WANT_NONEMPTY);
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700121
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800122 if (terms[0] == "Range:") {
Mike Frysinger0f9547d2012-02-16 12:11:37 -0500123 CHECK_EQ(terms.size(), static_cast<vector<string>::size_type>(2));
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800124 string& range = terms[1];
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800125 LOG(INFO) << "range attribute: " << range;
Alex Vakulenkoa3cf75a2016-01-20 07:56:15 -0800126 CHECK(base::StartsWith(range, "bytes=", base::CompareCase::SENSITIVE) &&
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800127 range.find('-') != string::npos);
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800128 request->start_offset = atoll(range.c_str() + strlen("bytes="));
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800129 // Decode end offset and increment it by one (so it is non-inclusive).
130 if (range.find('-') < range.length() - 1)
131 request->end_offset = atoll(range.c_str() + range.find('-') + 1) + 1;
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800132 request->return_code = kHttpResponsePartialContent;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800133 string tmp_str = base::StringPrintf(
134 "decoded range offsets: "
135 "start=%jd end=",
136 (intmax_t)request->start_offset);
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800137 if (request->end_offset > 0)
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800138 base::StringAppendF(
139 &tmp_str, "%jd (non-inclusive)", (intmax_t)request->end_offset);
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800140 else
141 base::StringAppendF(&tmp_str, "unspecified");
142 LOG(INFO) << tmp_str;
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800143 } else if (terms[0] == "Host:") {
Mike Frysinger0f9547d2012-02-16 12:11:37 -0500144 CHECK_EQ(terms.size(), static_cast<vector<string>::size_type>(2));
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800145 request->host = terms[1];
146 LOG(INFO) << "host attribute: " << request->host;
147 } else {
148 LOG(WARNING) << "ignoring HTTP attribute: `" << lines[i] << "'";
adlr@google.com3defe6a2009-12-04 20:57:17 +0000149 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000150 }
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800151
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700152 return true;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000153}
154
155string Itoa(off_t num) {
156 char buf[100] = {0};
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700157 snprintf(buf, sizeof(buf), "%" PRIi64, num);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000158 return buf;
159}
160
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800161// Writes a string into a file. Returns total number of bytes written or -1 if a
162// write error occurred.
163ssize_t WriteString(int fd, const string& str) {
164 const size_t total_size = str.size();
165 size_t remaining_size = total_size;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800166 char const* data = str.data();
Gilad Arnold48085ba2011-11-16 09:36:08 -0800167
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800168 while (remaining_size) {
169 ssize_t written = write(fd, data, remaining_size);
170 if (written < 0) {
171 perror("write");
172 LOG(INFO) << "write failed";
173 return -1;
174 }
175 data += written;
176 remaining_size -= written;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000177 }
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800178
179 return total_size;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000180}
181
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800182// Writes the headers of an HTTP response into a file.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800183ssize_t WriteHeaders(int fd,
184 const off_t start_offset,
185 const off_t end_offset,
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800186 HttpResponseCode return_code) {
187 ssize_t written = 0, ret;
188
189 ret = WriteString(fd,
190 string("HTTP/1.1 ") + Itoa(return_code) + " " +
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800191 GetHttpResponseDescription(return_code) +
Haibo Huang59ad2732020-09-09 15:23:59 -0700192 EOL "Content-Type: application/octet-stream" EOL
Vyshu852f57d2020-10-09 17:35:14 +0000193 "Connection: close" EOL);
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800194 if (ret < 0)
195 return -1;
196 written += ret;
197
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800198 // Compute content legnth.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800199 const off_t content_length = end_offset - start_offset;
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800200
201 // A start offset that equals the end offset indicates that the response
202 // should contain the full range of bytes in the requested resource.
203 if (start_offset || start_offset == end_offset) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800204 ret = WriteString(
205 fd,
206 string("Accept-Ranges: bytes" EOL "Content-Range: bytes ") +
207 Itoa(start_offset == end_offset ? 0 : start_offset) + "-" +
208 Itoa(end_offset - 1) + "/" + Itoa(end_offset) + EOL);
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800209 if (ret < 0)
210 return -1;
211 written += ret;
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800212 }
213
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800214 ret = WriteString(
215 fd, string("Content-Length: ") + Itoa(content_length) + EOL EOL);
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800216 if (ret < 0)
217 return -1;
218 written += ret;
219
220 return written;
221}
222
223// Writes a predetermined payload of lines of ascending bytes to a file. The
224// first byte of output is appropriately offset with respect to the request line
225// length. Returns the number of successfully written bytes.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800226size_t WritePayload(int fd,
227 const off_t start_offset,
228 const off_t end_offset,
229 const char first_byte,
230 const size_t line_len) {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800231 CHECK_LE(start_offset, end_offset);
Mike Frysinger0f9547d2012-02-16 12:11:37 -0500232 CHECK_GT(line_len, static_cast<size_t>(0));
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800233
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800234 LOG(INFO) << "writing payload: " << line_len << "-byte lines starting with `"
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800235 << first_byte << "', offset range " << start_offset << " -> "
236 << end_offset;
237
238 // Populate line of ascending characters.
239 string line;
240 line.reserve(line_len);
241 char byte = first_byte;
242 size_t i;
243 for (i = 0; i < line_len; i++)
244 line += byte++;
245
246 const size_t total_len = end_offset - start_offset;
247 size_t remaining_len = total_len;
248 bool success = true;
249
250 // If start offset is not aligned with line boundary, output partial line up
251 // to the first line boundary.
252 size_t start_modulo = start_offset % line_len;
253 if (start_modulo) {
254 string partial = line.substr(start_modulo, remaining_len);
255 ssize_t ret = WriteString(fd, partial);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800256 if ((success = (ret >= 0 && (size_t)ret == partial.length())))
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800257 remaining_len -= partial.length();
258 }
259
260 // Output full lines up to the maximal line boundary below the end offset.
261 while (success && remaining_len >= line_len) {
262 ssize_t ret = WriteString(fd, line);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800263 if ((success = (ret >= 0 && (size_t)ret == line_len)))
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800264 remaining_len -= line_len;
265 }
266
267 // Output a partial line up to the end offset.
268 if (success && remaining_len) {
269 string partial = line.substr(0, remaining_len);
270 ssize_t ret = WriteString(fd, partial);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800271 if ((success = (ret >= 0 && (size_t)ret == partial.length())))
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800272 remaining_len -= partial.length();
273 }
274
275 return (total_len - remaining_len);
276}
277
278// Write default payload lines of the form 'abcdefghij'.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800279inline size_t WritePayload(int fd,
280 const off_t start_offset,
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800281 const off_t end_offset) {
282 return WritePayload(fd, start_offset, end_offset, 'a', 10);
283}
284
285// Send an empty response, then kill the server.
286void HandleQuit(int fd) {
287 WriteHeaders(fd, 0, 0, kHttpResponseOk);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800288 LOG(INFO) << "pid(" << getpid() << "): HTTP server exiting ...";
Gilad Arnold97bdb3f2013-06-30 23:05:50 -0700289 exit(RC_OK);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000290}
291
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800292// Generates an HTTP response with payload corresponding to requested offsets
293// and length. Optionally, truncate the payload at a given length and add a
294// pause midway through the transfer. Returns the total number of bytes
295// delivered or -1 for error.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800296ssize_t HandleGet(int fd,
297 const HttpRequest& request,
298 const size_t total_length,
299 const size_t truncate_length,
300 const int sleep_every,
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800301 const int sleep_secs) {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800302 ssize_t ret;
303 size_t written = 0;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000304
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800305 // Obtain start offset, make sure it is within total payload length.
306 const size_t start_offset = request.start_offset;
307 if (start_offset >= total_length) {
308 LOG(WARNING) << "start offset (" << start_offset
309 << ") exceeds total length (" << total_length
310 << "), generating error response ("
311 << kHttpResponseReqRangeNotSat << ")";
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800312 return WriteHeaders(
313 fd, total_length, total_length, kHttpResponseReqRangeNotSat);
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800314 }
315
316 // Obtain end offset, adjust to fit in total payload length and ensure it does
317 // not preceded the start offset.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800318 size_t end_offset =
319 (request.end_offset > 0 ? request.end_offset : total_length);
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800320 if (end_offset < start_offset) {
321 LOG(WARNING) << "end offset (" << end_offset << ") precedes start offset ("
322 << start_offset << "), generating error response";
323 return WriteHeaders(fd, 0, 0, kHttpResponseBadRequest);
324 }
325 if (end_offset > total_length) {
326 LOG(INFO) << "requested end offset (" << end_offset
327 << ") exceeds total length (" << total_length << "), adjusting";
328 end_offset = total_length;
329 }
330
331 // Generate headers
332 LOG(INFO) << "generating response header: range=" << start_offset << "-"
333 << (end_offset - 1) << "/" << (end_offset - start_offset)
334 << ", return code=" << request.return_code;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800335 if ((ret = WriteHeaders(fd, start_offset, end_offset, request.return_code)) <
336 0)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800337 return -1;
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800338 LOG(INFO) << ret << " header bytes written";
339 written += ret;
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800340
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800341 // Compute payload length, truncate as necessary.
342 size_t payload_length = end_offset - start_offset;
343 if (truncate_length > 0 && truncate_length < payload_length) {
344 LOG(INFO) << "truncating request payload length (" << payload_length
345 << ") at " << truncate_length;
346 payload_length = truncate_length;
347 end_offset = start_offset + payload_length;
348 }
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800349
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800350 LOG(INFO) << "generating response payload: range=" << start_offset << "-"
351 << (end_offset - 1) << "/" << (end_offset - start_offset);
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800352
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800353 // Decide about optional midway delay.
354 if (truncate_length > 0 && sleep_every > 0 && sleep_secs >= 0 &&
355 start_offset % (truncate_length * sleep_every) == 0) {
356 const off_t midway_offset = start_offset + payload_length / 2;
357
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800358 if ((ret = WritePayload(fd, start_offset, midway_offset)) < 0)
359 return -1;
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800360 LOG(INFO) << ret << " payload bytes written (first chunk)";
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800361 written += ret;
362
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800363 LOG(INFO) << "sleeping for " << sleep_secs << " seconds...";
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800364 sleep(sleep_secs);
365
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800366 if ((ret = WritePayload(fd, midway_offset, end_offset)) < 0)
367 return -1;
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800368 LOG(INFO) << ret << " payload bytes written (second chunk)";
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800369 written += ret;
370 } else {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800371 if ((ret = WritePayload(fd, start_offset, end_offset)) < 0)
372 return -1;
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800373 LOG(INFO) << ret << " payload bytes written";
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800374 written += ret;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000375 }
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800376
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800377 LOG(INFO) << "response generation complete, " << written
378 << " total bytes written";
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800379 return written;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000380}
381
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800382ssize_t HandleGet(int fd,
383 const HttpRequest& request,
Gilad Arnolde4ad2502011-12-29 17:08:54 -0800384 const size_t total_length) {
385 return HandleGet(fd, request, total_length, 0, 0, 0);
386}
387
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700388// Handles /redirect/<code>/<url> requests by returning the specified
389// redirect <code> with a location pointing to /<url>.
390void HandleRedirect(int fd, const HttpRequest& request) {
391 LOG(INFO) << "Redirecting...";
392 string url = request.url;
Mike Frysinger0f9547d2012-02-16 12:11:37 -0500393 CHECK_EQ(static_cast<size_t>(0), url.find("/redirect/"));
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700394 url.erase(0, strlen("/redirect/"));
395 string::size_type url_start = url.find('/');
396 CHECK_NE(url_start, string::npos);
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800397 HttpResponseCode code = StringToHttpResponseCode(url.c_str());
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700398 url.erase(0, url_start);
399 url = "http://" + request.host + url;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800400 const char* status = GetHttpResponseDescription(code);
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800401 if (!status)
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700402 CHECK(false) << "Unrecognized redirection code: " << code;
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700403 LOG(INFO) << "Code: " << code << " " << status;
404 LOG(INFO) << "New URL: " << url;
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800405
406 ssize_t ret;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800407 if ((ret = WriteString(fd, "HTTP/1.1 " + Itoa(code) + " " + status + EOL)) <
408 0)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800409 return;
Haibo Huang59ad2732020-09-09 15:23:59 -0700410 WriteString(fd, "Connection: close" EOL);
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800411 WriteString(fd, "Location: " + url + EOL);
412}
413
414// Generate a page not found error response with actual text payload. Return
415// number of bytes written or -1 for error.
416ssize_t HandleError(int fd, const HttpRequest& request) {
417 LOG(INFO) << "Generating error HTTP response";
418
419 ssize_t ret;
420 size_t written = 0;
421
422 const string data("This is an error page.");
423
424 if ((ret = WriteHeaders(fd, 0, data.size(), kHttpResponseNotFound)) < 0)
425 return -1;
426 written += ret;
427
428 if ((ret = WriteString(fd, data)) < 0)
429 return -1;
430 written += ret;
431
432 return written;
433}
434
435// Generate an error response if the requested offset is nonzero, up to a given
436// maximal number of successive failures. The error generated is an "Internal
437// Server Error" (500).
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800438ssize_t HandleErrorIfOffset(int fd,
439 const HttpRequest& request,
440 size_t end_offset,
441 int max_fails) {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800442 static int num_fails = 0;
443
444 if (request.start_offset > 0 && num_fails < max_fails) {
445 LOG(INFO) << "Generating error HTTP response";
446
447 ssize_t ret;
448 size_t written = 0;
449
450 const string data("This is an error page.");
451
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800452 if ((ret = WriteHeaders(
453 fd, 0, data.size(), kHttpResponseInternalServerError)) < 0)
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800454 return -1;
455 written += ret;
456
457 if ((ret = WriteString(fd, data)) < 0)
458 return -1;
459 written += ret;
460
461 num_fails++;
462 return written;
463 } else {
464 num_fails = 0;
465 return HandleGet(fd, request, end_offset);
466 }
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700467}
468
Alex Deymo6f10c5f2016-03-03 22:35:43 -0800469// Returns a valid response echoing in the body of the response all the headers
470// sent by the client.
471void HandleEchoHeaders(int fd, const HttpRequest& request) {
472 WriteHeaders(fd, 0, request.raw_headers.size(), kHttpResponseOk);
473 WriteString(fd, request.raw_headers);
474}
475
Alex Deymof123ae22015-09-24 14:59:43 -0700476void HandleHang(int fd) {
477 LOG(INFO) << "Hanging until the other side of the connection is closed.";
478 char c;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800479 while (HANDLE_EINTR(read(fd, &c, 1)) > 0) {
480 }
Alex Deymof123ae22015-09-24 14:59:43 -0700481}
482
adlr@google.com3defe6a2009-12-04 20:57:17 +0000483void HandleDefault(int fd, const HttpRequest& request) {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800484 const off_t start_offset = request.start_offset;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000485 const string data("unhandled path");
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800486 const size_t size = data.size();
487 ssize_t ret;
488
489 if ((ret = WriteHeaders(fd, start_offset, size, request.return_code)) < 0)
490 return;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800491 WriteString(
492 fd,
493 (start_offset < static_cast<off_t>(size) ? data.substr(start_offset)
494 : ""));
adlr@google.com3defe6a2009-12-04 20:57:17 +0000495}
496
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800497// Break a URL into terms delimited by slashes.
498class UrlTerms {
499 public:
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800500 UrlTerms(const string& url, size_t num_terms) {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800501 // URL must be non-empty and start with a slash.
Mike Frysinger0f9547d2012-02-16 12:11:37 -0500502 CHECK_GT(url.size(), static_cast<size_t>(0));
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800503 CHECK_EQ(url[0], '/');
504
Alex Vakulenkoa3cf75a2016-01-20 07:56:15 -0800505 // Split it into terms delimited by slashes, omitting the preceding slash.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800506 terms = base::SplitString(
507 url.substr(1), "/", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800508
509 // Ensure expected length.
510 CHECK_EQ(terms.size(), num_terms);
511 }
512
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800513 inline const string& Get(const off_t index) const { return terms[index]; }
514 inline const char* GetCStr(const off_t index) const {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800515 return Get(index).c_str();
516 }
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800517 inline int GetInt(const off_t index) const { return atoi(GetCStr(index)); }
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700518 inline size_t GetSizeT(const off_t index) const {
519 return static_cast<size_t>(atol(GetCStr(index)));
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800520 }
521
522 private:
Alex Deymof329b932014-10-30 01:37:48 -0700523 vector<string> terms;
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800524};
Gilad Arnold48085ba2011-11-16 09:36:08 -0800525
adlr@google.com3defe6a2009-12-04 20:57:17 +0000526void HandleConnection(int fd) {
527 HttpRequest request;
528 ParseRequest(fd, &request);
529
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800530 string& url = request.url;
531 LOG(INFO) << "pid(" << getpid() << "): handling url " << url;
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800532 if (url == "/quitquitquit") {
533 HandleQuit(fd);
Alex Deymo6f10c5f2016-03-03 22:35:43 -0800534 } else if (base::StartsWith(
535 url, "/download/", base::CompareCase::SENSITIVE)) {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800536 const UrlTerms terms(url, 2);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700537 HandleGet(fd, request, terms.GetSizeT(1));
Alex Vakulenkoa3cf75a2016-01-20 07:56:15 -0800538 } else if (base::StartsWith(url, "/flaky/", base::CompareCase::SENSITIVE)) {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800539 const UrlTerms terms(url, 5);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800540 HandleGet(fd,
541 request,
542 terms.GetSizeT(1),
543 terms.GetSizeT(2),
544 terms.GetInt(3),
545 terms.GetInt(4));
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800546 } else if (url.find("/redirect/") == 0) {
Darin Petkov41c2fcf2010-08-25 13:14:48 -0700547 HandleRedirect(fd, request);
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800548 } else if (url == "/error") {
Gilad Arnold48085ba2011-11-16 09:36:08 -0800549 HandleError(fd, request);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800550 } else if (base::StartsWith(
551 url, "/error-if-offset/", base::CompareCase::SENSITIVE)) {
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800552 const UrlTerms terms(url, 3);
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700553 HandleErrorIfOffset(fd, request, terms.GetSizeT(1), terms.GetInt(2));
Alex Deymo6f10c5f2016-03-03 22:35:43 -0800554 } else if (url == "/echo-headers") {
555 HandleEchoHeaders(fd, request);
Alex Deymof123ae22015-09-24 14:59:43 -0700556 } else if (url == "/hang") {
557 HandleHang(fd);
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800558 } else {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000559 HandleDefault(fd, request);
Gilad Arnold9bedeb52011-11-17 16:19:57 -0800560 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000561
562 close(fd);
563}
564
565} // namespace chromeos_update_engine
566
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700567using namespace chromeos_update_engine; // NOLINT(build/namespaces)
adlr@google.com3defe6a2009-12-04 20:57:17 +0000568
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800569void usage(const char* prog_arg) {
570 fprintf(stderr,
571 "Usage: %s [ FILE ]\n"
572 "Once accepting connections, the following is written to FILE (or "
573 "stdout):\n"
574 "\"%sN\" (where N is an integer port number)\n",
575 basename(prog_arg),
576 kListeningMsgPrefix);
Gilad Arnold97bdb3f2013-06-30 23:05:50 -0700577}
578
adlr@google.com3defe6a2009-12-04 20:57:17 +0000579int main(int argc, char** argv) {
Gilad Arnold97bdb3f2013-06-30 23:05:50 -0700580 // Check invocation.
581 if (argc > 2)
582 errx(RC_BAD_ARGS, "unexpected number of arguments (use -h for usage)");
583
Gilad Arnoldb6c562a2013-07-01 02:19:26 -0700584 // Parse (optional) argument.
585 int report_fd = STDOUT_FILENO;
Gilad Arnold97bdb3f2013-06-30 23:05:50 -0700586 if (argc == 2) {
587 if (!strcmp(argv[1], "-h")) {
588 usage(argv[0]);
589 exit(RC_OK);
590 }
591
Gilad Arnoldb6c562a2013-07-01 02:19:26 -0700592 report_fd = open(argv[1], O_WRONLY | O_CREAT, 00644);
Gilad Arnold97bdb3f2013-06-30 23:05:50 -0700593 }
594
Andrew de los Reyes3fd5d302010-10-07 20:07:18 -0700595 // Ignore SIGPIPE on write() to sockets.
596 signal(SIGPIPE, SIG_IGN);
Darin Petkovf67bb1f2010-11-08 16:10:26 -0800597
adlr@google.com3defe6a2009-12-04 20:57:17 +0000598 int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
599 if (listen_fd < 0)
600 LOG(FATAL) << "socket() failed";
601
Gilad Arnoldb6c562a2013-07-01 02:19:26 -0700602 struct sockaddr_in server_addr = sockaddr_in();
adlr@google.com3defe6a2009-12-04 20:57:17 +0000603 server_addr.sin_family = AF_INET;
604 server_addr.sin_addr.s_addr = INADDR_ANY;
Gilad Arnoldb6c562a2013-07-01 02:19:26 -0700605 server_addr.sin_port = 0;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000606
607 {
608 // Get rid of "Address in use" error
609 int tr = 1;
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800610 if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &tr, sizeof(int)) ==
611 -1) {
adlr@google.com3defe6a2009-12-04 20:57:17 +0000612 perror("setsockopt");
Gilad Arnold97bdb3f2013-06-30 23:05:50 -0700613 exit(RC_ERR_SETSOCKOPT);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000614 }
615 }
616
Gilad Arnoldb6c562a2013-07-01 02:19:26 -0700617 // Bind the socket and set for listening.
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800618 if (bind(listen_fd,
619 reinterpret_cast<struct sockaddr*>(&server_addr),
adlr@google.com3defe6a2009-12-04 20:57:17 +0000620 sizeof(server_addr)) < 0) {
621 perror("bind");
Gilad Arnold97bdb3f2013-06-30 23:05:50 -0700622 exit(RC_ERR_BIND);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000623 }
Gilad Arnoldb6c562a2013-07-01 02:19:26 -0700624 if (listen(listen_fd, 5) < 0) {
625 perror("listen");
626 exit(RC_ERR_LISTEN);
627 }
628
629 // Check the actual port.
630 struct sockaddr_in bound_addr = sockaddr_in();
631 socklen_t bound_addr_len = sizeof(bound_addr);
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800632 if (getsockname(listen_fd,
633 reinterpret_cast<struct sockaddr*>(&bound_addr),
Gilad Arnoldb6c562a2013-07-01 02:19:26 -0700634 &bound_addr_len) < 0) {
635 perror("getsockname");
636 exit(RC_ERR_GETSOCKNAME);
637 }
638 in_port_t port = ntohs(bound_addr.sin_port);
639
640 // Output the listening port, indicating that the server is processing
641 // requests. IMPORTANT! (a) the format of this message is as expected by some
642 // unit tests, avoid unilateral changes; (b) it is necessary to flush/sync the
643 // file to prevent the spawning process from waiting indefinitely for this
644 // message.
Alex Vakulenko75039d72014-03-25 12:36:28 -0700645 string listening_msg = base::StringPrintf("%s%hu", kListeningMsgPrefix, port);
Gilad Arnoldb6c562a2013-07-01 02:19:26 -0700646 LOG(INFO) << listening_msg;
647 CHECK_EQ(write(report_fd, listening_msg.c_str(), listening_msg.length()),
648 static_cast<int>(listening_msg.length()));
649 CHECK_EQ(write(report_fd, "\n", 1), 1);
650 if (report_fd == STDOUT_FILENO)
651 fsync(report_fd);
652 else
653 close(report_fd);
654
adlr@google.com3defe6a2009-12-04 20:57:17 +0000655 while (1) {
Amin Hassani7cc8bb02019-01-14 16:29:47 -0800656 LOG(INFO) << "pid(" << getpid() << "): waiting to accept new connection";
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700657 int client_fd = accept(listen_fd, nullptr, nullptr);
adlr@google.com3defe6a2009-12-04 20:57:17 +0000658 LOG(INFO) << "got past accept";
659 if (client_fd < 0)
660 LOG(FATAL) << "ERROR on accept";
661 HandleConnection(client_fd);
662 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000663}