+int Server::parse_request(Client *client)
+{
+ vector<string> lines = split_lines(client->request);
+ if (lines.empty()) {
+ return 400; // Bad request (empty).
+ }
+
+ vector<string> request_tokens = split_tokens(lines[0]);
+ if (request_tokens.size() < 2) {
+ return 400; // Bad request (empty).
+ }
+ if (request_tokens[0] != "GET") {
+ return 400; // Should maybe be 405 instead?
+ }
+
+ string url = request_tokens[1];
+ if (url.find("?backlog") == url.size() - 8) {
+ client->stream_pos = -2;
+ url = url.substr(0, url.size() - 8);
+ } else {
+ client->stream_pos = -1;
+ }
+
+ map<string, int>::const_iterator url_map_it = url_map.find(url);
+ if (url_map_it == url_map.end()) {
+ return 404; // Not found.
+ }
+
+ Stream *stream = streams[url_map_it->second];
+ if (stream->http_header.empty()) {
+ return 503; // Service unavailable.
+ }
+
+ client->url = request_tokens[1];
+ client->stream = stream;
+ if (setsockopt(client->sock, SOL_SOCKET, SO_MAX_PACING_RATE, &client->stream->pacing_rate, sizeof(client->stream->pacing_rate)) == -1) {
+ if (client->stream->pacing_rate != ~0U) {
+ log_perror("setsockopt(SO_MAX_PACING_RATE)");
+ }
+ }
+ client->request.clear();
+
+ return 200; // OK!
+}
+
+void Server::construct_header(Client *client)
+{
+ Stream *stream = client->stream;
+ if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
+ client->header_or_error = stream->http_header +
+ "\r\n" +
+ stream->stream_header;
+ } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
+ client->header_or_error = stream->http_header +
+ "Content-encoding: metacube\r\n" +
+ "\r\n";
+ if (!stream->stream_header.empty()) {
+ metacube2_block_header hdr;
+ memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
+ hdr.size = htonl(stream->stream_header.size());
+ hdr.flags = htons(METACUBE_FLAGS_HEADER);
+ hdr.csum = htons(metacube2_compute_crc(&hdr));
+ client->header_or_error.append(
+ string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
+ }
+ client->header_or_error.append(stream->stream_header);
+ } else {
+ assert(false);
+ }