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 && APT::String::Startswith(filename
, "/_config/") == false)
422 if (absolute
.find("uri") == std::string::npos
)
424 sendError(client
, 400, request
, sendContent
, "Request is absoluteURI, but configured to not accept that", headers
);
428 // strip the host from the request to make it an absolute path
429 filename
.erase(0, host
.length());
431 std::string
const authConf
= _config
->Find("aptwebserver::proxy-authorization", "");
432 std::string auth
= LookupTag(request
, "Proxy-Authorization", "");
433 if (authConf
.empty() != auth
.empty())
436 sendError(client
, 407, request
, sendContent
, "Proxy requires authentication", headers
);
438 sendError(client
, 407, request
, sendContent
, "Client wants to authenticate to proxy, but proxy doesn't need it", headers
);
441 if (authConf
.empty() == false)
443 char const * const basic
= "Basic ";
444 if (strncmp(auth
.c_str(), basic
, strlen(basic
)) == 0)
446 auth
.erase(0, strlen(basic
));
447 if (auth
!= authConf
)
449 sendError(client
, 407, request
, sendContent
, "Proxy-Authentication doesn't match", headers
);
455 std::list
<std::string
> headers
;
456 headers
.push_back("Proxy-Authenticate: Basic");
457 sendError(client
, 407, request
, sendContent
, "Unsupported Proxy-Authentication Scheme", headers
);
462 else if (absolute
.find("path") == std::string::npos
&& APT::String::Startswith(filename
, "/_config/") == false)
464 sendError(client
, 400, request
, sendContent
, "Request is absolutePath, but configured to not accept that", headers
);
468 if (APT::String::Startswith(filename
, "/_config/") == false)
470 std::string
const authConf
= _config
->Find("aptwebserver::authorization", "");
471 std::string auth
= LookupTag(request
, "Authorization", "");
472 if (authConf
.empty() != auth
.empty())
475 sendError(client
, 401, request
, sendContent
, "Server requires authentication", headers
);
477 sendError(client
, 401, request
, sendContent
, "Client wants to authenticate to server, but server doesn't need it", headers
);
480 if (authConf
.empty() == false)
482 char const * const basic
= "Basic ";
483 if (strncmp(auth
.c_str(), basic
, strlen(basic
)) == 0)
485 auth
.erase(0, strlen(basic
));
486 if (auth
!= authConf
)
488 sendError(client
, 401, request
, sendContent
, "Authentication doesn't match", headers
);
494 headers
.push_back("WWW-Authenticate: Basic");
495 sendError(client
, 401, request
, sendContent
, "Unsupported Authentication Scheme", headers
);
501 size_t paramspos
= filename
.find('?');
502 if (paramspos
!= std::string::npos
)
504 params
= filename
.substr(paramspos
+ 1);
505 filename
.erase(paramspos
);
508 filename
= DeQuoteString(filename
);
510 // this is not a secure server, but at least prevent the obvious …
511 if (filename
.empty() == true || filename
[0] != '/' ||
512 strncmp(filename
.c_str(), "//", 2) == 0 ||
513 filename
.find_first_of("\r\n\t\f\v") != std::string::npos
||
514 filename
.find("/../") != std::string::npos
)
516 std::list
<std::string
> headers
;
517 sendError(client
, 400, request
, sendContent
, "Filename contains illegal character (sequence)", headers
);
521 // nuke the first character which is a / as we assured above
522 filename
.erase(0, 1);
523 if (filename
.empty() == true)
525 // support ~user/ uris to refer to /home/user/public_html/ as a kind-of special directory
526 else if (filename
[0] == '~')
528 // /home/user is actually not entirely correct, but good enough for now
529 size_t dashpos
= filename
.find('/');
530 if (dashpos
!= std::string::npos
)
532 std::string home
= filename
.substr(1, filename
.find('/') - 1);
533 std::string pubhtml
= filename
.substr(filename
.find('/') + 1);
534 filename
= "/home/" + home
+ "/public_html/" + pubhtml
;
537 filename
= "/home/" + filename
.substr(1) + "/public_html/";
540 // if no filename is given, but a valid directory see if we can use an index or
541 // have to resort to a autogenerated directory listing later on
542 if (DirectoryExists(filename
) == true)
544 std::string
const directoryIndex
= _config
->Find("aptwebserver::directoryindex");
545 if (directoryIndex
.empty() == false && directoryIndex
== flNotDir(directoryIndex
) &&
546 RealFileExists(filename
+ directoryIndex
) == true)
547 filename
+= directoryIndex
;
553 static bool handleOnTheFlyReconfiguration(int const client
, std::string
const &request
,/*{{{*/
554 std::vector
<std::string
> parts
, std::list
<std::string
> &headers
)
556 size_t const pcount
= parts
.size();
557 for (size_t i
= 0; i
< pcount
; ++i
)
558 parts
[i
] = DeQuoteString(parts
[i
]);
559 if (pcount
== 4 && parts
[1] == "set")
561 _config
->Set(parts
[2], parts
[3]);
562 sendSuccess(client
, request
, true, "Option '" + parts
[2] + "' was set to '" + parts
[3] + "'!", headers
);
565 else if (pcount
== 4 && parts
[1] == "find")
567 std::string response
= _config
->Find(parts
[2], parts
[3]);
568 addDataHeaders(headers
, response
);
569 sendHead(client
, 200, headers
);
570 sendData(client
, headers
, response
);
573 else if (pcount
== 3 && parts
[1] == "find")
575 if (_config
->Exists(parts
[2]) == true)
577 std::string response
= _config
->Find(parts
[2]);
578 addDataHeaders(headers
, response
);
579 sendHead(client
, 200, headers
);
580 sendData(client
, headers
, response
);
583 sendError(client
, 404, request
, true, "Requested Configuration option doesn't exist", headers
);
586 else if (pcount
== 3 && parts
[1] == "clear")
588 _config
->Clear(parts
[2]);
589 sendSuccess(client
, request
, true, "Option '" + parts
[2] + "' was cleared.", headers
);
593 sendError(client
, 400, request
, true, "Unknown on-the-fly configuration request", headers
);
597 static void * handleClient(void * voidclient
) /*{{{*/
599 int client
= *((int*)(voidclient
));
600 std::clog
<< "ACCEPT client " << client
<< std::endl
;
601 std::vector
<std::string
> messages
;
602 bool closeConnection
= false;
603 std::list
<std::string
> headers
;
604 while (closeConnection
== false && ReadMessages(client
, messages
))
606 // if we announced a closing, do the close
607 if (std::find(headers
.begin(), headers
.end(), std::string("Connection: close")) != headers
.end())
610 for (std::vector
<std::string
>::const_iterator m
= messages
.begin();
611 m
!= messages
.end() && closeConnection
== false; ++m
) {
612 std::clog
<< ">>> REQUEST from " << client
<< " >>>" << std::endl
<< *m
613 << std::endl
<< "<<<<<<<<<<<<<<<<" << std::endl
;
614 std::string filename
;
616 bool sendContent
= true;
617 if (parseFirstLine(client
, *m
, filename
, params
, sendContent
, closeConnection
, headers
) == false)
620 // special webserver command request
621 if (filename
.length() > 1 && filename
[0] == '_')
623 std::vector
<std::string
> parts
= VectorizeString(filename
, '/');
624 if (parts
[0] == "_config")
626 handleOnTheFlyReconfiguration(client
, *m
, parts
, headers
);
631 // string replacements in the requested filename
632 ::Configuration::Item
const *Replaces
= _config
->Tree("aptwebserver::redirect::replace");
633 if (Replaces
!= NULL
)
635 std::string redirect
= "/" + filename
;
636 for (::Configuration::Item
*I
= Replaces
->Child
; I
!= NULL
; I
= I
->Next
)
637 redirect
= SubstVar(redirect
, I
->Tag
, I
->Value
);
638 if (redirect
.empty() == false && redirect
[0] == '/')
640 if (redirect
!= filename
)
642 sendRedirect(client
, 301, redirect
, *m
, sendContent
);
647 ::Configuration::Item
const *Overwrite
= _config
->Tree("aptwebserver::overwrite");
648 if (Overwrite
!= NULL
)
650 for (::Configuration::Item
*I
= Overwrite
->Child
; I
!= NULL
; I
= I
->Next
)
652 regex_t
*pattern
= new regex_t
;
653 int const res
= regcomp(pattern
, I
->Tag
.c_str(), REG_EXTENDED
| REG_ICASE
| REG_NOSUB
);
657 regerror(res
, pattern
, error
, sizeof(error
));
658 sendError(client
, 500, *m
, sendContent
, error
, headers
);
661 if (regexec(pattern
, filename
.c_str(), 0, 0, 0) == 0)
663 filename
= _config
->Find("aptwebserver::overwrite::" + I
->Tag
+ "::filename", filename
);
664 if (filename
[0] == '/')
673 // deal with the request
674 if (_config
->FindB("aptwebserver::support::http", true) == false &&
675 LookupTag(*m
, "Host").find(":4433") == std::string::npos
)
677 sendError(client
, 400, *m
, sendContent
, "HTTP disabled, all requests must be HTTPS", headers
);
680 else if (RealFileExists(filename
) == true)
682 FileFd
data(filename
, FileFd::ReadOnly
);
683 std::string condition
= LookupTag(*m
, "If-Modified-Since", "");
684 if (_config
->FindB("aptwebserver::support::modified-since", true) == true && condition
.empty() == false)
687 if (RFC1123StrToTime(condition
.c_str(), cache
) == true &&
688 cache
>= data
.ModificationTime())
690 sendHead(client
, 304, headers
);
695 if (_config
->FindB("aptwebserver::support::range", true) == true)
696 condition
= LookupTag(*m
, "Range", "");
699 if (condition
.empty() == false && strncmp(condition
.c_str(), "bytes=", 6) == 0)
703 if (_config
->FindB("aptwebserver::support::if-range", true) == true)
704 ifrange
= LookupTag(*m
, "If-Range", "");
705 bool validrange
= (ifrange
.empty() == true ||
706 (RFC1123StrToTime(ifrange
.c_str(), cache
) == true &&
707 cache
<= data
.ModificationTime()));
709 // FIXME: support multiple byte-ranges (APT clients do not do this)
710 if (condition
.find(',') == std::string::npos
)
713 unsigned long long filestart
= strtoull(condition
.c_str() + start
, NULL
, 10);
714 // FIXME: no support for last-byte-pos being not the end of the file (APT clients do not do this)
715 size_t dash
= condition
.find('-') + 1;
716 unsigned long long fileend
= strtoull(condition
.c_str() + dash
, NULL
, 10);
717 unsigned long long filesize
= data
.FileSize();
718 if ((fileend
== 0 || (fileend
== filesize
&& fileend
>= filestart
)) &&
721 if (filesize
> filestart
)
723 data
.Skip(filestart
);
724 std::ostringstream contentlength
;
725 contentlength
<< "Content-Length: " << (filesize
- filestart
);
726 headers
.push_back(contentlength
.str());
727 std::ostringstream contentrange
;
728 contentrange
<< "Content-Range: bytes " << filestart
<< "-"
729 << filesize
- 1 << "/" << filesize
;
730 headers
.push_back(contentrange
.str());
731 sendHead(client
, 206, headers
);
732 if (sendContent
== true)
733 sendFile(client
, headers
, data
);
738 std::ostringstream contentrange
;
739 contentrange
<< "Content-Range: bytes */" << filesize
;
740 headers
.push_back(contentrange
.str());
741 sendError(client
, 416, *m
, sendContent
, "", headers
);
748 addFileHeaders(headers
, data
);
749 sendHead(client
, 200, headers
);
750 if (sendContent
== true)
751 sendFile(client
, headers
, data
);
753 else if (DirectoryExists(filename
) == true)
755 if (filename
[filename
.length()-1] == '/')
756 sendDirectoryListing(client
, filename
, *m
, sendContent
, headers
);
758 sendRedirect(client
, 301, filename
.append("/"), *m
, sendContent
);
761 sendError(client
, 404, *m
, sendContent
, "", headers
);
763 _error
->DumpErrors(std::cerr
);
767 std::clog
<< "CLOSE client " << client
<< std::endl
;
772 int main(int const argc
, const char * argv
[])
774 CommandLine::Args Args
[] = {
775 {0, "port", "aptwebserver::port", CommandLine::HasArg
},
776 {0, "request-absolute", "aptwebserver::request::absolute", CommandLine::HasArg
},
777 {0, "authorization", "aptwebserver::authorization", CommandLine::HasArg
},
778 {0, "proxy-authorization", "aptwebserver::proxy-authorization", CommandLine::HasArg
},
779 {'c',"config-file",0,CommandLine::ConfigFile
},
780 {'o',"option",0,CommandLine::ArbItem
},
784 CommandLine
CmdL(Args
, _config
);
785 if(CmdL
.Parse(argc
,argv
) == false)
787 _error
->DumpErrors();
791 // create socket, bind and listen to it {{{
792 // ignore SIGPIPE, this can happen on write() if the socket closes connection
793 signal(SIGPIPE
, SIG_IGN
);
794 // we don't care for our slaves, so ignore their death
795 signal(SIGCHLD
, SIG_IGN
);
797 int sock
= socket(AF_INET6
, SOCK_STREAM
, 0);
800 _error
->Errno("aptwerbserver", "Couldn't create socket");
801 _error
->DumpErrors(std::cerr
);
805 int const port
= _config
->FindI("aptwebserver::port", 8080);
807 // ensure that we accept all connections: v4 or v6
808 int const iponly
= 0;
809 setsockopt(sock
, IPPROTO_IPV6
, IPV6_V6ONLY
, &iponly
, sizeof(iponly
));
810 // to not linger on an address
811 int const enable
= 1;
812 setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, &enable
, sizeof(enable
));
814 struct sockaddr_in6 locAddr
;
815 memset(&locAddr
, 0, sizeof(locAddr
));
816 locAddr
.sin6_family
= AF_INET6
;
817 locAddr
.sin6_port
= htons(port
);
818 locAddr
.sin6_addr
= in6addr_any
;
820 if (bind(sock
, (struct sockaddr
*) &locAddr
, sizeof(locAddr
)) < 0)
822 _error
->Errno("aptwerbserver", "Couldn't bind");
823 _error
->DumpErrors(std::cerr
);
828 if (_config
->FindB("aptwebserver::fork", false) == true)
830 std::string
const pidfilename
= _config
->Find("aptwebserver::pidfile", "aptwebserver.pid");
831 int const pidfilefd
= GetLock(pidfilename
);
832 if (pidfilefd
< 0 || pidfile
.OpenDescriptor(pidfilefd
, FileFd::WriteOnly
) == false)
834 _error
->Errno("aptwebserver", "Couldn't acquire lock on pidfile '%s'", pidfilename
.c_str());
835 _error
->DumpErrors(std::cerr
);
839 pid_t child
= fork();
842 _error
->Errno("aptwebserver", "Forking failed");
843 _error
->DumpErrors(std::cerr
);
848 // successfully forked: ready to serve!
849 std::string pidcontent
;
850 strprintf(pidcontent
, "%d", child
);
851 pidfile
.Write(pidcontent
.c_str(), pidcontent
.size());
852 if (_error
->PendingError() == true)
854 _error
->DumpErrors(std::cerr
);
857 std::cout
<< "Successfully forked as " << child
<< std::endl
;
862 std::clog
<< "Serving ANY file on port: " << port
<< std::endl
;
864 int const slaves
= _config
->FindI("aptwebserver::slaves", SOMAXCONN
);
865 std::cerr
<< "SLAVES: " << slaves
<< std::endl
;
866 listen(sock
, slaves
);
869 _config
->CndSet("aptwebserver::response-header::Server", "APT webserver");
870 _config
->CndSet("aptwebserver::response-header::Accept-Ranges", "bytes");
871 _config
->CndSet("aptwebserver::directoryindex", "index.html");
873 std::list
<int> accepted_clients
;
877 int client
= accept(sock
, NULL
, NULL
);
882 _error
->Errno("accept", "Couldn't accept client on socket %d", sock
);
883 _error
->DumpErrors(std::cerr
);
888 if (pthread_attr_init(&attr
) != 0 || pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0)
890 _error
->Errno("pthread_attr", "Couldn't set detach attribute for a fresh thread to handle client %d on socket %d", client
, sock
);
891 _error
->DumpErrors(std::cerr
);
897 // thats rather dirty, but we need to store the client socket somewhere safe
898 accepted_clients
.push_front(client
);
899 if (pthread_create(&tid
, &attr
, &handleClient
, &(*accepted_clients
.begin())) != 0)
901 _error
->Errno("pthread_create", "Couldn't create a fresh thread to handle client %d on socket %d", client
, sock
);
902 _error
->DumpErrors(std::cerr
);