aptwebserver.cc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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. headers.push_back("Server: APT webserver");
  99. std::string date("Date: ");
  100. date.append(TimeRFC1123(time(NULL)));
  101. headers.push_back(date);
  102. std::clog << ">>> RESPONSE >>>" << std::endl;
  103. bool Success = true;
  104. for (std::list<std::string>::const_iterator h = headers.begin();
  105. Success == true && h != headers.end(); ++h)
  106. {
  107. Success &= FileFd::Write(client, h->c_str(), h->size());
  108. if (Success == true)
  109. Success &= FileFd::Write(client, "\r\n", 2);
  110. std::clog << *h << std::endl;
  111. }
  112. if (Success == true)
  113. Success &= FileFd::Write(client, "\r\n", 2);
  114. std::clog << "<<<<<<<<<<<<<<<<" << std::endl;
  115. return Success;
  116. }
  117. /*}}}*/
  118. bool sendFile(int const client, FileFd &data) /*{{{*/
  119. {
  120. bool Success = true;
  121. char buffer[500];
  122. unsigned long long actual = 0;
  123. while ((Success &= data.Read(buffer, sizeof(buffer), &actual)) == true)
  124. {
  125. if (actual == 0)
  126. break;
  127. if (Success == true)
  128. Success &= FileFd::Write(client, buffer, actual);
  129. }
  130. if (Success == true)
  131. Success &= FileFd::Write(client, "\r\n", 2);
  132. return Success;
  133. }
  134. /*}}}*/
  135. bool sendData(int const client, std::string const &data) /*{{{*/
  136. {
  137. bool Success = true;
  138. Success &= FileFd::Write(client, data.c_str(), data.size());
  139. if (Success == true)
  140. Success &= FileFd::Write(client, "\r\n", 2);
  141. return Success;
  142. }
  143. /*}}}*/
  144. void sendError(int const client, int const httpcode, std::string const &request,/*{{{*/
  145. bool content, std::string const &error = "")
  146. {
  147. std::list<std::string> headers;
  148. std::string response("<html><head><title>");
  149. response.append(httpcodeToStr(httpcode)).append("</title></head>");
  150. response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1>");
  151. if (httpcode != 200)
  152. {
  153. if (error.empty() == false)
  154. response.append("<p><em>Error</em>: ").append(error).append("</p>");
  155. response.append("This error is a result of the request: <pre>");
  156. }
  157. else
  158. {
  159. if (error.empty() == false)
  160. response.append("<p><em>Success</em>: ").append(error).append("</p>");
  161. response.append("The successfully executed operation was requested by: <pre>");
  162. }
  163. response.append(request).append("</pre></body></html>");
  164. addDataHeaders(headers, response);
  165. sendHead(client, httpcode, headers);
  166. if (content == true)
  167. sendData(client, response);
  168. }
  169. void sendSuccess(int const client, std::string const &request,
  170. bool content, std::string const &error = "")
  171. {
  172. sendError(client, 200, request, content, error);
  173. }
  174. /*}}}*/
  175. void sendRedirect(int const client, int const httpcode, std::string const &uri,/*{{{*/
  176. std::string const &request, bool content)
  177. {
  178. std::list<std::string> headers;
  179. std::string response("<html><head><title>");
  180. response.append(httpcodeToStr(httpcode)).append("</title></head>");
  181. response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1");
  182. response.append("<p>You should be redirected to <em>").append(uri).append("</em></p>");
  183. response.append("This page is a result of the request: <pre>");
  184. response.append(request).append("</pre></body></html>");
  185. addDataHeaders(headers, response);
  186. std::string location("Location: ");
  187. if (strncmp(uri.c_str(), "http://", 7) != 0)
  188. location.append("http://").append(LookupTag(request, "Host")).append("/").append(uri);
  189. else
  190. location.append(uri);
  191. headers.push_back(location);
  192. sendHead(client, httpcode, headers);
  193. if (content == true)
  194. sendData(client, response);
  195. }
  196. /*}}}*/
  197. int filter_hidden_files(const struct dirent *a) /*{{{*/
  198. {
  199. if (a->d_name[0] == '.')
  200. return 0;
  201. #ifdef _DIRENT_HAVE_D_TYPE
  202. // if we have the d_type check that only files and dirs will be included
  203. if (a->d_type != DT_UNKNOWN &&
  204. a->d_type != DT_REG &&
  205. a->d_type != DT_LNK && // this includes links to regular files
  206. a->d_type != DT_DIR)
  207. return 0;
  208. #endif
  209. return 1;
  210. }
  211. int grouped_alpha_case_sort(const struct dirent **a, const struct dirent **b) {
  212. #ifdef _DIRENT_HAVE_D_TYPE
  213. if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_DIR);
  214. else if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_REG)
  215. return -1;
  216. else if ((*b)->d_type == DT_DIR && (*a)->d_type == DT_REG)
  217. return 1;
  218. else
  219. #endif
  220. {
  221. struct stat f_prop; //File's property
  222. stat((*a)->d_name, &f_prop);
  223. int const amode = f_prop.st_mode;
  224. stat((*b)->d_name, &f_prop);
  225. int const bmode = f_prop.st_mode;
  226. if (S_ISDIR(amode) && S_ISDIR(bmode));
  227. else if (S_ISDIR(amode))
  228. return -1;
  229. else if (S_ISDIR(bmode))
  230. return 1;
  231. }
  232. return strcasecmp((*a)->d_name, (*b)->d_name);
  233. }
  234. /*}}}*/
  235. void sendDirectoryListing(int const client, std::string const &dir, /*{{{*/
  236. std::string const &request, bool content)
  237. {
  238. std::list<std::string> headers;
  239. std::ostringstream listing;
  240. struct dirent **namelist;
  241. int const counter = scandir(dir.c_str(), &namelist, filter_hidden_files, grouped_alpha_case_sort);
  242. if (counter == -1)
  243. {
  244. sendError(client, 500, request, content);
  245. return;
  246. }
  247. listing << "<html><head><title>Index of " << dir << "</title>"
  248. << "<style type=\"text/css\"><!-- td {padding: 0.02em 0.5em 0.02em 0.5em;}"
  249. << "tr:nth-child(even){background-color:#dfdfdf;}"
  250. << "h1, td:nth-child(3){text-align:center;}"
  251. << "table {margin-left:auto;margin-right:auto;} --></style>"
  252. << "</head>" << std::endl
  253. << "<body><h1>Index of " << dir << "</h1>" << std::endl
  254. << "<table><tr><th>#</th><th>Name</th><th>Size</th><th>Last-Modified</th></tr>" << std::endl;
  255. if (dir != ".")
  256. listing << "<tr><td>d</td><td><a href=\"..\">Parent Directory</a></td><td>-</td><td>-</td></tr>";
  257. for (int i = 0; i < counter; ++i) {
  258. struct stat fs;
  259. std::string filename(dir);
  260. filename.append("/").append(namelist[i]->d_name);
  261. stat(filename.c_str(), &fs);
  262. if (S_ISDIR(fs.st_mode))
  263. {
  264. listing << "<tr><td>d</td>"
  265. << "<td><a href=\"" << namelist[i]->d_name << "/\">" << namelist[i]->d_name << "</a></td>"
  266. << "<td>-</td>";
  267. }
  268. else
  269. {
  270. listing << "<tr><td>f</td>"
  271. << "<td><a href=\"" << namelist[i]->d_name << "\">" << namelist[i]->d_name << "</a></td>"
  272. << "<td>" << SizeToStr(fs.st_size) << "B</td>";
  273. }
  274. listing << "<td>" << TimeRFC1123(fs.st_mtime) << "</td></tr>" << std::endl;
  275. }
  276. listing << "</table></body></html>" << std::endl;
  277. std::string response(listing.str());
  278. addDataHeaders(headers, response);
  279. sendHead(client, 200, headers);
  280. if (content == true)
  281. sendData(client, response);
  282. }
  283. /*}}}*/
  284. bool parseFirstLine(int const client, std::string const &request, /*{{{*/
  285. std::string &filename, bool &sendContent,
  286. bool &closeConnection)
  287. {
  288. if (strncmp(request.c_str(), "HEAD ", 5) == 0)
  289. sendContent = false;
  290. if (strncmp(request.c_str(), "GET ", 4) != 0)
  291. {
  292. sendError(client, 501, request, true);
  293. return false;
  294. }
  295. size_t const lineend = request.find('\n');
  296. size_t filestart = request.find(' ');
  297. for (; request[filestart] == ' '; ++filestart);
  298. size_t fileend = request.rfind(' ', lineend);
  299. if (lineend == std::string::npos || filestart == std::string::npos ||
  300. fileend == std::string::npos || filestart == fileend)
  301. {
  302. sendError(client, 500, request, sendContent, "Filename can't be extracted");
  303. return false;
  304. }
  305. size_t httpstart = fileend;
  306. for (; request[httpstart] == ' '; ++httpstart);
  307. if (strncmp(request.c_str() + httpstart, "HTTP/1.1\r", 9) == 0)
  308. closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "Keep-Alive") != 0;
  309. else if (strncmp(request.c_str() + httpstart, "HTTP/1.0\r", 9) == 0)
  310. closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "close") == 0;
  311. else
  312. {
  313. sendError(client, 500, request, sendContent, "Not a HTTP/1.{0,1} request");
  314. return false;
  315. }
  316. filename = request.substr(filestart, fileend - filestart);
  317. if (filename.find(' ') != std::string::npos)
  318. {
  319. sendError(client, 500, request, sendContent, "Filename contains an unencoded space");
  320. return false;
  321. }
  322. std::string host = LookupTag(request, "Host", "");
  323. if (host.empty() == true)
  324. {
  325. // RFC 2616 §14.23 requires Host
  326. sendError(client, 400, request, sendContent, "Host header is required");
  327. return false;
  328. }
  329. host = "http://" + host;
  330. // Proxies require absolute uris, so this is a simple proxy-fake option
  331. std::string const absolute = _config->Find("aptwebserver::request::absolute", "uri,path");
  332. if (strncmp(host.c_str(), filename.c_str(), host.length()) == 0)
  333. {
  334. if (absolute.find("uri") == std::string::npos)
  335. {
  336. sendError(client, 400, request, sendContent, "Request is absoluteURI, but configured to not accept that");
  337. return false;
  338. }
  339. // strip the host from the request to make it an absolute path
  340. filename.erase(0, host.length());
  341. }
  342. else if (absolute.find("path") == std::string::npos)
  343. {
  344. sendError(client, 400, request, sendContent, "Request is absolutePath, but configured to not accept that");
  345. return false;
  346. }
  347. filename = DeQuoteString(filename);
  348. // this is not a secure server, but at least prevent the obvious …
  349. if (filename.empty() == true || filename[0] != '/' ||
  350. strncmp(filename.c_str(), "//", 2) == 0 ||
  351. filename.find_first_of("\r\n\t\f\v") != std::string::npos ||
  352. filename.find("/../") != std::string::npos)
  353. {
  354. sendError(client, 400, request, sendContent, "Filename contains illegal character (sequence)");
  355. return false;
  356. }
  357. // nuke the first character which is a / as we assured above
  358. filename.erase(0, 1);
  359. if (filename.empty() == true)
  360. filename = ".";
  361. return true;
  362. }
  363. /*}}}*/
  364. bool handleOnTheFlyReconfiguration(int const client, std::string const &request, std::vector<std::string> const &parts)/*{{{*/
  365. {
  366. size_t const pcount = parts.size();
  367. if (pcount == 4 && parts[1] == "set")
  368. {
  369. _config->Set(parts[2], parts[3]);
  370. sendSuccess(client, request, true, "Option '" + parts[2] + "' was set to '" + parts[3] + "'!");
  371. return true;
  372. }
  373. else if (pcount == 4 && parts[1] == "find")
  374. {
  375. std::list<std::string> headers;
  376. std::string response = _config->Find(parts[2], parts[3]);
  377. addDataHeaders(headers, response);
  378. sendHead(client, 200, headers);
  379. sendData(client, response);
  380. return true;
  381. }
  382. else if (pcount == 3 && parts[1] == "find")
  383. {
  384. std::list<std::string> headers;
  385. if (_config->Exists(parts[2]) == true)
  386. {
  387. std::string response = _config->Find(parts[2]);
  388. addDataHeaders(headers, response);
  389. sendHead(client, 200, headers);
  390. sendData(client, response);
  391. return true;
  392. }
  393. sendError(client, 404, request, "Requested Configuration option doesn't exist.");
  394. return false;
  395. }
  396. else if (pcount == 3 && parts[1] == "clear")
  397. {
  398. _config->Clear(parts[2]);
  399. sendSuccess(client, request, true, "Option '" + parts[2] + "' was cleared.");
  400. return true;
  401. }
  402. sendError(client, 400, request, true, "Unknown on-the-fly configuration request");
  403. return false;
  404. }
  405. /*}}}*/
  406. int main(int const argc, const char * argv[])
  407. {
  408. CommandLine::Args Args[] = {
  409. {0, "port", "aptwebserver::port", CommandLine::HasArg},
  410. {0, "request-absolute", "aptwebserver::request::absolute", CommandLine::HasArg},
  411. {'c',"config-file",0,CommandLine::ConfigFile},
  412. {'o',"option",0,CommandLine::ArbItem},
  413. {0,0,0,0}
  414. };
  415. CommandLine CmdL(Args, _config);
  416. if(CmdL.Parse(argc,argv) == false)
  417. {
  418. _error->DumpErrors();
  419. exit(1);
  420. }
  421. // create socket, bind and listen to it {{{
  422. // ignore SIGPIPE, this can happen on write() if the socket closes connection
  423. signal(SIGPIPE, SIG_IGN);
  424. int sock = socket(AF_INET6, SOCK_STREAM, 0);
  425. if(sock < 0)
  426. {
  427. _error->Errno("aptwerbserver", "Couldn't create socket");
  428. _error->DumpErrors(std::cerr);
  429. return 1;
  430. }
  431. int const port = _config->FindI("aptwebserver::port", 8080);
  432. // ensure that we accept all connections: v4 or v6
  433. int const iponly = 0;
  434. setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &iponly, sizeof(iponly));
  435. // to not linger on an address
  436. int const enable = 1;
  437. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
  438. struct sockaddr_in6 locAddr;
  439. memset(&locAddr, 0, sizeof(locAddr));
  440. locAddr.sin6_family = AF_INET6;
  441. locAddr.sin6_port = htons(port);
  442. locAddr.sin6_addr = in6addr_any;
  443. if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0)
  444. {
  445. _error->Errno("aptwerbserver", "Couldn't bind");
  446. _error->DumpErrors(std::cerr);
  447. return 2;
  448. }
  449. FileFd pidfile;
  450. if (_config->FindB("aptwebserver::fork", false) == true)
  451. {
  452. std::string const pidfilename = _config->Find("aptwebserver::pidfile", "aptwebserver.pid");
  453. int const pidfilefd = GetLock(pidfilename);
  454. if (pidfilefd < 0 || pidfile.OpenDescriptor(pidfilefd, FileFd::WriteOnly) == false)
  455. {
  456. _error->Errno("aptwebserver", "Couldn't acquire lock on pidfile '%s'", pidfilename.c_str());
  457. _error->DumpErrors(std::cerr);
  458. return 3;
  459. }
  460. pid_t child = fork();
  461. if (child < 0)
  462. {
  463. _error->Errno("aptwebserver", "Forking failed");
  464. _error->DumpErrors(std::cerr);
  465. return 4;
  466. }
  467. else if (child != 0)
  468. {
  469. // successfully forked: ready to serve!
  470. std::string pidcontent;
  471. strprintf(pidcontent, "%d", child);
  472. pidfile.Write(pidcontent.c_str(), pidcontent.size());
  473. if (_error->PendingError() == true)
  474. {
  475. _error->DumpErrors(std::cerr);
  476. return 5;
  477. }
  478. std::cout << "Successfully forked as " << child << std::endl;
  479. return 0;
  480. }
  481. }
  482. std::clog << "Serving ANY file on port: " << port << std::endl;
  483. listen(sock, 1);
  484. /*}}}*/
  485. std::vector<std::string> messages;
  486. int client;
  487. while ((client = accept(sock, NULL, NULL)) != -1)
  488. {
  489. std::clog << "ACCEPT client " << client
  490. << " on socket " << sock << std::endl;
  491. while (ReadMessages(client, messages))
  492. {
  493. bool closeConnection = false;
  494. for (std::vector<std::string>::const_iterator m = messages.begin();
  495. m != messages.end() && closeConnection == false; ++m) {
  496. std::clog << ">>> REQUEST >>>>" << std::endl << *m
  497. << std::endl << "<<<<<<<<<<<<<<<<" << std::endl;
  498. std::list<std::string> headers;
  499. std::string filename;
  500. bool sendContent = true;
  501. if (parseFirstLine(client, *m, filename, sendContent, closeConnection) == false)
  502. continue;
  503. // special webserver command request
  504. if (filename.length() > 1 && filename[0] == '_')
  505. {
  506. std::vector<std::string> parts = VectorizeString(filename, '/');
  507. if (parts[0] == "_config")
  508. {
  509. handleOnTheFlyReconfiguration(client, *m, parts);
  510. continue;
  511. }
  512. }
  513. // string replacements in the requested filename
  514. ::Configuration::Item const *Replaces = _config->Tree("aptwebserver::redirect::replace");
  515. if (Replaces != NULL)
  516. {
  517. std::string redirect = "/" + filename;
  518. for (::Configuration::Item *I = Replaces->Child; I != NULL; I = I->Next)
  519. redirect = SubstVar(redirect, I->Tag, I->Value);
  520. redirect.erase(0,1);
  521. if (redirect != filename)
  522. {
  523. sendRedirect(client, 301, redirect, *m, sendContent);
  524. continue;
  525. }
  526. }
  527. ::Configuration::Item const *Overwrite = _config->Tree("aptwebserver::overwrite");
  528. if (Overwrite != NULL)
  529. {
  530. for (::Configuration::Item *I = Overwrite->Child; I != NULL; I = I->Next)
  531. {
  532. regex_t *pattern = new regex_t;
  533. int const res = regcomp(pattern, I->Tag.c_str(), REG_EXTENDED | REG_ICASE | REG_NOSUB);
  534. if (res != 0)
  535. {
  536. char error[300];
  537. regerror(res, pattern, error, sizeof(error));
  538. sendError(client, 500, *m, sendContent, error);
  539. continue;
  540. }
  541. if (regexec(pattern, filename.c_str(), 0, 0, 0) == 0)
  542. {
  543. filename = _config->Find("aptwebserver::overwrite::" + I->Tag + "::filename", filename);
  544. if (filename[0] == '/')
  545. filename.erase(0,1);
  546. regfree(pattern);
  547. break;
  548. }
  549. regfree(pattern);
  550. }
  551. }
  552. // deal with the request
  553. if (RealFileExists(filename) == true)
  554. {
  555. FileFd data(filename, FileFd::ReadOnly);
  556. std::string condition = LookupTag(*m, "If-Modified-Since", "");
  557. if (condition.empty() == false)
  558. {
  559. time_t cache;
  560. if (RFC1123StrToTime(condition.c_str(), cache) == true &&
  561. cache >= data.ModificationTime())
  562. {
  563. sendHead(client, 304, headers);
  564. continue;
  565. }
  566. }
  567. addFileHeaders(headers, data);
  568. sendHead(client, 200, headers);
  569. if (sendContent == true)
  570. sendFile(client, data);
  571. }
  572. else if (DirectoryExists(filename) == true)
  573. {
  574. if (filename == "." || filename[filename.length()-1] == '/')
  575. sendDirectoryListing(client, filename, *m, sendContent);
  576. else
  577. sendRedirect(client, 301, filename.append("/"), *m, sendContent);
  578. }
  579. else
  580. sendError(client, 404, *m, sendContent);
  581. }
  582. _error->DumpErrors(std::cerr);
  583. messages.clear();
  584. if (closeConnection == true)
  585. break;
  586. }
  587. std::clog << "CLOSE client " << client
  588. << " on socket " << sock << std::endl;
  589. close(client);
  590. }
  591. pidfile.Close();
  592. return 0;
  593. }