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