aptwebserver.cc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. #include <config.h>
  2. #include <apt-pkg/strutl.h>
  3. #include <apt-pkg/fileutl.h>
  4. #include <apt-pkg/error.h>
  5. #include <apt-pkg/cmndline.h>
  6. #include <apt-pkg/configuration.h>
  7. #include <apt-pkg/init.h>
  8. #include <vector>
  9. #include <string>
  10. #include <list>
  11. #include <sstream>
  12. #include <sys/socket.h>
  13. #include <sys/types.h>
  14. #include <sys/stat.h>
  15. #include <netinet/in.h>
  16. #include <unistd.h>
  17. #include <errno.h>
  18. #include <time.h>
  19. #include <stdlib.h>
  20. #include <dirent.h>
  21. #include <signal.h>
  22. char const * const httpcodeToStr(int const httpcode) /*{{{*/
  23. {
  24. switch (httpcode)
  25. {
  26. // Informational 1xx
  27. case 100: return "100 Continue";
  28. case 101: return "101 Switching Protocols";
  29. // Successful 2xx
  30. case 200: return "200 OK";
  31. case 201: return "201 Created";
  32. case 202: return "202 Accepted";
  33. case 203: return "203 Non-Authoritative Information";
  34. case 204: return "204 No Content";
  35. case 205: return "205 Reset Content";
  36. case 206: return "206 Partial Content";
  37. // Redirections 3xx
  38. case 300: return "300 Multiple Choices";
  39. case 301: return "301 Moved Permanently";
  40. case 302: return "302 Found";
  41. case 303: return "303 See Other";
  42. case 304: return "304 Not Modified";
  43. case 305: return "304 Use Proxy";
  44. case 307: return "307 Temporary Redirect";
  45. // Client errors 4xx
  46. case 400: return "400 Bad Request";
  47. case 401: return "401 Unauthorized";
  48. case 402: return "402 Payment Required";
  49. case 403: return "403 Forbidden";
  50. case 404: return "404 Not Found";
  51. case 405: return "405 Method Not Allowed";
  52. case 406: return "406 Not Acceptable";
  53. case 407: return "407 Proxy Authentication Required";
  54. case 408: return "408 Request Time-out";
  55. case 409: return "409 Conflict";
  56. case 410: return "410 Gone";
  57. case 411: return "411 Length Required";
  58. case 412: return "412 Precondition Failed";
  59. case 413: return "413 Request Entity Too Large";
  60. case 414: return "414 Request-URI Too Large";
  61. case 415: return "415 Unsupported Media Type";
  62. case 416: return "416 Requested range not satisfiable";
  63. case 417: return "417 Expectation Failed";
  64. case 418: return "418 I'm a teapot";
  65. // Server error 5xx
  66. case 500: return "500 Internal Server Error";
  67. case 501: return "501 Not Implemented";
  68. case 502: return "502 Bad Gateway";
  69. case 503: return "503 Service Unavailable";
  70. case 504: return "504 Gateway Time-out";
  71. case 505: return "505 HTTP Version not supported";
  72. }
  73. return NULL;
  74. }
  75. /*}}}*/
  76. void addFileHeaders(std::list<std::string> &headers, FileFd &data) /*{{{*/
  77. {
  78. std::ostringstream contentlength;
  79. contentlength << "Content-Length: " << data.FileSize();
  80. headers.push_back(contentlength.str());
  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. {
  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. {
  95. std::string response("HTTP/1.1 ");
  96. response.append(httpcodeToStr(httpcode));
  97. headers.push_front(response);
  98. _config->Set("APTWebserver::Last-Status-Code", httpcode);
  99. std::stringstream buffer;
  100. _config->Dump(buffer, "aptwebserver::response-header", "%t: %v%n", false);
  101. std::vector<std::string> addheaders = VectorizeString(buffer.str(), '\n');
  102. for (std::vector<std::string>::const_iterator h = addheaders.begin(); h != addheaders.end(); ++h)
  103. headers.push_back(*h);
  104. std::string date("Date: ");
  105. date.append(TimeRFC1123(time(NULL)));
  106. headers.push_back(date);
  107. std::clog << ">>> RESPONSE >>>" << std::endl;
  108. bool Success = true;
  109. for (std::list<std::string>::const_iterator h = headers.begin();
  110. Success == true && h != headers.end(); ++h)
  111. {
  112. Success &= FileFd::Write(client, h->c_str(), h->size());
  113. if (Success == true)
  114. Success &= FileFd::Write(client, "\r\n", 2);
  115. std::clog << *h << std::endl;
  116. }
  117. if (Success == true)
  118. Success &= FileFd::Write(client, "\r\n", 2);
  119. std::clog << "<<<<<<<<<<<<<<<<" << std::endl;
  120. return Success;
  121. }
  122. /*}}}*/
  123. bool sendFile(int const client, FileFd &data) /*{{{*/
  124. {
  125. bool Success = true;
  126. char buffer[500];
  127. unsigned long long actual = 0;
  128. while ((Success &= data.Read(buffer, sizeof(buffer), &actual)) == true)
  129. {
  130. if (actual == 0)
  131. break;
  132. if (Success == true)
  133. Success &= FileFd::Write(client, buffer, actual);
  134. }
  135. if (Success == true)
  136. Success &= FileFd::Write(client, "\r\n", 2);
  137. return Success;
  138. }
  139. /*}}}*/
  140. bool sendData(int const client, std::string const &data) /*{{{*/
  141. {
  142. bool Success = true;
  143. Success &= FileFd::Write(client, data.c_str(), data.size());
  144. if (Success == true)
  145. Success &= FileFd::Write(client, "\r\n", 2);
  146. return Success;
  147. }
  148. /*}}}*/
  149. void sendError(int const client, int const httpcode, std::string const &request,/*{{{*/
  150. bool content, std::string const &error = "")
  151. {
  152. std::list<std::string> headers;
  153. std::string response("<html><head><title>");
  154. response.append(httpcodeToStr(httpcode)).append("</title></head>");
  155. response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1>");
  156. if (httpcode != 200)
  157. {
  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. }
  162. else
  163. {
  164. if (error.empty() == false)
  165. response.append("<p><em>Success</em>: ").append(error).append("</p>");
  166. response.append("The successfully executed operation was requested by: <pre>");
  167. }
  168. response.append(request).append("</pre></body></html>");
  169. addDataHeaders(headers, response);
  170. sendHead(client, httpcode, headers);
  171. if (content == true)
  172. sendData(client, response);
  173. }
  174. void sendSuccess(int const client, std::string const &request,
  175. bool content, std::string const &error = "")
  176. {
  177. sendError(client, 200, request, content, error);
  178. }
  179. /*}}}*/
  180. void sendRedirect(int const client, int const httpcode, std::string const &uri,/*{{{*/
  181. std::string const &request, bool content)
  182. {
  183. std::list<std::string> headers;
  184. std::string response("<html><head><title>");
  185. response.append(httpcodeToStr(httpcode)).append("</title></head>");
  186. response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1");
  187. response.append("<p>You should be redirected to <em>").append(uri).append("</em></p>");
  188. response.append("This page is a result of the request: <pre>");
  189. response.append(request).append("</pre></body></html>");
  190. addDataHeaders(headers, response);
  191. std::string location("Location: ");
  192. if (strncmp(uri.c_str(), "http://", 7) != 0)
  193. location.append("http://").append(LookupTag(request, "Host")).append("/").append(uri);
  194. else
  195. location.append(uri);
  196. headers.push_back(location);
  197. sendHead(client, httpcode, headers);
  198. if (content == true)
  199. sendData(client, response);
  200. }
  201. /*}}}*/
  202. int filter_hidden_files(const struct dirent *a) /*{{{*/
  203. {
  204. if (a->d_name[0] == '.')
  205. return 0;
  206. #ifdef _DIRENT_HAVE_D_TYPE
  207. // if we have the d_type check that only files and dirs will be included
  208. if (a->d_type != DT_UNKNOWN &&
  209. a->d_type != DT_REG &&
  210. a->d_type != DT_LNK && // this includes links to regular files
  211. a->d_type != DT_DIR)
  212. return 0;
  213. #endif
  214. return 1;
  215. }
  216. int grouped_alpha_case_sort(const struct dirent **a, const struct dirent **b) {
  217. #ifdef _DIRENT_HAVE_D_TYPE
  218. if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_DIR);
  219. else if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_REG)
  220. return -1;
  221. else if ((*b)->d_type == DT_DIR && (*a)->d_type == DT_REG)
  222. return 1;
  223. else
  224. #endif
  225. {
  226. struct stat f_prop; //File's property
  227. stat((*a)->d_name, &f_prop);
  228. int const amode = f_prop.st_mode;
  229. stat((*b)->d_name, &f_prop);
  230. int const bmode = f_prop.st_mode;
  231. if (S_ISDIR(amode) && S_ISDIR(bmode));
  232. else if (S_ISDIR(amode))
  233. return -1;
  234. else if (S_ISDIR(bmode))
  235. return 1;
  236. }
  237. return strcasecmp((*a)->d_name, (*b)->d_name);
  238. }
  239. /*}}}*/
  240. void sendDirectoryListing(int const client, std::string const &dir, /*{{{*/
  241. std::string const &request, bool content)
  242. {
  243. std::list<std::string> headers;
  244. std::ostringstream listing;
  245. struct dirent **namelist;
  246. int const counter = scandir(dir.c_str(), &namelist, filter_hidden_files, grouped_alpha_case_sort);
  247. if (counter == -1)
  248. {
  249. sendError(client, 500, request, content);
  250. return;
  251. }
  252. listing << "<html><head><title>Index of " << dir << "</title>"
  253. << "<style type=\"text/css\"><!-- td {padding: 0.02em 0.5em 0.02em 0.5em;}"
  254. << "tr:nth-child(even){background-color:#dfdfdf;}"
  255. << "h1, td:nth-child(3){text-align:center;}"
  256. << "table {margin-left:auto;margin-right:auto;} --></style>"
  257. << "</head>" << std::endl
  258. << "<body><h1>Index of " << dir << "</h1>" << std::endl
  259. << "<table><tr><th>#</th><th>Name</th><th>Size</th><th>Last-Modified</th></tr>" << std::endl;
  260. if (dir != ".")
  261. listing << "<tr><td>d</td><td><a href=\"..\">Parent Directory</a></td><td>-</td><td>-</td></tr>";
  262. for (int i = 0; i < counter; ++i) {
  263. struct stat fs;
  264. std::string filename(dir);
  265. filename.append("/").append(namelist[i]->d_name);
  266. stat(filename.c_str(), &fs);
  267. if (S_ISDIR(fs.st_mode))
  268. {
  269. listing << "<tr><td>d</td>"
  270. << "<td><a href=\"" << namelist[i]->d_name << "/\">" << namelist[i]->d_name << "</a></td>"
  271. << "<td>-</td>";
  272. }
  273. else
  274. {
  275. listing << "<tr><td>f</td>"
  276. << "<td><a href=\"" << namelist[i]->d_name << "\">" << namelist[i]->d_name << "</a></td>"
  277. << "<td>" << SizeToStr(fs.st_size) << "B</td>";
  278. }
  279. listing << "<td>" << TimeRFC1123(fs.st_mtime) << "</td></tr>" << std::endl;
  280. }
  281. listing << "</table></body></html>" << std::endl;
  282. std::string response(listing.str());
  283. addDataHeaders(headers, response);
  284. sendHead(client, 200, headers);
  285. if (content == true)
  286. sendData(client, response);
  287. }
  288. /*}}}*/
  289. bool parseFirstLine(int const client, std::string const &request, /*{{{*/
  290. std::string &filename, bool &sendContent,
  291. bool &closeConnection)
  292. {
  293. if (strncmp(request.c_str(), "HEAD ", 5) == 0)
  294. sendContent = false;
  295. if (strncmp(request.c_str(), "GET ", 4) != 0)
  296. {
  297. sendError(client, 501, request, true);
  298. return false;
  299. }
  300. size_t const lineend = request.find('\n');
  301. size_t filestart = request.find(' ');
  302. for (; request[filestart] == ' '; ++filestart);
  303. size_t fileend = request.rfind(' ', lineend);
  304. if (lineend == std::string::npos || filestart == std::string::npos ||
  305. fileend == std::string::npos || filestart == fileend)
  306. {
  307. sendError(client, 500, request, sendContent, "Filename can't be extracted");
  308. return false;
  309. }
  310. size_t httpstart = fileend;
  311. for (; request[httpstart] == ' '; ++httpstart);
  312. if (strncmp(request.c_str() + httpstart, "HTTP/1.1\r", 9) == 0)
  313. closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "Keep-Alive") != 0;
  314. else if (strncmp(request.c_str() + httpstart, "HTTP/1.0\r", 9) == 0)
  315. closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "close") == 0;
  316. else
  317. {
  318. sendError(client, 500, request, sendContent, "Not a HTTP/1.{0,1} request");
  319. return false;
  320. }
  321. filename = request.substr(filestart, fileend - filestart);
  322. if (filename.find(' ') != std::string::npos)
  323. {
  324. sendError(client, 500, request, sendContent, "Filename contains an unencoded space");
  325. return false;
  326. }
  327. std::string host = LookupTag(request, "Host", "");
  328. if (host.empty() == true)
  329. {
  330. // RFC 2616 §14.23 requires Host
  331. sendError(client, 400, request, sendContent, "Host header is required");
  332. return false;
  333. }
  334. host = "http://" + host;
  335. // Proxies require absolute uris, so this is a simple proxy-fake option
  336. std::string const absolute = _config->Find("aptwebserver::request::absolute", "uri,path");
  337. if (strncmp(host.c_str(), filename.c_str(), host.length()) == 0)
  338. {
  339. if (absolute.find("uri") == std::string::npos)
  340. {
  341. sendError(client, 400, request, sendContent, "Request is absoluteURI, but configured to not accept that");
  342. return false;
  343. }
  344. // strip the host from the request to make it an absolute path
  345. filename.erase(0, host.length());
  346. }
  347. else if (absolute.find("path") == std::string::npos)
  348. {
  349. sendError(client, 400, request, sendContent, "Request is absolutePath, but configured to not accept that");
  350. return false;
  351. }
  352. filename = DeQuoteString(filename);
  353. // this is not a secure server, but at least prevent the obvious …
  354. if (filename.empty() == true || filename[0] != '/' ||
  355. strncmp(filename.c_str(), "//", 2) == 0 ||
  356. filename.find_first_of("\r\n\t\f\v") != std::string::npos ||
  357. filename.find("/../") != std::string::npos)
  358. {
  359. sendError(client, 400, request, sendContent, "Filename contains illegal character (sequence)");
  360. return false;
  361. }
  362. // nuke the first character which is a / as we assured above
  363. filename.erase(0, 1);
  364. if (filename.empty() == true)
  365. filename = ".";
  366. return true;
  367. }
  368. /*}}}*/
  369. bool handleOnTheFlyReconfiguration(int const client, std::string const &request, std::vector<std::string> const &parts)/*{{{*/
  370. {
  371. size_t const pcount = parts.size();
  372. if (pcount == 4 && parts[1] == "set")
  373. {
  374. _config->Set(parts[2], parts[3]);
  375. sendSuccess(client, request, true, "Option '" + parts[2] + "' was set to '" + parts[3] + "'!");
  376. return true;
  377. }
  378. else if (pcount == 4 && parts[1] == "find")
  379. {
  380. std::list<std::string> headers;
  381. std::string response = _config->Find(parts[2], parts[3]);
  382. addDataHeaders(headers, response);
  383. sendHead(client, 200, headers);
  384. sendData(client, response);
  385. return true;
  386. }
  387. else if (pcount == 3 && parts[1] == "find")
  388. {
  389. std::list<std::string> headers;
  390. if (_config->Exists(parts[2]) == true)
  391. {
  392. std::string response = _config->Find(parts[2]);
  393. addDataHeaders(headers, response);
  394. sendHead(client, 200, headers);
  395. sendData(client, response);
  396. return true;
  397. }
  398. sendError(client, 404, request, "Requested Configuration option doesn't exist.");
  399. return false;
  400. }
  401. else if (pcount == 3 && parts[1] == "clear")
  402. {
  403. _config->Clear(parts[2]);
  404. sendSuccess(client, request, true, "Option '" + parts[2] + "' was cleared.");
  405. return true;
  406. }
  407. sendError(client, 400, request, true, "Unknown on-the-fly configuration request");
  408. return false;
  409. }
  410. /*}}}*/
  411. int main(int const argc, const char * argv[])
  412. {
  413. CommandLine::Args Args[] = {
  414. {0, "port", "aptwebserver::port", CommandLine::HasArg},
  415. {0, "request-absolute", "aptwebserver::request::absolute", CommandLine::HasArg},
  416. {'c',"config-file",0,CommandLine::ConfigFile},
  417. {'o',"option",0,CommandLine::ArbItem},
  418. {0,0,0,0}
  419. };
  420. CommandLine CmdL(Args, _config);
  421. if(CmdL.Parse(argc,argv) == false)
  422. {
  423. _error->DumpErrors();
  424. exit(1);
  425. }
  426. // create socket, bind and listen to it {{{
  427. // ignore SIGPIPE, this can happen on write() if the socket closes connection
  428. signal(SIGPIPE, SIG_IGN);
  429. int sock = socket(AF_INET6, SOCK_STREAM, 0);
  430. if(sock < 0)
  431. {
  432. _error->Errno("aptwerbserver", "Couldn't create socket");
  433. _error->DumpErrors(std::cerr);
  434. return 1;
  435. }
  436. int const port = _config->FindI("aptwebserver::port", 8080);
  437. // ensure that we accept all connections: v4 or v6
  438. int const iponly = 0;
  439. setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &iponly, sizeof(iponly));
  440. // to not linger on an address
  441. int const enable = 1;
  442. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
  443. struct sockaddr_in6 locAddr;
  444. memset(&locAddr, 0, sizeof(locAddr));
  445. locAddr.sin6_family = AF_INET6;
  446. locAddr.sin6_port = htons(port);
  447. locAddr.sin6_addr = in6addr_any;
  448. if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0)
  449. {
  450. _error->Errno("aptwerbserver", "Couldn't bind");
  451. _error->DumpErrors(std::cerr);
  452. return 2;
  453. }
  454. FileFd pidfile;
  455. if (_config->FindB("aptwebserver::fork", false) == true)
  456. {
  457. std::string const pidfilename = _config->Find("aptwebserver::pidfile", "aptwebserver.pid");
  458. int const pidfilefd = GetLock(pidfilename);
  459. if (pidfilefd < 0 || pidfile.OpenDescriptor(pidfilefd, FileFd::WriteOnly) == false)
  460. {
  461. _error->Errno("aptwebserver", "Couldn't acquire lock on pidfile '%s'", pidfilename.c_str());
  462. _error->DumpErrors(std::cerr);
  463. return 3;
  464. }
  465. pid_t child = fork();
  466. if (child < 0)
  467. {
  468. _error->Errno("aptwebserver", "Forking failed");
  469. _error->DumpErrors(std::cerr);
  470. return 4;
  471. }
  472. else if (child != 0)
  473. {
  474. // successfully forked: ready to serve!
  475. std::string pidcontent;
  476. strprintf(pidcontent, "%d", child);
  477. pidfile.Write(pidcontent.c_str(), pidcontent.size());
  478. if (_error->PendingError() == true)
  479. {
  480. _error->DumpErrors(std::cerr);
  481. return 5;
  482. }
  483. std::cout << "Successfully forked as " << child << std::endl;
  484. return 0;
  485. }
  486. }
  487. std::clog << "Serving ANY file on port: " << port << std::endl;
  488. listen(sock, 1);
  489. /*}}}*/
  490. _config->CndSet("aptwebserver::response-header::Server", "APT webserver");
  491. _config->CndSet("aptwebserver::response-header::Accept-Ranges", "bytes");
  492. std::vector<std::string> messages;
  493. int client;
  494. while ((client = accept(sock, NULL, NULL)) != -1)
  495. {
  496. std::clog << "ACCEPT client " << client
  497. << " on socket " << sock << std::endl;
  498. while (ReadMessages(client, messages))
  499. {
  500. bool closeConnection = false;
  501. for (std::vector<std::string>::const_iterator m = messages.begin();
  502. m != messages.end() && closeConnection == false; ++m) {
  503. std::clog << ">>> REQUEST >>>>" << std::endl << *m
  504. << std::endl << "<<<<<<<<<<<<<<<<" << std::endl;
  505. std::list<std::string> headers;
  506. std::string filename;
  507. bool sendContent = true;
  508. if (parseFirstLine(client, *m, filename, sendContent, closeConnection) == false)
  509. continue;
  510. // special webserver command request
  511. if (filename.length() > 1 && filename[0] == '_')
  512. {
  513. std::vector<std::string> parts = VectorizeString(filename, '/');
  514. if (parts[0] == "_config")
  515. {
  516. handleOnTheFlyReconfiguration(client, *m, parts);
  517. continue;
  518. }
  519. }
  520. // string replacements in the requested filename
  521. ::Configuration::Item const *Replaces = _config->Tree("aptwebserver::redirect::replace");
  522. if (Replaces != NULL)
  523. {
  524. std::string redirect = "/" + filename;
  525. for (::Configuration::Item *I = Replaces->Child; I != NULL; I = I->Next)
  526. redirect = SubstVar(redirect, I->Tag, I->Value);
  527. redirect.erase(0,1);
  528. if (redirect != filename)
  529. {
  530. sendRedirect(client, 301, redirect, *m, sendContent);
  531. continue;
  532. }
  533. }
  534. ::Configuration::Item const *Overwrite = _config->Tree("aptwebserver::overwrite");
  535. if (Overwrite != NULL)
  536. {
  537. for (::Configuration::Item *I = Overwrite->Child; I != NULL; I = I->Next)
  538. {
  539. regex_t *pattern = new regex_t;
  540. int const res = regcomp(pattern, I->Tag.c_str(), REG_EXTENDED | REG_ICASE | REG_NOSUB);
  541. if (res != 0)
  542. {
  543. char error[300];
  544. regerror(res, pattern, error, sizeof(error));
  545. sendError(client, 500, *m, sendContent, error);
  546. continue;
  547. }
  548. if (regexec(pattern, filename.c_str(), 0, 0, 0) == 0)
  549. {
  550. filename = _config->Find("aptwebserver::overwrite::" + I->Tag + "::filename", filename);
  551. if (filename[0] == '/')
  552. filename.erase(0,1);
  553. regfree(pattern);
  554. break;
  555. }
  556. regfree(pattern);
  557. }
  558. }
  559. // deal with the request
  560. if (RealFileExists(filename) == true)
  561. {
  562. FileFd data(filename, FileFd::ReadOnly);
  563. std::string condition = LookupTag(*m, "If-Modified-Since", "");
  564. if (condition.empty() == false)
  565. {
  566. time_t cache;
  567. if (RFC1123StrToTime(condition.c_str(), cache) == true &&
  568. cache >= data.ModificationTime())
  569. {
  570. sendHead(client, 304, headers);
  571. continue;
  572. }
  573. }
  574. if (_config->FindB("aptwebserver::support::range", true) == true)
  575. condition = LookupTag(*m, "Range", "");
  576. else
  577. condition.clear();
  578. if (condition.empty() == false && strncmp(condition.c_str(), "bytes=", 6) == 0)
  579. {
  580. time_t cache;
  581. std::string ifrange;
  582. if (_config->FindB("aptwebserver::support::if-range", true) == true)
  583. ifrange = LookupTag(*m, "If-Range", "");
  584. bool validrange = (ifrange.empty() == true ||
  585. (RFC1123StrToTime(ifrange.c_str(), cache) == true &&
  586. cache <= data.ModificationTime()));
  587. // FIXME: support multiple byte-ranges (APT clients do not do this)
  588. if (condition.find(',') == std::string::npos)
  589. {
  590. size_t start = 6;
  591. unsigned long long filestart = strtoull(condition.c_str() + start, NULL, 10);
  592. // FIXME: no support for last-byte-pos being not the end of the file (APT clients do not do this)
  593. size_t dash = condition.find('-') + 1;
  594. unsigned long long fileend = strtoull(condition.c_str() + dash, NULL, 10);
  595. unsigned long long filesize = data.FileSize();
  596. if ((fileend == 0 || (fileend == filesize && fileend >= filestart)) &&
  597. validrange == true)
  598. {
  599. if (filesize > filestart)
  600. {
  601. data.Skip(filestart);
  602. std::ostringstream contentlength;
  603. contentlength << "Content-Length: " << (filesize - filestart);
  604. headers.push_back(contentlength.str());
  605. std::ostringstream contentrange;
  606. contentrange << "Content-Range: bytes " << filestart << "-"
  607. << filesize - 1 << "/" << filesize;
  608. headers.push_back(contentrange.str());
  609. sendHead(client, 206, headers);
  610. if (sendContent == true)
  611. sendFile(client, data);
  612. continue;
  613. }
  614. else
  615. {
  616. headers.push_back("Content-Length: 0");
  617. std::ostringstream contentrange;
  618. contentrange << "Content-Range: bytes */" << filesize;
  619. headers.push_back(contentrange.str());
  620. sendHead(client, 416, headers);
  621. continue;
  622. }
  623. }
  624. }
  625. }
  626. addFileHeaders(headers, data);
  627. sendHead(client, 200, headers);
  628. if (sendContent == true)
  629. sendFile(client, data);
  630. }
  631. else if (DirectoryExists(filename) == true)
  632. {
  633. if (filename == "." || filename[filename.length()-1] == '/')
  634. sendDirectoryListing(client, filename, *m, sendContent);
  635. else
  636. sendRedirect(client, 301, filename.append("/"), *m, sendContent);
  637. }
  638. else
  639. sendError(client, 404, *m, sendContent);
  640. }
  641. _error->DumpErrors(std::cerr);
  642. messages.clear();
  643. if (closeConnection == true)
  644. break;
  645. }
  646. std::clog << "CLOSE client " << client
  647. << " on socket " << sock << std::endl;
  648. close(client);
  649. }
  650. pidfile.Close();
  651. return 0;
  652. }