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 std::string
httpcodeToStr(int const httpcode
) /*{{{*/
35 case 100: return _config
->Find("aptwebserver::httpcode::100", "100 Continue");
36 case 101: return _config
->Find("aptwebserver::httpcode::101", "101 Switching Protocols");
38 case 200: return _config
->Find("aptwebserver::httpcode::200", "200 OK");
39 case 201: return _config
->Find("aptwebserver::httpcode::201", "201 Created");
40 case 202: return _config
->Find("aptwebserver::httpcode::202", "202 Accepted");
41 case 203: return _config
->Find("aptwebserver::httpcode::203", "203 Non-Authoritative Information");
42 case 204: return _config
->Find("aptwebserver::httpcode::204", "204 No Content");
43 case 205: return _config
->Find("aptwebserver::httpcode::205", "205 Reset Content");
44 case 206: return _config
->Find("aptwebserver::httpcode::206", "206 Partial Content");
46 case 300: return _config
->Find("aptwebserver::httpcode::300", "300 Multiple Choices");
47 case 301: return _config
->Find("aptwebserver::httpcode::301", "301 Moved Permanently");
48 case 302: return _config
->Find("aptwebserver::httpcode::302", "302 Found");
49 case 303: return _config
->Find("aptwebserver::httpcode::303", "303 See Other");
50 case 304: return _config
->Find("aptwebserver::httpcode::304", "304 Not Modified");
51 case 305: return _config
->Find("aptwebserver::httpcode::305", "305 Use Proxy");
52 case 307: return _config
->Find("aptwebserver::httpcode::307", "307 Temporary Redirect");
54 case 400: return _config
->Find("aptwebserver::httpcode::400", "400 Bad Request");
55 case 401: return _config
->Find("aptwebserver::httpcode::401", "401 Unauthorized");
56 case 402: return _config
->Find("aptwebserver::httpcode::402", "402 Payment Required");
57 case 403: return _config
->Find("aptwebserver::httpcode::403", "403 Forbidden");
58 case 404: return _config
->Find("aptwebserver::httpcode::404", "404 Not Found");
59 case 405: return _config
->Find("aptwebserver::httpcode::405", "405 Method Not Allowed");
60 case 406: return _config
->Find("aptwebserver::httpcode::406", "406 Not Acceptable");
61 case 407: return _config
->Find("aptwebserver::httpcode::407", "407 Proxy Authentication Required");
62 case 408: return _config
->Find("aptwebserver::httpcode::408", "408 Request Time-out");
63 case 409: return _config
->Find("aptwebserver::httpcode::409", "409 Conflict");
64 case 410: return _config
->Find("aptwebserver::httpcode::410", "410 Gone");
65 case 411: return _config
->Find("aptwebserver::httpcode::411", "411 Length Required");
66 case 412: return _config
->Find("aptwebserver::httpcode::412", "412 Precondition Failed");
67 case 413: return _config
->Find("aptwebserver::httpcode::413", "413 Request Entity Too Large");
68 case 414: return _config
->Find("aptwebserver::httpcode::414", "414 Request-URI Too Large");
69 case 415: return _config
->Find("aptwebserver::httpcode::415", "415 Unsupported Media Type");
70 case 416: return _config
->Find("aptwebserver::httpcode::416", "416 Requested range not satisfiable");
71 case 417: return _config
->Find("aptwebserver::httpcode::417", "417 Expectation Failed");
72 case 418: return _config
->Find("aptwebserver::httpcode::418", "418 I'm a teapot");
74 case 500: return _config
->Find("aptwebserver::httpcode::500", "500 Internal Server Error");
75 case 501: return _config
->Find("aptwebserver::httpcode::501", "501 Not Implemented");
76 case 502: return _config
->Find("aptwebserver::httpcode::502", "502 Bad Gateway");
77 case 503: return _config
->Find("aptwebserver::httpcode::503", "503 Service Unavailable");
78 case 504: return _config
->Find("aptwebserver::httpcode::504", "504 Gateway Time-out");
79 case 505: return _config
->Find("aptwebserver::httpcode::505", "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 if (_config
->FindB("aptwebserver::support::last-modified", true) == true)
101 std::string
lastmodified("Last-Modified: ");
102 lastmodified
.append(TimeRFC1123(data
.ModificationTime()));
103 headers
.push_back(lastmodified
);
107 static void addDataHeaders(std::list
<std::string
> &headers
, std::string
&data
)/*{{{*/
109 if (chunkedTransferEncoding(headers
) == false)
111 std::ostringstream contentlength
;
112 contentlength
<< "Content-Length: " << data
.size();
113 headers
.push_back(contentlength
.str());
117 static bool sendHead(int const client
, int const httpcode
, std::list
<std::string
> &headers
)/*{{{*/
119 std::string
response("HTTP/1.1 ");
120 response
.append(httpcodeToStr(httpcode
));
121 headers
.push_front(response
);
122 _config
->Set("APTWebserver::Last-Status-Code", httpcode
);
124 std::stringstream buffer
;
125 _config
->Dump(buffer
, "aptwebserver::response-header", "%t: %v%n", false);
126 std::vector
<std::string
> addheaders
= VectorizeString(buffer
.str(), '\n');
127 for (std::vector
<std::string
>::const_iterator h
= addheaders
.begin(); h
!= addheaders
.end(); ++h
)
128 headers
.push_back(*h
);
130 std::string
date("Date: ");
131 date
.append(TimeRFC1123(time(NULL
)));
132 headers
.push_back(date
);
134 if (chunkedTransferEncoding(headers
) == true)
135 headers
.push_back("Transfer-Encoding: chunked");
137 std::clog
<< ">>> RESPONSE to " << client
<< " >>>" << std::endl
;
139 for (std::list
<std::string
>::const_iterator h
= headers
.begin();
140 Success
== true && h
!= headers
.end(); ++h
)
142 Success
&= FileFd::Write(client
, h
->c_str(), h
->size());
144 Success
&= FileFd::Write(client
, "\r\n", 2);
145 std::clog
<< *h
<< std::endl
;
148 Success
&= FileFd::Write(client
, "\r\n", 2);
149 std::clog
<< "<<<<<<<<<<<<<<<<" << std::endl
;
153 static bool sendFile(int const client
, std::list
<std::string
> const &headers
, FileFd
&data
)/*{{{*/
156 bool const chunked
= chunkedTransferEncoding(headers
);
158 unsigned long long actual
= 0;
159 while ((Success
&= data
.Read(buffer
, sizeof(buffer
), &actual
)) == true)
167 strprintf(size
, "%llX\r\n", actual
);
168 Success
&= FileFd::Write(client
, size
.c_str(), size
.size());
169 Success
&= FileFd::Write(client
, buffer
, actual
);
170 Success
&= FileFd::Write(client
, "\r\n", strlen("\r\n"));
173 Success
&= FileFd::Write(client
, buffer
, actual
);
177 char const * const finish
= "0\r\n\r\n";
178 Success
&= FileFd::Write(client
, finish
, strlen(finish
));
180 if (Success
== false)
181 std::cerr
<< "SENDFILE:" << (chunked
? " CHUNKED" : "") << " READ/WRITE ERROR to " << client
<< std::endl
;
185 static bool sendData(int const client
, std::list
<std::string
> const &headers
, std::string
const &data
)/*{{{*/
187 if (chunkedTransferEncoding(headers
) == true)
189 unsigned long long const ullsize
= data
.length();
191 strprintf(size
, "%llX\r\n", ullsize
);
192 char const * const finish
= "\r\n0\r\n\r\n";
193 if (FileFd::Write(client
, size
.c_str(), size
.length()) == false ||
194 FileFd::Write(client
, data
.c_str(), ullsize
) == false ||
195 FileFd::Write(client
, finish
, strlen(finish
)) == false)
197 std::cerr
<< "SENDDATA: CHUNK WRITE ERROR to " << client
<< std::endl
;
201 else if (FileFd::Write(client
, data
.c_str(), data
.size()) == false)
203 std::cerr
<< "SENDDATA: WRITE ERROR to " << client
<< std::endl
;
209 static void sendError(int const client
, int const httpcode
, std::string
const &request
,/*{{{*/
210 bool const content
, std::string
const &error
, std::list
<std::string
> &headers
)
212 std::string
response("<html><head><title>");
213 response
.append(httpcodeToStr(httpcode
)).append("</title></head>");
214 response
.append("<body><h1>").append(httpcodeToStr(httpcode
)).append("</h1>");
216 response
.append("<p><em>Error</em>: ");
218 response
.append("<p><em>Success</em>: ");
219 if (error
.empty() == false)
220 response
.append(error
);
222 response
.append(httpcodeToStr(httpcode
));
224 response
.append("</p>This error is a result of the request: <pre>");
226 response
.append("The successfully executed operation was requested by: <pre>");
227 response
.append(request
).append("</pre></body></html>");
230 if (_config
->FindB("aptwebserver::closeOnError", false) == true)
231 headers
.push_back("Connection: close");
233 addDataHeaders(headers
, response
);
234 sendHead(client
, httpcode
, headers
);
236 sendData(client
, headers
, response
);
238 static void sendSuccess(int const client
, std::string
const &request
,
239 bool const content
, std::string
const &error
, std::list
<std::string
> &headers
)
241 sendError(client
, 200, request
, content
, error
, headers
);
244 static void sendRedirect(int const client
, int const httpcode
, std::string
const &uri
,/*{{{*/
245 std::string
const &request
, bool content
)
247 std::list
<std::string
> headers
;
248 std::string
response("<html><head><title>");
249 response
.append(httpcodeToStr(httpcode
)).append("</title></head>");
250 response
.append("<body><h1>").append(httpcodeToStr(httpcode
)).append("</h1");
251 response
.append("<p>You should be redirected to <em>").append(uri
).append("</em></p>");
252 response
.append("This page is a result of the request: <pre>");
253 response
.append(request
).append("</pre></body></html>");
254 addDataHeaders(headers
, response
);
255 std::string
location("Location: ");
256 if (strncmp(uri
.c_str(), "http://", 7) != 0 && strncmp(uri
.c_str(), "https://", 8) != 0)
258 std::string
const host
= LookupTag(request
, "Host");
259 if (host
.find(":4433") != std::string::npos
)
260 location
.append("https://");
262 location
.append("http://");
263 location
.append(host
).append("/");
264 if (strncmp("/home/", uri
.c_str(), strlen("/home/")) == 0 && uri
.find("/public_html/") != std::string::npos
)
266 std::string homeuri
= SubstVar(uri
, "/home/", "~");
267 homeuri
= SubstVar(homeuri
, "/public_html/", "/");
268 location
.append(homeuri
);
271 location
.append(uri
);
274 location
.append(uri
);
275 headers
.push_back(location
);
276 sendHead(client
, httpcode
, headers
);
278 sendData(client
, headers
, response
);
281 static int filter_hidden_files(const struct dirent
*a
) /*{{{*/
283 if (a
->d_name
[0] == '.')
285 #ifdef _DIRENT_HAVE_D_TYPE
286 // if we have the d_type check that only files and dirs will be included
287 if (a
->d_type
!= DT_UNKNOWN
&&
288 a
->d_type
!= DT_REG
&&
289 a
->d_type
!= DT_LNK
&& // this includes links to regular files
295 static int grouped_alpha_case_sort(const struct dirent
**a
, const struct dirent
**b
) {
296 #ifdef _DIRENT_HAVE_D_TYPE
297 if ((*a
)->d_type
== DT_DIR
&& (*b
)->d_type
== DT_DIR
);
298 else if ((*a
)->d_type
== DT_DIR
&& (*b
)->d_type
== DT_REG
)
300 else if ((*b
)->d_type
== DT_DIR
&& (*a
)->d_type
== DT_REG
)
305 struct stat f_prop
; //File's property
306 stat((*a
)->d_name
, &f_prop
);
307 int const amode
= f_prop
.st_mode
;
308 stat((*b
)->d_name
, &f_prop
);
309 int const bmode
= f_prop
.st_mode
;
310 if (S_ISDIR(amode
) && S_ISDIR(bmode
));
311 else if (S_ISDIR(amode
))
313 else if (S_ISDIR(bmode
))
316 return strcasecmp((*a
)->d_name
, (*b
)->d_name
);
319 static void sendDirectoryListing(int const client
, std::string
const &dir
,/*{{{*/
320 std::string
const &request
, bool content
, std::list
<std::string
> &headers
)
322 std::ostringstream listing
;
324 struct dirent
**namelist
;
325 int const counter
= scandir(dir
.c_str(), &namelist
, filter_hidden_files
, grouped_alpha_case_sort
);
328 sendError(client
, 500, request
, content
, "scandir failed", headers
);
332 listing
<< "<html><head><title>Index of " << dir
<< "</title>"
333 << "<style type=\"text/css\"><!-- td {padding: 0.02em 0.5em 0.02em 0.5em;}"
334 << "tr:nth-child(even){background-color:#dfdfdf;}"
335 << "h1, td:nth-child(3){text-align:center;}"
336 << "table {margin-left:auto;margin-right:auto;} --></style>"
337 << "</head>" << std::endl
338 << "<body><h1>Index of " << dir
<< "</h1>" << std::endl
339 << "<table><tr><th>#</th><th>Name</th><th>Size</th><th>Last-Modified</th></tr>" << std::endl
;
341 listing
<< "<tr><td>d</td><td><a href=\"..\">Parent Directory</a></td><td>-</td><td>-</td></tr>";
342 for (int i
= 0; i
< counter
; ++i
) {
344 std::string
filename(dir
);
345 filename
.append("/").append(namelist
[i
]->d_name
);
346 stat(filename
.c_str(), &fs
);
347 if (S_ISDIR(fs
.st_mode
))
349 listing
<< "<tr><td>d</td>"
350 << "<td><a href=\"" << namelist
[i
]->d_name
<< "/\">" << namelist
[i
]->d_name
<< "</a></td>"
355 listing
<< "<tr><td>f</td>"
356 << "<td><a href=\"" << namelist
[i
]->d_name
<< "\">" << namelist
[i
]->d_name
<< "</a></td>"
357 << "<td>" << SizeToStr(fs
.st_size
) << "B</td>";
359 listing
<< "<td>" << TimeRFC1123(fs
.st_mtime
) << "</td></tr>" << std::endl
;
361 listing
<< "</table></body></html>" << std::endl
;
363 std::string
response(listing
.str());
364 addDataHeaders(headers
, response
);
365 sendHead(client
, 200, headers
);
367 sendData(client
, headers
, response
);
370 static bool parseFirstLine(int const client
, std::string
const &request
,/*{{{*/
371 std::string
&filename
, std::string
¶ms
, bool &sendContent
,
372 bool &closeConnection
, std::list
<std::string
> &headers
)
374 if (strncmp(request
.c_str(), "HEAD ", 5) == 0)
376 if (strncmp(request
.c_str(), "GET ", 4) != 0)
378 sendError(client
, 501, request
, true, "", headers
);
382 size_t const lineend
= request
.find('\n');
383 size_t filestart
= request
.find(' ');
384 for (; request
[filestart
] == ' '; ++filestart
);
385 size_t fileend
= request
.rfind(' ', lineend
);
386 if (lineend
== std::string::npos
|| filestart
== std::string::npos
||
387 fileend
== std::string::npos
|| filestart
== fileend
)
389 sendError(client
, 500, request
, sendContent
, "Filename can't be extracted", headers
);
393 size_t httpstart
= fileend
;
394 for (; request
[httpstart
] == ' '; ++httpstart
);
395 if (strncmp(request
.c_str() + httpstart
, "HTTP/1.1\r", 9) == 0)
396 closeConnection
= strcasecmp(LookupTag(request
, "Connection", "Keep-Alive").c_str(), "Keep-Alive") != 0;
397 else if (strncmp(request
.c_str() + httpstart
, "HTTP/1.0\r", 9) == 0)
398 closeConnection
= strcasecmp(LookupTag(request
, "Connection", "Keep-Alive").c_str(), "close") == 0;
401 sendError(client
, 500, request
, sendContent
, "Not a HTTP/1.{0,1} request", headers
);
405 filename
= request
.substr(filestart
, fileend
- filestart
);
406 if (filename
.find(' ') != std::string::npos
)
408 sendError(client
, 500, request
, sendContent
, "Filename contains an unencoded space", headers
);
412 std::string host
= LookupTag(request
, "Host", "");
413 if (host
.empty() == true)
415 // RFC 2616 §14.23 requires Host
416 sendError(client
, 400, request
, sendContent
, "Host header is required", headers
);
419 host
= "http://" + host
;
421 // Proxies require absolute uris, so this is a simple proxy-fake option
422 std::string
const absolute
= _config
->Find("aptwebserver::request::absolute", "uri,path");
423 if (strncmp(host
.c_str(), filename
.c_str(), host
.length()) == 0 && APT::String::Startswith(filename
, "/_config/") == false)
425 if (absolute
.find("uri") == std::string::npos
)
427 sendError(client
, 400, request
, sendContent
, "Request is absoluteURI, but configured to not accept that", headers
);
431 // strip the host from the request to make it an absolute path
432 filename
.erase(0, host
.length());
434 std::string
const authConf
= _config
->Find("aptwebserver::proxy-authorization", "");
435 std::string auth
= LookupTag(request
, "Proxy-Authorization", "");
436 if (authConf
.empty() != auth
.empty())
439 sendError(client
, 407, request
, sendContent
, "Proxy requires authentication", headers
);
441 sendError(client
, 407, request
, sendContent
, "Client wants to authenticate to proxy, but proxy doesn't need it", headers
);
444 if (authConf
.empty() == false)
446 char const * const basic
= "Basic ";
447 if (strncmp(auth
.c_str(), basic
, strlen(basic
)) == 0)
449 auth
.erase(0, strlen(basic
));
450 if (auth
!= authConf
)
452 sendError(client
, 407, request
, sendContent
, "Proxy-Authentication doesn't match", headers
);
458 std::list
<std::string
> headers
;
459 headers
.push_back("Proxy-Authenticate: Basic");
460 sendError(client
, 407, request
, sendContent
, "Unsupported Proxy-Authentication Scheme", headers
);
465 else if (absolute
.find("path") == std::string::npos
&& APT::String::Startswith(filename
, "/_config/") == false)
467 sendError(client
, 400, request
, sendContent
, "Request is absolutePath, but configured to not accept that", headers
);
471 if (APT::String::Startswith(filename
, "/_config/") == false)
473 std::string
const authConf
= _config
->Find("aptwebserver::authorization", "");
474 std::string auth
= LookupTag(request
, "Authorization", "");
475 if (authConf
.empty() != auth
.empty())
478 sendError(client
, 401, request
, sendContent
, "Server requires authentication", headers
);
480 sendError(client
, 401, request
, sendContent
, "Client wants to authenticate to server, but server doesn't need it", headers
);
483 if (authConf
.empty() == false)
485 char const * const basic
= "Basic ";
486 if (strncmp(auth
.c_str(), basic
, strlen(basic
)) == 0)
488 auth
.erase(0, strlen(basic
));
489 if (auth
!= authConf
)
491 sendError(client
, 401, request
, sendContent
, "Authentication doesn't match", headers
);
497 headers
.push_back("WWW-Authenticate: Basic");
498 sendError(client
, 401, request
, sendContent
, "Unsupported Authentication Scheme", headers
);
504 size_t paramspos
= filename
.find('?');
505 if (paramspos
!= std::string::npos
)
507 params
= filename
.substr(paramspos
+ 1);
508 filename
.erase(paramspos
);
511 filename
= DeQuoteString(filename
);
513 // this is not a secure server, but at least prevent the obvious …
514 if (filename
.empty() == true || filename
[0] != '/' ||
515 strncmp(filename
.c_str(), "//", 2) == 0 ||
516 filename
.find_first_of("\r\n\t\f\v") != std::string::npos
||
517 filename
.find("/../") != std::string::npos
)
519 std::list
<std::string
> headers
;
520 sendError(client
, 400, request
, sendContent
, "Filename contains illegal character (sequence)", headers
);
524 // nuke the first character which is a / as we assured above
525 filename
.erase(0, 1);
526 if (filename
.empty() == true)
528 // support ~user/ uris to refer to /home/user/public_html/ as a kind-of special directory
529 else if (filename
[0] == '~')
531 // /home/user is actually not entirely correct, but good enough for now
532 size_t dashpos
= filename
.find('/');
533 if (dashpos
!= std::string::npos
)
535 std::string home
= filename
.substr(1, filename
.find('/') - 1);
536 std::string pubhtml
= filename
.substr(filename
.find('/') + 1);
537 filename
= "/home/" + home
+ "/public_html/" + pubhtml
;
540 filename
= "/home/" + filename
.substr(1) + "/public_html/";
543 // if no filename is given, but a valid directory see if we can use an index or
544 // have to resort to a autogenerated directory listing later on
545 if (DirectoryExists(filename
) == true)
547 std::string
const directoryIndex
= _config
->Find("aptwebserver::directoryindex");
548 if (directoryIndex
.empty() == false && directoryIndex
== flNotDir(directoryIndex
) &&
549 RealFileExists(filename
+ directoryIndex
) == true)
550 filename
+= directoryIndex
;
556 static bool handleOnTheFlyReconfiguration(int const client
, std::string
const &request
,/*{{{*/
557 std::vector
<std::string
> parts
, std::list
<std::string
> &headers
)
559 size_t const pcount
= parts
.size();
560 for (size_t i
= 0; i
< pcount
; ++i
)
561 parts
[i
] = DeQuoteString(parts
[i
]);
562 if (pcount
== 4 && parts
[1] == "set")
564 _config
->Set(parts
[2], parts
[3]);
565 sendSuccess(client
, request
, true, "Option '" + parts
[2] + "' was set to '" + parts
[3] + "'!", headers
);
568 else if (pcount
== 4 && parts
[1] == "find")
570 std::string response
= _config
->Find(parts
[2], parts
[3]);
571 addDataHeaders(headers
, response
);
572 sendHead(client
, 200, headers
);
573 sendData(client
, headers
, response
);
576 else if (pcount
== 3 && parts
[1] == "find")
578 if (_config
->Exists(parts
[2]) == true)
580 std::string response
= _config
->Find(parts
[2]);
581 addDataHeaders(headers
, response
);
582 sendHead(client
, 200, headers
);
583 sendData(client
, headers
, response
);
586 sendError(client
, 404, request
, true, "Requested Configuration option doesn't exist", headers
);
589 else if (pcount
== 3 && parts
[1] == "clear")
591 _config
->Clear(parts
[2]);
592 sendSuccess(client
, request
, true, "Option '" + parts
[2] + "' was cleared.", headers
);
596 sendError(client
, 400, request
, true, "Unknown on-the-fly configuration request", headers
);
600 static void * handleClient(void * voidclient
) /*{{{*/
602 int client
= *((int*)(voidclient
));
603 std::clog
<< "ACCEPT client " << client
<< std::endl
;
604 bool closeConnection
= false;
605 while (closeConnection
== false)
607 std::vector
<std::string
> messages
;
608 if (ReadMessages(client
, messages
) == false)
611 std::list
<std::string
> headers
;
612 for (std::vector
<std::string
>::const_iterator m
= messages
.begin();
613 m
!= messages
.end() && closeConnection
== false; ++m
) {
614 // if we announced a closing in previous response, do the close now
615 if (std::find(headers
.begin(), headers
.end(), std::string("Connection: close")) != headers
.end())
617 closeConnection
= true;
622 std::clog
<< ">>> REQUEST from " << client
<< " >>>" << std::endl
<< *m
623 << std::endl
<< "<<<<<<<<<<<<<<<<" << std::endl
;
624 std::string filename
;
626 bool sendContent
= true;
627 if (parseFirstLine(client
, *m
, filename
, params
, sendContent
, closeConnection
, headers
) == false)
630 // special webserver command request
631 if (filename
.length() > 1 && filename
[0] == '_')
633 std::vector
<std::string
> parts
= VectorizeString(filename
, '/');
634 if (parts
[0] == "_config")
636 handleOnTheFlyReconfiguration(client
, *m
, parts
, headers
);
641 // string replacements in the requested filename
642 ::Configuration::Item
const *Replaces
= _config
->Tree("aptwebserver::redirect::replace");
643 if (Replaces
!= NULL
)
645 std::string redirect
= "/" + filename
;
646 for (::Configuration::Item
*I
= Replaces
->Child
; I
!= NULL
; I
= I
->Next
)
647 redirect
= SubstVar(redirect
, I
->Tag
, I
->Value
);
648 if (redirect
.empty() == false && redirect
[0] == '/')
650 if (redirect
!= filename
)
652 sendRedirect(client
, 301, redirect
, *m
, sendContent
);
657 ::Configuration::Item
const *Overwrite
= _config
->Tree("aptwebserver::overwrite");
658 if (Overwrite
!= NULL
)
660 for (::Configuration::Item
*I
= Overwrite
->Child
; I
!= NULL
; I
= I
->Next
)
662 regex_t
*pattern
= new regex_t
;
663 int const res
= regcomp(pattern
, I
->Tag
.c_str(), REG_EXTENDED
| REG_ICASE
| REG_NOSUB
);
667 regerror(res
, pattern
, error
, sizeof(error
));
668 sendError(client
, 500, *m
, sendContent
, error
, headers
);
671 if (regexec(pattern
, filename
.c_str(), 0, 0, 0) == 0)
673 filename
= _config
->Find("aptwebserver::overwrite::" + I
->Tag
+ "::filename", filename
);
674 if (filename
[0] == '/')
683 // deal with the request
684 if (_config
->FindB("aptwebserver::support::http", true) == false &&
685 LookupTag(*m
, "Host").find(":4433") == std::string::npos
)
687 sendError(client
, 400, *m
, sendContent
, "HTTP disabled, all requests must be HTTPS", headers
);
690 else if (RealFileExists(filename
) == true)
692 FileFd
data(filename
, FileFd::ReadOnly
);
693 std::string condition
= LookupTag(*m
, "If-Modified-Since", "");
694 if (_config
->FindB("aptwebserver::support::modified-since", true) == true && condition
.empty() == false)
697 if (RFC1123StrToTime(condition
.c_str(), cache
) == true &&
698 cache
>= data
.ModificationTime())
700 sendHead(client
, 304, headers
);
705 if (_config
->FindB("aptwebserver::support::range", true) == true)
706 condition
= LookupTag(*m
, "Range", "");
709 if (condition
.empty() == false && strncmp(condition
.c_str(), "bytes=", 6) == 0)
713 if (_config
->FindB("aptwebserver::support::if-range", true) == true)
714 ifrange
= LookupTag(*m
, "If-Range", "");
715 bool validrange
= (ifrange
.empty() == true ||
716 (RFC1123StrToTime(ifrange
.c_str(), cache
) == true &&
717 cache
<= data
.ModificationTime()));
719 // FIXME: support multiple byte-ranges (APT clients do not do this)
720 if (condition
.find(',') == std::string::npos
)
723 unsigned long long filestart
= strtoull(condition
.c_str() + start
, NULL
, 10);
724 // FIXME: no support for last-byte-pos being not the end of the file (APT clients do not do this)
725 size_t dash
= condition
.find('-') + 1;
726 unsigned long long fileend
= strtoull(condition
.c_str() + dash
, NULL
, 10);
727 unsigned long long filesize
= data
.FileSize();
728 if ((fileend
== 0 || (fileend
== filesize
&& fileend
>= filestart
)) &&
731 if (filesize
> filestart
)
733 data
.Skip(filestart
);
734 // make sure to send content-range before conent-length
735 // as regression test for LP: #1445239
736 std::ostringstream contentrange
;
737 contentrange
<< "Content-Range: bytes " << filestart
<< "-"
738 << filesize
- 1 << "/" << filesize
;
739 headers
.push_back(contentrange
.str());
740 std::ostringstream contentlength
;
741 contentlength
<< "Content-Length: " << (filesize
- filestart
);
742 headers
.push_back(contentlength
.str());
743 sendHead(client
, 206, headers
);
744 if (sendContent
== true)
745 sendFile(client
, headers
, data
);
750 if (_config
->FindB("aptwebserver::support::content-range", true) == true)
752 std::ostringstream contentrange
;
753 contentrange
<< "Content-Range: bytes */" << filesize
;
754 headers
.push_back(contentrange
.str());
756 sendError(client
, 416, *m
, sendContent
, "", headers
);
763 addFileHeaders(headers
, data
);
764 sendHead(client
, 200, headers
);
765 if (sendContent
== true)
766 sendFile(client
, headers
, data
);
768 else if (DirectoryExists(filename
) == true)
770 if (filename
[filename
.length()-1] == '/')
771 sendDirectoryListing(client
, filename
, *m
, sendContent
, headers
);
773 sendRedirect(client
, 301, filename
.append("/"), *m
, sendContent
);
776 sendError(client
, 404, *m
, sendContent
, "", headers
);
779 // if we announced a closing in the last response, do the close now
780 if (std::find(headers
.begin(), headers
.end(), std::string("Connection: close")) != headers
.end())
781 closeConnection
= true;
783 if (_error
->PendingError() == true)
785 _error
->DumpErrors(std::cerr
);
787 _error
->DumpErrors(std::cerr
);
789 std::clog
<< "CLOSE client " << client
<< std::endl
;
794 int main(int const argc
, const char * argv
[])
796 CommandLine::Args Args
[] = {
797 {0, "port", "aptwebserver::port", CommandLine::HasArg
},
798 {0, "request-absolute", "aptwebserver::request::absolute", CommandLine::HasArg
},
799 {0, "authorization", "aptwebserver::authorization", CommandLine::HasArg
},
800 {0, "proxy-authorization", "aptwebserver::proxy-authorization", CommandLine::HasArg
},
801 {'c',"config-file",0,CommandLine::ConfigFile
},
802 {'o',"option",0,CommandLine::ArbItem
},
806 CommandLine
CmdL(Args
, _config
);
807 if(CmdL
.Parse(argc
,argv
) == false)
809 _error
->DumpErrors();
813 // create socket, bind and listen to it {{{
814 // ignore SIGPIPE, this can happen on write() if the socket closes connection
815 signal(SIGPIPE
, SIG_IGN
);
816 // we don't care for our slaves, so ignore their death
817 signal(SIGCHLD
, SIG_IGN
);
819 int sock
= socket(AF_INET6
, SOCK_STREAM
, 0);
822 _error
->Errno("aptwerbserver", "Couldn't create socket");
823 _error
->DumpErrors(std::cerr
);
827 int const port
= _config
->FindI("aptwebserver::port", 8080);
829 // ensure that we accept all connections: v4 or v6
830 int const iponly
= 0;
831 setsockopt(sock
, IPPROTO_IPV6
, IPV6_V6ONLY
, &iponly
, sizeof(iponly
));
832 // to not linger on an address
833 int const enable
= 1;
834 setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, &enable
, sizeof(enable
));
836 struct sockaddr_in6 locAddr
;
837 memset(&locAddr
, 0, sizeof(locAddr
));
838 locAddr
.sin6_family
= AF_INET6
;
839 locAddr
.sin6_port
= htons(port
);
840 locAddr
.sin6_addr
= in6addr_any
;
842 if (bind(sock
, (struct sockaddr
*) &locAddr
, sizeof(locAddr
)) < 0)
844 _error
->Errno("aptwerbserver", "Couldn't bind");
845 _error
->DumpErrors(std::cerr
);
850 if (_config
->FindB("aptwebserver::fork", false) == true)
852 std::string
const pidfilename
= _config
->Find("aptwebserver::pidfile", "aptwebserver.pid");
853 int const pidfilefd
= GetLock(pidfilename
);
854 if (pidfilefd
< 0 || pidfile
.OpenDescriptor(pidfilefd
, FileFd::WriteOnly
) == false)
856 _error
->Errno("aptwebserver", "Couldn't acquire lock on pidfile '%s'", pidfilename
.c_str());
857 _error
->DumpErrors(std::cerr
);
861 pid_t child
= fork();
864 _error
->Errno("aptwebserver", "Forking failed");
865 _error
->DumpErrors(std::cerr
);
870 // successfully forked: ready to serve!
871 std::string pidcontent
;
872 strprintf(pidcontent
, "%d", child
);
873 pidfile
.Write(pidcontent
.c_str(), pidcontent
.size());
874 if (_error
->PendingError() == true)
876 _error
->DumpErrors(std::cerr
);
879 std::cout
<< "Successfully forked as " << child
<< std::endl
;
884 std::clog
<< "Serving ANY file on port: " << port
<< std::endl
;
886 int const slaves
= _config
->FindI("aptwebserver::slaves", SOMAXCONN
);
887 std::cerr
<< "SLAVES: " << slaves
<< std::endl
;
888 listen(sock
, slaves
);
891 _config
->CndSet("aptwebserver::response-header::Server", "APT webserver");
892 _config
->CndSet("aptwebserver::response-header::Accept-Ranges", "bytes");
893 _config
->CndSet("aptwebserver::directoryindex", "index.html");
895 std::list
<int> accepted_clients
;
899 int client
= accept(sock
, NULL
, NULL
);
904 _error
->Errno("accept", "Couldn't accept client on socket %d", sock
);
905 _error
->DumpErrors(std::cerr
);
910 if (pthread_attr_init(&attr
) != 0 || pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0)
912 _error
->Errno("pthread_attr", "Couldn't set detach attribute for a fresh thread to handle client %d on socket %d", client
, sock
);
913 _error
->DumpErrors(std::cerr
);
919 // thats rather dirty, but we need to store the client socket somewhere safe
920 accepted_clients
.push_front(client
);
921 if (pthread_create(&tid
, &attr
, &handleClient
, &(*accepted_clients
.begin())) != 0)
923 _error
->Errno("pthread_create", "Couldn't create a fresh thread to handle client %d on socket %d", client
, sock
);
924 _error
->DumpErrors(std::cerr
);