]> git.saurik.com Git - apt.git/blame - test/interactive-helper/aptwebserver.cc
rework parsing of the first request-line to be more robust
[apt.git] / test / interactive-helper / aptwebserver.cc
CommitLineData
4958ba98
DK
1#include <config.h>
2
e6cd40dc
DK
3#include <apt-pkg/strutl.h>
4#include <apt-pkg/fileutl.h>
5#include <apt-pkg/error.h>
6#include <apt-pkg/cmndline.h>
90d1d54e
MV
7#include <apt-pkg/configuration.h>
8#include <apt-pkg/init.h>
e6cd40dc
DK
9
10#include <vector>
11#include <string>
12#include <list>
13#include <sstream>
14
15#include <sys/socket.h>
16#include <sys/types.h>
d6405329 17#include <sys/stat.h>
e6cd40dc
DK
18#include <netinet/in.h>
19#include <unistd.h>
20#include <errno.h>
21#include <time.h>
22#include <stdlib.h>
d6405329 23#include <dirent.h>
e6cd40dc 24
dc57a59b 25char const * const httpcodeToStr(int const httpcode) { /*{{{*/
e6cd40dc
DK
26 switch (httpcode) {
27 // Informational 1xx
28 case 100: return "100 Continue";
29 case 101: return "101 Switching Protocols";
30 // Successful 2xx
31 case 200: return "200 OK";
32 case 201: return "201 Created";
33 case 202: return "202 Accepted";
34 case 203: return "203 Non-Authoritative Information";
35 case 204: return "204 No Content";
36 case 205: return "205 Reset Content";
37 case 206: return "206 Partial Conent";
38 // Redirections 3xx
39 case 300: return "300 Multiple Choices";
40 case 301: return "301 Moved Permanently";
41 case 302: return "302 Found";
42 case 303: return "303 See Other";
43 case 304: return "304 Not Modified";
44 case 305: return "304 Use Proxy";
45 case 307: return "307 Temporary Redirect";
46 // Client errors 4xx
47 case 400: return "400 Bad Request";
48 case 401: return "401 Unauthorized";
49 case 402: return "402 Payment Required";
50 case 403: return "403 Forbidden";
51 case 404: return "404 Not Found";
52 case 405: return "405 Method Not Allowed";
53 case 406: return "406 Not Acceptable";
7a1bed9d
DK
54 case 407: return "407 Proxy Authentication Required";
55 case 408: return "408 Request Time-out";
56 case 409: return "409 Conflict";
57 case 410: return "410 Gone";
58 case 411: return "411 Length Required";
59 case 412: return "412 Precondition Failed";
60 case 413: return "413 Request Entity Too Large";
61 case 414: return "414 Request-URI Too Large";
62 case 415: return "415 Unsupported Media Type";
63 case 416: return "416 Requested range not satisfiable";
64 case 417: return "417 Expectation Failed";
e6cd40dc 65 // Server error 5xx
7a1bed9d
DK
66 case 500: return "500 Internal Server Error";
67 case 501: return "501 Not Implemented";
68 case 502: return "502 Bad Gateway";
69 case 503: return "503 Service Unavailable";
70 case 504: return "504 Gateway Time-out";
71 case 505: return "505 HTTP Version not supported";
e6cd40dc
DK
72 }
73 return NULL;
dc57a59b
DK
74}
75 /*}}}*/
76void addFileHeaders(std::list<std::string> &headers, FileFd &data) { /*{{{*/
e6cd40dc
DK
77 std::ostringstream contentlength;
78 contentlength << "Content-Length: " << data.FileSize();
79 headers.push_back(contentlength.str());
80
81 std::string lastmodified("Last-Modified: ");
82 lastmodified.append(TimeRFC1123(data.ModificationTime()));
83 headers.push_back(lastmodified);
dc57a59b
DK
84}
85 /*}}}*/
a38a00b9
MV
86void addDataHeaders(std::list<std::string> &headers, std::string &data) {/*{{{*/
87 std::ostringstream contentlength;
88 contentlength << "Content-Length: " << data.size();
89 headers.push_back(contentlength.str());
dc57a59b
DK
90}
91 /*}}}*/
92bool sendHead(int const client, int const httpcode, std::list<std::string> &headers) { /*{{{*/
4958ba98 93 std::string response("HTTP/1.1 ");
e6cd40dc
DK
94 response.append(httpcodeToStr(httpcode));
95 headers.push_front(response);
96
97 headers.push_back("Server: APT webserver");
98
99 std::string date("Date: ");
100 date.append(TimeRFC1123(time(NULL)));
101 headers.push_back(date);
102
103 std::clog << ">>> RESPONSE >>>" << std::endl;
104 bool Success = true;
105 for (std::list<std::string>::const_iterator h = headers.begin();
106 Success == true && h != headers.end(); ++h) {
107 Success &= FileFd::Write(client, h->c_str(), h->size());
108 Success &= FileFd::Write(client, "\r\n", 2);
109 std::clog << *h << std::endl;
110 }
111 Success &= FileFd::Write(client, "\r\n", 2);
112 std::clog << "<<<<<<<<<<<<<<<<" << std::endl;
113 return Success;
dc57a59b
DK
114}
115 /*}}}*/
116bool sendFile(int const client, FileFd &data) { /*{{{*/
e6cd40dc
DK
117 bool Success = true;
118 char buffer[500];
119 unsigned long long actual = 0;
120 while ((Success &= data.Read(buffer, sizeof(buffer), &actual)) == true) {
121 if (actual == 0)
122 break;
123 Success &= FileFd::Write(client, buffer, actual);
124 }
125 Success &= FileFd::Write(client, "\r\n", 2);
126 return Success;
dc57a59b
DK
127}
128 /*}}}*/
129bool sendData(int const client, std::string const &data) { /*{{{*/
e6cd40dc
DK
130 bool Success = true;
131 Success &= FileFd::Write(client, data.c_str(), data.size());
132 Success &= FileFd::Write(client, "\r\n", 2);
133 return Success;
dc57a59b
DK
134}
135 /*}}}*/
7a1bed9d 136void sendError(int const client, int const httpcode, std::string const &request, bool content, std::string const &error = "") { /*{{{*/
e6cd40dc 137 std::list<std::string> headers;
4958ba98 138 std::string response("<html><head><title>");
dc57a59b 139 response.append(httpcodeToStr(httpcode)).append("</title></head>");
d37911ac 140 response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1>");
7a1bed9d
DK
141 if (error.empty() == false)
142 response.append("<p><em>Error</em>: ").append(error).append("</p>");
dc57a59b
DK
143 response.append("This error is a result of the request: <pre>");
144 response.append(request).append("</pre></body></html>");
145 addDataHeaders(headers, response);
e6cd40dc 146 sendHead(client, httpcode, headers);
dc57a59b
DK
147 if (content == true)
148 sendData(client, response);
149}
150 /*}}}*/
64a28515
DK
151void sendRedirect(int const client, int const httpcode, std::string const &uri, std::string const &request, bool content) { /*{{{*/
152 std::list<std::string> headers;
153 std::string response("<html><head><title>");
154 response.append(httpcodeToStr(httpcode)).append("</title></head>");
155 response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1");
156 response.append("<p>You should be redirected to <em>").append(uri).append("</em></p>");
157 response.append("This page is a result of the request: <pre>");
158 response.append(request).append("</pre></body></html>");
159 addDataHeaders(headers, response);
160 std::string location("Location: ");
161 if (strncmp(uri.c_str(), "http://", 7) != 0)
162 location.append("http://").append(LookupTag(request, "Host")).append("/").append(uri);
163 else
164 location.append(uri);
165 headers.push_back(location);
166 sendHead(client, httpcode, headers);
167 if (content == true)
168 sendData(client, response);
169}
170 /*}}}*/
d6405329
DK
171// sendDirectoryLisiting /*{{{*/
172int filter_hidden_files(const struct dirent *a) {
173 if (a->d_name[0] == '.')
174 return 0;
175#ifdef _DIRENT_HAVE_D_TYPE
176 // if we have the d_type check that only files and dirs will be included
177 if (a->d_type != DT_UNKNOWN &&
178 a->d_type != DT_REG &&
179 a->d_type != DT_LNK && // this includes links to regular files
180 a->d_type != DT_DIR)
181 return 0;
182#endif
183 return 1;
184}
185int grouped_alpha_case_sort(const struct dirent **a, const struct dirent **b) {
186#ifdef _DIRENT_HAVE_D_TYPE
187 if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_DIR);
188 else if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_REG)
189 return -1;
190 else if ((*b)->d_type == DT_DIR && (*a)->d_type == DT_REG)
191 return 1;
192 else
193#endif
194 {
195 struct stat f_prop; //File's property
196 stat((*a)->d_name, &f_prop);
197 int const amode = f_prop.st_mode;
198 stat((*b)->d_name, &f_prop);
199 int const bmode = f_prop.st_mode;
200 if (S_ISDIR(amode) && S_ISDIR(bmode));
201 else if (S_ISDIR(amode))
202 return -1;
203 else if (S_ISDIR(bmode))
204 return 1;
205 }
206 return strcasecmp((*a)->d_name, (*b)->d_name);
207}
4958ba98 208void sendDirectoryListing(int const client, std::string const &dir, std::string const &request, bool content) {
d6405329
DK
209 std::list<std::string> headers;
210 std::ostringstream listing;
211
212 struct dirent **namelist;
213 int const counter = scandir(dir.c_str(), &namelist, filter_hidden_files, grouped_alpha_case_sort);
214 if (counter == -1) {
215 sendError(client, 500, request, content);
216 return;
217 }
218
219 listing << "<html><head><title>Index of " << dir << "</title>"
220 << "<style type=\"text/css\"><!-- td {padding: 0.02em 0.5em 0.02em 0.5em;}"
221 << "tr:nth-child(even){background-color:#dfdfdf;}"
222 << "h1, td:nth-child(3){text-align:center;}"
223 << "table {margin-left:auto;margin-right:auto;} --></style>"
224 << "</head>" << std::endl
225 << "<body><h1>Index of " << dir << "</h1>" << std::endl
226 << "<table><tr><th>#</th><th>Name</th><th>Size</th><th>Last-Modified</th></tr>" << std::endl;
227 if (dir != ".")
228 listing << "<tr><td>d</td><td><a href=\"..\">Parent Directory</a></td><td>-</td><td>-</td></tr>";
229 for (int i = 0; i < counter; ++i) {
230 struct stat fs;
231 std::string filename(dir);
232 filename.append("/").append(namelist[i]->d_name);
233 stat(filename.c_str(), &fs);
64a28515
DK
234 if (S_ISDIR(fs.st_mode)) {
235 listing << "<tr><td>d</td>"
236 << "<td><a href=\"" << namelist[i]->d_name << "/\">" << namelist[i]->d_name << "</a></td>"
237 << "<td>-</td>";
238 } else {
239 listing << "<tr><td>f</td>"
240 << "<td><a href=\"" << namelist[i]->d_name << "\">" << namelist[i]->d_name << "</a></td>"
241 << "<td>" << SizeToStr(fs.st_size) << "B</td>";
242 }
d6405329
DK
243 listing << "<td>" << TimeRFC1123(fs.st_mtime) << "</td></tr>" << std::endl;
244 }
245 listing << "</table></body></html>" << std::endl;
246
247 std::string response(listing.str());
248 addDataHeaders(headers, response);
249 sendHead(client, 200, headers);
250 if (content == true)
251 sendData(client, response);
252}
253 /*}}}*/
7a1bed9d
DK
254bool parseFirstLine(int const client, std::string const &request, std::string &filename, bool &sendContent) { /*{{{*/
255 if (strncmp(request.c_str(), "HEAD ", 5) == 0)
256 sendContent = false;
257 if (strncmp(request.c_str(), "GET ", 4) != 0)
258 {
259 sendError(client, 501, request, true);
260 return false;
261 }
262
263 size_t const lineend = request.find('\n');
264 size_t filestart = request.find(' ');
265 for (; request[filestart] == ' '; ++filestart);
266 size_t fileend = request.rfind(' ', lineend);
267 if (lineend == std::string::npos || filestart == std::string::npos ||
268 fileend == std::string::npos || filestart == fileend) {
269 sendError(client, 500, request, sendContent, "Filename can't be extracted");
270 return false;
271 }
272
273 size_t httpstart = fileend;
274 for (; request[httpstart] == ' '; ++httpstart);
275 if (strncmp(request.c_str() + httpstart, "HTTP/1.1\r", 9) != 0) {
276 sendError(client, 500, request, sendContent, "Not an HTTP/1.1 request");
277 return false;
278 }
279
280 filename = request.substr(filestart, fileend - filestart);
281 if (filename.find(' ') != std::string::npos) {
282 sendError(client, 500, request, sendContent, "Filename contains an unencoded space");
283 return false;
284 }
285 filename = DeQuoteString(filename);
286
287 // this is not a secure server, but at least prevent the obvious …
288 if (filename.empty() == true || filename[0] != '/' ||
289 strncmp(filename.c_str(), "//", 2) == 0 ||
290 filename.find_first_of("\r\n\t\f\v") != std::string::npos ||
291 filename.find("/../") != std::string::npos) {
292 sendError(client, 400, request, sendContent, "Filename contains illegal character (sequence)");
293 return false;
294 }
295
296 // nuke the first character which is a / as we assured above
297 filename.erase(0, 1);
298 if (filename.empty() == true)
299 filename = ".";
300 return true;
301}
302 /*}}}*/
dc57a59b 303int main(int const argc, const char * argv[])
e6cd40dc 304{
90d1d54e 305 CommandLine::Args Args[] = {
dc57a59b 306 {0, "simulate-paywall", "aptwebserver::Simulate-Paywall",
90d1d54e
MV
307 CommandLine::Boolean},
308 {0, "port", "aptwebserver::port", CommandLine::HasArg},
d37911ac
DK
309 {'c',"config-file",0,CommandLine::ConfigFile},
310 {'o',"option",0,CommandLine::ArbItem},
90d1d54e
MV
311 {0,0,0,0}
312 };
313
314 CommandLine CmdL(Args, _config);
3ce22d4f 315 if(CmdL.Parse(argc,argv) == false) {
90d1d54e
MV
316 _error->DumpErrors();
317 exit(1);
318 }
319
e6cd40dc
DK
320 // create socket, bind and listen to it {{{
321 int sock = socket(AF_INET6, SOCK_STREAM, 0);
322 if(sock < 0 ) {
323 _error->Errno("aptwerbserver", "Couldn't create socket");
324 _error->DumpErrors(std::cerr);
325 return 1;
326 }
327
90d1d54e
MV
328 // get the port
329 int const port = _config->FindI("aptwebserver::port", 8080);
330 bool const simulate_broken_server = _config->FindB("aptwebserver::Simulate-Paywall", false);
331
e6cd40dc
DK
332 // ensure that we accept all connections: v4 or v6
333 int const iponly = 0;
334 setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &iponly, sizeof(iponly));
335 // to not linger to an address
336 int const enable = 1;
337 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
338
339 struct sockaddr_in6 locAddr;
340 memset(&locAddr, 0, sizeof(locAddr));
341 locAddr.sin6_family = AF_INET6;
90d1d54e 342 locAddr.sin6_port = htons(port);
e6cd40dc
DK
343 locAddr.sin6_addr = in6addr_any;
344
345 if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0) {
346 _error->Errno("aptwerbserver", "Couldn't bind");
347 _error->DumpErrors(std::cerr);
348 return 2;
349 }
350
90d1d54e
MV
351 if (simulate_broken_server) {
352 std::clog << "Simulating a broken web server that return nonsense "
353 "for all querries" << std::endl;
354 } else {
355 std::clog << "Serving ANY file on port: " << port << std::endl;
356 }
357
e6cd40dc 358 listen(sock, 1);
dc57a59b 359 /*}}}*/
e6cd40dc
DK
360
361 std::vector<std::string> messages;
362 int client;
363 while ((client = accept(sock, NULL, NULL)) != -1) {
90d1d54e 364 std::clog << "ACCEPT client " << client
dc57a59b 365 << " on socket " << sock << std::endl;
e6cd40dc
DK
366
367 while (ReadMessages(client, messages)) {
368 for (std::vector<std::string>::const_iterator m = messages.begin();
369 m != messages.end(); ++m) {
dc57a59b
DK
370 std::clog << ">>> REQUEST >>>>" << std::endl << *m
371 << std::endl << "<<<<<<<<<<<<<<<<" << std::endl;
7a1bed9d 372
e6cd40dc 373 std::list<std::string> headers;
7a1bed9d 374 std::string filename;
e6cd40dc 375 bool sendContent = true;
7a1bed9d
DK
376 if (parseFirstLine(client, *m, filename, sendContent) == false)
377 continue;
e6cd40dc
DK
378
379 std::string host = LookupTag(*m, "Host", "");
380 if (host.empty() == true) {
7a1bed9d
DK
381 // RFC 2616 §14.23 requires Host
382 sendError(client, 400, *m, sendContent, "Host header is required");
e6cd40dc
DK
383 continue;
384 }
385
dc57a59b 386 if (simulate_broken_server == true) {
4958ba98 387 std::string data("ni ni ni\n");
dc57a59b
DK
388 addDataHeaders(headers, data);
389 sendHead(client, 200, headers);
390 sendData(client, data);
391 }
d6405329 392 else if (RealFileExists(filename) == true) {
e6cd40dc
DK
393 FileFd data(filename, FileFd::ReadOnly);
394 std::string condition = LookupTag(*m, "If-Modified-Since", "");
395 if (condition.empty() == false) {
396 time_t cache;
dc57a59b
DK
397 if (RFC1123StrToTime(condition.c_str(), cache) == true &&
398 cache >= data.ModificationTime()) {
d6405329 399 sendHead(client, 304, headers);
e6cd40dc
DK
400 continue;
401 }
402 }
403 addFileHeaders(headers, data);
404 sendHead(client, 200, headers);
405 if (sendContent == true)
406 sendFile(client, data);
407 }
d6405329 408 else if (DirectoryExists(filename) == true) {
64a28515
DK
409 if (filename == "." || filename[filename.length()-1] == '/')
410 sendDirectoryListing(client, filename, *m, sendContent);
411 else
412 sendRedirect(client, 301, filename.append("/"), *m, sendContent);
d6405329
DK
413 }
414 else
d37911ac
DK
415 {
416 ::Configuration::Item const *Replaces = _config->Tree("aptwebserver::redirect::replace");
417 if (Replaces != NULL) {
418 std::string redirect = "/" + filename;
419 for (::Configuration::Item *I = Replaces->Child; I != NULL; I = I->Next)
420 redirect = SubstVar(redirect, I->Tag, I->Value);
421 redirect.erase(0,1);
422 if (redirect != filename) {
423 sendRedirect(client, 301, redirect, *m, sendContent);
424 continue;
425 }
426 }
427 sendError(client, 404, *m, sendContent);
428 }
e6cd40dc
DK
429 }
430 _error->DumpErrors(std::cerr);
431 messages.clear();
da3ebfe7 432 }
a38a00b9 433
dc57a59b
DK
434 std::clog << "CLOSE client " << client
435 << " on socket " << sock << std::endl;
a38a00b9 436 close(client);
e6cd40dc
DK
437 }
438 return 0;
439}