aptwebserver.cc 26 KB

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