aptwebserver.cc 34 KB

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