]> git.saurik.com Git - apt.git/blob - test/interactive-helper/aptwebserver.cc
2052fe6d865884df7276587e7fc6b8cb33aba16c
[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
25 char const * const httpcodeToStr(int const httpcode) { /*{{{*/
26 switch (httpcode) {
27 // Informational 1xx
28 case 100: return "100 Continue";
29 case 101: return "101 Switching Protocols";
30 // Successful 2xx
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";
38 // Redirections 3xx
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";
46 // Client errors 4xx
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";
65 // Server error 5xx
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";
72 }
73 return NULL;
74 }
75 /*}}}*/
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());
80
81 std::string lastmodified("Last-Modified: ");
82 lastmodified.append(TimeRFC1123(data.ModificationTime()));
83 headers.push_back(lastmodified);
84 }
85 /*}}}*/
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());
90 }
91 /*}}}*/
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);
96
97 headers.push_back("Server: APT webserver");
98
99 std::string date("Date: ");
100 date.append(TimeRFC1123(time(NULL)));
101 headers.push_back(date);
102
103 std::clog << ">>> RESPONSE >>>" << std::endl;
104 bool Success = true;
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;
110 }
111 Success &= FileFd::Write(client, "\r\n", 2);
112 std::clog << "<<<<<<<<<<<<<<<<" << std::endl;
113 return Success;
114 }
115 /*}}}*/
116 bool sendFile(int const client, FileFd &data) { /*{{{*/
117 bool Success = true;
118 char buffer[500];
119 unsigned long long actual = 0;
120 while ((Success &= data.Read(buffer, sizeof(buffer), &actual)) == true) {
121 if (actual == 0)
122 break;
123 Success &= FileFd::Write(client, buffer, actual);
124 }
125 Success &= FileFd::Write(client, "\r\n", 2);
126 return Success;
127 }
128 /*}}}*/
129 bool sendData(int const client, std::string const &data) { /*{{{*/
130 bool Success = true;
131 Success &= FileFd::Write(client, data.c_str(), data.size());
132 Success &= FileFd::Write(client, "\r\n", 2);
133 return Success;
134 }
135 /*}}}*/
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);
145 if (content == true)
146 sendData(client, response);
147 }
148 /*}}}*/
149 void sendRedirect(int const client, int const httpcode, std::string const &uri, std::string const &request, bool content) { /*{{{*/
150 std::list<std::string> headers;
151 std::string response("<html><head><title>");
152 response.append(httpcodeToStr(httpcode)).append("</title></head>");
153 response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1");
154 response.append("<p>You should be redirected to <em>").append(uri).append("</em></p>");
155 response.append("This page is a result of the request: <pre>");
156 response.append(request).append("</pre></body></html>");
157 addDataHeaders(headers, response);
158 std::string location("Location: ");
159 if (strncmp(uri.c_str(), "http://", 7) != 0)
160 location.append("http://").append(LookupTag(request, "Host")).append("/").append(uri);
161 else
162 location.append(uri);
163 headers.push_back(location);
164 sendHead(client, httpcode, headers);
165 if (content == true)
166 sendData(client, response);
167 }
168 /*}}}*/
169 // sendDirectoryLisiting /*{{{*/
170 int filter_hidden_files(const struct dirent *a) {
171 if (a->d_name[0] == '.')
172 return 0;
173 #ifdef _DIRENT_HAVE_D_TYPE
174 // if we have the d_type check that only files and dirs will be included
175 if (a->d_type != DT_UNKNOWN &&
176 a->d_type != DT_REG &&
177 a->d_type != DT_LNK && // this includes links to regular files
178 a->d_type != DT_DIR)
179 return 0;
180 #endif
181 return 1;
182 }
183 int grouped_alpha_case_sort(const struct dirent **a, const struct dirent **b) {
184 #ifdef _DIRENT_HAVE_D_TYPE
185 if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_DIR);
186 else if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_REG)
187 return -1;
188 else if ((*b)->d_type == DT_DIR && (*a)->d_type == DT_REG)
189 return 1;
190 else
191 #endif
192 {
193 struct stat f_prop; //File's property
194 stat((*a)->d_name, &f_prop);
195 int const amode = f_prop.st_mode;
196 stat((*b)->d_name, &f_prop);
197 int const bmode = f_prop.st_mode;
198 if (S_ISDIR(amode) && S_ISDIR(bmode));
199 else if (S_ISDIR(amode))
200 return -1;
201 else if (S_ISDIR(bmode))
202 return 1;
203 }
204 return strcasecmp((*a)->d_name, (*b)->d_name);
205 }
206 void sendDirectoryListing(int const client, std::string const &dir, std::string const &request, bool content) {
207 std::list<std::string> headers;
208 std::ostringstream listing;
209
210 struct dirent **namelist;
211 int const counter = scandir(dir.c_str(), &namelist, filter_hidden_files, grouped_alpha_case_sort);
212 if (counter == -1) {
213 sendError(client, 500, request, content);
214 return;
215 }
216
217 listing << "<html><head><title>Index of " << dir << "</title>"
218 << "<style type=\"text/css\"><!-- td {padding: 0.02em 0.5em 0.02em 0.5em;}"
219 << "tr:nth-child(even){background-color:#dfdfdf;}"
220 << "h1, td:nth-child(3){text-align:center;}"
221 << "table {margin-left:auto;margin-right:auto;} --></style>"
222 << "</head>" << std::endl
223 << "<body><h1>Index of " << dir << "</h1>" << std::endl
224 << "<table><tr><th>#</th><th>Name</th><th>Size</th><th>Last-Modified</th></tr>" << std::endl;
225 if (dir != ".")
226 listing << "<tr><td>d</td><td><a href=\"..\">Parent Directory</a></td><td>-</td><td>-</td></tr>";
227 for (int i = 0; i < counter; ++i) {
228 struct stat fs;
229 std::string filename(dir);
230 filename.append("/").append(namelist[i]->d_name);
231 stat(filename.c_str(), &fs);
232 if (S_ISDIR(fs.st_mode)) {
233 listing << "<tr><td>d</td>"
234 << "<td><a href=\"" << namelist[i]->d_name << "/\">" << namelist[i]->d_name << "</a></td>"
235 << "<td>-</td>";
236 } else {
237 listing << "<tr><td>f</td>"
238 << "<td><a href=\"" << namelist[i]->d_name << "\">" << namelist[i]->d_name << "</a></td>"
239 << "<td>" << SizeToStr(fs.st_size) << "B</td>";
240 }
241 listing << "<td>" << TimeRFC1123(fs.st_mtime) << "</td></tr>" << std::endl;
242 }
243 listing << "</table></body></html>" << std::endl;
244
245 std::string response(listing.str());
246 addDataHeaders(headers, response);
247 sendHead(client, 200, headers);
248 if (content == true)
249 sendData(client, response);
250 }
251 /*}}}*/
252 int main(int const argc, const char * argv[])
253 {
254 CommandLine::Args Args[] = {
255 {0, "simulate-paywall", "aptwebserver::Simulate-Paywall",
256 CommandLine::Boolean},
257 {0, "port", "aptwebserver::port", CommandLine::HasArg},
258 {0,0,0,0}
259 };
260
261 CommandLine CmdL(Args, _config);
262 if(CmdL.Parse(argc,argv) == false) {
263 _error->DumpErrors();
264 exit(1);
265 }
266
267 // create socket, bind and listen to it {{{
268 int sock = socket(AF_INET6, SOCK_STREAM, 0);
269 if(sock < 0 ) {
270 _error->Errno("aptwerbserver", "Couldn't create socket");
271 _error->DumpErrors(std::cerr);
272 return 1;
273 }
274
275 // get the port
276 int const port = _config->FindI("aptwebserver::port", 8080);
277 bool const simulate_broken_server = _config->FindB("aptwebserver::Simulate-Paywall", false);
278
279 // ensure that we accept all connections: v4 or v6
280 int const iponly = 0;
281 setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &iponly, sizeof(iponly));
282 // to not linger to an address
283 int const enable = 1;
284 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
285
286 struct sockaddr_in6 locAddr;
287 memset(&locAddr, 0, sizeof(locAddr));
288 locAddr.sin6_family = AF_INET6;
289 locAddr.sin6_port = htons(port);
290 locAddr.sin6_addr = in6addr_any;
291
292 if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0) {
293 _error->Errno("aptwerbserver", "Couldn't bind");
294 _error->DumpErrors(std::cerr);
295 return 2;
296 }
297
298 if (simulate_broken_server) {
299 std::clog << "Simulating a broken web server that return nonsense "
300 "for all querries" << std::endl;
301 } else {
302 std::clog << "Serving ANY file on port: " << port << std::endl;
303 }
304
305 listen(sock, 1);
306 /*}}}*/
307
308 std::vector<std::string> messages;
309 int client;
310 while ((client = accept(sock, NULL, NULL)) != -1) {
311 std::clog << "ACCEPT client " << client
312 << " on socket " << sock << std::endl;
313
314 while (ReadMessages(client, messages)) {
315 for (std::vector<std::string>::const_iterator m = messages.begin();
316 m != messages.end(); ++m) {
317 std::clog << ">>> REQUEST >>>>" << std::endl << *m
318 << std::endl << "<<<<<<<<<<<<<<<<" << std::endl;
319 std::list<std::string> headers;
320 bool sendContent = true;
321 if (strncmp(m->c_str(), "HEAD ", 5) == 0)
322 sendContent = false;
323 if (strncmp(m->c_str(), "GET ", 4) != 0)
324 sendError(client, 501, *m, true);
325
326 std::string host = LookupTag(*m, "Host", "");
327 if (host.empty() == true) {
328 // RFC 2616 ยง14.23 Host
329 sendError(client, 400, *m, sendContent);
330 continue;
331 }
332
333 size_t const filestart = m->find(' ', 5);
334 std::string filename = m->substr(5, filestart - 5);
335 if (filename.empty() == true)
336 filename = ".";
337 else
338 filename = DeQuoteString(filename);
339
340 if (simulate_broken_server == true) {
341 std::string data("ni ni ni\n");
342 addDataHeaders(headers, data);
343 sendHead(client, 200, headers);
344 sendData(client, data);
345 }
346 else if (RealFileExists(filename) == true) {
347 FileFd data(filename, FileFd::ReadOnly);
348 std::string condition = LookupTag(*m, "If-Modified-Since", "");
349 if (condition.empty() == false) {
350 time_t cache;
351 if (RFC1123StrToTime(condition.c_str(), cache) == true &&
352 cache >= data.ModificationTime()) {
353 sendHead(client, 304, headers);
354 continue;
355 }
356 }
357 addFileHeaders(headers, data);
358 sendHead(client, 200, headers);
359 if (sendContent == true)
360 sendFile(client, data);
361 }
362 else if (DirectoryExists(filename) == true) {
363 if (filename == "." || filename[filename.length()-1] == '/')
364 sendDirectoryListing(client, filename, *m, sendContent);
365 else
366 sendRedirect(client, 301, filename.append("/"), *m, sendContent);
367 }
368 else
369 sendError(client, 404, *m, false);
370 }
371 _error->DumpErrors(std::cerr);
372 messages.clear();
373 }
374
375 std::clog << "CLOSE client " << client
376 << " on socket " << sock << std::endl;
377 close(client);
378 }
379 return 0;
380 }