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>
11 #include <netinet/in.h>
18 #include <sys/socket.h>
30 static char const * httpcodeToStr(int const httpcode
) /*{{{*/
35 case 100: return "100 Continue";
36 case 101: return "101 Switching Protocols";
38 case 200: return "200 OK";
39 case 201: return "201 Created";
40 case 202: return "202 Accepted";
41 case 203: return "203 Non-Authoritative Information";
42 case 204: return "204 No Content";
43 case 205: return "205 Reset Content";
44 case 206: return "206 Partial Content";
46 case 300: return "300 Multiple Choices";
47 case 301: return "301 Moved Permanently";
48 case 302: return "302 Found";
49 case 303: return "303 See Other";
50 case 304: return "304 Not Modified";
51 case 305: return "304 Use Proxy";
52 case 307: return "307 Temporary Redirect";
54 case 400: return "400 Bad Request";
55 case 401: return "401 Unauthorized";
56 case 402: return "402 Payment Required";
57 case 403: return "403 Forbidden";
58 case 404: return "404 Not Found";
59 case 405: return "405 Method Not Allowed";
60 case 406: return "406 Not Acceptable";
61 case 407: return "407 Proxy Authentication Required";
62 case 408: return "408 Request Time-out";
63 case 409: return "409 Conflict";
64 case 410: return "410 Gone";
65 case 411: return "411 Length Required";
66 case 412: return "412 Precondition Failed";
67 case 413: return "413 Request Entity Too Large";
68 case 414: return "414 Request-URI Too Large";
69 case 415: return "415 Unsupported Media Type";
70 case 416: return "416 Requested range not satisfiable";
71 case 417: return "417 Expectation Failed";
72 case 418: return "418 I'm a teapot";
74 case 500: return "500 Internal Server Error";
75 case 501: return "501 Not Implemented";
76 case 502: return "502 Bad Gateway";
77 case 503: return "503 Service Unavailable";
78 case 504: return "504 Gateway Time-out";
79 case 505: return "505 HTTP Version not supported";
84 static bool chunkedTransferEncoding(std::list
<std::string
> const &headers
) {
85 if (std::find(headers
.begin(), headers
.end(), "Transfer-Encoding: chunked") != headers
.end())
87 if (_config
->FindB("aptwebserver::chunked-transfer-encoding", false) == true)
91 static void addFileHeaders(std::list
<std::string
> &headers
, FileFd
&data
)/*{{{*/
93 if (chunkedTransferEncoding(headers
) == false)
95 std::ostringstream contentlength
;
96 contentlength
<< "Content-Length: " << data
.FileSize();
97 headers
.push_back(contentlength
.str());
99 std::string
lastmodified("Last-Modified: ");
100 lastmodified
.append(TimeRFC1123(data
.ModificationTime()));
101 headers
.push_back(lastmodified
);
104 static void addDataHeaders(std::list
<std::string
> &headers
, std::string
&data
)/*{{{*/
106 if (chunkedTransferEncoding(headers
) == false)
108 std::ostringstream contentlength
;
109 contentlength
<< "Content-Length: " << data
.size();
110 headers
.push_back(contentlength
.str());
114 static bool sendHead(int const client
, int const httpcode
, std::list
<std::string
> &headers
)/*{{{*/
116 std::string
response("HTTP/1.1 ");
117 response
.append(httpcodeToStr(httpcode
));
118 headers
.push_front(response
);
119 _config
->Set("APTWebserver::Last-Status-Code", httpcode
);
121 std::stringstream buffer
;
122 _config
->Dump(buffer
, "aptwebserver::response-header", "%t: %v%n", false);
123 std::vector
<std::string
> addheaders
= VectorizeString(buffer
.str(), '\n');
124 for (std::vector
<std::string
>::const_iterator h
= addheaders
.begin(); h
!= addheaders
.end(); ++h
)
125 headers
.push_back(*h
);
127 std::string
date("Date: ");
128 date
.append(TimeRFC1123(time(NULL
)));
129 headers
.push_back(date
);
131 if (chunkedTransferEncoding(headers
) == true)
132 headers
.push_back("Transfer-Encoding: chunked");
134 std::clog
<< ">>> RESPONSE to " << client
<< " >>>" << std::endl
;
136 for (std::list
<std::string
>::const_iterator h
= headers
.begin();
137 Success
== true && h
!= headers
.end(); ++h
)
139 Success
&= FileFd::Write(client
, h
->c_str(), h
->size());
141 Success
&= FileFd::Write(client
, "\r\n", 2);
142 std::clog
<< *h
<< std::endl
;
145 Success
&= FileFd::Write(client
, "\r\n", 2);
146 std::clog
<< "<<<<<<<<<<<<<<<<" << std::endl
;
150 static bool sendFile(int const client
, std::list
<std::string
> const &headers
, FileFd
&data
)/*{{{*/
153 bool const chunked
= chunkedTransferEncoding(headers
);
155 unsigned long long actual
= 0;
156 while ((Success
&= data
.Read(buffer
, sizeof(buffer
), &actual
)) == true)
164 strprintf(size
, "%llX\r\n", actual
);
165 Success
&= FileFd::Write(client
, size
.c_str(), size
.size());
166 Success
&= FileFd::Write(client
, buffer
, actual
);
167 Success
&= FileFd::Write(client
, "\r\n", strlen("\r\n"));
170 Success
&= FileFd::Write(client
, buffer
, actual
);
174 char const * const finish
= "0\r\n\r\n";
175 Success
&= FileFd::Write(client
, finish
, strlen(finish
));
177 if (Success
== false)
178 std::cerr
<< "SENDFILE:" << (chunked
? " CHUNKED" : "") << " READ/WRITE ERROR to " << client
<< std::endl
;
182 static bool sendData(int const client
, std::list
<std::string
> const &headers
, std::string
const &data
)/*{{{*/
184 if (chunkedTransferEncoding(headers
) == true)
186 unsigned long long const ullsize
= data
.length();
188 strprintf(size
, "%llX\r\n", ullsize
);
189 char const * const finish
= "\r\n0\r\n\r\n";
190 if (FileFd::Write(client
, size
.c_str(), size
.length()) == false ||
191 FileFd::Write(client
, data
.c_str(), ullsize
) == false ||
192 FileFd::Write(client
, finish
, strlen(finish
)) == false)
194 std::cerr
<< "SENDDATA: CHUNK WRITE ERROR to " << client
<< std::endl
;
198 else if (FileFd::Write(client
, data
.c_str(), data
.size()) == false)
200 std::cerr
<< "SENDDATA: WRITE ERROR to " << client
<< std::endl
;
206 static void sendError(int const client
, int const httpcode
, std::string
const &request
,/*{{{*/
207 bool const content
, std::string
const &error
, std::list
<std::string
> &headers
)
209 std::string
response("<html><head><title>");
210 response
.append(httpcodeToStr(httpcode
)).append("</title></head>");
211 response
.append("<body><h1>").append(httpcodeToStr(httpcode
)).append("</h1>");
213 response
.append("<p><em>Error</em>: ");
215 response
.append("<p><em>Success</em>: ");
216 if (error
.empty() == false)
217 response
.append(error
);
219 response
.append(httpcodeToStr(httpcode
));
221 response
.append("</p>This error is a result of the request: <pre>");
223 response
.append("The successfully executed operation was requested by: <pre>");
224 response
.append(request
).append("</pre></body></html>");
227 if (_config
->FindB("aptwebserver::closeOnError", false) == true)
228 headers
.push_back("Connection: close");
230 addDataHeaders(headers
, response
);
231 sendHead(client
, httpcode
, headers
);
233 sendData(client
, headers
, response
);
235 static void sendSuccess(int const client
, std::string
const &request
,
236 bool const content
, std::string
const &error
, std::list
<std::string
> &headers
)
238 sendError(client
, 200, request
, content
, error
, headers
);
241 static void sendRedirect(int const client
, int const httpcode
, std::string
const &uri
,/*{{{*/
242 std::string
const &request
, bool content
)
244 std::list
<std::string
> headers
;
245 std::string
response("<html><head><title>");
246 response
.append(httpcodeToStr(httpcode
)).append("</title></head>");
247 response
.append("<body><h1>").append(httpcodeToStr(httpcode
)).append("</h1");
248 response
.append("<p>You should be redirected to <em>").append(uri
).append("</em></p>");
249 response
.append("This page is a result of the request: <pre>");
250 response
.append(request
).append("</pre></body></html>");
251 addDataHeaders(headers
, response
);
252 std::string
location("Location: ");
253 if (strncmp(uri
.c_str(), "http://", 7) != 0 && strncmp(uri
.c_str(), "https://", 8) != 0)
255 std::string
const host
= LookupTag(request
, "Host");
256 if (host
.find(":4433") != std::string::npos
)
257 location
.append("https://");
259 location
.append("http://");
260 location
.append(host
).append("/");
261 if (strncmp("/home/", uri
.c_str(), strlen("/home/")) == 0 && uri
.find("/public_html/") != std::string::npos
)
263 std::string homeuri
= SubstVar(uri
, "/home/", "~");
264 homeuri
= SubstVar(homeuri
, "/public_html/", "/");
265 location
.append(homeuri
);
268 location
.append(uri
);
271 location
.append(uri
);
272 headers
.push_back(location
);
273 sendHead(client
, httpcode
, headers
);
275 sendData(client
, headers
, response
);
278 static int filter_hidden_files(const struct dirent
*a
) /*{{{*/
280 if (a
->d_name
[0] == '.')
282 #ifdef _DIRENT_HAVE_D_TYPE
283 // if we have the d_type check that only files and dirs will be included
284 if (a
->d_type
!= DT_UNKNOWN
&&
285 a
->d_type
!= DT_REG
&&
286 a
->d_type
!= DT_LNK
&& // this includes links to regular files
292 static int grouped_alpha_case_sort(const struct dirent
**a
, const struct dirent
**b
) {
293 #ifdef _DIRENT_HAVE_D_TYPE
294 if ((*a
)->d_type
== DT_DIR
&& (*b
)->d_type
== DT_DIR
);
295 else if ((*a
)->d_type
== DT_DIR
&& (*b
)->d_type
== DT_REG
)
297 else if ((*b
)->d_type
== DT_DIR
&& (*a
)->d_type
== DT_REG
)
302 struct stat f_prop
; //File's property
303 stat((*a
)->d_name
, &f_prop
);
304 int const amode
= f_prop
.st_mode
;
305 stat((*b
)->d_name
, &f_prop
);
306 int const bmode
= f_prop
.st_mode
;
307 if (S_ISDIR(amode
) && S_ISDIR(bmode
));
308 else if (S_ISDIR(amode
))
310 else if (S_ISDIR(bmode
))
313 return strcasecmp((*a
)->d_name
, (*b
)->d_name
);
316 static void sendDirectoryListing(int const client
, std::string
const &dir
,/*{{{*/
317 std::string
const &request
, bool content
, std::list
<std::string
> &headers
)
319 std::ostringstream listing
;
321 struct dirent
**namelist
;
322 int const counter
= scandir(dir
.c_str(), &namelist
, filter_hidden_files
, grouped_alpha_case_sort
);
325 sendError(client
, 500, request
, content
, "scandir failed", headers
);
329 listing
<< "<html><head><title>Index of " << dir
<< "</title>"
330 << "<style type=\"text/css\"><!-- td {padding: 0.02em 0.5em 0.02em 0.5em;}"
331 << "tr:nth-child(even){background-color:#dfdfdf;}"
332 << "h1, td:nth-child(3){text-align:center;}"
333 << "table {margin-left:auto;margin-right:auto;} --></style>"
334 << "</head>" << std::endl
335 << "<body><h1>Index of " << dir
<< "</h1>" << std::endl
336 << "<table><tr><th>#</th><th>Name</th><th>Size</th><th>Last-Modified</th></tr>" << std::endl
;
338 listing
<< "<tr><td>d</td><td><a href=\"..\">Parent Directory</a></td><td>-</td><td>-</td></tr>";
339 for (int i
= 0; i
< counter
; ++i
) {
341 std::string
filename(dir
);
342 filename
.append("/").append(namelist
[i
]->d_name
);
343 stat(filename
.c_str(), &fs
);
344 if (S_ISDIR(fs
.st_mode
))
346 listing
<< "<tr><td>d</td>"
347 << "<td><a href=\"" << namelist
[i
]->d_name
<< "/\">" << namelist
[i
]->d_name
<< "</a></td>"
352 listing
<< "<tr><td>f</td>"
353 << "<td><a href=\"" << namelist
[i
]->d_name
<< "\">" << namelist
[i
]->d_name
<< "</a></td>"
354 << "<td>" << SizeToStr(fs
.st_size
) << "B</td>";
356 listing
<< "<td>" << TimeRFC1123(fs
.st_mtime
) << "</td></tr>" << std::endl
;
358 listing
<< "</table></body></html>" << std::endl
;
360 std::string
response(listing
.str());
361 addDataHeaders(headers
, response
);
362 sendHead(client
, 200, headers
);
364 sendData(client
, headers
, response
);
367 static bool parseFirstLine(int const client
, std::string
const &request
,/*{{{*/
368 std::string
&filename
, std::string
¶ms
, bool &sendContent
,
369 bool &closeConnection
, std::list
<std::string
> &headers
)
371 if (strncmp(request
.c_str(), "HEAD ", 5) == 0)
373 if (strncmp(request
.c_str(), "GET ", 4) != 0)
375 sendError(client
, 501, request
, true, "", headers
);
379 size_t const lineend
= request
.find('\n');
380 size_t filestart
= request
.find(' ');
381 for (; request
[filestart
] == ' '; ++filestart
);
382 size_t fileend
= request
.rfind(' ', lineend
);
383 if (lineend
== std::string::npos
|| filestart
== std::string::npos
||
384 fileend
== std::string::npos
|| filestart
== fileend
)
386 sendError(client
, 500, request
, sendContent
, "Filename can't be extracted", headers
);
390 size_t httpstart
= fileend
;
391 for (; request
[httpstart
] == ' '; ++httpstart
);
392 if (strncmp(request
.c_str() + httpstart
, "HTTP/1.1\r", 9) == 0)
393 closeConnection
= strcasecmp(LookupTag(request
, "Connection", "Keep-Alive").c_str(), "Keep-Alive") != 0;
394 else if (strncmp(request
.c_str() + httpstart
, "HTTP/1.0\r", 9) == 0)
395 closeConnection
= strcasecmp(LookupTag(request
, "Connection", "Keep-Alive").c_str(), "close") == 0;
398 sendError(client
, 500, request
, sendContent
, "Not a HTTP/1.{0,1} request", headers
);
402 filename
= request
.substr(filestart
, fileend
- filestart
);
403 if (filename
.find(' ') != std::string::npos
)
405 sendError(client
, 500, request
, sendContent
, "Filename contains an unencoded space", headers
);
409 std::string host
= LookupTag(request
, "Host", "");
410 if (host
.empty() == true)
412 // RFC 2616 §14.23 requires Host
413 sendError(client
, 400, request
, sendContent
, "Host header is required", headers
);
416 host
= "http://" + host
;
418 // Proxies require absolute uris, so this is a simple proxy-fake option
419 std::string
const absolute
= _config
->Find("aptwebserver::request::absolute", "uri,path");
420 if (strncmp(host
.c_str(), filename
.c_str(), host
.length()) == 0)
422 if (absolute
.find("uri") == std::string::npos
)
424 sendError(client
, 400, request
, sendContent
, "Request is absoluteURI, but configured to not accept that", headers
);
427 // strip the host from the request to make it an absolute path
428 filename
.erase(0, host
.length());
430 else if (absolute
.find("path") == std::string::npos
)
432 sendError(client
, 400, request
, sendContent
, "Request is absolutePath, but configured to not accept that", headers
);
436 size_t paramspos
= filename
.find('?');
437 if (paramspos
!= std::string::npos
)
439 params
= filename
.substr(paramspos
+ 1);
440 filename
.erase(paramspos
);
443 filename
= DeQuoteString(filename
);
445 // this is not a secure server, but at least prevent the obvious …
446 if (filename
.empty() == true || filename
[0] != '/' ||
447 strncmp(filename
.c_str(), "//", 2) == 0 ||
448 filename
.find_first_of("\r\n\t\f\v") != std::string::npos
||
449 filename
.find("/../") != std::string::npos
)
451 std::list
<std::string
> headers
;
452 sendError(client
, 400, request
, sendContent
, "Filename contains illegal character (sequence)", headers
);
456 // nuke the first character which is a / as we assured above
457 filename
.erase(0, 1);
458 if (filename
.empty() == true)
460 // support ~user/ uris to refer to /home/user/public_html/ as a kind-of special directory
461 else if (filename
[0] == '~')
463 // /home/user is actually not entirely correct, but good enough for now
464 size_t dashpos
= filename
.find('/');
465 if (dashpos
!= std::string::npos
)
467 std::string home
= filename
.substr(1, filename
.find('/') - 1);
468 std::string pubhtml
= filename
.substr(filename
.find('/') + 1);
469 filename
= "/home/" + home
+ "/public_html/" + pubhtml
;
472 filename
= "/home/" + filename
.substr(1) + "/public_html/";
475 // if no filename is given, but a valid directory see if we can use an index or
476 // have to resort to a autogenerated directory listing later on
477 if (DirectoryExists(filename
) == true)
479 std::string
const directoryIndex
= _config
->Find("aptwebserver::directoryindex");
480 if (directoryIndex
.empty() == false && directoryIndex
== flNotDir(directoryIndex
) &&
481 RealFileExists(filename
+ directoryIndex
) == true)
482 filename
+= directoryIndex
;
488 static bool handleOnTheFlyReconfiguration(int const client
, std::string
const &request
,/*{{{*/
489 std::vector
<std::string
> parts
, std::list
<std::string
> &headers
)
491 size_t const pcount
= parts
.size();
492 if (pcount
== 4 && parts
[1] == "set")
494 _config
->Set(parts
[2], parts
[3]);
495 sendSuccess(client
, request
, true, "Option '" + parts
[2] + "' was set to '" + parts
[3] + "'!", headers
);
498 else if (pcount
== 4 && parts
[1] == "find")
500 std::string response
= _config
->Find(parts
[2], parts
[3]);
501 addDataHeaders(headers
, response
);
502 sendHead(client
, 200, headers
);
503 sendData(client
, headers
, response
);
506 else if (pcount
== 3 && parts
[1] == "find")
508 if (_config
->Exists(parts
[2]) == true)
510 std::string response
= _config
->Find(parts
[2]);
511 addDataHeaders(headers
, response
);
512 sendHead(client
, 200, headers
);
513 sendData(client
, headers
, response
);
516 sendError(client
, 404, request
, true, "Requested Configuration option doesn't exist", headers
);
519 else if (pcount
== 3 && parts
[1] == "clear")
521 _config
->Clear(parts
[2]);
522 sendSuccess(client
, request
, true, "Option '" + parts
[2] + "' was cleared.", headers
);
526 sendError(client
, 400, request
, true, "Unknown on-the-fly configuration request", headers
);
530 static void * handleClient(void * voidclient
) /*{{{*/
532 int client
= *((int*)(voidclient
));
533 std::clog
<< "ACCEPT client " << client
<< std::endl
;
534 std::vector
<std::string
> messages
;
535 bool closeConnection
= false;
536 std::list
<std::string
> headers
;
537 while (closeConnection
== false && ReadMessages(client
, messages
))
539 // if we announced a closing, do the close
540 if (std::find(headers
.begin(), headers
.end(), std::string("Connection: close")) != headers
.end())
543 for (std::vector
<std::string
>::const_iterator m
= messages
.begin();
544 m
!= messages
.end() && closeConnection
== false; ++m
) {
545 std::clog
<< ">>> REQUEST from " << client
<< " >>>" << std::endl
<< *m
546 << std::endl
<< "<<<<<<<<<<<<<<<<" << std::endl
;
547 std::string filename
;
549 bool sendContent
= true;
550 if (parseFirstLine(client
, *m
, filename
, params
, sendContent
, closeConnection
, headers
) == false)
553 // special webserver command request
554 if (filename
.length() > 1 && filename
[0] == '_')
556 std::vector
<std::string
> parts
= VectorizeString(filename
, '/');
557 if (parts
[0] == "_config")
559 handleOnTheFlyReconfiguration(client
, *m
, parts
, headers
);
564 // string replacements in the requested filename
565 ::Configuration::Item
const *Replaces
= _config
->Tree("aptwebserver::redirect::replace");
566 if (Replaces
!= NULL
)
568 std::string redirect
= "/" + filename
;
569 for (::Configuration::Item
*I
= Replaces
->Child
; I
!= NULL
; I
= I
->Next
)
570 redirect
= SubstVar(redirect
, I
->Tag
, I
->Value
);
571 if (redirect
.empty() == false && redirect
[0] == '/')
573 if (redirect
!= filename
)
575 sendRedirect(client
, 301, redirect
, *m
, sendContent
);
580 ::Configuration::Item
const *Overwrite
= _config
->Tree("aptwebserver::overwrite");
581 if (Overwrite
!= NULL
)
583 for (::Configuration::Item
*I
= Overwrite
->Child
; I
!= NULL
; I
= I
->Next
)
585 regex_t
*pattern
= new regex_t
;
586 int const res
= regcomp(pattern
, I
->Tag
.c_str(), REG_EXTENDED
| REG_ICASE
| REG_NOSUB
);
590 regerror(res
, pattern
, error
, sizeof(error
));
591 sendError(client
, 500, *m
, sendContent
, error
, headers
);
594 if (regexec(pattern
, filename
.c_str(), 0, 0, 0) == 0)
596 filename
= _config
->Find("aptwebserver::overwrite::" + I
->Tag
+ "::filename", filename
);
597 if (filename
[0] == '/')
606 // deal with the request
607 if (_config
->FindB("aptwebserver::support::http", true) == false &&
608 LookupTag(*m
, "Host").find(":4433") == std::string::npos
)
610 sendError(client
, 400, *m
, sendContent
, "HTTP disabled, all requests must be HTTPS", headers
);
613 else if (RealFileExists(filename
) == true)
615 FileFd
data(filename
, FileFd::ReadOnly
);
616 std::string condition
= LookupTag(*m
, "If-Modified-Since", "");
617 if (_config
->FindB("aptwebserver::support::modified-since", true) == true && condition
.empty() == false)
620 if (RFC1123StrToTime(condition
.c_str(), cache
) == true &&
621 cache
>= data
.ModificationTime())
623 sendHead(client
, 304, headers
);
628 if (_config
->FindB("aptwebserver::support::range", true) == true)
629 condition
= LookupTag(*m
, "Range", "");
632 if (condition
.empty() == false && strncmp(condition
.c_str(), "bytes=", 6) == 0)
636 if (_config
->FindB("aptwebserver::support::if-range", true) == true)
637 ifrange
= LookupTag(*m
, "If-Range", "");
638 bool validrange
= (ifrange
.empty() == true ||
639 (RFC1123StrToTime(ifrange
.c_str(), cache
) == true &&
640 cache
<= data
.ModificationTime()));
642 // FIXME: support multiple byte-ranges (APT clients do not do this)
643 if (condition
.find(',') == std::string::npos
)
646 unsigned long long filestart
= strtoull(condition
.c_str() + start
, NULL
, 10);
647 // FIXME: no support for last-byte-pos being not the end of the file (APT clients do not do this)
648 size_t dash
= condition
.find('-') + 1;
649 unsigned long long fileend
= strtoull(condition
.c_str() + dash
, NULL
, 10);
650 unsigned long long filesize
= data
.FileSize();
651 if ((fileend
== 0 || (fileend
== filesize
&& fileend
>= filestart
)) &&
654 if (filesize
> filestart
)
656 data
.Skip(filestart
);
657 std::ostringstream contentlength
;
658 contentlength
<< "Content-Length: " << (filesize
- filestart
);
659 headers
.push_back(contentlength
.str());
660 std::ostringstream contentrange
;
661 contentrange
<< "Content-Range: bytes " << filestart
<< "-"
662 << filesize
- 1 << "/" << filesize
;
663 headers
.push_back(contentrange
.str());
664 sendHead(client
, 206, headers
);
665 if (sendContent
== true)
666 sendFile(client
, headers
, data
);
671 std::ostringstream contentrange
;
672 contentrange
<< "Content-Range: bytes */" << filesize
;
673 headers
.push_back(contentrange
.str());
674 sendError(client
, 416, *m
, sendContent
, "", headers
);
681 addFileHeaders(headers
, data
);
682 sendHead(client
, 200, headers
);
683 if (sendContent
== true)
684 sendFile(client
, headers
, data
);
686 else if (DirectoryExists(filename
) == true)
688 if (filename
[filename
.length()-1] == '/')
689 sendDirectoryListing(client
, filename
, *m
, sendContent
, headers
);
691 sendRedirect(client
, 301, filename
.append("/"), *m
, sendContent
);
694 sendError(client
, 404, *m
, sendContent
, "", headers
);
696 _error
->DumpErrors(std::cerr
);
700 std::clog
<< "CLOSE client " << client
<< std::endl
;
705 int main(int const argc
, const char * argv
[])
707 CommandLine::Args Args
[] = {
708 {0, "port", "aptwebserver::port", CommandLine::HasArg
},
709 {0, "request-absolute", "aptwebserver::request::absolute", CommandLine::HasArg
},
710 {'c',"config-file",0,CommandLine::ConfigFile
},
711 {'o',"option",0,CommandLine::ArbItem
},
715 CommandLine
CmdL(Args
, _config
);
716 if(CmdL
.Parse(argc
,argv
) == false)
718 _error
->DumpErrors();
722 // create socket, bind and listen to it {{{
723 // ignore SIGPIPE, this can happen on write() if the socket closes connection
724 signal(SIGPIPE
, SIG_IGN
);
725 // we don't care for our slaves, so ignore their death
726 signal(SIGCHLD
, SIG_IGN
);
728 int sock
= socket(AF_INET6
, SOCK_STREAM
, 0);
731 _error
->Errno("aptwerbserver", "Couldn't create socket");
732 _error
->DumpErrors(std::cerr
);
736 int const port
= _config
->FindI("aptwebserver::port", 8080);
738 // ensure that we accept all connections: v4 or v6
739 int const iponly
= 0;
740 setsockopt(sock
, IPPROTO_IPV6
, IPV6_V6ONLY
, &iponly
, sizeof(iponly
));
741 // to not linger on an address
742 int const enable
= 1;
743 setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, &enable
, sizeof(enable
));
745 struct sockaddr_in6 locAddr
;
746 memset(&locAddr
, 0, sizeof(locAddr
));
747 locAddr
.sin6_family
= AF_INET6
;
748 locAddr
.sin6_port
= htons(port
);
749 locAddr
.sin6_addr
= in6addr_any
;
751 if (bind(sock
, (struct sockaddr
*) &locAddr
, sizeof(locAddr
)) < 0)
753 _error
->Errno("aptwerbserver", "Couldn't bind");
754 _error
->DumpErrors(std::cerr
);
759 if (_config
->FindB("aptwebserver::fork", false) == true)
761 std::string
const pidfilename
= _config
->Find("aptwebserver::pidfile", "aptwebserver.pid");
762 int const pidfilefd
= GetLock(pidfilename
);
763 if (pidfilefd
< 0 || pidfile
.OpenDescriptor(pidfilefd
, FileFd::WriteOnly
) == false)
765 _error
->Errno("aptwebserver", "Couldn't acquire lock on pidfile '%s'", pidfilename
.c_str());
766 _error
->DumpErrors(std::cerr
);
770 pid_t child
= fork();
773 _error
->Errno("aptwebserver", "Forking failed");
774 _error
->DumpErrors(std::cerr
);
779 // successfully forked: ready to serve!
780 std::string pidcontent
;
781 strprintf(pidcontent
, "%d", child
);
782 pidfile
.Write(pidcontent
.c_str(), pidcontent
.size());
783 if (_error
->PendingError() == true)
785 _error
->DumpErrors(std::cerr
);
788 std::cout
<< "Successfully forked as " << child
<< std::endl
;
793 std::clog
<< "Serving ANY file on port: " << port
<< std::endl
;
795 int const slaves
= _config
->FindB("aptwebserver::slaves", SOMAXCONN
);
796 listen(sock
, slaves
);
799 _config
->CndSet("aptwebserver::response-header::Server", "APT webserver");
800 _config
->CndSet("aptwebserver::response-header::Accept-Ranges", "bytes");
801 _config
->CndSet("aptwebserver::directoryindex", "index.html");
803 std::list
<int> accepted_clients
;
807 int client
= accept(sock
, NULL
, NULL
);
812 _error
->Errno("accept", "Couldn't accept client on socket %d", sock
);
813 _error
->DumpErrors(std::cerr
);
818 if (pthread_attr_init(&attr
) != 0 || pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0)
820 _error
->Errno("pthread_attr", "Couldn't set detach attribute for a fresh thread to handle client %d on socket %d", client
, sock
);
821 _error
->DumpErrors(std::cerr
);
827 // thats rather dirty, but we need to store the client socket somewhere safe
828 accepted_clients
.push_front(client
);
829 if (pthread_create(&tid
, &attr
, &handleClient
, &(*accepted_clients
.begin())) != 0)
831 _error
->Errno("pthread_create", "Couldn't create a fresh thread to handle client %d on socket %d", client
, sock
);
832 _error
->DumpErrors(std::cerr
);