]> git.saurik.com Git - apt.git/blame - test/interactive-helper/aptwebserver.cc
pass versioned provides to external solvers in EDSP
[apt.git] / test / interactive-helper / aptwebserver.cc
CommitLineData
fbd29dd6
DK
1#include <config.h>
2
fbd29dd6
DK
3#include <apt-pkg/cmndline.h>
4#include <apt-pkg/configuration.h>
453b82a3
DK
5#include <apt-pkg/error.h>
6#include <apt-pkg/fileutl.h>
7#include <apt-pkg/strutl.h>
fbd29dd6 8
453b82a3
DK
9#include <dirent.h>
10#include <errno.h>
11#include <netinet/in.h>
12#include <pthread.h>
13#include <regex.h>
14#include <signal.h>
15#include <stddef.h>
16#include <stdlib.h>
17#include <string.h>
fbd29dd6
DK
18#include <sys/socket.h>
19#include <sys/stat.h>
fbd29dd6 20#include <time.h>
453b82a3 21#include <unistd.h>
ed793a19
DK
22
23#include <algorithm>
453b82a3
DK
24#include <iostream>
25#include <sstream>
26#include <list>
27#include <string>
28#include <vector>
fbd29dd6 29
905fba60 30static std::string httpcodeToStr(int const httpcode) /*{{{*/
fbd29dd6
DK
31{
32 switch (httpcode)
33 {
34 // Informational 1xx
905fba60
DK
35 case 100: return _config->Find("aptwebserver::httpcode::100", "100 Continue");
36 case 101: return _config->Find("aptwebserver::httpcode::101", "101 Switching Protocols");
fbd29dd6 37 // Successful 2xx
905fba60
DK
38 case 200: return _config->Find("aptwebserver::httpcode::200", "200 OK");
39 case 201: return _config->Find("aptwebserver::httpcode::201", "201 Created");
40 case 202: return _config->Find("aptwebserver::httpcode::202", "202 Accepted");
41 case 203: return _config->Find("aptwebserver::httpcode::203", "203 Non-Authoritative Information");
42 case 204: return _config->Find("aptwebserver::httpcode::204", "204 No Content");
43 case 205: return _config->Find("aptwebserver::httpcode::205", "205 Reset Content");
44 case 206: return _config->Find("aptwebserver::httpcode::206", "206 Partial Content");
fbd29dd6 45 // Redirections 3xx
905fba60
DK
46 case 300: return _config->Find("aptwebserver::httpcode::300", "300 Multiple Choices");
47 case 301: return _config->Find("aptwebserver::httpcode::301", "301 Moved Permanently");
48 case 302: return _config->Find("aptwebserver::httpcode::302", "302 Found");
49 case 303: return _config->Find("aptwebserver::httpcode::303", "303 See Other");
50 case 304: return _config->Find("aptwebserver::httpcode::304", "304 Not Modified");
51 case 305: return _config->Find("aptwebserver::httpcode::305", "305 Use Proxy");
52 case 307: return _config->Find("aptwebserver::httpcode::307", "307 Temporary Redirect");
fbd29dd6 53 // Client errors 4xx
905fba60
DK
54 case 400: return _config->Find("aptwebserver::httpcode::400", "400 Bad Request");
55 case 401: return _config->Find("aptwebserver::httpcode::401", "401 Unauthorized");
56 case 402: return _config->Find("aptwebserver::httpcode::402", "402 Payment Required");
57 case 403: return _config->Find("aptwebserver::httpcode::403", "403 Forbidden");
58 case 404: return _config->Find("aptwebserver::httpcode::404", "404 Not Found");
59 case 405: return _config->Find("aptwebserver::httpcode::405", "405 Method Not Allowed");
60 case 406: return _config->Find("aptwebserver::httpcode::406", "406 Not Acceptable");
61 case 407: return _config->Find("aptwebserver::httpcode::407", "407 Proxy Authentication Required");
62 case 408: return _config->Find("aptwebserver::httpcode::408", "408 Request Time-out");
63 case 409: return _config->Find("aptwebserver::httpcode::409", "409 Conflict");
64 case 410: return _config->Find("aptwebserver::httpcode::410", "410 Gone");
65 case 411: return _config->Find("aptwebserver::httpcode::411", "411 Length Required");
66 case 412: return _config->Find("aptwebserver::httpcode::412", "412 Precondition Failed");
67 case 413: return _config->Find("aptwebserver::httpcode::413", "413 Request Entity Too Large");
68 case 414: return _config->Find("aptwebserver::httpcode::414", "414 Request-URI Too Large");
69 case 415: return _config->Find("aptwebserver::httpcode::415", "415 Unsupported Media Type");
70 case 416: return _config->Find("aptwebserver::httpcode::416", "416 Requested range not satisfiable");
71 case 417: return _config->Find("aptwebserver::httpcode::417", "417 Expectation Failed");
72 case 418: return _config->Find("aptwebserver::httpcode::418", "418 I'm a teapot");
fbd29dd6 73 // Server error 5xx
905fba60
DK
74 case 500: return _config->Find("aptwebserver::httpcode::500", "500 Internal Server Error");
75 case 501: return _config->Find("aptwebserver::httpcode::501", "501 Not Implemented");
76 case 502: return _config->Find("aptwebserver::httpcode::502", "502 Bad Gateway");
77 case 503: return _config->Find("aptwebserver::httpcode::503", "503 Service Unavailable");
78 case 504: return _config->Find("aptwebserver::httpcode::504", "504 Gateway Time-out");
79 case 505: return _config->Find("aptwebserver::httpcode::505", "505 HTTP Version not supported");
fbd29dd6 80 }
905fba60 81 return "";
fbd29dd6
DK
82}
83 /*}}}*/
ed793a19
DK
84static bool chunkedTransferEncoding(std::list<std::string> const &headers) {
85 if (std::find(headers.begin(), headers.end(), "Transfer-Encoding: chunked") != headers.end())
86 return true;
87 if (_config->FindB("aptwebserver::chunked-transfer-encoding", false) == true)
88 return true;
89 return false;
90}
c3ccac92 91static void addFileHeaders(std::list<std::string> &headers, FileFd &data)/*{{{*/
fbd29dd6 92{
ed793a19
DK
93 if (chunkedTransferEncoding(headers) == false)
94 {
95 std::ostringstream contentlength;
96 contentlength << "Content-Length: " << data.FileSize();
97 headers.push_back(contentlength.str());
98 }
ba6b79bd
DK
99 if (_config->FindB("aptwebserver::support::last-modified", true) == true)
100 {
101 std::string lastmodified("Last-Modified: ");
102 lastmodified.append(TimeRFC1123(data.ModificationTime()));
103 headers.push_back(lastmodified);
104 }
fbd29dd6
DK
105}
106 /*}}}*/
c3ccac92 107static void addDataHeaders(std::list<std::string> &headers, std::string &data)/*{{{*/
fbd29dd6 108{
ed793a19
DK
109 if (chunkedTransferEncoding(headers) == false)
110 {
111 std::ostringstream contentlength;
112 contentlength << "Content-Length: " << data.size();
113 headers.push_back(contentlength.str());
114 }
fbd29dd6
DK
115}
116 /*}}}*/
c3ccac92 117static bool sendHead(int const client, int const httpcode, std::list<std::string> &headers)/*{{{*/
fbd29dd6
DK
118{
119 std::string response("HTTP/1.1 ");
120 response.append(httpcodeToStr(httpcode));
121 headers.push_front(response);
14c84d02 122 _config->Set("APTWebserver::Last-Status-Code", httpcode);
fbd29dd6 123
14c84d02
DK
124 std::stringstream buffer;
125 _config->Dump(buffer, "aptwebserver::response-header", "%t: %v%n", false);
126 std::vector<std::string> addheaders = VectorizeString(buffer.str(), '\n');
127 for (std::vector<std::string>::const_iterator h = addheaders.begin(); h != addheaders.end(); ++h)
128 headers.push_back(*h);
fbd29dd6
DK
129
130 std::string date("Date: ");
131 date.append(TimeRFC1123(time(NULL)));
132 headers.push_back(date);
133
ed793a19
DK
134 if (chunkedTransferEncoding(headers) == true)
135 headers.push_back("Transfer-Encoding: chunked");
136
575fe03e 137 std::clog << ">>> RESPONSE to " << client << " >>>" << std::endl;
fbd29dd6
DK
138 bool Success = true;
139 for (std::list<std::string>::const_iterator h = headers.begin();
140 Success == true && h != headers.end(); ++h)
141 {
142 Success &= FileFd::Write(client, h->c_str(), h->size());
143 if (Success == true)
144 Success &= FileFd::Write(client, "\r\n", 2);
145 std::clog << *h << std::endl;
146 }
147 if (Success == true)
148 Success &= FileFd::Write(client, "\r\n", 2);
149 std::clog << "<<<<<<<<<<<<<<<<" << std::endl;
150 return Success;
151}
152 /*}}}*/
ed793a19 153static bool sendFile(int const client, std::list<std::string> const &headers, FileFd &data)/*{{{*/
fbd29dd6
DK
154{
155 bool Success = true;
ed793a19 156 bool const chunked = chunkedTransferEncoding(headers);
fbd29dd6
DK
157 char buffer[500];
158 unsigned long long actual = 0;
159 while ((Success &= data.Read(buffer, sizeof(buffer), &actual)) == true)
160 {
161 if (actual == 0)
162 break;
ed793a19
DK
163
164 if (chunked == true)
165 {
166 std::string size;
167 strprintf(size, "%llX\r\n", actual);
168 Success &= FileFd::Write(client, size.c_str(), size.size());
169 Success &= FileFd::Write(client, buffer, actual);
170 Success &= FileFd::Write(client, "\r\n", strlen("\r\n"));
171 }
172 else
173 Success &= FileFd::Write(client, buffer, actual);
174 }
175 if (chunked == true)
176 {
177 char const * const finish = "0\r\n\r\n";
178 Success &= FileFd::Write(client, finish, strlen(finish));
fbd29dd6 179 }
93a99dac 180 if (Success == false)
ed793a19 181 std::cerr << "SENDFILE:" << (chunked ? " CHUNKED" : "") << " READ/WRITE ERROR to " << client << std::endl;
fbd29dd6
DK
182 return Success;
183}
184 /*}}}*/
ed793a19 185static bool sendData(int const client, std::list<std::string> const &headers, std::string const &data)/*{{{*/
fbd29dd6 186{
ed793a19
DK
187 if (chunkedTransferEncoding(headers) == true)
188 {
189 unsigned long long const ullsize = data.length();
190 std::string size;
191 strprintf(size, "%llX\r\n", ullsize);
192 char const * const finish = "\r\n0\r\n\r\n";
193 if (FileFd::Write(client, size.c_str(), size.length()) == false ||
194 FileFd::Write(client, data.c_str(), ullsize) == false ||
195 FileFd::Write(client, finish, strlen(finish)) == false)
196 {
197 std::cerr << "SENDDATA: CHUNK WRITE ERROR to " << client << std::endl;
198 return false;
199 }
200 }
201 else if (FileFd::Write(client, data.c_str(), data.size()) == false)
93a99dac
DK
202 {
203 std::cerr << "SENDDATA: WRITE ERROR to " << client << std::endl;
204 return false;
205 }
206 return true;
fbd29dd6
DK
207}
208 /*}}}*/
c3ccac92 209static void sendError(int const client, int const httpcode, std::string const &request,/*{{{*/
ed793a19 210 bool const content, std::string const &error, std::list<std::string> &headers)
fbd29dd6 211{
fbd29dd6
DK
212 std::string response("<html><head><title>");
213 response.append(httpcodeToStr(httpcode)).append("</title></head>");
214 response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1>");
6beca0eb 215 if (httpcode != 200)
ed793a19
DK
216 response.append("<p><em>Error</em>: ");
217 else
218 response.append("<p><em>Success</em>: ");
219 if (error.empty() == false)
220 response.append(error);
221 else
222 response.append(httpcodeToStr(httpcode));
223 if (httpcode != 200)
224 response.append("</p>This error is a result of the request: <pre>");
6beca0eb 225 else
6beca0eb 226 response.append("The successfully executed operation was requested by: <pre>");
fbd29dd6 227 response.append(request).append("</pre></body></html>");
ed793a19
DK
228 if (httpcode != 200)
229 {
230 if (_config->FindB("aptwebserver::closeOnError", false) == true)
231 headers.push_back("Connection: close");
232 }
fbd29dd6
DK
233 addDataHeaders(headers, response);
234 sendHead(client, httpcode, headers);
235 if (content == true)
ed793a19 236 sendData(client, headers, response);
6beca0eb 237}
c3ccac92 238static void sendSuccess(int const client, std::string const &request,
ed793a19 239 bool const content, std::string const &error, std::list<std::string> &headers)
6beca0eb 240{
ed793a19 241 sendError(client, 200, request, content, error, headers);
fbd29dd6
DK
242}
243 /*}}}*/
c3ccac92 244static void sendRedirect(int const client, int const httpcode, std::string const &uri,/*{{{*/
bf3daa15
DK
245 std::string const &request, bool content)
246{
247 std::list<std::string> headers;
248 std::string response("<html><head><title>");
249 response.append(httpcodeToStr(httpcode)).append("</title></head>");
250 response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1");
251 response.append("<p>You should be redirected to <em>").append(uri).append("</em></p>");
252 response.append("This page is a result of the request: <pre>");
253 response.append(request).append("</pre></body></html>");
254 addDataHeaders(headers, response);
255 std::string location("Location: ");
f9b4f12d 256 if (strncmp(uri.c_str(), "http://", 7) != 0 && strncmp(uri.c_str(), "https://", 8) != 0)
eab3a9b2 257 {
f9b4f12d 258 std::string const host = LookupTag(request, "Host");
6c0765c0
DK
259 unsigned int const httpsport = _config->FindI("aptwebserver::port::https", 4433);
260 std::string hosthttpsport;
261 strprintf(hosthttpsport, ":%u", httpsport);
262 if (host.find(hosthttpsport) != std::string::npos)
f9b4f12d
DK
263 location.append("https://");
264 else
265 location.append("http://");
266 location.append(host).append("/");
eab3a9b2
DK
267 if (strncmp("/home/", uri.c_str(), strlen("/home/")) == 0 && uri.find("/public_html/") != std::string::npos)
268 {
269 std::string homeuri = SubstVar(uri, "/home/", "~");
270 homeuri = SubstVar(homeuri, "/public_html/", "/");
271 location.append(homeuri);
272 }
273 else
274 location.append(uri);
275 }
bf3daa15
DK
276 else
277 location.append(uri);
278 headers.push_back(location);
279 sendHead(client, httpcode, headers);
280 if (content == true)
ed793a19 281 sendData(client, headers, response);
bf3daa15
DK
282}
283 /*}}}*/
c3ccac92 284static int filter_hidden_files(const struct dirent *a) /*{{{*/
bf3daa15
DK
285{
286 if (a->d_name[0] == '.')
287 return 0;
288#ifdef _DIRENT_HAVE_D_TYPE
289 // if we have the d_type check that only files and dirs will be included
290 if (a->d_type != DT_UNKNOWN &&
291 a->d_type != DT_REG &&
292 a->d_type != DT_LNK && // this includes links to regular files
293 a->d_type != DT_DIR)
294 return 0;
295#endif
296 return 1;
297}
c3ccac92 298static int grouped_alpha_case_sort(const struct dirent **a, const struct dirent **b) {
bf3daa15
DK
299#ifdef _DIRENT_HAVE_D_TYPE
300 if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_DIR);
301 else if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_REG)
302 return -1;
303 else if ((*b)->d_type == DT_DIR && (*a)->d_type == DT_REG)
304 return 1;
305 else
306#endif
307 {
308 struct stat f_prop; //File's property
309 stat((*a)->d_name, &f_prop);
310 int const amode = f_prop.st_mode;
311 stat((*b)->d_name, &f_prop);
312 int const bmode = f_prop.st_mode;
313 if (S_ISDIR(amode) && S_ISDIR(bmode));
314 else if (S_ISDIR(amode))
315 return -1;
316 else if (S_ISDIR(bmode))
317 return 1;
318 }
319 return strcasecmp((*a)->d_name, (*b)->d_name);
320}
321 /*}}}*/
c3ccac92 322static void sendDirectoryListing(int const client, std::string const &dir,/*{{{*/
ed793a19 323 std::string const &request, bool content, std::list<std::string> &headers)
bf3daa15 324{
bf3daa15
DK
325 std::ostringstream listing;
326
327 struct dirent **namelist;
328 int const counter = scandir(dir.c_str(), &namelist, filter_hidden_files, grouped_alpha_case_sort);
329 if (counter == -1)
330 {
ed793a19 331 sendError(client, 500, request, content, "scandir failed", headers);
bf3daa15
DK
332 return;
333 }
334
335 listing << "<html><head><title>Index of " << dir << "</title>"
336 << "<style type=\"text/css\"><!-- td {padding: 0.02em 0.5em 0.02em 0.5em;}"
337 << "tr:nth-child(even){background-color:#dfdfdf;}"
338 << "h1, td:nth-child(3){text-align:center;}"
339 << "table {margin-left:auto;margin-right:auto;} --></style>"
340 << "</head>" << std::endl
341 << "<body><h1>Index of " << dir << "</h1>" << std::endl
342 << "<table><tr><th>#</th><th>Name</th><th>Size</th><th>Last-Modified</th></tr>" << std::endl;
3c16b5fe 343 if (dir != "./")
bf3daa15
DK
344 listing << "<tr><td>d</td><td><a href=\"..\">Parent Directory</a></td><td>-</td><td>-</td></tr>";
345 for (int i = 0; i < counter; ++i) {
346 struct stat fs;
347 std::string filename(dir);
348 filename.append("/").append(namelist[i]->d_name);
349 stat(filename.c_str(), &fs);
350 if (S_ISDIR(fs.st_mode))
351 {
352 listing << "<tr><td>d</td>"
353 << "<td><a href=\"" << namelist[i]->d_name << "/\">" << namelist[i]->d_name << "</a></td>"
354 << "<td>-</td>";
355 }
356 else
357 {
358 listing << "<tr><td>f</td>"
359 << "<td><a href=\"" << namelist[i]->d_name << "\">" << namelist[i]->d_name << "</a></td>"
360 << "<td>" << SizeToStr(fs.st_size) << "B</td>";
361 }
362 listing << "<td>" << TimeRFC1123(fs.st_mtime) << "</td></tr>" << std::endl;
363 }
364 listing << "</table></body></html>" << std::endl;
365
366 std::string response(listing.str());
367 addDataHeaders(headers, response);
368 sendHead(client, 200, headers);
369 if (content == true)
ed793a19 370 sendData(client, headers, response);
bf3daa15
DK
371}
372 /*}}}*/
c3ccac92 373static bool parseFirstLine(int const client, std::string const &request,/*{{{*/
d23bda42 374 std::string &filename, std::string &params, bool &sendContent,
ed793a19 375 bool &closeConnection, std::list<std::string> &headers)
fbd29dd6
DK
376{
377 if (strncmp(request.c_str(), "HEAD ", 5) == 0)
378 sendContent = false;
379 if (strncmp(request.c_str(), "GET ", 4) != 0)
380 {
ed793a19 381 sendError(client, 501, request, true, "", headers);
fbd29dd6
DK
382 return false;
383 }
384
385 size_t const lineend = request.find('\n');
386 size_t filestart = request.find(' ');
387 for (; request[filestart] == ' '; ++filestart);
388 size_t fileend = request.rfind(' ', lineend);
389 if (lineend == std::string::npos || filestart == std::string::npos ||
390 fileend == std::string::npos || filestart == fileend)
391 {
ed793a19 392 sendError(client, 500, request, sendContent, "Filename can't be extracted", headers);
fbd29dd6
DK
393 return false;
394 }
395
396 size_t httpstart = fileend;
397 for (; request[httpstart] == ' '; ++httpstart);
398 if (strncmp(request.c_str() + httpstart, "HTTP/1.1\r", 9) == 0)
399 closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "Keep-Alive") != 0;
400 else if (strncmp(request.c_str() + httpstart, "HTTP/1.0\r", 9) == 0)
401 closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "close") == 0;
402 else
403 {
ed793a19 404 sendError(client, 500, request, sendContent, "Not a HTTP/1.{0,1} request", headers);
fbd29dd6
DK
405 return false;
406 }
407
408 filename = request.substr(filestart, fileend - filestart);
409 if (filename.find(' ') != std::string::npos)
410 {
ed793a19 411 sendError(client, 500, request, sendContent, "Filename contains an unencoded space", headers);
fbd29dd6
DK
412 return false;
413 }
f2380a78
DK
414
415 std::string host = LookupTag(request, "Host", "");
416 if (host.empty() == true)
417 {
418 // RFC 2616 §14.23 requires Host
ed793a19 419 sendError(client, 400, request, sendContent, "Host header is required", headers);
f2380a78
DK
420 return false;
421 }
422 host = "http://" + host;
423
424 // Proxies require absolute uris, so this is a simple proxy-fake option
425 std::string const absolute = _config->Find("aptwebserver::request::absolute", "uri,path");
b0314abb 426 if (strncmp(host.c_str(), filename.c_str(), host.length()) == 0 && APT::String::Startswith(filename, "/_config/") == false)
f2380a78
DK
427 {
428 if (absolute.find("uri") == std::string::npos)
429 {
ed793a19 430 sendError(client, 400, request, sendContent, "Request is absoluteURI, but configured to not accept that", headers);
f2380a78
DK
431 return false;
432 }
b0314abb 433
f2380a78
DK
434 // strip the host from the request to make it an absolute path
435 filename.erase(0, host.length());
b0314abb
DK
436
437 std::string const authConf = _config->Find("aptwebserver::proxy-authorization", "");
438 std::string auth = LookupTag(request, "Proxy-Authorization", "");
439 if (authConf.empty() != auth.empty())
440 {
441 if (auth.empty())
ed793a19 442 sendError(client, 407, request, sendContent, "Proxy requires authentication", headers);
b0314abb 443 else
ed793a19 444 sendError(client, 407, request, sendContent, "Client wants to authenticate to proxy, but proxy doesn't need it", headers);
b0314abb
DK
445 return false;
446 }
447 if (authConf.empty() == false)
448 {
449 char const * const basic = "Basic ";
450 if (strncmp(auth.c_str(), basic, strlen(basic)) == 0)
451 {
452 auth.erase(0, strlen(basic));
453 if (auth != authConf)
454 {
ed793a19 455 sendError(client, 407, request, sendContent, "Proxy-Authentication doesn't match", headers);
b0314abb
DK
456 return false;
457 }
458 }
459 else
460 {
461 std::list<std::string> headers;
462 headers.push_back("Proxy-Authenticate: Basic");
463 sendError(client, 407, request, sendContent, "Unsupported Proxy-Authentication Scheme", headers);
464 return false;
465 }
466 }
f2380a78 467 }
b0314abb 468 else if (absolute.find("path") == std::string::npos && APT::String::Startswith(filename, "/_config/") == false)
f2380a78 469 {
ed793a19 470 sendError(client, 400, request, sendContent, "Request is absolutePath, but configured to not accept that", headers);
f2380a78
DK
471 return false;
472 }
d23bda42 473
b0314abb
DK
474 if (APT::String::Startswith(filename, "/_config/") == false)
475 {
476 std::string const authConf = _config->Find("aptwebserver::authorization", "");
477 std::string auth = LookupTag(request, "Authorization", "");
478 if (authConf.empty() != auth.empty())
479 {
480 if (auth.empty())
ed793a19 481 sendError(client, 401, request, sendContent, "Server requires authentication", headers);
b0314abb 482 else
ed793a19 483 sendError(client, 401, request, sendContent, "Client wants to authenticate to server, but server doesn't need it", headers);
b0314abb
DK
484 return false;
485 }
486 if (authConf.empty() == false)
487 {
488 char const * const basic = "Basic ";
489 if (strncmp(auth.c_str(), basic, strlen(basic)) == 0)
490 {
491 auth.erase(0, strlen(basic));
492 if (auth != authConf)
493 {
ed793a19 494 sendError(client, 401, request, sendContent, "Authentication doesn't match", headers);
b0314abb
DK
495 return false;
496 }
497 }
498 else
499 {
b0314abb
DK
500 headers.push_back("WWW-Authenticate: Basic");
501 sendError(client, 401, request, sendContent, "Unsupported Authentication Scheme", headers);
502 return false;
503 }
504 }
505 }
506
d23bda42
DK
507 size_t paramspos = filename.find('?');
508 if (paramspos != std::string::npos)
509 {
510 params = filename.substr(paramspos + 1);
511 filename.erase(paramspos);
512 }
513
fbd29dd6
DK
514 filename = DeQuoteString(filename);
515
516 // this is not a secure server, but at least prevent the obvious …
517 if (filename.empty() == true || filename[0] != '/' ||
518 strncmp(filename.c_str(), "//", 2) == 0 ||
519 filename.find_first_of("\r\n\t\f\v") != std::string::npos ||
520 filename.find("/../") != std::string::npos)
521 {
ed793a19
DK
522 std::list<std::string> headers;
523 sendError(client, 400, request, sendContent, "Filename contains illegal character (sequence)", headers);
fbd29dd6
DK
524 return false;
525 }
526
527 // nuke the first character which is a / as we assured above
528 filename.erase(0, 1);
529 if (filename.empty() == true)
3c16b5fe 530 filename = "./";
eab3a9b2
DK
531 // support ~user/ uris to refer to /home/user/public_html/ as a kind-of special directory
532 else if (filename[0] == '~')
533 {
534 // /home/user is actually not entirely correct, but good enough for now
535 size_t dashpos = filename.find('/');
536 if (dashpos != std::string::npos)
537 {
538 std::string home = filename.substr(1, filename.find('/') - 1);
539 std::string pubhtml = filename.substr(filename.find('/') + 1);
540 filename = "/home/" + home + "/public_html/" + pubhtml;
541 }
542 else
543 filename = "/home/" + filename.substr(1) + "/public_html/";
544 }
3c16b5fe
DK
545
546 // if no filename is given, but a valid directory see if we can use an index or
547 // have to resort to a autogenerated directory listing later on
548 if (DirectoryExists(filename) == true)
549 {
550 std::string const directoryIndex = _config->Find("aptwebserver::directoryindex");
551 if (directoryIndex.empty() == false && directoryIndex == flNotDir(directoryIndex) &&
552 RealFileExists(filename + directoryIndex) == true)
553 filename += directoryIndex;
554 }
555
fbd29dd6
DK
556 return true;
557}
558 /*}}}*/
ed793a19
DK
559static bool handleOnTheFlyReconfiguration(int const client, std::string const &request,/*{{{*/
560 std::vector<std::string> parts, std::list<std::string> &headers)
6beca0eb
DK
561{
562 size_t const pcount = parts.size();
23397c9d
DK
563 for (size_t i = 0; i < pcount; ++i)
564 parts[i] = DeQuoteString(parts[i]);
6beca0eb
DK
565 if (pcount == 4 && parts[1] == "set")
566 {
567 _config->Set(parts[2], parts[3]);
ed793a19 568 sendSuccess(client, request, true, "Option '" + parts[2] + "' was set to '" + parts[3] + "'!", headers);
6beca0eb
DK
569 return true;
570 }
571 else if (pcount == 4 && parts[1] == "find")
572 {
6beca0eb
DK
573 std::string response = _config->Find(parts[2], parts[3]);
574 addDataHeaders(headers, response);
575 sendHead(client, 200, headers);
ed793a19 576 sendData(client, headers, response);
6beca0eb
DK
577 return true;
578 }
579 else if (pcount == 3 && parts[1] == "find")
580 {
6beca0eb
DK
581 if (_config->Exists(parts[2]) == true)
582 {
583 std::string response = _config->Find(parts[2]);
584 addDataHeaders(headers, response);
585 sendHead(client, 200, headers);
ed793a19 586 sendData(client, headers, response);
6beca0eb
DK
587 return true;
588 }
ed793a19 589 sendError(client, 404, request, true, "Requested Configuration option doesn't exist", headers);
6beca0eb
DK
590 return false;
591 }
592 else if (pcount == 3 && parts[1] == "clear")
593 {
594 _config->Clear(parts[2]);
ed793a19 595 sendSuccess(client, request, true, "Option '" + parts[2] + "' was cleared.", headers);
6beca0eb
DK
596 return true;
597 }
598
ed793a19 599 sendError(client, 400, request, true, "Unknown on-the-fly configuration request", headers);
6beca0eb
DK
600 return false;
601}
602 /*}}}*/
c3ccac92 603static void * handleClient(void * voidclient) /*{{{*/
575fe03e
DK
604{
605 int client = *((int*)(voidclient));
606 std::clog << "ACCEPT client " << client << std::endl;
ed793a19 607 bool closeConnection = false;
117038ba 608 while (closeConnection == false)
575fe03e 609 {
117038ba
DK
610 std::vector<std::string> messages;
611 if (ReadMessages(client, messages) == false)
ed793a19 612 break;
117038ba
DK
613
614 std::list<std::string> headers;
575fe03e
DK
615 for (std::vector<std::string>::const_iterator m = messages.begin();
616 m != messages.end() && closeConnection == false; ++m) {
117038ba
DK
617 // if we announced a closing in previous response, do the close now
618 if (std::find(headers.begin(), headers.end(), std::string("Connection: close")) != headers.end())
619 {
620 closeConnection = true;
621 break;
622 }
623 headers.clear();
624
575fe03e
DK
625 std::clog << ">>> REQUEST from " << client << " >>>" << std::endl << *m
626 << std::endl << "<<<<<<<<<<<<<<<<" << std::endl;
575fe03e
DK
627 std::string filename;
628 std::string params;
629 bool sendContent = true;
ed793a19 630 if (parseFirstLine(client, *m, filename, params, sendContent, closeConnection, headers) == false)
575fe03e
DK
631 continue;
632
633 // special webserver command request
634 if (filename.length() > 1 && filename[0] == '_')
635 {
636 std::vector<std::string> parts = VectorizeString(filename, '/');
637 if (parts[0] == "_config")
638 {
ed793a19 639 handleOnTheFlyReconfiguration(client, *m, parts, headers);
575fe03e
DK
640 continue;
641 }
642 }
643
644 // string replacements in the requested filename
645 ::Configuration::Item const *Replaces = _config->Tree("aptwebserver::redirect::replace");
646 if (Replaces != NULL)
647 {
648 std::string redirect = "/" + filename;
649 for (::Configuration::Item *I = Replaces->Child; I != NULL; I = I->Next)
650 redirect = SubstVar(redirect, I->Tag, I->Value);
f9b4f12d
DK
651 if (redirect.empty() == false && redirect[0] == '/')
652 redirect.erase(0,1);
575fe03e
DK
653 if (redirect != filename)
654 {
aa3e7b32 655 sendRedirect(client, _config->FindI("aptwebserver::redirect::httpcode", 301), redirect, *m, sendContent);
575fe03e
DK
656 continue;
657 }
658 }
659
660 ::Configuration::Item const *Overwrite = _config->Tree("aptwebserver::overwrite");
661 if (Overwrite != NULL)
662 {
663 for (::Configuration::Item *I = Overwrite->Child; I != NULL; I = I->Next)
664 {
665 regex_t *pattern = new regex_t;
666 int const res = regcomp(pattern, I->Tag.c_str(), REG_EXTENDED | REG_ICASE | REG_NOSUB);
667 if (res != 0)
668 {
669 char error[300];
670 regerror(res, pattern, error, sizeof(error));
ed793a19 671 sendError(client, 500, *m, sendContent, error, headers);
575fe03e
DK
672 continue;
673 }
674 if (regexec(pattern, filename.c_str(), 0, 0, 0) == 0)
675 {
676 filename = _config->Find("aptwebserver::overwrite::" + I->Tag + "::filename", filename);
677 if (filename[0] == '/')
678 filename.erase(0,1);
679 regfree(pattern);
680 break;
681 }
682 regfree(pattern);
683 }
684 }
685
686 // deal with the request
6c0765c0
DK
687 unsigned int const httpsport = _config->FindI("aptwebserver::port::https", 4433);
688 std::string hosthttpsport;
689 strprintf(hosthttpsport, ":%u", httpsport);
f9b4f12d 690 if (_config->FindB("aptwebserver::support::http", true) == false &&
6c0765c0 691 LookupTag(*m, "Host").find(hosthttpsport) == std::string::npos)
f9b4f12d 692 {
ed793a19 693 sendError(client, 400, *m, sendContent, "HTTP disabled, all requests must be HTTPS", headers);
f9b4f12d
DK
694 continue;
695 }
696 else if (RealFileExists(filename) == true)
575fe03e
DK
697 {
698 FileFd data(filename, FileFd::ReadOnly);
699 std::string condition = LookupTag(*m, "If-Modified-Since", "");
f2c0ec8b 700 if (_config->FindB("aptwebserver::support::modified-since", true) == true && condition.empty() == false)
575fe03e
DK
701 {
702 time_t cache;
703 if (RFC1123StrToTime(condition.c_str(), cache) == true &&
704 cache >= data.ModificationTime())
705 {
706 sendHead(client, 304, headers);
707 continue;
708 }
709 }
710
711 if (_config->FindB("aptwebserver::support::range", true) == true)
712 condition = LookupTag(*m, "Range", "");
713 else
714 condition.clear();
715 if (condition.empty() == false && strncmp(condition.c_str(), "bytes=", 6) == 0)
716 {
717 time_t cache;
718 std::string ifrange;
719 if (_config->FindB("aptwebserver::support::if-range", true) == true)
720 ifrange = LookupTag(*m, "If-Range", "");
721 bool validrange = (ifrange.empty() == true ||
722 (RFC1123StrToTime(ifrange.c_str(), cache) == true &&
723 cache <= data.ModificationTime()));
724
725 // FIXME: support multiple byte-ranges (APT clients do not do this)
726 if (condition.find(',') == std::string::npos)
727 {
728 size_t start = 6;
729 unsigned long long filestart = strtoull(condition.c_str() + start, NULL, 10);
730 // FIXME: no support for last-byte-pos being not the end of the file (APT clients do not do this)
731 size_t dash = condition.find('-') + 1;
732 unsigned long long fileend = strtoull(condition.c_str() + dash, NULL, 10);
733 unsigned long long filesize = data.FileSize();
734 if ((fileend == 0 || (fileend == filesize && fileend >= filestart)) &&
735 validrange == true)
736 {
737 if (filesize > filestart)
738 {
739 data.Skip(filestart);
f4a91278
MV
740 // make sure to send content-range before conent-length
741 // as regression test for LP: #1445239
575fe03e
DK
742 std::ostringstream contentrange;
743 contentrange << "Content-Range: bytes " << filestart << "-"
744 << filesize - 1 << "/" << filesize;
745 headers.push_back(contentrange.str());
ceafe8a6
MV
746 std::ostringstream contentlength;
747 contentlength << "Content-Length: " << (filesize - filestart);
748 headers.push_back(contentlength.str());
575fe03e
DK
749 sendHead(client, 206, headers);
750 if (sendContent == true)
ed793a19 751 sendFile(client, headers, data);
575fe03e
DK
752 continue;
753 }
754 else
755 {
dcbb364f
DK
756 if (_config->FindB("aptwebserver::support::content-range", true) == true)
757 {
758 std::ostringstream contentrange;
759 contentrange << "Content-Range: bytes */" << filesize;
760 headers.push_back(contentrange.str());
761 }
ed793a19
DK
762 sendError(client, 416, *m, sendContent, "", headers);
763 break;
575fe03e
DK
764 }
765 }
766 }
767 }
768
769 addFileHeaders(headers, data);
770 sendHead(client, 200, headers);
771 if (sendContent == true)
ed793a19 772 sendFile(client, headers, data);
575fe03e
DK
773 }
774 else if (DirectoryExists(filename) == true)
775 {
776 if (filename[filename.length()-1] == '/')
ed793a19 777 sendDirectoryListing(client, filename, *m, sendContent, headers);
575fe03e
DK
778 else
779 sendRedirect(client, 301, filename.append("/"), *m, sendContent);
780 }
781 else
ed793a19 782 sendError(client, 404, *m, sendContent, "", headers);
575fe03e 783 }
117038ba
DK
784
785 // if we announced a closing in the last response, do the close now
786 if (std::find(headers.begin(), headers.end(), std::string("Connection: close")) != headers.end())
787 closeConnection = true;
788
789 if (_error->PendingError() == true)
790 break;
575fe03e 791 _error->DumpErrors(std::cerr);
575fe03e 792 }
117038ba 793 _error->DumpErrors(std::cerr);
575fe03e
DK
794 close(client);
795 std::clog << "CLOSE client " << client << std::endl;
796 return NULL;
797}
798 /*}}}*/
799
fbd29dd6
DK
800int main(int const argc, const char * argv[])
801{
802 CommandLine::Args Args[] = {
803 {0, "port", "aptwebserver::port", CommandLine::HasArg},
f2380a78 804 {0, "request-absolute", "aptwebserver::request::absolute", CommandLine::HasArg},
b0314abb
DK
805 {0, "authorization", "aptwebserver::authorization", CommandLine::HasArg},
806 {0, "proxy-authorization", "aptwebserver::proxy-authorization", CommandLine::HasArg},
fbd29dd6
DK
807 {'c',"config-file",0,CommandLine::ConfigFile},
808 {'o',"option",0,CommandLine::ArbItem},
809 {0,0,0,0}
810 };
811
812 CommandLine CmdL(Args, _config);
813 if(CmdL.Parse(argc,argv) == false)
814 {
815 _error->DumpErrors();
816 exit(1);
817 }
818
819 // create socket, bind and listen to it {{{
820 // ignore SIGPIPE, this can happen on write() if the socket closes connection
821 signal(SIGPIPE, SIG_IGN);
575fe03e
DK
822 // we don't care for our slaves, so ignore their death
823 signal(SIGCHLD, SIG_IGN);
824
fbd29dd6
DK
825 int sock = socket(AF_INET6, SOCK_STREAM, 0);
826 if(sock < 0)
827 {
828 _error->Errno("aptwerbserver", "Couldn't create socket");
829 _error->DumpErrors(std::cerr);
830 return 1;
831 }
832
6c0765c0 833 int port = _config->FindI("aptwebserver::port", 8080);
fbd29dd6
DK
834
835 // ensure that we accept all connections: v4 or v6
836 int const iponly = 0;
837 setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &iponly, sizeof(iponly));
838 // to not linger on an address
839 int const enable = 1;
840 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
841
842 struct sockaddr_in6 locAddr;
843 memset(&locAddr, 0, sizeof(locAddr));
844 locAddr.sin6_family = AF_INET6;
845 locAddr.sin6_port = htons(port);
846 locAddr.sin6_addr = in6addr_any;
847
848 if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0)
849 {
850 _error->Errno("aptwerbserver", "Couldn't bind");
851 _error->DumpErrors(std::cerr);
852 return 2;
853 }
854
6c0765c0
DK
855 if (port == 0)
856 {
857 struct sockaddr_in6 addr;
858 socklen_t addrlen = sizeof(sockaddr_in6);
859 if (getsockname(sock, (struct sockaddr*) &addr, &addrlen) != 0)
860 _error->Errno("getsockname", "Could not get chosen port number");
861 else
862 port = ntohs(addr.sin6_port);
863 }
864 std::string const portfilename = _config->Find("aptwebserver::portfile", "");
865 if (portfilename.empty() == false)
866 {
867 FileFd portfile(portfilename, FileFd::WriteOnly | FileFd::Create | FileFd::Empty);
868 std::string portcontent;
869 strprintf(portcontent, "%d", port);
870 portfile.Write(portcontent.c_str(), portcontent.size());
871 portfile.Sync();
872 }
873 _config->Set("aptwebserver::port::http", port);
874
e3c62328
DK
875 FileFd pidfile;
876 if (_config->FindB("aptwebserver::fork", false) == true)
877 {
878 std::string const pidfilename = _config->Find("aptwebserver::pidfile", "aptwebserver.pid");
879 int const pidfilefd = GetLock(pidfilename);
880 if (pidfilefd < 0 || pidfile.OpenDescriptor(pidfilefd, FileFd::WriteOnly) == false)
881 {
882 _error->Errno("aptwebserver", "Couldn't acquire lock on pidfile '%s'", pidfilename.c_str());
883 _error->DumpErrors(std::cerr);
884 return 3;
885 }
886
887 pid_t child = fork();
888 if (child < 0)
889 {
890 _error->Errno("aptwebserver", "Forking failed");
891 _error->DumpErrors(std::cerr);
892 return 4;
893 }
894 else if (child != 0)
895 {
896 // successfully forked: ready to serve!
897 std::string pidcontent;
898 strprintf(pidcontent, "%d", child);
899 pidfile.Write(pidcontent.c_str(), pidcontent.size());
6c0765c0 900 pidfile.Sync();
e3c62328
DK
901 if (_error->PendingError() == true)
902 {
903 _error->DumpErrors(std::cerr);
904 return 5;
905 }
906 std::cout << "Successfully forked as " << child << std::endl;
907 return 0;
908 }
909 }
910
fbd29dd6
DK
911 std::clog << "Serving ANY file on port: " << port << std::endl;
912
d61960d9
DK
913 int const slaves = _config->FindI("aptwebserver::slaves", SOMAXCONN);
914 std::cerr << "SLAVES: " << slaves << std::endl;
575fe03e 915 listen(sock, slaves);
fbd29dd6
DK
916 /*}}}*/
917
14c84d02
DK
918 _config->CndSet("aptwebserver::response-header::Server", "APT webserver");
919 _config->CndSet("aptwebserver::response-header::Accept-Ranges", "bytes");
3c16b5fe 920 _config->CndSet("aptwebserver::directoryindex", "index.html");
14c84d02 921
575fe03e 922 std::list<int> accepted_clients;
fbd29dd6 923
575fe03e
DK
924 while (true)
925 {
926 int client = accept(sock, NULL, NULL);
927 if (client == -1)
fbd29dd6 928 {
575fe03e
DK
929 if (errno == EINTR)
930 continue;
931 _error->Errno("accept", "Couldn't accept client on socket %d", sock);
932 _error->DumpErrors(std::cerr);
933 return 6;
934 }
14c84d02 935
575fe03e
DK
936 pthread_attr_t attr;
937 if (pthread_attr_init(&attr) != 0 || pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0)
938 {
939 _error->Errno("pthread_attr", "Couldn't set detach attribute for a fresh thread to handle client %d on socket %d", client, sock);
fbd29dd6 940 _error->DumpErrors(std::cerr);
575fe03e
DK
941 close(client);
942 continue;
fbd29dd6
DK
943 }
944
575fe03e
DK
945 pthread_t tid;
946 // thats rather dirty, but we need to store the client socket somewhere safe
947 accepted_clients.push_front(client);
948 if (pthread_create(&tid, &attr, &handleClient, &(*accepted_clients.begin())) != 0)
949 {
950 _error->Errno("pthread_create", "Couldn't create a fresh thread to handle client %d on socket %d", client, sock);
951 _error->DumpErrors(std::cerr);
952 close(client);
953 continue;
954 }
fbd29dd6 955 }
e3c62328
DK
956 pidfile.Close();
957
fbd29dd6
DK
958 return 0;
959}