aptwebserver.cc 26 KB

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