]> git.saurik.com Git - apt.git/blob - test/interactive-helper/aptwebserver.cc
4ef9631b8145446c3357fde34f4f3e1df38859d9
[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 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);
95 }
96 }
97 }
98 /*}}}*/
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());
103 }
104 /*}}}*/
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);
109
110 headers.push_back("Server: APT webserver");
111
112 std::string date("Date: ");
113 date.append(TimeRFC1123(time(NULL)));
114 headers.push_back(date);
115
116 std::clog << ">>> RESPONSE >>>" << std::endl;
117 bool Success = true;
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());
121 if (Success == true)
122 Success &= FileFd::Write(client, "\r\n", 2);
123 std::clog << *h << std::endl;
124 }
125 if (Success == true)
126 Success &= FileFd::Write(client, "\r\n", 2);
127 std::clog << "<<<<<<<<<<<<<<<<" << std::endl;
128 return Success;
129 }
130 /*}}}*/
131 bool sendFile(int const client, FileFd &data) { /*{{{*/
132 bool Success = true;
133 char buffer[500];
134 unsigned long long actual = 0;
135 while ((Success &= data.Read(buffer, sizeof(buffer), &actual)) == true) {
136 if (actual == 0)
137 break;
138 Success &= FileFd::Write(client, buffer, actual);
139 }
140 if (Success == true)
141 Success &= FileFd::Write(client, "\r\n", 2);
142 return Success;
143 }
144 /*}}}*/
145 bool sendData(int const client, std::string const &data) { /*{{{*/
146 bool Success = true;
147 Success &= FileFd::Write(client, data.c_str(), data.size());
148 if (Success == true)
149 Success &= FileFd::Write(client, "\r\n", 2);
150 return Success;
151 }
152 /*}}}*/
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);
164 if (content == true)
165 sendData(client, response);
166 }
167 /*}}}*/
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);
180 else
181 location.append(uri);
182 headers.push_back(location);
183 sendHead(client, httpcode, headers);
184 if (content == true)
185 sendData(client, response);
186 }
187 /*}}}*/
188 // sendDirectoryLisiting /*{{{*/
189 int filter_hidden_files(const struct dirent *a) {
190 if (a->d_name[0] == '.')
191 return 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
197 a->d_type != DT_DIR)
198 return 0;
199 #endif
200 return 1;
201 }
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)
206 return -1;
207 else if ((*b)->d_type == DT_DIR && (*a)->d_type == DT_REG)
208 return 1;
209 else
210 #endif
211 {
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))
219 return -1;
220 else if (S_ISDIR(bmode))
221 return 1;
222 }
223 return strcasecmp((*a)->d_name, (*b)->d_name);
224 }
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;
228
229 struct dirent **namelist;
230 int const counter = scandir(dir.c_str(), &namelist, filter_hidden_files, grouped_alpha_case_sort);
231 if (counter == -1) {
232 sendError(client, 500, request, content);
233 return;
234 }
235
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;
244 if (dir != ".")
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) {
247 struct stat fs;
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>"
254 << "<td>-</td>";
255 } else {
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>";
259 }
260 listing << "<td>" << TimeRFC1123(fs.st_mtime) << "</td></tr>" << std::endl;
261 }
262 listing << "</table></body></html>" << std::endl;
263
264 std::string response(listing.str());
265 addDataHeaders(headers, response);
266 sendHead(client, 200, headers);
267 if (content == true)
268 sendData(client, response);
269 }
270 /*}}}*/
271 bool parseFirstLine(int const client, std::string const &request, std::string &filename, bool &sendContent) { /*{{{*/
272 if (strncmp(request.c_str(), "HEAD ", 5) == 0)
273 sendContent = false;
274 if (strncmp(request.c_str(), "GET ", 4) != 0)
275 {
276 sendError(client, 501, request, true);
277 return false;
278 }
279
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");
287 return false;
288 }
289
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");
294 return false;
295 }
296
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");
300 return false;
301 }
302 filename = DeQuoteString(filename);
303
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)");
310 return false;
311 }
312
313 // nuke the first character which is a / as we assured above
314 filename.erase(0, 1);
315 if (filename.empty() == true)
316 filename = ".";
317 return true;
318 }
319 /*}}}*/
320 int main(int const argc, const char * argv[])
321 {
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},
328 {0,0,0,0}
329 };
330
331 CommandLine CmdL(Args, _config);
332 if(CmdL.Parse(argc,argv) == false) {
333 _error->DumpErrors();
334 exit(1);
335 }
336
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);
341 if(sock < 0 ) {
342 _error->Errno("aptwerbserver", "Couldn't create socket");
343 _error->DumpErrors(std::cerr);
344 return 1;
345 }
346
347 // get the port
348 int const port = _config->FindI("aptwebserver::port", 8080);
349 bool const simulate_broken_server = _config->FindB("aptwebserver::Simulate-Paywall", false);
350
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));
357
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;
363
364 if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0) {
365 _error->Errno("aptwerbserver", "Couldn't bind");
366 _error->DumpErrors(std::cerr);
367 return 2;
368 }
369
370 if (simulate_broken_server) {
371 std::clog << "Simulating a broken web server that return nonsense "
372 "for all querries" << std::endl;
373 } else {
374 std::clog << "Serving ANY file on port: " << port << std::endl;
375 }
376
377 listen(sock, 1);
378 /*}}}*/
379
380 std::vector<std::string> messages;
381 int client;
382 while ((client = accept(sock, NULL, NULL)) != -1) {
383 std::clog << "ACCEPT client " << client
384 << " on socket " << sock << std::endl;
385
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;
391
392 std::list<std::string> headers;
393 std::string filename;
394 bool sendContent = true;
395 if (parseFirstLine(client, *m, filename, sendContent) == false)
396 continue;
397
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");
402 continue;
403 }
404
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);
410 }
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) {
415 time_t cache;
416 if (RFC1123StrToTime(condition.c_str(), cache) == true &&
417 cache >= data.ModificationTime()) {
418 sendHead(client, 304, headers);
419 continue;
420 }
421 }
422 addFileHeaders(headers, data);
423 sendHead(client, 200, headers);
424 if (sendContent == true)
425 sendFile(client, data);
426 }
427 else if (DirectoryExists(filename) == true) {
428 if (filename == "." || filename[filename.length()-1] == '/')
429 sendDirectoryListing(client, filename, *m, sendContent);
430 else
431 sendRedirect(client, 301, filename.append("/"), *m, sendContent);
432 }
433 else
434 {
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);
440 redirect.erase(0,1);
441 if (redirect != filename) {
442 sendRedirect(client, 301, redirect, *m, sendContent);
443 continue;
444 }
445 }
446 sendError(client, 404, *m, sendContent);
447 }
448 }
449 _error->DumpErrors(std::cerr);
450 messages.clear();
451 }
452
453 std::clog << "CLOSE client " << client
454 << " on socket " << sock << std::endl;
455 close(client);
456 }
457 return 0;
458 }