]> git.saurik.com Git - apt.git/blob - test/interactive-helper/aptwebserver.cc
dbc4a19e0cf04540134361206f312cb633bb6b18
[apt.git] / test / interactive-helper / aptwebserver.cc
1 #include <config.h>
2
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>
9
10 #include <vector>
11 #include <string>
12 #include <list>
13 #include <sstream>
14
15 #include <sys/socket.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <netinet/in.h>
19 #include <unistd.h>
20 #include <errno.h>
21 #include <time.h>
22 #include <stdlib.h>
23 #include <dirent.h>
24 #include <signal.h>
25
26 char const * const httpcodeToStr(int const httpcode) { /*{{{*/
27 switch (httpcode) {
28 // Informational 1xx
29 case 100: return "100 Continue";
30 case 101: return "101 Switching Protocols";
31 // Successful 2xx
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";
39 // Redirections 3xx
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";
47 // Client errors 4xx
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";
66 // Server error 5xx
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";
73 }
74 return NULL;
75 }
76 /*}}}*/
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());
81
82 std::string lastmodified("Last-Modified: ");
83 lastmodified.append(TimeRFC1123(data.ModificationTime()));
84 headers.push_back(lastmodified);
85 }
86 /*}}}*/
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());
91 }
92 /*}}}*/
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);
97
98 headers.push_back("Server: APT webserver");
99
100 std::string date("Date: ");
101 date.append(TimeRFC1123(time(NULL)));
102 headers.push_back(date);
103
104 std::clog << ">>> RESPONSE >>>" << std::endl;
105 bool Success = true;
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());
109 if (Success == true)
110 Success &= FileFd::Write(client, "\r\n", 2);
111 std::clog << *h << std::endl;
112 }
113 if (Success == true)
114 Success &= FileFd::Write(client, "\r\n", 2);
115 std::clog << "<<<<<<<<<<<<<<<<" << std::endl;
116 return Success;
117 }
118 /*}}}*/
119 bool sendFile(int const client, FileFd &data) { /*{{{*/
120 bool Success = true;
121 char buffer[500];
122 unsigned long long actual = 0;
123 while ((Success &= data.Read(buffer, sizeof(buffer), &actual)) == true) {
124 if (actual == 0)
125 break;
126 Success &= FileFd::Write(client, buffer, actual);
127 }
128 if (Success == true)
129 Success &= FileFd::Write(client, "\r\n", 2);
130 return Success;
131 }
132 /*}}}*/
133 bool sendData(int const client, std::string const &data) { /*{{{*/
134 bool Success = true;
135 Success &= FileFd::Write(client, data.c_str(), data.size());
136 if (Success == true)
137 Success &= FileFd::Write(client, "\r\n", 2);
138 return Success;
139 }
140 /*}}}*/
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);
152 if (content == true)
153 sendData(client, response);
154 }
155 /*}}}*/
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);
168 else
169 location.append(uri);
170 headers.push_back(location);
171 sendHead(client, httpcode, headers);
172 if (content == true)
173 sendData(client, response);
174 }
175 /*}}}*/
176 // sendDirectoryLisiting /*{{{*/
177 int filter_hidden_files(const struct dirent *a) {
178 if (a->d_name[0] == '.')
179 return 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
185 a->d_type != DT_DIR)
186 return 0;
187 #endif
188 return 1;
189 }
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)
194 return -1;
195 else if ((*b)->d_type == DT_DIR && (*a)->d_type == DT_REG)
196 return 1;
197 else
198 #endif
199 {
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))
207 return -1;
208 else if (S_ISDIR(bmode))
209 return 1;
210 }
211 return strcasecmp((*a)->d_name, (*b)->d_name);
212 }
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;
216
217 struct dirent **namelist;
218 int const counter = scandir(dir.c_str(), &namelist, filter_hidden_files, grouped_alpha_case_sort);
219 if (counter == -1) {
220 sendError(client, 500, request, content);
221 return;
222 }
223
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;
232 if (dir != ".")
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) {
235 struct stat fs;
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>"
242 << "<td>-</td>";
243 } else {
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>";
247 }
248 listing << "<td>" << TimeRFC1123(fs.st_mtime) << "</td></tr>" << std::endl;
249 }
250 listing << "</table></body></html>" << std::endl;
251
252 std::string response(listing.str());
253 addDataHeaders(headers, response);
254 sendHead(client, 200, headers);
255 if (content == true)
256 sendData(client, response);
257 }
258 /*}}}*/
259 bool parseFirstLine(int const client, std::string const &request, std::string &filename, bool &sendContent) { /*{{{*/
260 if (strncmp(request.c_str(), "HEAD ", 5) == 0)
261 sendContent = false;
262 if (strncmp(request.c_str(), "GET ", 4) != 0)
263 {
264 sendError(client, 501, request, true);
265 return false;
266 }
267
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");
275 return false;
276 }
277
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");
282 return false;
283 }
284
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");
288 return false;
289 }
290 filename = DeQuoteString(filename);
291
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)");
298 return false;
299 }
300
301 // nuke the first character which is a / as we assured above
302 filename.erase(0, 1);
303 if (filename.empty() == true)
304 filename = ".";
305 return true;
306 }
307 /*}}}*/
308 int main(int const argc, const char * argv[])
309 {
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},
316 {0,0,0,0}
317 };
318
319 CommandLine CmdL(Args, _config);
320 if(CmdL.Parse(argc,argv) == false) {
321 _error->DumpErrors();
322 exit(1);
323 }
324
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);
329 if(sock < 0 ) {
330 _error->Errno("aptwerbserver", "Couldn't create socket");
331 _error->DumpErrors(std::cerr);
332 return 1;
333 }
334
335 // get the port
336 int const port = _config->FindI("aptwebserver::port", 8080);
337 bool const simulate_broken_server = _config->FindB("aptwebserver::Simulate-Paywall", false);
338
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));
345
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;
351
352 if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0) {
353 _error->Errno("aptwerbserver", "Couldn't bind");
354 _error->DumpErrors(std::cerr);
355 return 2;
356 }
357
358 if (simulate_broken_server) {
359 std::clog << "Simulating a broken web server that return nonsense "
360 "for all querries" << std::endl;
361 } else {
362 std::clog << "Serving ANY file on port: " << port << std::endl;
363 }
364
365 listen(sock, 1);
366 /*}}}*/
367
368 std::vector<std::string> messages;
369 int client;
370 while ((client = accept(sock, NULL, NULL)) != -1) {
371 std::clog << "ACCEPT client " << client
372 << " on socket " << sock << std::endl;
373
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;
379
380 std::list<std::string> headers;
381 std::string filename;
382 bool sendContent = true;
383 if (parseFirstLine(client, *m, filename, sendContent) == false)
384 continue;
385
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");
390 continue;
391 }
392
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);
398 }
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) {
403 time_t cache;
404 if (RFC1123StrToTime(condition.c_str(), cache) == true &&
405 cache >= data.ModificationTime()) {
406 sendHead(client, 304, headers);
407 continue;
408 }
409 }
410 addFileHeaders(headers, data);
411 sendHead(client, 200, headers);
412 if (sendContent == true)
413 sendFile(client, data);
414 }
415 else if (DirectoryExists(filename) == true) {
416 if (filename == "." || filename[filename.length()-1] == '/')
417 sendDirectoryListing(client, filename, *m, sendContent);
418 else
419 sendRedirect(client, 301, filename.append("/"), *m, sendContent);
420 }
421 else
422 {
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);
428 redirect.erase(0,1);
429 if (redirect != filename) {
430 sendRedirect(client, 301, redirect, *m, sendContent);
431 continue;
432 }
433 }
434 sendError(client, 404, *m, sendContent);
435 }
436 }
437 _error->DumpErrors(std::cerr);
438 messages.clear();
439 }
440
441 std::clog << "CLOSE client " << client
442 << " on socket " << sock << std::endl;
443 close(client);
444 }
445 return 0;
446 }