Merge remote-tracking branch 'upstream/debian/sid' into bugfix/coverity
[ntk/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 {
28 switch (httpcode)
29 {
30 // Informational 1xx
31 case 100: return "100 Continue";
32 case 101: return "101 Switching Protocols";
33 // Successful 2xx
34 case 200: return "200 OK";
35 case 201: return "201 Created";
36 case 202: return "202 Accepted";
37 case 203: return "203 Non-Authoritative Information";
38 case 204: return "204 No Content";
39 case 205: return "205 Reset Content";
40 case 206: return "206 Partial Content";
41 // Redirections 3xx
42 case 300: return "300 Multiple Choices";
43 case 301: return "301 Moved Permanently";
44 case 302: return "302 Found";
45 case 303: return "303 See Other";
46 case 304: return "304 Not Modified";
47 case 305: return "304 Use Proxy";
48 case 307: return "307 Temporary Redirect";
49 // Client errors 4xx
50 case 400: return "400 Bad Request";
51 case 401: return "401 Unauthorized";
52 case 402: return "402 Payment Required";
53 case 403: return "403 Forbidden";
54 case 404: return "404 Not Found";
55 case 405: return "405 Method Not Allowed";
56 case 406: return "406 Not Acceptable";
57 case 407: return "407 Proxy Authentication Required";
58 case 408: return "408 Request Time-out";
59 case 409: return "409 Conflict";
60 case 410: return "410 Gone";
61 case 411: return "411 Length Required";
62 case 412: return "412 Precondition Failed";
63 case 413: return "413 Request Entity Too Large";
64 case 414: return "414 Request-URI Too Large";
65 case 415: return "415 Unsupported Media Type";
66 case 416: return "416 Requested range not satisfiable";
67 case 417: return "417 Expectation Failed";
68 case 418: return "418 I'm a teapot";
69 // Server error 5xx
70 case 500: return "500 Internal Server Error";
71 case 501: return "501 Not Implemented";
72 case 502: return "502 Bad Gateway";
73 case 503: return "503 Service Unavailable";
74 case 504: return "504 Gateway Time-out";
75 case 505: return "505 HTTP Version not supported";
76 }
77 return NULL;
78 }
79 /*}}}*/
80 void addFileHeaders(std::list<std::string> &headers, FileFd &data) /*{{{*/
81 {
82 std::ostringstream contentlength;
83 contentlength << "Content-Length: " << data.FileSize();
84 headers.push_back(contentlength.str());
85
86 std::string lastmodified("Last-Modified: ");
87 lastmodified.append(TimeRFC1123(data.ModificationTime()));
88 headers.push_back(lastmodified);
89 }
90 /*}}}*/
91 void addDataHeaders(std::list<std::string> &headers, std::string &data) /*{{{*/
92 {
93 std::ostringstream contentlength;
94 contentlength << "Content-Length: " << data.size();
95 headers.push_back(contentlength.str());
96 }
97 /*}}}*/
98 bool sendHead(int const client, int const httpcode, std::list<std::string> &headers)/*{{{*/
99 {
100 std::string response("HTTP/1.1 ");
101 response.append(httpcodeToStr(httpcode));
102 headers.push_front(response);
103
104 headers.push_back("Server: APT webserver");
105
106 std::string date("Date: ");
107 date.append(TimeRFC1123(time(NULL)));
108 headers.push_back(date);
109
110 std::clog << ">>> RESPONSE >>>" << std::endl;
111 bool Success = true;
112 for (std::list<std::string>::const_iterator h = headers.begin();
113 Success == true && h != headers.end(); ++h)
114 {
115 Success &= FileFd::Write(client, h->c_str(), h->size());
116 if (Success == true)
117 Success &= FileFd::Write(client, "\r\n", 2);
118 std::clog << *h << std::endl;
119 }
120 if (Success == true)
121 Success &= FileFd::Write(client, "\r\n", 2);
122 std::clog << "<<<<<<<<<<<<<<<<" << std::endl;
123 return Success;
124 }
125 /*}}}*/
126 bool sendFile(int const client, FileFd &data) /*{{{*/
127 {
128 bool Success = true;
129 char buffer[500];
130 unsigned long long actual = 0;
131 while ((Success &= data.Read(buffer, sizeof(buffer), &actual)) == true)
132 {
133 if (actual == 0)
134 break;
135 if (Success == true)
136 Success &= FileFd::Write(client, buffer, actual);
137 }
138 if (Success == true)
139 Success &= FileFd::Write(client, "\r\n", 2);
140 return Success;
141 }
142 /*}}}*/
143 bool sendData(int const client, std::string const &data) /*{{{*/
144 {
145 bool Success = true;
146 Success &= FileFd::Write(client, data.c_str(), data.size());
147 if (Success == true)
148 Success &= FileFd::Write(client, "\r\n", 2);
149 return Success;
150 }
151 /*}}}*/
152 void sendError(int const client, int const httpcode, std::string const &request,/*{{{*/
153 bool content, std::string const &error = "")
154 {
155 std::list<std::string> headers;
156 std::string response("<html><head><title>");
157 response.append(httpcodeToStr(httpcode)).append("</title></head>");
158 response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1>");
159 if (error.empty() == false)
160 response.append("<p><em>Error</em>: ").append(error).append("</p>");
161 response.append("This error is a result of the request: <pre>");
162 response.append(request).append("</pre></body></html>");
163 addDataHeaders(headers, response);
164 sendHead(client, httpcode, headers);
165 if (content == true)
166 sendData(client, response);
167 }
168 /*}}}*/
169 void sendRedirect(int const client, int const httpcode, std::string const &uri,/*{{{*/
170 std::string const &request, bool content)
171 {
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 int filter_hidden_files(const struct dirent *a) /*{{{*/
192 {
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 /*}}}*/
229 void sendDirectoryListing(int const client, std::string const &dir, /*{{{*/
230 std::string const &request, bool content)
231 {
232 std::list<std::string> headers;
233 std::ostringstream listing;
234
235 struct dirent **namelist;
236 int const counter = scandir(dir.c_str(), &namelist, filter_hidden_files, grouped_alpha_case_sort);
237 if (counter == -1)
238 {
239 sendError(client, 500, request, content);
240 return;
241 }
242
243 listing << "<html><head><title>Index of " << dir << "</title>"
244 << "<style type=\"text/css\"><!-- td {padding: 0.02em 0.5em 0.02em 0.5em;}"
245 << "tr:nth-child(even){background-color:#dfdfdf;}"
246 << "h1, td:nth-child(3){text-align:center;}"
247 << "table {margin-left:auto;margin-right:auto;} --></style>"
248 << "</head>" << std::endl
249 << "<body><h1>Index of " << dir << "</h1>" << std::endl
250 << "<table><tr><th>#</th><th>Name</th><th>Size</th><th>Last-Modified</th></tr>" << std::endl;
251 if (dir != ".")
252 listing << "<tr><td>d</td><td><a href=\"..\">Parent Directory</a></td><td>-</td><td>-</td></tr>";
253 for (int i = 0; i < counter; ++i) {
254 struct stat fs;
255 std::string filename(dir);
256 filename.append("/").append(namelist[i]->d_name);
257 stat(filename.c_str(), &fs);
258 if (S_ISDIR(fs.st_mode))
259 {
260 listing << "<tr><td>d</td>"
261 << "<td><a href=\"" << namelist[i]->d_name << "/\">" << namelist[i]->d_name << "</a></td>"
262 << "<td>-</td>";
263 }
264 else
265 {
266 listing << "<tr><td>f</td>"
267 << "<td><a href=\"" << namelist[i]->d_name << "\">" << namelist[i]->d_name << "</a></td>"
268 << "<td>" << SizeToStr(fs.st_size) << "B</td>";
269 }
270 listing << "<td>" << TimeRFC1123(fs.st_mtime) << "</td></tr>" << std::endl;
271 }
272 listing << "</table></body></html>" << std::endl;
273
274 std::string response(listing.str());
275 addDataHeaders(headers, response);
276 sendHead(client, 200, headers);
277 if (content == true)
278 sendData(client, response);
279 }
280 /*}}}*/
281 bool parseFirstLine(int const client, std::string const &request, /*{{{*/
282 std::string &filename, bool &sendContent,
283 bool &closeConnection)
284 {
285 if (strncmp(request.c_str(), "HEAD ", 5) == 0)
286 sendContent = false;
287 if (strncmp(request.c_str(), "GET ", 4) != 0)
288 {
289 sendError(client, 501, request, true);
290 return false;
291 }
292
293 size_t const lineend = request.find('\n');
294 size_t filestart = request.find(' ');
295 for (; request[filestart] == ' '; ++filestart);
296 size_t fileend = request.rfind(' ', lineend);
297 if (lineend == std::string::npos || filestart == std::string::npos ||
298 fileend == std::string::npos || filestart == fileend)
299 {
300 sendError(client, 500, request, sendContent, "Filename can't be extracted");
301 return false;
302 }
303
304 size_t httpstart = fileend;
305 for (; request[httpstart] == ' '; ++httpstart);
306 if (strncmp(request.c_str() + httpstart, "HTTP/1.1\r", 9) == 0)
307 closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "Keep-Alive") != 0;
308 else if (strncmp(request.c_str() + httpstart, "HTTP/1.0\r", 9) == 0)
309 closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "close") == 0;
310 else
311 {
312 sendError(client, 500, request, sendContent, "Not a HTTP/1.{0,1} request");
313 return false;
314 }
315
316 filename = request.substr(filestart, fileend - filestart);
317 if (filename.find(' ') != std::string::npos)
318 {
319 sendError(client, 500, request, sendContent, "Filename contains an unencoded space");
320 return false;
321 }
322
323 std::string host = LookupTag(request, "Host", "");
324 if (host.empty() == true)
325 {
326 // RFC 2616 §14.23 requires Host
327 sendError(client, 400, request, sendContent, "Host header is required");
328 return false;
329 }
330 host = "http://" + host;
331
332 // Proxies require absolute uris, so this is a simple proxy-fake option
333 std::string const absolute = _config->Find("aptwebserver::request::absolute", "uri,path");
334 if (strncmp(host.c_str(), filename.c_str(), host.length()) == 0)
335 {
336 if (absolute.find("uri") == std::string::npos)
337 {
338 sendError(client, 400, request, sendContent, "Request is absoluteURI, but configured to not accept that");
339 return false;
340 }
341 // strip the host from the request to make it an absolute path
342 filename.erase(0, host.length());
343 }
344 else if (absolute.find("path") == std::string::npos)
345 {
346 sendError(client, 400, request, sendContent, "Request is absolutePath, but configured to not accept that");
347 return false;
348 }
349 filename = DeQuoteString(filename);
350
351 // this is not a secure server, but at least prevent the obvious …
352 if (filename.empty() == true || filename[0] != '/' ||
353 strncmp(filename.c_str(), "//", 2) == 0 ||
354 filename.find_first_of("\r\n\t\f\v") != std::string::npos ||
355 filename.find("/../") != std::string::npos)
356 {
357 sendError(client, 400, request, sendContent, "Filename contains illegal character (sequence)");
358 return false;
359 }
360
361 // nuke the first character which is a / as we assured above
362 filename.erase(0, 1);
363 if (filename.empty() == true)
364 filename = ".";
365 return true;
366 }
367 /*}}}*/
368 int main(int const argc, const char * argv[])
369 {
370 CommandLine::Args Args[] = {
371 {0, "port", "aptwebserver::port", CommandLine::HasArg},
372 {0, "request-absolute", "aptwebserver::request::absolute", CommandLine::HasArg},
373 {'c',"config-file",0,CommandLine::ConfigFile},
374 {'o',"option",0,CommandLine::ArbItem},
375 {0,0,0,0}
376 };
377
378 CommandLine CmdL(Args, _config);
379 if(CmdL.Parse(argc,argv) == false)
380 {
381 _error->DumpErrors();
382 exit(1);
383 }
384
385 // create socket, bind and listen to it {{{
386 // ignore SIGPIPE, this can happen on write() if the socket closes connection
387 signal(SIGPIPE, SIG_IGN);
388 int sock = socket(AF_INET6, SOCK_STREAM, 0);
389 if(sock < 0)
390 {
391 _error->Errno("aptwerbserver", "Couldn't create socket");
392 _error->DumpErrors(std::cerr);
393 return 1;
394 }
395
396 int const port = _config->FindI("aptwebserver::port", 8080);
397
398 // ensure that we accept all connections: v4 or v6
399 int const iponly = 0;
400 setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &iponly, sizeof(iponly));
401 // to not linger on an address
402 int const enable = 1;
403 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
404
405 struct sockaddr_in6 locAddr;
406 memset(&locAddr, 0, sizeof(locAddr));
407 locAddr.sin6_family = AF_INET6;
408 locAddr.sin6_port = htons(port);
409 locAddr.sin6_addr = in6addr_any;
410
411 if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0)
412 {
413 _error->Errno("aptwerbserver", "Couldn't bind");
414 _error->DumpErrors(std::cerr);
415 return 2;
416 }
417
418 FileFd pidfile;
419 if (_config->FindB("aptwebserver::fork", false) == true)
420 {
421 std::string const pidfilename = _config->Find("aptwebserver::pidfile", "aptwebserver.pid");
422 int const pidfilefd = GetLock(pidfilename);
423 if (pidfilefd < 0 || pidfile.OpenDescriptor(pidfilefd, FileFd::WriteOnly) == false)
424 {
425 _error->Errno("aptwebserver", "Couldn't acquire lock on pidfile '%s'", pidfilename.c_str());
426 _error->DumpErrors(std::cerr);
427 return 3;
428 }
429
430 pid_t child = fork();
431 if (child < 0)
432 {
433 _error->Errno("aptwebserver", "Forking failed");
434 _error->DumpErrors(std::cerr);
435 return 4;
436 }
437 else if (child != 0)
438 {
439 // successfully forked: ready to serve!
440 std::string pidcontent;
441 strprintf(pidcontent, "%d", child);
442 pidfile.Write(pidcontent.c_str(), pidcontent.size());
443 if (_error->PendingError() == true)
444 {
445 _error->DumpErrors(std::cerr);
446 return 5;
447 }
448 std::cout << "Successfully forked as " << child << std::endl;
449 return 0;
450 }
451 }
452
453 std::clog << "Serving ANY file on port: " << port << std::endl;
454
455 listen(sock, 1);
456 /*}}}*/
457
458 std::vector<std::string> messages;
459 int client;
460 while ((client = accept(sock, NULL, NULL)) != -1)
461 {
462 std::clog << "ACCEPT client " << client
463 << " on socket " << sock << std::endl;
464
465 while (ReadMessages(client, messages))
466 {
467 bool closeConnection = false;
468 for (std::vector<std::string>::const_iterator m = messages.begin();
469 m != messages.end() && closeConnection == false; ++m) {
470 std::clog << ">>> REQUEST >>>>" << std::endl << *m
471 << std::endl << "<<<<<<<<<<<<<<<<" << std::endl;
472 std::list<std::string> headers;
473 std::string filename;
474 bool sendContent = true;
475 if (parseFirstLine(client, *m, filename, sendContent, closeConnection) == false)
476 continue;
477
478 // string replacements in the requested filename
479 ::Configuration::Item const *Replaces = _config->Tree("aptwebserver::redirect::replace");
480 if (Replaces != NULL)
481 {
482 std::string redirect = "/" + filename;
483 for (::Configuration::Item *I = Replaces->Child; I != NULL; I = I->Next)
484 redirect = SubstVar(redirect, I->Tag, I->Value);
485 redirect.erase(0,1);
486 if (redirect != filename)
487 {
488 sendRedirect(client, 301, redirect, *m, sendContent);
489 continue;
490 }
491 }
492
493 ::Configuration::Item const *Overwrite = _config->Tree("aptwebserver::overwrite");
494 if (Overwrite != NULL)
495 {
496 for (::Configuration::Item *I = Overwrite->Child; I != NULL; I = I->Next)
497 {
498 regex_t *pattern = new regex_t;
499 int const res = regcomp(pattern, I->Tag.c_str(), REG_EXTENDED | REG_ICASE | REG_NOSUB);
500 if (res != 0)
501 {
502 char error[300];
503 regerror(res, pattern, error, sizeof(error));
504 sendError(client, 500, *m, sendContent, error);
505 continue;
506 }
507 if (regexec(pattern, filename.c_str(), 0, 0, 0) == 0)
508 {
509 filename = _config->Find("aptwebserver::overwrite::" + I->Tag + "::filename", filename);
510 if (filename[0] == '/')
511 filename.erase(0,1);
512 regfree(pattern);
513 break;
514 }
515 regfree(pattern);
516 }
517 }
518
519 // deal with the request
520 if (RealFileExists(filename) == true)
521 {
522 FileFd data(filename, FileFd::ReadOnly);
523 std::string condition = LookupTag(*m, "If-Modified-Since", "");
524 if (condition.empty() == false)
525 {
526 time_t cache;
527 if (RFC1123StrToTime(condition.c_str(), cache) == true &&
528 cache >= data.ModificationTime())
529 {
530 sendHead(client, 304, headers);
531 continue;
532 }
533 }
534
535 addFileHeaders(headers, data);
536 sendHead(client, 200, headers);
537 if (sendContent == true)
538 sendFile(client, data);
539 }
540 else if (DirectoryExists(filename) == true)
541 {
542 if (filename == "." || filename[filename.length()-1] == '/')
543 sendDirectoryListing(client, filename, *m, sendContent);
544 else
545 sendRedirect(client, 301, filename.append("/"), *m, sendContent);
546 }
547 else
548 sendError(client, 404, *m, sendContent);
549 }
550 _error->DumpErrors(std::cerr);
551 messages.clear();
552 if (closeConnection == true)
553 break;
554 }
555
556 std::clog << "CLOSE client " << client
557 << " on socket " << sock << std::endl;
558 close(client);
559 }
560 pidfile.Close();
561
562 return 0;
563 }