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
);
86 std::string
const fileext
= flExtension(data
.Name());
87 if (fileext
.empty() == false && fileext
!= data
.Name()) {
88 std::string
confcontenttype("aptwebserver::ContentType::");
89 confcontenttype
.append(fileext
);
90 std::string
const contenttype
= _config
->Find(confcontenttype
);
91 if (contenttype
.empty() == false) {
92 std::string
header("Content-Type: ");
93 header
.append(contenttype
);
94 headers
.push_back(header
);
99 void addDataHeaders(std::list
<std::string
> &headers
, std::string
&data
) {/*{{{*/
100 std::ostringstream contentlength
;
101 contentlength
<< "Content-Length: " << data
.size();
102 headers
.push_back(contentlength
.str());
105 bool sendHead(int const client
, int const httpcode
, std::list
<std::string
> &headers
) { /*{{{*/
106 std::string
response("HTTP/1.1 ");
107 response
.append(httpcodeToStr(httpcode
));
108 headers
.push_front(response
);
110 headers
.push_back("Server: APT webserver");
112 std::string
date("Date: ");
113 date
.append(TimeRFC1123(time(NULL
)));
114 headers
.push_back(date
);
116 std::clog
<< ">>> RESPONSE >>>" << std::endl
;
118 for (std::list
<std::string
>::const_iterator h
= headers
.begin();
119 Success
== true && h
!= headers
.end(); ++h
) {
120 Success
&= FileFd::Write(client
, h
->c_str(), h
->size());
122 Success
&= FileFd::Write(client
, "\r\n", 2);
123 std::clog
<< *h
<< std::endl
;
126 Success
&= FileFd::Write(client
, "\r\n", 2);
127 std::clog
<< "<<<<<<<<<<<<<<<<" << std::endl
;
131 bool sendFile(int const client
, FileFd
&data
) { /*{{{*/
134 unsigned long long actual
= 0;
135 while ((Success
&= data
.Read(buffer
, sizeof(buffer
), &actual
)) == true) {
138 Success
&= FileFd::Write(client
, buffer
, actual
);
141 Success
&= FileFd::Write(client
, "\r\n", 2);
145 bool sendData(int const client
, std::string
const &data
) { /*{{{*/
147 Success
&= FileFd::Write(client
, data
.c_str(), data
.size());
149 Success
&= FileFd::Write(client
, "\r\n", 2);
153 void sendError(int const client
, int const httpcode
, std::string
const &request
, bool content
, std::string
const &error
= "") { /*{{{*/
154 std::list
<std::string
> headers
;
155 std::string
response("<html><head><title>");
156 response
.append(httpcodeToStr(httpcode
)).append("</title></head>");
157 response
.append("<body><h1>").append(httpcodeToStr(httpcode
)).append("</h1>");
158 if (error
.empty() == false)
159 response
.append("<p><em>Error</em>: ").append(error
).append("</p>");
160 response
.append("This error is a result of the request: <pre>");
161 response
.append(request
).append("</pre></body></html>");
162 addDataHeaders(headers
, response
);
163 sendHead(client
, httpcode
, headers
);
165 sendData(client
, response
);
168 void sendRedirect(int const client
, int const httpcode
, std::string
const &uri
, std::string
const &request
, bool content
) { /*{{{*/
169 std::list
<std::string
> headers
;
170 std::string
response("<html><head><title>");
171 response
.append(httpcodeToStr(httpcode
)).append("</title></head>");
172 response
.append("<body><h1>").append(httpcodeToStr(httpcode
)).append("</h1");
173 response
.append("<p>You should be redirected to <em>").append(uri
).append("</em></p>");
174 response
.append("This page is a result of the request: <pre>");
175 response
.append(request
).append("</pre></body></html>");
176 addDataHeaders(headers
, response
);
177 std::string
location("Location: ");
178 if (strncmp(uri
.c_str(), "http://", 7) != 0)
179 location
.append("http://").append(LookupTag(request
, "Host")).append("/").append(uri
);
181 location
.append(uri
);
182 headers
.push_back(location
);
183 sendHead(client
, httpcode
, headers
);
185 sendData(client
, response
);
188 // sendDirectoryLisiting /*{{{*/
189 int filter_hidden_files(const struct dirent
*a
) {
190 if (a
->d_name
[0] == '.')
192 #ifdef _DIRENT_HAVE_D_TYPE
193 // if we have the d_type check that only files and dirs will be included
194 if (a
->d_type
!= DT_UNKNOWN
&&
195 a
->d_type
!= DT_REG
&&
196 a
->d_type
!= DT_LNK
&& // this includes links to regular files
202 int grouped_alpha_case_sort(const struct dirent
**a
, const struct dirent
**b
) {
203 #ifdef _DIRENT_HAVE_D_TYPE
204 if ((*a
)->d_type
== DT_DIR
&& (*b
)->d_type
== DT_DIR
);
205 else if ((*a
)->d_type
== DT_DIR
&& (*b
)->d_type
== DT_REG
)
207 else if ((*b
)->d_type
== DT_DIR
&& (*a
)->d_type
== DT_REG
)
212 struct stat f_prop
; //File's property
213 stat((*a
)->d_name
, &f_prop
);
214 int const amode
= f_prop
.st_mode
;
215 stat((*b
)->d_name
, &f_prop
);
216 int const bmode
= f_prop
.st_mode
;
217 if (S_ISDIR(amode
) && S_ISDIR(bmode
));
218 else if (S_ISDIR(amode
))
220 else if (S_ISDIR(bmode
))
223 return strcasecmp((*a
)->d_name
, (*b
)->d_name
);
225 void sendDirectoryListing(int const client
, std::string
const &dir
, std::string
const &request
, bool content
) {
226 std::list
<std::string
> headers
;
227 std::ostringstream listing
;
229 struct dirent
**namelist
;
230 int const counter
= scandir(dir
.c_str(), &namelist
, filter_hidden_files
, grouped_alpha_case_sort
);
232 sendError(client
, 500, request
, content
);
236 listing
<< "<html><head><title>Index of " << dir
<< "</title>"
237 << "<style type=\"text/css\"><!-- td {padding: 0.02em 0.5em 0.02em 0.5em;}"
238 << "tr:nth-child(even){background-color:#dfdfdf;}"
239 << "h1, td:nth-child(3){text-align:center;}"
240 << "table {margin-left:auto;margin-right:auto;} --></style>"
241 << "</head>" << std::endl
242 << "<body><h1>Index of " << dir
<< "</h1>" << std::endl
243 << "<table><tr><th>#</th><th>Name</th><th>Size</th><th>Last-Modified</th></tr>" << std::endl
;
245 listing
<< "<tr><td>d</td><td><a href=\"..\">Parent Directory</a></td><td>-</td><td>-</td></tr>";
246 for (int i
= 0; i
< counter
; ++i
) {
248 std::string
filename(dir
);
249 filename
.append("/").append(namelist
[i
]->d_name
);
250 stat(filename
.c_str(), &fs
);
251 if (S_ISDIR(fs
.st_mode
)) {
252 listing
<< "<tr><td>d</td>"
253 << "<td><a href=\"" << namelist
[i
]->d_name
<< "/\">" << namelist
[i
]->d_name
<< "</a></td>"
256 listing
<< "<tr><td>f</td>"
257 << "<td><a href=\"" << namelist
[i
]->d_name
<< "\">" << namelist
[i
]->d_name
<< "</a></td>"
258 << "<td>" << SizeToStr(fs
.st_size
) << "B</td>";
260 listing
<< "<td>" << TimeRFC1123(fs
.st_mtime
) << "</td></tr>" << std::endl
;
262 listing
<< "</table></body></html>" << std::endl
;
264 std::string
response(listing
.str());
265 addDataHeaders(headers
, response
);
266 sendHead(client
, 200, headers
);
268 sendData(client
, response
);
271 bool parseFirstLine(int const client
, std::string
const &request
, std::string
&filename
, bool &sendContent
) { /*{{{*/
272 if (strncmp(request
.c_str(), "HEAD ", 5) == 0)
274 if (strncmp(request
.c_str(), "GET ", 4) != 0)
276 sendError(client
, 501, request
, true);
280 size_t const lineend
= request
.find('\n');
281 size_t filestart
= request
.find(' ');
282 for (; request
[filestart
] == ' '; ++filestart
);
283 size_t fileend
= request
.rfind(' ', lineend
);
284 if (lineend
== std::string::npos
|| filestart
== std::string::npos
||
285 fileend
== std::string::npos
|| filestart
== fileend
) {
286 sendError(client
, 500, request
, sendContent
, "Filename can't be extracted");
290 size_t httpstart
= fileend
;
291 for (; request
[httpstart
] == ' '; ++httpstart
);
292 if (strncmp(request
.c_str() + httpstart
, "HTTP/1.1\r", 9) != 0) {
293 sendError(client
, 500, request
, sendContent
, "Not an HTTP/1.1 request");
297 filename
= request
.substr(filestart
, fileend
- filestart
);
298 if (filename
.find(' ') != std::string::npos
) {
299 sendError(client
, 500, request
, sendContent
, "Filename contains an unencoded space");
302 filename
= DeQuoteString(filename
);
304 // this is not a secure server, but at least prevent the obvious …
305 if (filename
.empty() == true || filename
[0] != '/' ||
306 strncmp(filename
.c_str(), "//", 2) == 0 ||
307 filename
.find_first_of("\r\n\t\f\v") != std::string::npos
||
308 filename
.find("/../") != std::string::npos
) {
309 sendError(client
, 400, request
, sendContent
, "Filename contains illegal character (sequence)");
313 // nuke the first character which is a / as we assured above
314 filename
.erase(0, 1);
315 if (filename
.empty() == true)
320 int main(int const argc
, const char * argv
[])
322 CommandLine::Args Args
[] = {
323 {0, "simulate-paywall", "aptwebserver::Simulate-Paywall",
324 CommandLine::Boolean
},
325 {0, "port", "aptwebserver::port", CommandLine::HasArg
},
326 {'c',"config-file",0,CommandLine::ConfigFile
},
327 {'o',"option",0,CommandLine::ArbItem
},
331 CommandLine
CmdL(Args
, _config
);
332 if(CmdL
.Parse(argc
,argv
) == false) {
333 _error
->DumpErrors();
337 // create socket, bind and listen to it {{{
338 // ignore SIGPIPE, this can happen on write() if the socket closes connection
339 signal(SIGPIPE
, SIG_IGN
);
340 int sock
= socket(AF_INET6
, SOCK_STREAM
, 0);
342 _error
->Errno("aptwerbserver", "Couldn't create socket");
343 _error
->DumpErrors(std::cerr
);
348 int const port
= _config
->FindI("aptwebserver::port", 8080);
349 bool const simulate_broken_server
= _config
->FindB("aptwebserver::Simulate-Paywall", false);
351 // ensure that we accept all connections: v4 or v6
352 int const iponly
= 0;
353 setsockopt(sock
, IPPROTO_IPV6
, IPV6_V6ONLY
, &iponly
, sizeof(iponly
));
354 // to not linger to an address
355 int const enable
= 1;
356 setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, &enable
, sizeof(enable
));
358 struct sockaddr_in6 locAddr
;
359 memset(&locAddr
, 0, sizeof(locAddr
));
360 locAddr
.sin6_family
= AF_INET6
;
361 locAddr
.sin6_port
= htons(port
);
362 locAddr
.sin6_addr
= in6addr_any
;
364 if (bind(sock
, (struct sockaddr
*) &locAddr
, sizeof(locAddr
)) < 0) {
365 _error
->Errno("aptwerbserver", "Couldn't bind");
366 _error
->DumpErrors(std::cerr
);
370 if (simulate_broken_server
) {
371 std::clog
<< "Simulating a broken web server that return nonsense "
372 "for all querries" << std::endl
;
374 std::clog
<< "Serving ANY file on port: " << port
<< std::endl
;
380 std::vector
<std::string
> messages
;
382 while ((client
= accept(sock
, NULL
, NULL
)) != -1) {
383 std::clog
<< "ACCEPT client " << client
384 << " on socket " << sock
<< std::endl
;
386 while (ReadMessages(client
, messages
)) {
387 for (std::vector
<std::string
>::const_iterator m
= messages
.begin();
388 m
!= messages
.end(); ++m
) {
389 std::clog
<< ">>> REQUEST >>>>" << std::endl
<< *m
390 << std::endl
<< "<<<<<<<<<<<<<<<<" << std::endl
;
392 std::list
<std::string
> headers
;
393 std::string filename
;
394 bool sendContent
= true;
395 if (parseFirstLine(client
, *m
, filename
, sendContent
) == false)
398 std::string host
= LookupTag(*m
, "Host", "");
399 if (host
.empty() == true) {
400 // RFC 2616 §14.23 requires Host
401 sendError(client
, 400, *m
, sendContent
, "Host header is required");
405 if (simulate_broken_server
== true) {
406 std::string
data("ni ni ni\n");
407 addDataHeaders(headers
, data
);
408 sendHead(client
, 200, headers
);
409 sendData(client
, data
);
411 else if (RealFileExists(filename
) == true) {
412 FileFd
data(filename
, FileFd::ReadOnly
);
413 std::string condition
= LookupTag(*m
, "If-Modified-Since", "");
414 if (condition
.empty() == false) {
416 if (RFC1123StrToTime(condition
.c_str(), cache
) == true &&
417 cache
>= data
.ModificationTime()) {
418 sendHead(client
, 304, headers
);
422 addFileHeaders(headers
, data
);
423 sendHead(client
, 200, headers
);
424 if (sendContent
== true)
425 sendFile(client
, data
);
427 else if (DirectoryExists(filename
) == true) {
428 if (filename
== "." || filename
[filename
.length()-1] == '/')
429 sendDirectoryListing(client
, filename
, *m
, sendContent
);
431 sendRedirect(client
, 301, filename
.append("/"), *m
, sendContent
);
435 ::Configuration::Item
const *Replaces
= _config
->Tree("aptwebserver::redirect::replace");
436 if (Replaces
!= NULL
) {
437 std::string redirect
= "/" + filename
;
438 for (::Configuration::Item
*I
= Replaces
->Child
; I
!= NULL
; I
= I
->Next
)
439 redirect
= SubstVar(redirect
, I
->Tag
, I
->Value
);
441 if (redirect
!= filename
) {
442 sendRedirect(client
, 301, redirect
, *m
, sendContent
);
446 sendError(client
, 404, *m
, sendContent
);
449 _error
->DumpErrors(std::cerr
);
453 std::clog
<< "CLOSE client " << client
454 << " on socket " << sock
<< std::endl
;