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.
 
 
 
 
 
 

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