]> git.saurik.com Git - apt.git/blob - test/interactive-helper/aptwebserver.cc
use getline() instead of rolling our own
[apt.git] / test / interactive-helper / aptwebserver.cc
1 #include <config.h>
2
3 #include <apt-pkg/cmndline.h>
4 #include <apt-pkg/configuration.h>
5 #include <apt-pkg/error.h>
6 #include <apt-pkg/fileutl.h>
7 #include <apt-pkg/strutl.h>
8
9 #include <dirent.h>
10 #include <errno.h>
11 #include <netinet/in.h>
12 #include <pthread.h>
13 #include <regex.h>
14 #include <signal.h>
15 #include <stddef.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <sys/socket.h>
19 #include <sys/stat.h>
20 #include <time.h>
21 #include <unistd.h>
22 #include <iostream>
23 #include <sstream>
24 #include <list>
25 #include <string>
26 #include <vector>
27
28 static char const * httpcodeToStr(int const httpcode) /*{{{*/
29 {
30 switch (httpcode)
31 {
32 // Informational 1xx
33 case 100: return "100 Continue";
34 case 101: return "101 Switching Protocols";
35 // Successful 2xx
36 case 200: return "200 OK";
37 case 201: return "201 Created";
38 case 202: return "202 Accepted";
39 case 203: return "203 Non-Authoritative Information";
40 case 204: return "204 No Content";
41 case 205: return "205 Reset Content";
42 case 206: return "206 Partial Content";
43 // Redirections 3xx
44 case 300: return "300 Multiple Choices";
45 case 301: return "301 Moved Permanently";
46 case 302: return "302 Found";
47 case 303: return "303 See Other";
48 case 304: return "304 Not Modified";
49 case 305: return "304 Use Proxy";
50 case 307: return "307 Temporary Redirect";
51 // Client errors 4xx
52 case 400: return "400 Bad Request";
53 case 401: return "401 Unauthorized";
54 case 402: return "402 Payment Required";
55 case 403: return "403 Forbidden";
56 case 404: return "404 Not Found";
57 case 405: return "405 Method Not Allowed";
58 case 406: return "406 Not Acceptable";
59 case 407: return "407 Proxy Authentication Required";
60 case 408: return "408 Request Time-out";
61 case 409: return "409 Conflict";
62 case 410: return "410 Gone";
63 case 411: return "411 Length Required";
64 case 412: return "412 Precondition Failed";
65 case 413: return "413 Request Entity Too Large";
66 case 414: return "414 Request-URI Too Large";
67 case 415: return "415 Unsupported Media Type";
68 case 416: return "416 Requested range not satisfiable";
69 case 417: return "417 Expectation Failed";
70 case 418: return "418 I'm a teapot";
71 // Server error 5xx
72 case 500: return "500 Internal Server Error";
73 case 501: return "501 Not Implemented";
74 case 502: return "502 Bad Gateway";
75 case 503: return "503 Service Unavailable";
76 case 504: return "504 Gateway Time-out";
77 case 505: return "505 HTTP Version not supported";
78 }
79 return NULL;
80 }
81 /*}}}*/
82 static void addFileHeaders(std::list<std::string> &headers, FileFd &data)/*{{{*/
83 {
84 std::ostringstream contentlength;
85 contentlength << "Content-Length: " << data.FileSize();
86 headers.push_back(contentlength.str());
87
88 std::string lastmodified("Last-Modified: ");
89 lastmodified.append(TimeRFC1123(data.ModificationTime()));
90 headers.push_back(lastmodified);
91 }
92 /*}}}*/
93 static void addDataHeaders(std::list<std::string> &headers, std::string &data)/*{{{*/
94 {
95 std::ostringstream contentlength;
96 contentlength << "Content-Length: " << data.size();
97 headers.push_back(contentlength.str());
98 }
99 /*}}}*/
100 static bool sendHead(int const client, int const httpcode, std::list<std::string> &headers)/*{{{*/
101 {
102 std::string response("HTTP/1.1 ");
103 response.append(httpcodeToStr(httpcode));
104 headers.push_front(response);
105 _config->Set("APTWebserver::Last-Status-Code", httpcode);
106
107 std::stringstream buffer;
108 _config->Dump(buffer, "aptwebserver::response-header", "%t: %v%n", false);
109 std::vector<std::string> addheaders = VectorizeString(buffer.str(), '\n');
110 for (std::vector<std::string>::const_iterator h = addheaders.begin(); h != addheaders.end(); ++h)
111 headers.push_back(*h);
112
113 std::string date("Date: ");
114 date.append(TimeRFC1123(time(NULL)));
115 headers.push_back(date);
116
117 std::clog << ">>> RESPONSE to " << client << " >>>" << std::endl;
118 bool Success = true;
119 for (std::list<std::string>::const_iterator h = headers.begin();
120 Success == true && h != headers.end(); ++h)
121 {
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 static bool sendFile(int const client, FileFd &data) /*{{{*/
134 {
135 bool Success = true;
136 char buffer[500];
137 unsigned long long actual = 0;
138 while ((Success &= data.Read(buffer, sizeof(buffer), &actual)) == true)
139 {
140 if (actual == 0)
141 break;
142 Success &= FileFd::Write(client, buffer, actual);
143 }
144 if (Success == false)
145 std::cerr << "SENDFILE: READ/WRITE ERROR to " << client << std::endl;
146 return Success;
147 }
148 /*}}}*/
149 static bool sendData(int const client, std::string const &data) /*{{{*/
150 {
151 if (FileFd::Write(client, data.c_str(), data.size()) == false)
152 {
153 std::cerr << "SENDDATA: WRITE ERROR to " << client << std::endl;
154 return false;
155 }
156 return true;
157 }
158 /*}}}*/
159 static void sendError(int const client, int const httpcode, std::string const &request,/*{{{*/
160 bool content, std::string const &error = "", std::list<std::string> headers = std::list<std::string>())
161 {
162 std::string response("<html><head><title>");
163 response.append(httpcodeToStr(httpcode)).append("</title></head>");
164 response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1>");
165 if (httpcode != 200)
166 {
167 if (error.empty() == false)
168 response.append("<p><em>Error</em>: ").append(error).append("</p>");
169 response.append("This error is a result of the request: <pre>");
170 }
171 else
172 {
173 if (error.empty() == false)
174 response.append("<p><em>Success</em>: ").append(error).append("</p>");
175 response.append("The successfully executed operation was requested by: <pre>");
176 }
177 response.append(request).append("</pre></body></html>");
178 addDataHeaders(headers, response);
179 sendHead(client, httpcode, headers);
180 if (content == true)
181 sendData(client, response);
182 }
183 static void sendSuccess(int const client, std::string const &request,
184 bool content, std::string const &error = "")
185 {
186 sendError(client, 200, request, content, error);
187 }
188 /*}}}*/
189 static void sendRedirect(int const client, int const httpcode, std::string const &uri,/*{{{*/
190 std::string const &request, bool content)
191 {
192 std::list<std::string> headers;
193 std::string response("<html><head><title>");
194 response.append(httpcodeToStr(httpcode)).append("</title></head>");
195 response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1");
196 response.append("<p>You should be redirected to <em>").append(uri).append("</em></p>");
197 response.append("This page is a result of the request: <pre>");
198 response.append(request).append("</pre></body></html>");
199 addDataHeaders(headers, response);
200 std::string location("Location: ");
201 if (strncmp(uri.c_str(), "http://", 7) != 0 && strncmp(uri.c_str(), "https://", 8) != 0)
202 {
203 std::string const host = LookupTag(request, "Host");
204 if (host.find(":4433") != std::string::npos)
205 location.append("https://");
206 else
207 location.append("http://");
208 location.append(host).append("/");
209 if (strncmp("/home/", uri.c_str(), strlen("/home/")) == 0 && uri.find("/public_html/") != std::string::npos)
210 {
211 std::string homeuri = SubstVar(uri, "/home/", "~");
212 homeuri = SubstVar(homeuri, "/public_html/", "/");
213 location.append(homeuri);
214 }
215 else
216 location.append(uri);
217 }
218 else
219 location.append(uri);
220 headers.push_back(location);
221 sendHead(client, httpcode, headers);
222 if (content == true)
223 sendData(client, response);
224 }
225 /*}}}*/
226 static int filter_hidden_files(const struct dirent *a) /*{{{*/
227 {
228 if (a->d_name[0] == '.')
229 return 0;
230 #ifdef _DIRENT_HAVE_D_TYPE
231 // if we have the d_type check that only files and dirs will be included
232 if (a->d_type != DT_UNKNOWN &&
233 a->d_type != DT_REG &&
234 a->d_type != DT_LNK && // this includes links to regular files
235 a->d_type != DT_DIR)
236 return 0;
237 #endif
238 return 1;
239 }
240 static int grouped_alpha_case_sort(const struct dirent **a, const struct dirent **b) {
241 #ifdef _DIRENT_HAVE_D_TYPE
242 if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_DIR);
243 else if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_REG)
244 return -1;
245 else if ((*b)->d_type == DT_DIR && (*a)->d_type == DT_REG)
246 return 1;
247 else
248 #endif
249 {
250 struct stat f_prop; //File's property
251 stat((*a)->d_name, &f_prop);
252 int const amode = f_prop.st_mode;
253 stat((*b)->d_name, &f_prop);
254 int const bmode = f_prop.st_mode;
255 if (S_ISDIR(amode) && S_ISDIR(bmode));
256 else if (S_ISDIR(amode))
257 return -1;
258 else if (S_ISDIR(bmode))
259 return 1;
260 }
261 return strcasecmp((*a)->d_name, (*b)->d_name);
262 }
263 /*}}}*/
264 static void sendDirectoryListing(int const client, std::string const &dir,/*{{{*/
265 std::string const &request, bool content)
266 {
267 std::list<std::string> headers;
268 std::ostringstream listing;
269
270 struct dirent **namelist;
271 int const counter = scandir(dir.c_str(), &namelist, filter_hidden_files, grouped_alpha_case_sort);
272 if (counter == -1)
273 {
274 sendError(client, 500, request, content);
275 return;
276 }
277
278 listing << "<html><head><title>Index of " << dir << "</title>"
279 << "<style type=\"text/css\"><!-- td {padding: 0.02em 0.5em 0.02em 0.5em;}"
280 << "tr:nth-child(even){background-color:#dfdfdf;}"
281 << "h1, td:nth-child(3){text-align:center;}"
282 << "table {margin-left:auto;margin-right:auto;} --></style>"
283 << "</head>" << std::endl
284 << "<body><h1>Index of " << dir << "</h1>" << std::endl
285 << "<table><tr><th>#</th><th>Name</th><th>Size</th><th>Last-Modified</th></tr>" << std::endl;
286 if (dir != "./")
287 listing << "<tr><td>d</td><td><a href=\"..\">Parent Directory</a></td><td>-</td><td>-</td></tr>";
288 for (int i = 0; i < counter; ++i) {
289 struct stat fs;
290 std::string filename(dir);
291 filename.append("/").append(namelist[i]->d_name);
292 stat(filename.c_str(), &fs);
293 if (S_ISDIR(fs.st_mode))
294 {
295 listing << "<tr><td>d</td>"
296 << "<td><a href=\"" << namelist[i]->d_name << "/\">" << namelist[i]->d_name << "</a></td>"
297 << "<td>-</td>";
298 }
299 else
300 {
301 listing << "<tr><td>f</td>"
302 << "<td><a href=\"" << namelist[i]->d_name << "\">" << namelist[i]->d_name << "</a></td>"
303 << "<td>" << SizeToStr(fs.st_size) << "B</td>";
304 }
305 listing << "<td>" << TimeRFC1123(fs.st_mtime) << "</td></tr>" << std::endl;
306 }
307 listing << "</table></body></html>" << std::endl;
308
309 std::string response(listing.str());
310 addDataHeaders(headers, response);
311 sendHead(client, 200, headers);
312 if (content == true)
313 sendData(client, response);
314 }
315 /*}}}*/
316 static bool parseFirstLine(int const client, std::string const &request,/*{{{*/
317 std::string &filename, std::string &params, bool &sendContent,
318 bool &closeConnection)
319 {
320 if (strncmp(request.c_str(), "HEAD ", 5) == 0)
321 sendContent = false;
322 if (strncmp(request.c_str(), "GET ", 4) != 0)
323 {
324 sendError(client, 501, request, true);
325 return false;
326 }
327
328 size_t const lineend = request.find('\n');
329 size_t filestart = request.find(' ');
330 for (; request[filestart] == ' '; ++filestart);
331 size_t fileend = request.rfind(' ', lineend);
332 if (lineend == std::string::npos || filestart == std::string::npos ||
333 fileend == std::string::npos || filestart == fileend)
334 {
335 sendError(client, 500, request, sendContent, "Filename can't be extracted");
336 return false;
337 }
338
339 size_t httpstart = fileend;
340 for (; request[httpstart] == ' '; ++httpstart);
341 if (strncmp(request.c_str() + httpstart, "HTTP/1.1\r", 9) == 0)
342 closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "Keep-Alive") != 0;
343 else if (strncmp(request.c_str() + httpstart, "HTTP/1.0\r", 9) == 0)
344 closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "close") == 0;
345 else
346 {
347 sendError(client, 500, request, sendContent, "Not a HTTP/1.{0,1} request");
348 return false;
349 }
350
351 filename = request.substr(filestart, fileend - filestart);
352 if (filename.find(' ') != std::string::npos)
353 {
354 sendError(client, 500, request, sendContent, "Filename contains an unencoded space");
355 return false;
356 }
357
358 std::string host = LookupTag(request, "Host", "");
359 if (host.empty() == true)
360 {
361 // RFC 2616 §14.23 requires Host
362 sendError(client, 400, request, sendContent, "Host header is required");
363 return false;
364 }
365 host = "http://" + host;
366
367 // Proxies require absolute uris, so this is a simple proxy-fake option
368 std::string const absolute = _config->Find("aptwebserver::request::absolute", "uri,path");
369 if (strncmp(host.c_str(), filename.c_str(), host.length()) == 0 && APT::String::Startswith(filename, "/_config/") == false)
370 {
371 if (absolute.find("uri") == std::string::npos)
372 {
373 sendError(client, 400, request, sendContent, "Request is absoluteURI, but configured to not accept that");
374 return false;
375 }
376
377 // strip the host from the request to make it an absolute path
378 filename.erase(0, host.length());
379
380 std::string const authConf = _config->Find("aptwebserver::proxy-authorization", "");
381 std::string auth = LookupTag(request, "Proxy-Authorization", "");
382 if (authConf.empty() != auth.empty())
383 {
384 if (auth.empty())
385 sendError(client, 407, request, sendContent, "Proxy requires authentication");
386 else
387 sendError(client, 407, request, sendContent, "Client wants to authenticate to proxy, but proxy doesn't need it");
388 return false;
389 }
390 if (authConf.empty() == false)
391 {
392 char const * const basic = "Basic ";
393 if (strncmp(auth.c_str(), basic, strlen(basic)) == 0)
394 {
395 auth.erase(0, strlen(basic));
396 if (auth != authConf)
397 {
398 sendError(client, 407, request, sendContent, "Proxy-Authentication doesn't match");
399 return false;
400 }
401 }
402 else
403 {
404 std::list<std::string> headers;
405 headers.push_back("Proxy-Authenticate: Basic");
406 sendError(client, 407, request, sendContent, "Unsupported Proxy-Authentication Scheme", headers);
407 return false;
408 }
409 }
410 }
411 else if (absolute.find("path") == std::string::npos && APT::String::Startswith(filename, "/_config/") == false)
412 {
413 sendError(client, 400, request, sendContent, "Request is absolutePath, but configured to not accept that");
414 return false;
415 }
416
417 if (APT::String::Startswith(filename, "/_config/") == false)
418 {
419 std::string const authConf = _config->Find("aptwebserver::authorization", "");
420 std::string auth = LookupTag(request, "Authorization", "");
421 if (authConf.empty() != auth.empty())
422 {
423 if (auth.empty())
424 sendError(client, 401, request, sendContent, "Server requires authentication");
425 else
426 sendError(client, 401, request, sendContent, "Client wants to authenticate to server, but server doesn't need it");
427 return false;
428 }
429 if (authConf.empty() == false)
430 {
431 char const * const basic = "Basic ";
432 if (strncmp(auth.c_str(), basic, strlen(basic)) == 0)
433 {
434 auth.erase(0, strlen(basic));
435 if (auth != authConf)
436 {
437 sendError(client, 401, request, sendContent, "Authentication doesn't match");
438 return false;
439 }
440 }
441 else
442 {
443 std::list<std::string> headers;
444 headers.push_back("WWW-Authenticate: Basic");
445 sendError(client, 401, request, sendContent, "Unsupported Authentication Scheme", headers);
446 return false;
447 }
448 }
449 }
450
451 size_t paramspos = filename.find('?');
452 if (paramspos != std::string::npos)
453 {
454 params = filename.substr(paramspos + 1);
455 filename.erase(paramspos);
456 }
457
458 filename = DeQuoteString(filename);
459
460 // this is not a secure server, but at least prevent the obvious …
461 if (filename.empty() == true || filename[0] != '/' ||
462 strncmp(filename.c_str(), "//", 2) == 0 ||
463 filename.find_first_of("\r\n\t\f\v") != std::string::npos ||
464 filename.find("/../") != std::string::npos)
465 {
466 sendError(client, 400, request, sendContent, "Filename contains illegal character (sequence)");
467 return false;
468 }
469
470 // nuke the first character which is a / as we assured above
471 filename.erase(0, 1);
472 if (filename.empty() == true)
473 filename = "./";
474 // support ~user/ uris to refer to /home/user/public_html/ as a kind-of special directory
475 else if (filename[0] == '~')
476 {
477 // /home/user is actually not entirely correct, but good enough for now
478 size_t dashpos = filename.find('/');
479 if (dashpos != std::string::npos)
480 {
481 std::string home = filename.substr(1, filename.find('/') - 1);
482 std::string pubhtml = filename.substr(filename.find('/') + 1);
483 filename = "/home/" + home + "/public_html/" + pubhtml;
484 }
485 else
486 filename = "/home/" + filename.substr(1) + "/public_html/";
487 }
488
489 // if no filename is given, but a valid directory see if we can use an index or
490 // have to resort to a autogenerated directory listing later on
491 if (DirectoryExists(filename) == true)
492 {
493 std::string const directoryIndex = _config->Find("aptwebserver::directoryindex");
494 if (directoryIndex.empty() == false && directoryIndex == flNotDir(directoryIndex) &&
495 RealFileExists(filename + directoryIndex) == true)
496 filename += directoryIndex;
497 }
498
499 return true;
500 }
501 /*}}}*/
502 static bool handleOnTheFlyReconfiguration(int const client, std::string const &request, std::vector<std::string> parts)/*{{{*/
503 {
504 size_t const pcount = parts.size();
505 for (size_t i = 0; i < pcount; ++i)
506 parts[i] = DeQuoteString(parts[i]);
507 if (pcount == 4 && parts[1] == "set")
508 {
509 _config->Set(parts[2], parts[3]);
510 sendSuccess(client, request, true, "Option '" + parts[2] + "' was set to '" + parts[3] + "'!");
511 return true;
512 }
513 else if (pcount == 4 && parts[1] == "find")
514 {
515 std::list<std::string> headers;
516 std::string response = _config->Find(parts[2], parts[3]);
517 addDataHeaders(headers, response);
518 sendHead(client, 200, headers);
519 sendData(client, response);
520 return true;
521 }
522 else if (pcount == 3 && parts[1] == "find")
523 {
524 std::list<std::string> headers;
525 if (_config->Exists(parts[2]) == true)
526 {
527 std::string response = _config->Find(parts[2]);
528 addDataHeaders(headers, response);
529 sendHead(client, 200, headers);
530 sendData(client, response);
531 return true;
532 }
533 sendError(client, 404, request, "Requested Configuration option doesn't exist.");
534 return false;
535 }
536 else if (pcount == 3 && parts[1] == "clear")
537 {
538 _config->Clear(parts[2]);
539 sendSuccess(client, request, true, "Option '" + parts[2] + "' was cleared.");
540 return true;
541 }
542
543 sendError(client, 400, request, true, "Unknown on-the-fly configuration request");
544 return false;
545 }
546 /*}}}*/
547 static void * handleClient(void * voidclient) /*{{{*/
548 {
549 int client = *((int*)(voidclient));
550 std::clog << "ACCEPT client " << client << std::endl;
551 std::vector<std::string> messages;
552 while (ReadMessages(client, messages))
553 {
554 bool closeConnection = false;
555 for (std::vector<std::string>::const_iterator m = messages.begin();
556 m != messages.end() && closeConnection == false; ++m) {
557 std::clog << ">>> REQUEST from " << client << " >>>" << std::endl << *m
558 << std::endl << "<<<<<<<<<<<<<<<<" << std::endl;
559 std::list<std::string> headers;
560 std::string filename;
561 std::string params;
562 bool sendContent = true;
563 if (parseFirstLine(client, *m, filename, params, sendContent, closeConnection) == false)
564 continue;
565
566 // special webserver command request
567 if (filename.length() > 1 && filename[0] == '_')
568 {
569 std::vector<std::string> parts = VectorizeString(filename, '/');
570 if (parts[0] == "_config")
571 {
572 handleOnTheFlyReconfiguration(client, *m, parts);
573 continue;
574 }
575 }
576
577 // string replacements in the requested filename
578 ::Configuration::Item const *Replaces = _config->Tree("aptwebserver::redirect::replace");
579 if (Replaces != NULL)
580 {
581 std::string redirect = "/" + filename;
582 for (::Configuration::Item *I = Replaces->Child; I != NULL; I = I->Next)
583 redirect = SubstVar(redirect, I->Tag, I->Value);
584 if (redirect.empty() == false && redirect[0] == '/')
585 redirect.erase(0,1);
586 if (redirect != filename)
587 {
588 sendRedirect(client, 301, redirect, *m, sendContent);
589 continue;
590 }
591 }
592
593 ::Configuration::Item const *Overwrite = _config->Tree("aptwebserver::overwrite");
594 if (Overwrite != NULL)
595 {
596 for (::Configuration::Item *I = Overwrite->Child; I != NULL; I = I->Next)
597 {
598 regex_t *pattern = new regex_t;
599 int const res = regcomp(pattern, I->Tag.c_str(), REG_EXTENDED | REG_ICASE | REG_NOSUB);
600 if (res != 0)
601 {
602 char error[300];
603 regerror(res, pattern, error, sizeof(error));
604 sendError(client, 500, *m, sendContent, error);
605 continue;
606 }
607 if (regexec(pattern, filename.c_str(), 0, 0, 0) == 0)
608 {
609 filename = _config->Find("aptwebserver::overwrite::" + I->Tag + "::filename", filename);
610 if (filename[0] == '/')
611 filename.erase(0,1);
612 regfree(pattern);
613 break;
614 }
615 regfree(pattern);
616 }
617 }
618
619 // deal with the request
620 if (_config->FindB("aptwebserver::support::http", true) == false &&
621 LookupTag(*m, "Host").find(":4433") == std::string::npos)
622 {
623 sendError(client, 400, *m, sendContent, "HTTP disabled, all requests must be HTTPS");
624 continue;
625 }
626 else if (RealFileExists(filename) == true)
627 {
628 FileFd data(filename, FileFd::ReadOnly);
629 std::string condition = LookupTag(*m, "If-Modified-Since", "");
630 if (_config->FindB("aptwebserver::support::modified-since", true) == true && condition.empty() == false)
631 {
632 time_t cache;
633 if (RFC1123StrToTime(condition.c_str(), cache) == true &&
634 cache >= data.ModificationTime())
635 {
636 sendHead(client, 304, headers);
637 continue;
638 }
639 }
640
641 if (_config->FindB("aptwebserver::support::range", true) == true)
642 condition = LookupTag(*m, "Range", "");
643 else
644 condition.clear();
645 if (condition.empty() == false && strncmp(condition.c_str(), "bytes=", 6) == 0)
646 {
647 time_t cache;
648 std::string ifrange;
649 if (_config->FindB("aptwebserver::support::if-range", true) == true)
650 ifrange = LookupTag(*m, "If-Range", "");
651 bool validrange = (ifrange.empty() == true ||
652 (RFC1123StrToTime(ifrange.c_str(), cache) == true &&
653 cache <= data.ModificationTime()));
654
655 // FIXME: support multiple byte-ranges (APT clients do not do this)
656 if (condition.find(',') == std::string::npos)
657 {
658 size_t start = 6;
659 unsigned long long filestart = strtoull(condition.c_str() + start, NULL, 10);
660 // FIXME: no support for last-byte-pos being not the end of the file (APT clients do not do this)
661 size_t dash = condition.find('-') + 1;
662 unsigned long long fileend = strtoull(condition.c_str() + dash, NULL, 10);
663 unsigned long long filesize = data.FileSize();
664 if ((fileend == 0 || (fileend == filesize && fileend >= filestart)) &&
665 validrange == true)
666 {
667 if (filesize > filestart)
668 {
669 data.Skip(filestart);
670 std::ostringstream contentlength;
671 contentlength << "Content-Length: " << (filesize - filestart);
672 headers.push_back(contentlength.str());
673 std::ostringstream contentrange;
674 contentrange << "Content-Range: bytes " << filestart << "-"
675 << filesize - 1 << "/" << filesize;
676 headers.push_back(contentrange.str());
677 sendHead(client, 206, headers);
678 if (sendContent == true)
679 sendFile(client, data);
680 continue;
681 }
682 else
683 {
684 headers.push_back("Content-Length: 0");
685 std::ostringstream contentrange;
686 contentrange << "Content-Range: bytes */" << filesize;
687 headers.push_back(contentrange.str());
688 sendHead(client, 416, headers);
689 continue;
690 }
691 }
692 }
693 }
694
695 addFileHeaders(headers, data);
696 sendHead(client, 200, headers);
697 if (sendContent == true)
698 sendFile(client, data);
699 }
700 else if (DirectoryExists(filename) == true)
701 {
702 if (filename[filename.length()-1] == '/')
703 sendDirectoryListing(client, filename, *m, sendContent);
704 else
705 sendRedirect(client, 301, filename.append("/"), *m, sendContent);
706 }
707 else
708 sendError(client, 404, *m, sendContent);
709 }
710 _error->DumpErrors(std::cerr);
711 messages.clear();
712 if (closeConnection == true)
713 break;
714 }
715 close(client);
716 std::clog << "CLOSE client " << client << std::endl;
717 return NULL;
718 }
719 /*}}}*/
720
721 int main(int const argc, const char * argv[])
722 {
723 CommandLine::Args Args[] = {
724 {0, "port", "aptwebserver::port", CommandLine::HasArg},
725 {0, "request-absolute", "aptwebserver::request::absolute", CommandLine::HasArg},
726 {0, "authorization", "aptwebserver::authorization", CommandLine::HasArg},
727 {0, "proxy-authorization", "aptwebserver::proxy-authorization", CommandLine::HasArg},
728 {'c',"config-file",0,CommandLine::ConfigFile},
729 {'o',"option",0,CommandLine::ArbItem},
730 {0,0,0,0}
731 };
732
733 CommandLine CmdL(Args, _config);
734 if(CmdL.Parse(argc,argv) == false)
735 {
736 _error->DumpErrors();
737 exit(1);
738 }
739
740 // create socket, bind and listen to it {{{
741 // ignore SIGPIPE, this can happen on write() if the socket closes connection
742 signal(SIGPIPE, SIG_IGN);
743 // we don't care for our slaves, so ignore their death
744 signal(SIGCHLD, SIG_IGN);
745
746 int sock = socket(AF_INET6, SOCK_STREAM, 0);
747 if(sock < 0)
748 {
749 _error->Errno("aptwerbserver", "Couldn't create socket");
750 _error->DumpErrors(std::cerr);
751 return 1;
752 }
753
754 int const port = _config->FindI("aptwebserver::port", 8080);
755
756 // ensure that we accept all connections: v4 or v6
757 int const iponly = 0;
758 setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &iponly, sizeof(iponly));
759 // to not linger on an address
760 int const enable = 1;
761 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
762
763 struct sockaddr_in6 locAddr;
764 memset(&locAddr, 0, sizeof(locAddr));
765 locAddr.sin6_family = AF_INET6;
766 locAddr.sin6_port = htons(port);
767 locAddr.sin6_addr = in6addr_any;
768
769 if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0)
770 {
771 _error->Errno("aptwerbserver", "Couldn't bind");
772 _error->DumpErrors(std::cerr);
773 return 2;
774 }
775
776 FileFd pidfile;
777 if (_config->FindB("aptwebserver::fork", false) == true)
778 {
779 std::string const pidfilename = _config->Find("aptwebserver::pidfile", "aptwebserver.pid");
780 int const pidfilefd = GetLock(pidfilename);
781 if (pidfilefd < 0 || pidfile.OpenDescriptor(pidfilefd, FileFd::WriteOnly) == false)
782 {
783 _error->Errno("aptwebserver", "Couldn't acquire lock on pidfile '%s'", pidfilename.c_str());
784 _error->DumpErrors(std::cerr);
785 return 3;
786 }
787
788 pid_t child = fork();
789 if (child < 0)
790 {
791 _error->Errno("aptwebserver", "Forking failed");
792 _error->DumpErrors(std::cerr);
793 return 4;
794 }
795 else if (child != 0)
796 {
797 // successfully forked: ready to serve!
798 std::string pidcontent;
799 strprintf(pidcontent, "%d", child);
800 pidfile.Write(pidcontent.c_str(), pidcontent.size());
801 if (_error->PendingError() == true)
802 {
803 _error->DumpErrors(std::cerr);
804 return 5;
805 }
806 std::cout << "Successfully forked as " << child << std::endl;
807 return 0;
808 }
809 }
810
811 std::clog << "Serving ANY file on port: " << port << std::endl;
812
813 int const slaves = _config->FindB("aptwebserver::slaves", SOMAXCONN);
814 listen(sock, slaves);
815 /*}}}*/
816
817 _config->CndSet("aptwebserver::response-header::Server", "APT webserver");
818 _config->CndSet("aptwebserver::response-header::Accept-Ranges", "bytes");
819 _config->CndSet("aptwebserver::directoryindex", "index.html");
820
821 std::list<int> accepted_clients;
822
823 while (true)
824 {
825 int client = accept(sock, NULL, NULL);
826 if (client == -1)
827 {
828 if (errno == EINTR)
829 continue;
830 _error->Errno("accept", "Couldn't accept client on socket %d", sock);
831 _error->DumpErrors(std::cerr);
832 return 6;
833 }
834
835 pthread_attr_t attr;
836 if (pthread_attr_init(&attr) != 0 || pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0)
837 {
838 _error->Errno("pthread_attr", "Couldn't set detach attribute for a fresh thread to handle client %d on socket %d", client, sock);
839 _error->DumpErrors(std::cerr);
840 close(client);
841 continue;
842 }
843
844 pthread_t tid;
845 // thats rather dirty, but we need to store the client socket somewhere safe
846 accepted_clients.push_front(client);
847 if (pthread_create(&tid, &attr, &handleClient, &(*accepted_clients.begin())) != 0)
848 {
849 _error->Errno("pthread_create", "Couldn't create a fresh thread to handle client %d on socket %d", client, sock);
850 _error->DumpErrors(std::cerr);
851 close(client);
852 continue;
853 }
854 }
855 pidfile.Close();
856
857 return 0;
858 }