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>
15 #include <sys/socket.h>
16 #include <sys/types.h>
18 #include <netinet/in.h>
26 char const * const httpcodeToStr(int const httpcode
) { /*{{{*/
29 case 100: return "100 Continue";
30 case 101: return "101 Switching Protocols";
32 case 200: return "200 OK";
33 case 201: return "201 Created";
34 case 202: return "202 Accepted";
35 case 203: return "203 Non-Authoritative Information";
36 case 204: return "204 No Content";
37 case 205: return "205 Reset Content";
38 case 206: return "206 Partial Conent";
40 case 300: return "300 Multiple Choices";
41 case 301: return "301 Moved Permanently";
42 case 302: return "302 Found";
43 case 303: return "303 See Other";
44 case 304: return "304 Not Modified";
45 case 305: return "304 Use Proxy";
46 case 307: return "307 Temporary Redirect";
48 case 400: return "400 Bad Request";
49 case 401: return "401 Unauthorized";
50 case 402: return "402 Payment Required";
51 case 403: return "403 Forbidden";
52 case 404: return "404 Not Found";
53 case 405: return "405 Method Not Allowed";
54 case 406: return "406 Not Acceptable";
55 case 407: return "407 Proxy Authentication Required";
56 case 408: return "408 Request Time-out";
57 case 409: return "409 Conflict";
58 case 410: return "410 Gone";
59 case 411: return "411 Length Required";
60 case 412: return "412 Precondition Failed";
61 case 413: return "413 Request Entity Too Large";
62 case 414: return "414 Request-URI Too Large";
63 case 415: return "415 Unsupported Media Type";
64 case 416: return "416 Requested range not satisfiable";
65 case 417: return "417 Expectation Failed";
67 case 500: return "500 Internal Server Error";
68 case 501: return "501 Not Implemented";
69 case 502: return "502 Bad Gateway";
70 case 503: return "503 Service Unavailable";
71 case 504: return "504 Gateway Time-out";
72 case 505: return "505 HTTP Version not supported";
77 void addFileHeaders(std::list
<std::string
> &headers
, FileFd
&data
) { /*{{{*/
78 std::ostringstream contentlength
;
79 contentlength
<< "Content-Length: " << data
.FileSize();
80 headers
.push_back(contentlength
.str());
82 std::string
lastmodified("Last-Modified: ");
83 lastmodified
.append(TimeRFC1123(data
.ModificationTime()));
84 headers
.push_back(lastmodified
);
87 void addDataHeaders(std::list
<std::string
> &headers
, std::string
&data
) {/*{{{*/
88 std::ostringstream contentlength
;
89 contentlength
<< "Content-Length: " << data
.size();
90 headers
.push_back(contentlength
.str());
93 bool sendHead(int const client
, int const httpcode
, std::list
<std::string
> &headers
) { /*{{{*/
94 std::string
response("HTTP/1.1 ");
95 response
.append(httpcodeToStr(httpcode
));
96 headers
.push_front(response
);
98 headers
.push_back("Server: APT webserver");
100 std::string
date("Date: ");
101 date
.append(TimeRFC1123(time(NULL
)));
102 headers
.push_back(date
);
104 std::clog
<< ">>> RESPONSE >>>" << std::endl
;
106 for (std::list
<std::string
>::const_iterator h
= headers
.begin();
107 Success
== true && h
!= headers
.end(); ++h
) {
108 Success
&= FileFd::Write(client
, h
->c_str(), h
->size());
110 Success
&= FileFd::Write(client
, "\r\n", 2);
111 std::clog
<< *h
<< std::endl
;
114 Success
&= FileFd::Write(client
, "\r\n", 2);
115 std::clog
<< "<<<<<<<<<<<<<<<<" << std::endl
;
119 bool sendFile(int const client
, FileFd
&data
) { /*{{{*/
122 unsigned long long actual
= 0;
123 while ((Success
&= data
.Read(buffer
, sizeof(buffer
), &actual
)) == true) {
126 Success
&= FileFd::Write(client
, buffer
, actual
);
129 Success
&= FileFd::Write(client
, "\r\n", 2);
133 bool sendData(int const client
, std::string
const &data
) { /*{{{*/
135 Success
&= FileFd::Write(client
, data
.c_str(), data
.size());
137 Success
&= FileFd::Write(client
, "\r\n", 2);
141 void sendError(int const client
, int const httpcode
, std::string
const &request
, bool content
, std::string
const &error
= "") { /*{{{*/
142 std::list
<std::string
> headers
;
143 std::string
response("<html><head><title>");
144 response
.append(httpcodeToStr(httpcode
)).append("</title></head>");
145 response
.append("<body><h1>").append(httpcodeToStr(httpcode
)).append("</h1>");
146 if (error
.empty() == false)
147 response
.append("<p><em>Error</em>: ").append(error
).append("</p>");
148 response
.append("This error is a result of the request: <pre>");
149 response
.append(request
).append("</pre></body></html>");
150 addDataHeaders(headers
, response
);
151 sendHead(client
, httpcode
, headers
);
153 sendData(client
, response
);
156 void sendRedirect(int const client
, int const httpcode
, std::string
const &uri
, std::string
const &request
, bool content
) { /*{{{*/
157 std::list
<std::string
> headers
;
158 std::string
response("<html><head><title>");
159 response
.append(httpcodeToStr(httpcode
)).append("</title></head>");
160 response
.append("<body><h1>").append(httpcodeToStr(httpcode
)).append("</h1");
161 response
.append("<p>You should be redirected to <em>").append(uri
).append("</em></p>");
162 response
.append("This page is a result of the request: <pre>");
163 response
.append(request
).append("</pre></body></html>");
164 addDataHeaders(headers
, response
);
165 std::string
location("Location: ");
166 if (strncmp(uri
.c_str(), "http://", 7) != 0)
167 location
.append("http://").append(LookupTag(request
, "Host")).append("/").append(uri
);
169 location
.append(uri
);
170 headers
.push_back(location
);
171 sendHead(client
, httpcode
, headers
);
173 sendData(client
, response
);
176 // sendDirectoryLisiting /*{{{*/
177 int filter_hidden_files(const struct dirent
*a
) {
178 if (a
->d_name
[0] == '.')
180 #ifdef _DIRENT_HAVE_D_TYPE
181 // if we have the d_type check that only files and dirs will be included
182 if (a
->d_type
!= DT_UNKNOWN
&&
183 a
->d_type
!= DT_REG
&&
184 a
->d_type
!= DT_LNK
&& // this includes links to regular files
190 int grouped_alpha_case_sort(const struct dirent
**a
, const struct dirent
**b
) {
191 #ifdef _DIRENT_HAVE_D_TYPE
192 if ((*a
)->d_type
== DT_DIR
&& (*b
)->d_type
== DT_DIR
);
193 else if ((*a
)->d_type
== DT_DIR
&& (*b
)->d_type
== DT_REG
)
195 else if ((*b
)->d_type
== DT_DIR
&& (*a
)->d_type
== DT_REG
)
200 struct stat f_prop
; //File's property
201 stat((*a
)->d_name
, &f_prop
);
202 int const amode
= f_prop
.st_mode
;
203 stat((*b
)->d_name
, &f_prop
);
204 int const bmode
= f_prop
.st_mode
;
205 if (S_ISDIR(amode
) && S_ISDIR(bmode
));
206 else if (S_ISDIR(amode
))
208 else if (S_ISDIR(bmode
))
211 return strcasecmp((*a
)->d_name
, (*b
)->d_name
);
213 void sendDirectoryListing(int const client
, std::string
const &dir
, std::string
const &request
, bool content
) {
214 std::list
<std::string
> headers
;
215 std::ostringstream listing
;
217 struct dirent
**namelist
;
218 int const counter
= scandir(dir
.c_str(), &namelist
, filter_hidden_files
, grouped_alpha_case_sort
);
220 sendError(client
, 500, request
, content
);
224 listing
<< "<html><head><title>Index of " << dir
<< "</title>"
225 << "<style type=\"text/css\"><!-- td {padding: 0.02em 0.5em 0.02em 0.5em;}"
226 << "tr:nth-child(even){background-color:#dfdfdf;}"
227 << "h1, td:nth-child(3){text-align:center;}"
228 << "table {margin-left:auto;margin-right:auto;} --></style>"
229 << "</head>" << std::endl
230 << "<body><h1>Index of " << dir
<< "</h1>" << std::endl
231 << "<table><tr><th>#</th><th>Name</th><th>Size</th><th>Last-Modified</th></tr>" << std::endl
;
233 listing
<< "<tr><td>d</td><td><a href=\"..\">Parent Directory</a></td><td>-</td><td>-</td></tr>";
234 for (int i
= 0; i
< counter
; ++i
) {
236 std::string
filename(dir
);
237 filename
.append("/").append(namelist
[i
]->d_name
);
238 stat(filename
.c_str(), &fs
);
239 if (S_ISDIR(fs
.st_mode
)) {
240 listing
<< "<tr><td>d</td>"
241 << "<td><a href=\"" << namelist
[i
]->d_name
<< "/\">" << namelist
[i
]->d_name
<< "</a></td>"
244 listing
<< "<tr><td>f</td>"
245 << "<td><a href=\"" << namelist
[i
]->d_name
<< "\">" << namelist
[i
]->d_name
<< "</a></td>"
246 << "<td>" << SizeToStr(fs
.st_size
) << "B</td>";
248 listing
<< "<td>" << TimeRFC1123(fs
.st_mtime
) << "</td></tr>" << std::endl
;
250 listing
<< "</table></body></html>" << std::endl
;
252 std::string
response(listing
.str());
253 addDataHeaders(headers
, response
);
254 sendHead(client
, 200, headers
);
256 sendData(client
, response
);
259 bool parseFirstLine(int const client
, std::string
const &request
, std::string
&filename
, bool &sendContent
) { /*{{{*/
260 if (strncmp(request
.c_str(), "HEAD ", 5) == 0)
262 if (strncmp(request
.c_str(), "GET ", 4) != 0)
264 sendError(client
, 501, request
, true);
268 size_t const lineend
= request
.find('\n');
269 size_t filestart
= request
.find(' ');
270 for (; request
[filestart
] == ' '; ++filestart
);
271 size_t fileend
= request
.rfind(' ', lineend
);
272 if (lineend
== std::string::npos
|| filestart
== std::string::npos
||
273 fileend
== std::string::npos
|| filestart
== fileend
) {
274 sendError(client
, 500, request
, sendContent
, "Filename can't be extracted");
278 size_t httpstart
= fileend
;
279 for (; request
[httpstart
] == ' '; ++httpstart
);
280 if (strncmp(request
.c_str() + httpstart
, "HTTP/1.1\r", 9) != 0) {
281 sendError(client
, 500, request
, sendContent
, "Not an HTTP/1.1 request");
285 filename
= request
.substr(filestart
, fileend
- filestart
);
286 if (filename
.find(' ') != std::string::npos
) {
287 sendError(client
, 500, request
, sendContent
, "Filename contains an unencoded space");
290 filename
= DeQuoteString(filename
);
292 // this is not a secure server, but at least prevent the obvious …
293 if (filename
.empty() == true || filename
[0] != '/' ||
294 strncmp(filename
.c_str(), "//", 2) == 0 ||
295 filename
.find_first_of("\r\n\t\f\v") != std::string::npos
||
296 filename
.find("/../") != std::string::npos
) {
297 sendError(client
, 400, request
, sendContent
, "Filename contains illegal character (sequence)");
301 // nuke the first character which is a / as we assured above
302 filename
.erase(0, 1);
303 if (filename
.empty() == true)
308 int main(int const argc
, const char * argv
[])
310 CommandLine::Args Args
[] = {
311 {0, "simulate-paywall", "aptwebserver::Simulate-Paywall",
312 CommandLine::Boolean
},
313 {0, "port", "aptwebserver::port", CommandLine::HasArg
},
314 {'c',"config-file",0,CommandLine::ConfigFile
},
315 {'o',"option",0,CommandLine::ArbItem
},
319 CommandLine
CmdL(Args
, _config
);
320 if(CmdL
.Parse(argc
,argv
) == false) {
321 _error
->DumpErrors();
325 // create socket, bind and listen to it {{{
326 // ignore SIGPIPE, this can happen on write() if the socket closes connection
327 signal(SIGPIPE
, SIG_IGN
);
328 int sock
= socket(AF_INET6
, SOCK_STREAM
, 0);
330 _error
->Errno("aptwerbserver", "Couldn't create socket");
331 _error
->DumpErrors(std::cerr
);
336 int const port
= _config
->FindI("aptwebserver::port", 8080);
337 bool const simulate_broken_server
= _config
->FindB("aptwebserver::Simulate-Paywall", false);
339 // ensure that we accept all connections: v4 or v6
340 int const iponly
= 0;
341 setsockopt(sock
, IPPROTO_IPV6
, IPV6_V6ONLY
, &iponly
, sizeof(iponly
));
342 // to not linger to an address
343 int const enable
= 1;
344 setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, &enable
, sizeof(enable
));
346 struct sockaddr_in6 locAddr
;
347 memset(&locAddr
, 0, sizeof(locAddr
));
348 locAddr
.sin6_family
= AF_INET6
;
349 locAddr
.sin6_port
= htons(port
);
350 locAddr
.sin6_addr
= in6addr_any
;
352 if (bind(sock
, (struct sockaddr
*) &locAddr
, sizeof(locAddr
)) < 0) {
353 _error
->Errno("aptwerbserver", "Couldn't bind");
354 _error
->DumpErrors(std::cerr
);
358 if (simulate_broken_server
) {
359 std::clog
<< "Simulating a broken web server that return nonsense "
360 "for all querries" << std::endl
;
362 std::clog
<< "Serving ANY file on port: " << port
<< std::endl
;
368 std::vector
<std::string
> messages
;
370 while ((client
= accept(sock
, NULL
, NULL
)) != -1) {
371 std::clog
<< "ACCEPT client " << client
372 << " on socket " << sock
<< std::endl
;
374 while (ReadMessages(client
, messages
)) {
375 for (std::vector
<std::string
>::const_iterator m
= messages
.begin();
376 m
!= messages
.end(); ++m
) {
377 std::clog
<< ">>> REQUEST >>>>" << std::endl
<< *m
378 << std::endl
<< "<<<<<<<<<<<<<<<<" << std::endl
;
380 std::list
<std::string
> headers
;
381 std::string filename
;
382 bool sendContent
= true;
383 if (parseFirstLine(client
, *m
, filename
, sendContent
) == false)
386 std::string host
= LookupTag(*m
, "Host", "");
387 if (host
.empty() == true) {
388 // RFC 2616 §14.23 requires Host
389 sendError(client
, 400, *m
, sendContent
, "Host header is required");
393 if (simulate_broken_server
== true) {
394 std::string
data("ni ni ni\n");
395 addDataHeaders(headers
, data
);
396 sendHead(client
, 200, headers
);
397 sendData(client
, data
);
399 else if (RealFileExists(filename
) == true) {
400 FileFd
data(filename
, FileFd::ReadOnly
);
401 std::string condition
= LookupTag(*m
, "If-Modified-Since", "");
402 if (condition
.empty() == false) {
404 if (RFC1123StrToTime(condition
.c_str(), cache
) == true &&
405 cache
>= data
.ModificationTime()) {
406 sendHead(client
, 304, headers
);
410 addFileHeaders(headers
, data
);
411 sendHead(client
, 200, headers
);
412 if (sendContent
== true)
413 sendFile(client
, data
);
415 else if (DirectoryExists(filename
) == true) {
416 if (filename
== "." || filename
[filename
.length()-1] == '/')
417 sendDirectoryListing(client
, filename
, *m
, sendContent
);
419 sendRedirect(client
, 301, filename
.append("/"), *m
, sendContent
);
423 ::Configuration::Item
const *Replaces
= _config
->Tree("aptwebserver::redirect::replace");
424 if (Replaces
!= NULL
) {
425 std::string redirect
= "/" + filename
;
426 for (::Configuration::Item
*I
= Replaces
->Child
; I
!= NULL
; I
= I
->Next
)
427 redirect
= SubstVar(redirect
, I
->Tag
, I
->Value
);
429 if (redirect
!= filename
) {
430 sendRedirect(client
, 301, redirect
, *m
, sendContent
);
434 sendError(client
, 404, *m
, sendContent
);
437 _error
->DumpErrors(std::cerr
);
441 std::clog
<< "CLOSE client " << client
442 << " on socket " << sock
<< std::endl
;