aptwebserver.cc 33 KB

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