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.
 
 
 
 
 
 

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