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>
25 char const * const httpcodeToStr(int const httpcode
) { /*{{{*/
28 case 100: return "100 Continue";
29 case 101: return "101 Switching Protocols";
31 case 200: return "200 OK";
32 case 201: return "201 Created";
33 case 202: return "202 Accepted";
34 case 203: return "203 Non-Authoritative Information";
35 case 204: return "204 No Content";
36 case 205: return "205 Reset Content";
37 case 206: return "206 Partial Conent";
39 case 300: return "300 Multiple Choices";
40 case 301: return "301 Moved Permanently";
41 case 302: return "302 Found";
42 case 303: return "303 See Other";
43 case 304: return "304 Not Modified";
44 case 305: return "304 Use Proxy";
45 case 307: return "307 Temporary Redirect";
47 case 400: return "400 Bad Request";
48 case 401: return "401 Unauthorized";
49 case 402: return "402 Payment Required";
50 case 403: return "403 Forbidden";
51 case 404: return "404 Not Found";
52 case 405: return "405 Method Not Allowed";
53 case 406: return "406 Not Acceptable";
54 case 407: return "Proxy Authentication Required";
55 case 408: return "Request Time-out";
56 case 409: return "Conflict";
57 case 410: return "Gone";
58 case 411: return "Length Required";
59 case 412: return "Precondition Failed";
60 case 413: return "Request Entity Too Large";
61 case 414: return "Request-URI Too Large";
62 case 415: return "Unsupported Media Type";
63 case 416: return "Requested range not satisfiable";
64 case 417: return "Expectation Failed";
66 case 500: return "Internal Server Error";
67 case 501: return "Not Implemented";
68 case 502: return "Bad Gateway";
69 case 503: return "Service Unavailable";
70 case 504: return "Gateway Time-out";
71 case 505: return "HTTP Version not supported";
76 void addFileHeaders(std::list
<std::string
> &headers
, FileFd
&data
) { /*{{{*/
77 std::ostringstream contentlength
;
78 contentlength
<< "Content-Length: " << data
.FileSize();
79 headers
.push_back(contentlength
.str());
81 std::string
lastmodified("Last-Modified: ");
82 lastmodified
.append(TimeRFC1123(data
.ModificationTime()));
83 headers
.push_back(lastmodified
);
86 void addDataHeaders(std::list
<std::string
> &headers
, std::string
&data
) {/*{{{*/
87 std::ostringstream contentlength
;
88 contentlength
<< "Content-Length: " << data
.size();
89 headers
.push_back(contentlength
.str());
92 bool sendHead(int const client
, int const httpcode
, std::list
<std::string
> &headers
) { /*{{{*/
93 std::string
response("HTTP/1.1 ");
94 response
.append(httpcodeToStr(httpcode
));
95 headers
.push_front(response
);
97 headers
.push_back("Server: APT webserver");
99 std::string
date("Date: ");
100 date
.append(TimeRFC1123(time(NULL
)));
101 headers
.push_back(date
);
103 std::clog
<< ">>> RESPONSE >>>" << std::endl
;
105 for (std::list
<std::string
>::const_iterator h
= headers
.begin();
106 Success
== true && h
!= headers
.end(); ++h
) {
107 Success
&= FileFd::Write(client
, h
->c_str(), h
->size());
108 Success
&= FileFd::Write(client
, "\r\n", 2);
109 std::clog
<< *h
<< std::endl
;
111 Success
&= FileFd::Write(client
, "\r\n", 2);
112 std::clog
<< "<<<<<<<<<<<<<<<<" << std::endl
;
116 bool sendFile(int const client
, FileFd
&data
) { /*{{{*/
119 unsigned long long actual
= 0;
120 while ((Success
&= data
.Read(buffer
, sizeof(buffer
), &actual
)) == true) {
123 Success
&= FileFd::Write(client
, buffer
, actual
);
125 Success
&= FileFd::Write(client
, "\r\n", 2);
129 bool sendData(int const client
, std::string
const &data
) { /*{{{*/
131 Success
&= FileFd::Write(client
, data
.c_str(), data
.size());
132 Success
&= FileFd::Write(client
, "\r\n", 2);
136 void sendError(int const client
, int const httpcode
, std::string
const &request
, bool content
) { /*{{{*/
137 std::list
<std::string
> headers
;
138 std::string
response("<html><head><title>");
139 response
.append(httpcodeToStr(httpcode
)).append("</title></head>");
140 response
.append("<body><h1>").append(httpcodeToStr(httpcode
)).append("</h1");
141 response
.append("This error is a result of the request: <pre>");
142 response
.append(request
).append("</pre></body></html>");
143 addDataHeaders(headers
, response
);
144 sendHead(client
, httpcode
, headers
);
146 sendData(client
, response
);
149 // sendDirectoryLisiting /*{{{*/
150 int filter_hidden_files(const struct dirent
*a
) {
151 if (a
->d_name
[0] == '.')
153 #ifdef _DIRENT_HAVE_D_TYPE
154 // if we have the d_type check that only files and dirs will be included
155 if (a
->d_type
!= DT_UNKNOWN
&&
156 a
->d_type
!= DT_REG
&&
157 a
->d_type
!= DT_LNK
&& // this includes links to regular files
163 int grouped_alpha_case_sort(const struct dirent
**a
, const struct dirent
**b
) {
164 #ifdef _DIRENT_HAVE_D_TYPE
165 if ((*a
)->d_type
== DT_DIR
&& (*b
)->d_type
== DT_DIR
);
166 else if ((*a
)->d_type
== DT_DIR
&& (*b
)->d_type
== DT_REG
)
168 else if ((*b
)->d_type
== DT_DIR
&& (*a
)->d_type
== DT_REG
)
173 struct stat f_prop
; //File's property
174 stat((*a
)->d_name
, &f_prop
);
175 int const amode
= f_prop
.st_mode
;
176 stat((*b
)->d_name
, &f_prop
);
177 int const bmode
= f_prop
.st_mode
;
178 if (S_ISDIR(amode
) && S_ISDIR(bmode
));
179 else if (S_ISDIR(amode
))
181 else if (S_ISDIR(bmode
))
184 return strcasecmp((*a
)->d_name
, (*b
)->d_name
);
186 void sendDirectoryListing(int const client
, std::string
const &dir
, std::string
const &request
, bool content
) {
187 std::list
<std::string
> headers
;
188 std::ostringstream listing
;
190 struct dirent
**namelist
;
191 int const counter
= scandir(dir
.c_str(), &namelist
, filter_hidden_files
, grouped_alpha_case_sort
);
193 sendError(client
, 500, request
, content
);
197 listing
<< "<html><head><title>Index of " << dir
<< "</title>"
198 << "<style type=\"text/css\"><!-- td {padding: 0.02em 0.5em 0.02em 0.5em;}"
199 << "tr:nth-child(even){background-color:#dfdfdf;}"
200 << "h1, td:nth-child(3){text-align:center;}"
201 << "table {margin-left:auto;margin-right:auto;} --></style>"
202 << "</head>" << std::endl
203 << "<body><h1>Index of " << dir
<< "</h1>" << std::endl
204 << "<table><tr><th>#</th><th>Name</th><th>Size</th><th>Last-Modified</th></tr>" << std::endl
;
206 listing
<< "<tr><td>d</td><td><a href=\"..\">Parent Directory</a></td><td>-</td><td>-</td></tr>";
207 for (int i
= 0; i
< counter
; ++i
) {
209 std::string
filename(dir
);
210 filename
.append("/").append(namelist
[i
]->d_name
);
211 stat(filename
.c_str(), &fs
);
212 listing
<< "<tr><td>" << ((S_ISDIR(fs
.st_mode
)) ? 'd' : 'f') << "</td>"
213 << "<td><a href=\"" << namelist
[i
]->d_name
<< "\">" << namelist
[i
]->d_name
<< "</a></td>";
214 if (S_ISDIR(fs
.st_mode
))
215 listing
<< "<td>-</td>";
217 listing
<< "<td>" << SizeToStr(fs
.st_size
) << "B</td>";
218 listing
<< "<td>" << TimeRFC1123(fs
.st_mtime
) << "</td></tr>" << std::endl
;
220 listing
<< "</table></body></html>" << std::endl
;
222 std::string
response(listing
.str());
223 addDataHeaders(headers
, response
);
224 sendHead(client
, 200, headers
);
226 sendData(client
, response
);
229 int main(int const argc
, const char * argv
[])
231 CommandLine::Args Args
[] = {
232 {0, "simulate-paywall", "aptwebserver::Simulate-Paywall",
233 CommandLine::Boolean
},
234 {0, "port", "aptwebserver::port", CommandLine::HasArg
},
238 CommandLine
CmdL(Args
, _config
);
239 if(CmdL
.Parse(argc
,argv
) == false) {
240 _error
->DumpErrors();
244 // create socket, bind and listen to it {{{
245 int sock
= socket(AF_INET6
, SOCK_STREAM
, 0);
247 _error
->Errno("aptwerbserver", "Couldn't create socket");
248 _error
->DumpErrors(std::cerr
);
253 int const port
= _config
->FindI("aptwebserver::port", 8080);
254 bool const simulate_broken_server
= _config
->FindB("aptwebserver::Simulate-Paywall", false);
256 // ensure that we accept all connections: v4 or v6
257 int const iponly
= 0;
258 setsockopt(sock
, IPPROTO_IPV6
, IPV6_V6ONLY
, &iponly
, sizeof(iponly
));
259 // to not linger to an address
260 int const enable
= 1;
261 setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, &enable
, sizeof(enable
));
263 struct sockaddr_in6 locAddr
;
264 memset(&locAddr
, 0, sizeof(locAddr
));
265 locAddr
.sin6_family
= AF_INET6
;
266 locAddr
.sin6_port
= htons(port
);
267 locAddr
.sin6_addr
= in6addr_any
;
269 if (bind(sock
, (struct sockaddr
*) &locAddr
, sizeof(locAddr
)) < 0) {
270 _error
->Errno("aptwerbserver", "Couldn't bind");
271 _error
->DumpErrors(std::cerr
);
275 if (simulate_broken_server
) {
276 std::clog
<< "Simulating a broken web server that return nonsense "
277 "for all querries" << std::endl
;
279 std::clog
<< "Serving ANY file on port: " << port
<< std::endl
;
285 std::vector
<std::string
> messages
;
287 while ((client
= accept(sock
, NULL
, NULL
)) != -1) {
288 std::clog
<< "ACCEPT client " << client
289 << " on socket " << sock
<< std::endl
;
291 while (ReadMessages(client
, messages
)) {
292 for (std::vector
<std::string
>::const_iterator m
= messages
.begin();
293 m
!= messages
.end(); ++m
) {
294 std::clog
<< ">>> REQUEST >>>>" << std::endl
<< *m
295 << std::endl
<< "<<<<<<<<<<<<<<<<" << std::endl
;
296 std::list
<std::string
> headers
;
297 bool sendContent
= true;
298 if (strncmp(m
->c_str(), "HEAD ", 5) == 0)
300 if (strncmp(m
->c_str(), "GET ", 4) != 0)
301 sendError(client
, 501, *m
, true);
303 std::string host
= LookupTag(*m
, "Host", "");
304 if (host
.empty() == true) {
305 // RFC 2616 ยง14.23 Host
306 sendError(client
, 400, *m
, sendContent
);
310 size_t const filestart
= m
->find(' ', 5);
311 std::string filename
= m
->substr(5, filestart
- 5);
312 if (filename
.empty() == true)
315 if (simulate_broken_server
== true) {
316 std::string
data("ni ni ni\n");
317 addDataHeaders(headers
, data
);
318 sendHead(client
, 200, headers
);
319 sendData(client
, data
);
321 else if (RealFileExists(filename
) == true) {
322 FileFd
data(filename
, FileFd::ReadOnly
);
323 std::string condition
= LookupTag(*m
, "If-Modified-Since", "");
324 if (condition
.empty() == false) {
326 if (RFC1123StrToTime(condition
.c_str(), cache
) == true &&
327 cache
>= data
.ModificationTime()) {
328 sendHead(client
, 304, headers
);
332 addFileHeaders(headers
, data
);
333 sendHead(client
, 200, headers
);
334 if (sendContent
== true)
335 sendFile(client
, data
);
337 else if (DirectoryExists(filename
) == true) {
338 sendDirectoryListing(client
, filename
, *m
, sendContent
);
341 sendError(client
, 404, *m
, false);
343 _error
->DumpErrors(std::cerr
);
347 std::clog
<< "CLOSE client " << client
348 << " on socket " << sock
<< std::endl
;