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