aptwebserver.cc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  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 to " << client << " >>>" << 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. Success &= FileFd::Write(client, buffer, actual);
  133. }
  134. if (Success == false)
  135. std::cerr << "SENDFILE: READ/WRITE ERROR to " << client << std::endl;
  136. return Success;
  137. }
  138. /*}}}*/
  139. bool sendData(int const client, std::string const &data) /*{{{*/
  140. {
  141. if (FileFd::Write(client, data.c_str(), data.size()) == false)
  142. {
  143. std::cerr << "SENDDATA: WRITE ERROR to " << client << std::endl;
  144. return false;
  145. }
  146. return true;
  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. {
  194. location.append("http://").append(LookupTag(request, "Host")).append("/");
  195. if (strncmp("/home/", uri.c_str(), strlen("/home/")) == 0 && uri.find("/public_html/") != std::string::npos)
  196. {
  197. std::string homeuri = SubstVar(uri, "/home/", "~");
  198. homeuri = SubstVar(homeuri, "/public_html/", "/");
  199. location.append(homeuri);
  200. }
  201. else
  202. location.append(uri);
  203. }
  204. else
  205. location.append(uri);
  206. headers.push_back(location);
  207. sendHead(client, httpcode, headers);
  208. if (content == true)
  209. sendData(client, response);
  210. }
  211. /*}}}*/
  212. int filter_hidden_files(const struct dirent *a) /*{{{*/
  213. {
  214. if (a->d_name[0] == '.')
  215. return 0;
  216. #ifdef _DIRENT_HAVE_D_TYPE
  217. // if we have the d_type check that only files and dirs will be included
  218. if (a->d_type != DT_UNKNOWN &&
  219. a->d_type != DT_REG &&
  220. a->d_type != DT_LNK && // this includes links to regular files
  221. a->d_type != DT_DIR)
  222. return 0;
  223. #endif
  224. return 1;
  225. }
  226. int grouped_alpha_case_sort(const struct dirent **a, const struct dirent **b) {
  227. #ifdef _DIRENT_HAVE_D_TYPE
  228. if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_DIR);
  229. else if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_REG)
  230. return -1;
  231. else if ((*b)->d_type == DT_DIR && (*a)->d_type == DT_REG)
  232. return 1;
  233. else
  234. #endif
  235. {
  236. struct stat f_prop; //File's property
  237. stat((*a)->d_name, &f_prop);
  238. int const amode = f_prop.st_mode;
  239. stat((*b)->d_name, &f_prop);
  240. int const bmode = f_prop.st_mode;
  241. if (S_ISDIR(amode) && S_ISDIR(bmode));
  242. else if (S_ISDIR(amode))
  243. return -1;
  244. else if (S_ISDIR(bmode))
  245. return 1;
  246. }
  247. return strcasecmp((*a)->d_name, (*b)->d_name);
  248. }
  249. /*}}}*/
  250. void sendDirectoryListing(int const client, std::string const &dir, /*{{{*/
  251. std::string const &request, bool content)
  252. {
  253. std::list<std::string> headers;
  254. std::ostringstream listing;
  255. struct dirent **namelist;
  256. int const counter = scandir(dir.c_str(), &namelist, filter_hidden_files, grouped_alpha_case_sort);
  257. if (counter == -1)
  258. {
  259. sendError(client, 500, request, content);
  260. return;
  261. }
  262. listing << "<html><head><title>Index of " << dir << "</title>"
  263. << "<style type=\"text/css\"><!-- td {padding: 0.02em 0.5em 0.02em 0.5em;}"
  264. << "tr:nth-child(even){background-color:#dfdfdf;}"
  265. << "h1, td:nth-child(3){text-align:center;}"
  266. << "table {margin-left:auto;margin-right:auto;} --></style>"
  267. << "</head>" << std::endl
  268. << "<body><h1>Index of " << dir << "</h1>" << std::endl
  269. << "<table><tr><th>#</th><th>Name</th><th>Size</th><th>Last-Modified</th></tr>" << std::endl;
  270. if (dir != "./")
  271. listing << "<tr><td>d</td><td><a href=\"..\">Parent Directory</a></td><td>-</td><td>-</td></tr>";
  272. for (int i = 0; i < counter; ++i) {
  273. struct stat fs;
  274. std::string filename(dir);
  275. filename.append("/").append(namelist[i]->d_name);
  276. stat(filename.c_str(), &fs);
  277. if (S_ISDIR(fs.st_mode))
  278. {
  279. listing << "<tr><td>d</td>"
  280. << "<td><a href=\"" << namelist[i]->d_name << "/\">" << namelist[i]->d_name << "</a></td>"
  281. << "<td>-</td>";
  282. }
  283. else
  284. {
  285. listing << "<tr><td>f</td>"
  286. << "<td><a href=\"" << namelist[i]->d_name << "\">" << namelist[i]->d_name << "</a></td>"
  287. << "<td>" << SizeToStr(fs.st_size) << "B</td>";
  288. }
  289. listing << "<td>" << TimeRFC1123(fs.st_mtime) << "</td></tr>" << std::endl;
  290. }
  291. listing << "</table></body></html>" << std::endl;
  292. std::string response(listing.str());
  293. addDataHeaders(headers, response);
  294. sendHead(client, 200, headers);
  295. if (content == true)
  296. sendData(client, response);
  297. }
  298. /*}}}*/
  299. bool parseFirstLine(int const client, std::string const &request, /*{{{*/
  300. std::string &filename, std::string &params, bool &sendContent,
  301. bool &closeConnection)
  302. {
  303. if (strncmp(request.c_str(), "HEAD ", 5) == 0)
  304. sendContent = false;
  305. if (strncmp(request.c_str(), "GET ", 4) != 0)
  306. {
  307. sendError(client, 501, request, true);
  308. return false;
  309. }
  310. size_t const lineend = request.find('\n');
  311. size_t filestart = request.find(' ');
  312. for (; request[filestart] == ' '; ++filestart);
  313. size_t fileend = request.rfind(' ', lineend);
  314. if (lineend == std::string::npos || filestart == std::string::npos ||
  315. fileend == std::string::npos || filestart == fileend)
  316. {
  317. sendError(client, 500, request, sendContent, "Filename can't be extracted");
  318. return false;
  319. }
  320. size_t httpstart = fileend;
  321. for (; request[httpstart] == ' '; ++httpstart);
  322. if (strncmp(request.c_str() + httpstart, "HTTP/1.1\r", 9) == 0)
  323. closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "Keep-Alive") != 0;
  324. else if (strncmp(request.c_str() + httpstart, "HTTP/1.0\r", 9) == 0)
  325. closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "close") == 0;
  326. else
  327. {
  328. sendError(client, 500, request, sendContent, "Not a HTTP/1.{0,1} request");
  329. return false;
  330. }
  331. filename = request.substr(filestart, fileend - filestart);
  332. if (filename.find(' ') != std::string::npos)
  333. {
  334. sendError(client, 500, request, sendContent, "Filename contains an unencoded space");
  335. return false;
  336. }
  337. std::string host = LookupTag(request, "Host", "");
  338. if (host.empty() == true)
  339. {
  340. // RFC 2616 §14.23 requires Host
  341. sendError(client, 400, request, sendContent, "Host header is required");
  342. return false;
  343. }
  344. host = "http://" + host;
  345. // Proxies require absolute uris, so this is a simple proxy-fake option
  346. std::string const absolute = _config->Find("aptwebserver::request::absolute", "uri,path");
  347. if (strncmp(host.c_str(), filename.c_str(), host.length()) == 0)
  348. {
  349. if (absolute.find("uri") == std::string::npos)
  350. {
  351. sendError(client, 400, request, sendContent, "Request is absoluteURI, but configured to not accept that");
  352. return false;
  353. }
  354. // strip the host from the request to make it an absolute path
  355. filename.erase(0, host.length());
  356. }
  357. else if (absolute.find("path") == std::string::npos)
  358. {
  359. sendError(client, 400, request, sendContent, "Request is absolutePath, but configured to not accept that");
  360. return false;
  361. }
  362. size_t paramspos = filename.find('?');
  363. if (paramspos != std::string::npos)
  364. {
  365. params = filename.substr(paramspos + 1);
  366. filename.erase(paramspos);
  367. }
  368. filename = DeQuoteString(filename);
  369. // this is not a secure server, but at least prevent the obvious …
  370. if (filename.empty() == true || filename[0] != '/' ||
  371. strncmp(filename.c_str(), "//", 2) == 0 ||
  372. filename.find_first_of("\r\n\t\f\v") != std::string::npos ||
  373. filename.find("/../") != std::string::npos)
  374. {
  375. sendError(client, 400, request, sendContent, "Filename contains illegal character (sequence)");
  376. return false;
  377. }
  378. // nuke the first character which is a / as we assured above
  379. filename.erase(0, 1);
  380. if (filename.empty() == true)
  381. filename = "./";
  382. // support ~user/ uris to refer to /home/user/public_html/ as a kind-of special directory
  383. else if (filename[0] == '~')
  384. {
  385. // /home/user is actually not entirely correct, but good enough for now
  386. size_t dashpos = filename.find('/');
  387. if (dashpos != std::string::npos)
  388. {
  389. std::string home = filename.substr(1, filename.find('/') - 1);
  390. std::string pubhtml = filename.substr(filename.find('/') + 1);
  391. filename = "/home/" + home + "/public_html/" + pubhtml;
  392. }
  393. else
  394. filename = "/home/" + filename.substr(1) + "/public_html/";
  395. }
  396. // if no filename is given, but a valid directory see if we can use an index or
  397. // have to resort to a autogenerated directory listing later on
  398. if (DirectoryExists(filename) == true)
  399. {
  400. std::string const directoryIndex = _config->Find("aptwebserver::directoryindex");
  401. if (directoryIndex.empty() == false && directoryIndex == flNotDir(directoryIndex) &&
  402. RealFileExists(filename + directoryIndex) == true)
  403. filename += directoryIndex;
  404. }
  405. return true;
  406. }
  407. /*}}}*/
  408. bool handleOnTheFlyReconfiguration(int const client, std::string const &request, std::vector<std::string> const &parts)/*{{{*/
  409. {
  410. size_t const pcount = parts.size();
  411. if (pcount == 4 && parts[1] == "set")
  412. {
  413. _config->Set(parts[2], parts[3]);
  414. sendSuccess(client, request, true, "Option '" + parts[2] + "' was set to '" + parts[3] + "'!");
  415. return true;
  416. }
  417. else if (pcount == 4 && parts[1] == "find")
  418. {
  419. std::list<std::string> headers;
  420. std::string response = _config->Find(parts[2], parts[3]);
  421. addDataHeaders(headers, response);
  422. sendHead(client, 200, headers);
  423. sendData(client, response);
  424. return true;
  425. }
  426. else if (pcount == 3 && parts[1] == "find")
  427. {
  428. std::list<std::string> headers;
  429. if (_config->Exists(parts[2]) == true)
  430. {
  431. std::string response = _config->Find(parts[2]);
  432. addDataHeaders(headers, response);
  433. sendHead(client, 200, headers);
  434. sendData(client, response);
  435. return true;
  436. }
  437. sendError(client, 404, request, "Requested Configuration option doesn't exist.");
  438. return false;
  439. }
  440. else if (pcount == 3 && parts[1] == "clear")
  441. {
  442. _config->Clear(parts[2]);
  443. sendSuccess(client, request, true, "Option '" + parts[2] + "' was cleared.");
  444. return true;
  445. }
  446. sendError(client, 400, request, true, "Unknown on-the-fly configuration request");
  447. return false;
  448. }
  449. /*}}}*/
  450. void * handleClient(void * voidclient) /*{{{*/
  451. {
  452. int client = *((int*)(voidclient));
  453. std::clog << "ACCEPT client " << client << std::endl;
  454. std::vector<std::string> messages;
  455. while (ReadMessages(client, messages))
  456. {
  457. bool closeConnection = false;
  458. for (std::vector<std::string>::const_iterator m = messages.begin();
  459. m != messages.end() && closeConnection == false; ++m) {
  460. std::clog << ">>> REQUEST from " << client << " >>>" << std::endl << *m
  461. << std::endl << "<<<<<<<<<<<<<<<<" << std::endl;
  462. std::list<std::string> headers;
  463. std::string filename;
  464. std::string params;
  465. bool sendContent = true;
  466. if (parseFirstLine(client, *m, filename, params, sendContent, closeConnection) == false)
  467. continue;
  468. // special webserver command request
  469. if (filename.length() > 1 && filename[0] == '_')
  470. {
  471. std::vector<std::string> parts = VectorizeString(filename, '/');
  472. if (parts[0] == "_config")
  473. {
  474. handleOnTheFlyReconfiguration(client, *m, parts);
  475. continue;
  476. }
  477. }
  478. // string replacements in the requested filename
  479. ::Configuration::Item const *Replaces = _config->Tree("aptwebserver::redirect::replace");
  480. if (Replaces != NULL)
  481. {
  482. std::string redirect = "/" + filename;
  483. for (::Configuration::Item *I = Replaces->Child; I != NULL; I = I->Next)
  484. redirect = SubstVar(redirect, I->Tag, I->Value);
  485. redirect.erase(0,1);
  486. if (redirect != filename)
  487. {
  488. sendRedirect(client, 301, redirect, *m, sendContent);
  489. continue;
  490. }
  491. }
  492. ::Configuration::Item const *Overwrite = _config->Tree("aptwebserver::overwrite");
  493. if (Overwrite != NULL)
  494. {
  495. for (::Configuration::Item *I = Overwrite->Child; I != NULL; I = I->Next)
  496. {
  497. regex_t *pattern = new regex_t;
  498. int const res = regcomp(pattern, I->Tag.c_str(), REG_EXTENDED | REG_ICASE | REG_NOSUB);
  499. if (res != 0)
  500. {
  501. char error[300];
  502. regerror(res, pattern, error, sizeof(error));
  503. sendError(client, 500, *m, sendContent, error);
  504. continue;
  505. }
  506. if (regexec(pattern, filename.c_str(), 0, 0, 0) == 0)
  507. {
  508. filename = _config->Find("aptwebserver::overwrite::" + I->Tag + "::filename", filename);
  509. if (filename[0] == '/')
  510. filename.erase(0,1);
  511. regfree(pattern);
  512. break;
  513. }
  514. regfree(pattern);
  515. }
  516. }
  517. // deal with the request
  518. if (RealFileExists(filename) == true)
  519. {
  520. FileFd data(filename, FileFd::ReadOnly);
  521. std::string condition = LookupTag(*m, "If-Modified-Since", "");
  522. if (_config->FindB("aptwebserver::support::modified-since", true) == true && condition.empty() == false)
  523. {
  524. time_t cache;
  525. if (RFC1123StrToTime(condition.c_str(), cache) == true &&
  526. cache >= data.ModificationTime())
  527. {
  528. sendHead(client, 304, headers);
  529. continue;
  530. }
  531. }
  532. if (_config->FindB("aptwebserver::support::range", true) == true)
  533. condition = LookupTag(*m, "Range", "");
  534. else
  535. condition.clear();
  536. if (condition.empty() == false && strncmp(condition.c_str(), "bytes=", 6) == 0)
  537. {
  538. time_t cache;
  539. std::string ifrange;
  540. if (_config->FindB("aptwebserver::support::if-range", true) == true)
  541. ifrange = LookupTag(*m, "If-Range", "");
  542. bool validrange = (ifrange.empty() == true ||
  543. (RFC1123StrToTime(ifrange.c_str(), cache) == true &&
  544. cache <= data.ModificationTime()));
  545. // FIXME: support multiple byte-ranges (APT clients do not do this)
  546. if (condition.find(',') == std::string::npos)
  547. {
  548. size_t start = 6;
  549. unsigned long long filestart = strtoull(condition.c_str() + start, NULL, 10);
  550. // FIXME: no support for last-byte-pos being not the end of the file (APT clients do not do this)
  551. size_t dash = condition.find('-') + 1;
  552. unsigned long long fileend = strtoull(condition.c_str() + dash, NULL, 10);
  553. unsigned long long filesize = data.FileSize();
  554. if ((fileend == 0 || (fileend == filesize && fileend >= filestart)) &&
  555. validrange == true)
  556. {
  557. if (filesize > filestart)
  558. {
  559. data.Skip(filestart);
  560. std::ostringstream contentlength;
  561. contentlength << "Content-Length: " << (filesize - filestart);
  562. headers.push_back(contentlength.str());
  563. std::ostringstream contentrange;
  564. contentrange << "Content-Range: bytes " << filestart << "-"
  565. << filesize - 1 << "/" << filesize;
  566. headers.push_back(contentrange.str());
  567. sendHead(client, 206, headers);
  568. if (sendContent == true)
  569. sendFile(client, data);
  570. continue;
  571. }
  572. else
  573. {
  574. headers.push_back("Content-Length: 0");
  575. std::ostringstream contentrange;
  576. contentrange << "Content-Range: bytes */" << filesize;
  577. headers.push_back(contentrange.str());
  578. sendHead(client, 416, headers);
  579. continue;
  580. }
  581. }
  582. }
  583. }
  584. addFileHeaders(headers, data);
  585. sendHead(client, 200, headers);
  586. if (sendContent == true)
  587. sendFile(client, data);
  588. }
  589. else if (DirectoryExists(filename) == true)
  590. {
  591. if (filename[filename.length()-1] == '/')
  592. sendDirectoryListing(client, filename, *m, sendContent);
  593. else
  594. sendRedirect(client, 301, filename.append("/"), *m, sendContent);
  595. }
  596. else
  597. sendError(client, 404, *m, sendContent);
  598. }
  599. _error->DumpErrors(std::cerr);
  600. messages.clear();
  601. if (closeConnection == true)
  602. break;
  603. }
  604. close(client);
  605. std::clog << "CLOSE client " << client << std::endl;
  606. return NULL;
  607. }
  608. /*}}}*/
  609. int main(int const argc, const char * argv[])
  610. {
  611. CommandLine::Args Args[] = {
  612. {0, "port", "aptwebserver::port", CommandLine::HasArg},
  613. {0, "request-absolute", "aptwebserver::request::absolute", CommandLine::HasArg},
  614. {'c',"config-file",0,CommandLine::ConfigFile},
  615. {'o',"option",0,CommandLine::ArbItem},
  616. {0,0,0,0}
  617. };
  618. CommandLine CmdL(Args, _config);
  619. if(CmdL.Parse(argc,argv) == false)
  620. {
  621. _error->DumpErrors();
  622. exit(1);
  623. }
  624. // create socket, bind and listen to it {{{
  625. // ignore SIGPIPE, this can happen on write() if the socket closes connection
  626. signal(SIGPIPE, SIG_IGN);
  627. // we don't care for our slaves, so ignore their death
  628. signal(SIGCHLD, SIG_IGN);
  629. int sock = socket(AF_INET6, SOCK_STREAM, 0);
  630. if(sock < 0)
  631. {
  632. _error->Errno("aptwerbserver", "Couldn't create socket");
  633. _error->DumpErrors(std::cerr);
  634. return 1;
  635. }
  636. int const port = _config->FindI("aptwebserver::port", 8080);
  637. // ensure that we accept all connections: v4 or v6
  638. int const iponly = 0;
  639. setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &iponly, sizeof(iponly));
  640. // to not linger on an address
  641. int const enable = 1;
  642. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
  643. struct sockaddr_in6 locAddr;
  644. memset(&locAddr, 0, sizeof(locAddr));
  645. locAddr.sin6_family = AF_INET6;
  646. locAddr.sin6_port = htons(port);
  647. locAddr.sin6_addr = in6addr_any;
  648. if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0)
  649. {
  650. _error->Errno("aptwerbserver", "Couldn't bind");
  651. _error->DumpErrors(std::cerr);
  652. return 2;
  653. }
  654. FileFd pidfile;
  655. if (_config->FindB("aptwebserver::fork", false) == true)
  656. {
  657. std::string const pidfilename = _config->Find("aptwebserver::pidfile", "aptwebserver.pid");
  658. int const pidfilefd = GetLock(pidfilename);
  659. if (pidfilefd < 0 || pidfile.OpenDescriptor(pidfilefd, FileFd::WriteOnly) == false)
  660. {
  661. _error->Errno("aptwebserver", "Couldn't acquire lock on pidfile '%s'", pidfilename.c_str());
  662. _error->DumpErrors(std::cerr);
  663. return 3;
  664. }
  665. pid_t child = fork();
  666. if (child < 0)
  667. {
  668. _error->Errno("aptwebserver", "Forking failed");
  669. _error->DumpErrors(std::cerr);
  670. return 4;
  671. }
  672. else if (child != 0)
  673. {
  674. // successfully forked: ready to serve!
  675. std::string pidcontent;
  676. strprintf(pidcontent, "%d", child);
  677. pidfile.Write(pidcontent.c_str(), pidcontent.size());
  678. if (_error->PendingError() == true)
  679. {
  680. _error->DumpErrors(std::cerr);
  681. return 5;
  682. }
  683. std::cout << "Successfully forked as " << child << std::endl;
  684. return 0;
  685. }
  686. }
  687. std::clog << "Serving ANY file on port: " << port << std::endl;
  688. int const slaves = _config->FindB("aptwebserver::slaves", SOMAXCONN);
  689. listen(sock, slaves);
  690. /*}}}*/
  691. _config->CndSet("aptwebserver::response-header::Server", "APT webserver");
  692. _config->CndSet("aptwebserver::response-header::Accept-Ranges", "bytes");
  693. _config->CndSet("aptwebserver::directoryindex", "index.html");
  694. std::list<int> accepted_clients;
  695. while (true)
  696. {
  697. int client = accept(sock, NULL, NULL);
  698. if (client == -1)
  699. {
  700. if (errno == EINTR)
  701. continue;
  702. _error->Errno("accept", "Couldn't accept client on socket %d", sock);
  703. _error->DumpErrors(std::cerr);
  704. return 6;
  705. }
  706. pthread_attr_t attr;
  707. if (pthread_attr_init(&attr) != 0 || pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0)
  708. {
  709. _error->Errno("pthread_attr", "Couldn't set detach attribute for a fresh thread to handle client %d on socket %d", client, sock);
  710. _error->DumpErrors(std::cerr);
  711. close(client);
  712. continue;
  713. }
  714. pthread_t tid;
  715. // thats rather dirty, but we need to store the client socket somewhere safe
  716. accepted_clients.push_front(client);
  717. if (pthread_create(&tid, &attr, &handleClient, &(*accepted_clients.begin())) != 0)
  718. {
  719. _error->Errno("pthread_create", "Couldn't create a fresh thread to handle client %d on socket %d", client, sock);
  720. _error->DumpErrors(std::cerr);
  721. close(client);
  722. continue;
  723. }
  724. }
  725. pidfile.Close();
  726. return 0;
  727. }