You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

966 lines
36 KiB

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