aptwebserver.cc 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  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 char const * httpcodeToStr(int const httpcode) /*{{{*/
  27. {
  28. switch (httpcode)
  29. {
  30. // Informational 1xx
  31. case 100: return "100 Continue";
  32. case 101: return "101 Switching Protocols";
  33. // Successful 2xx
  34. case 200: return "200 OK";
  35. case 201: return "201 Created";
  36. case 202: return "202 Accepted";
  37. case 203: return "203 Non-Authoritative Information";
  38. case 204: return "204 No Content";
  39. case 205: return "205 Reset Content";
  40. case 206: return "206 Partial Content";
  41. // Redirections 3xx
  42. case 300: return "300 Multiple Choices";
  43. case 301: return "301 Moved Permanently";
  44. case 302: return "302 Found";
  45. case 303: return "303 See Other";
  46. case 304: return "304 Not Modified";
  47. case 305: return "304 Use Proxy";
  48. case 307: return "307 Temporary Redirect";
  49. // Client errors 4xx
  50. case 400: return "400 Bad Request";
  51. case 401: return "401 Unauthorized";
  52. case 402: return "402 Payment Required";
  53. case 403: return "403 Forbidden";
  54. case 404: return "404 Not Found";
  55. case 405: return "405 Method Not Allowed";
  56. case 406: return "406 Not Acceptable";
  57. case 407: return "407 Proxy Authentication Required";
  58. case 408: return "408 Request Time-out";
  59. case 409: return "409 Conflict";
  60. case 410: return "410 Gone";
  61. case 411: return "411 Length Required";
  62. case 412: return "412 Precondition Failed";
  63. case 413: return "413 Request Entity Too Large";
  64. case 414: return "414 Request-URI Too Large";
  65. case 415: return "415 Unsupported Media Type";
  66. case 416: return "416 Requested range not satisfiable";
  67. case 417: return "417 Expectation Failed";
  68. case 418: return "418 I'm a teapot";
  69. // Server error 5xx
  70. case 500: return "500 Internal Server Error";
  71. case 501: return "501 Not Implemented";
  72. case 502: return "502 Bad Gateway";
  73. case 503: return "503 Service Unavailable";
  74. case 504: return "504 Gateway Time-out";
  75. case 505: return "505 HTTP Version not supported";
  76. }
  77. return NULL;
  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)
  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. }
  413. else if (absolute.find("path") == std::string::npos)
  414. {
  415. sendError(client, 400, request, sendContent, "Request is absolutePath, but configured to not accept that", headers);
  416. return false;
  417. }
  418. size_t paramspos = filename.find('?');
  419. if (paramspos != std::string::npos)
  420. {
  421. params = filename.substr(paramspos + 1);
  422. filename.erase(paramspos);
  423. }
  424. filename = DeQuoteString(filename);
  425. // this is not a secure server, but at least prevent the obvious …
  426. if (filename.empty() == true || filename[0] != '/' ||
  427. strncmp(filename.c_str(), "//", 2) == 0 ||
  428. filename.find_first_of("\r\n\t\f\v") != std::string::npos ||
  429. filename.find("/../") != std::string::npos)
  430. {
  431. std::list<std::string> headers;
  432. sendError(client, 400, request, sendContent, "Filename contains illegal character (sequence)", headers);
  433. return false;
  434. }
  435. // nuke the first character which is a / as we assured above
  436. filename.erase(0, 1);
  437. if (filename.empty() == true)
  438. filename = "./";
  439. // support ~user/ uris to refer to /home/user/public_html/ as a kind-of special directory
  440. else if (filename[0] == '~')
  441. {
  442. // /home/user is actually not entirely correct, but good enough for now
  443. size_t dashpos = filename.find('/');
  444. if (dashpos != std::string::npos)
  445. {
  446. std::string home = filename.substr(1, filename.find('/') - 1);
  447. std::string pubhtml = filename.substr(filename.find('/') + 1);
  448. filename = "/home/" + home + "/public_html/" + pubhtml;
  449. }
  450. else
  451. filename = "/home/" + filename.substr(1) + "/public_html/";
  452. }
  453. // if no filename is given, but a valid directory see if we can use an index or
  454. // have to resort to a autogenerated directory listing later on
  455. if (DirectoryExists(filename) == true)
  456. {
  457. std::string const directoryIndex = _config->Find("aptwebserver::directoryindex");
  458. if (directoryIndex.empty() == false && directoryIndex == flNotDir(directoryIndex) &&
  459. RealFileExists(filename + directoryIndex) == true)
  460. filename += directoryIndex;
  461. }
  462. return true;
  463. }
  464. /*}}}*/
  465. static bool handleOnTheFlyReconfiguration(int const client, std::string const &request,/*{{{*/
  466. std::vector<std::string> parts, std::list<std::string> &headers)
  467. {
  468. size_t const pcount = parts.size();
  469. if (pcount == 4 && parts[1] == "set")
  470. {
  471. _config->Set(parts[2], parts[3]);
  472. sendSuccess(client, request, true, "Option '" + parts[2] + "' was set to '" + parts[3] + "'!", headers);
  473. return true;
  474. }
  475. else if (pcount == 4 && parts[1] == "find")
  476. {
  477. std::string response = _config->Find(parts[2], parts[3]);
  478. addDataHeaders(headers, response);
  479. sendHead(client, 200, headers);
  480. sendData(client, headers, response);
  481. return true;
  482. }
  483. else if (pcount == 3 && parts[1] == "find")
  484. {
  485. if (_config->Exists(parts[2]) == true)
  486. {
  487. std::string response = _config->Find(parts[2]);
  488. addDataHeaders(headers, response);
  489. sendHead(client, 200, headers);
  490. sendData(client, headers, response);
  491. return true;
  492. }
  493. sendError(client, 404, request, true, "Requested Configuration option doesn't exist", headers);
  494. return false;
  495. }
  496. else if (pcount == 3 && parts[1] == "clear")
  497. {
  498. _config->Clear(parts[2]);
  499. sendSuccess(client, request, true, "Option '" + parts[2] + "' was cleared.", headers);
  500. return true;
  501. }
  502. sendError(client, 400, request, true, "Unknown on-the-fly configuration request", headers);
  503. return false;
  504. }
  505. /*}}}*/
  506. static void * handleClient(void * voidclient) /*{{{*/
  507. {
  508. int client = *((int*)(voidclient));
  509. std::clog << "ACCEPT client " << client << std::endl;
  510. std::vector<std::string> messages;
  511. bool closeConnection = false;
  512. std::list<std::string> headers;
  513. while (closeConnection == false && ReadMessages(client, messages))
  514. {
  515. // if we announced a closing, do the close
  516. if (std::find(headers.begin(), headers.end(), std::string("Connection: close")) != headers.end())
  517. break;
  518. headers.clear();
  519. for (std::vector<std::string>::const_iterator m = messages.begin();
  520. m != messages.end() && closeConnection == false; ++m) {
  521. std::clog << ">>> REQUEST from " << client << " >>>" << std::endl << *m
  522. << std::endl << "<<<<<<<<<<<<<<<<" << std::endl;
  523. std::string filename;
  524. std::string params;
  525. bool sendContent = true;
  526. if (parseFirstLine(client, *m, filename, params, sendContent, closeConnection, headers) == false)
  527. continue;
  528. // special webserver command request
  529. if (filename.length() > 1 && filename[0] == '_')
  530. {
  531. std::vector<std::string> parts = VectorizeString(filename, '/');
  532. if (parts[0] == "_config")
  533. {
  534. handleOnTheFlyReconfiguration(client, *m, parts, headers);
  535. continue;
  536. }
  537. }
  538. // string replacements in the requested filename
  539. ::Configuration::Item const *Replaces = _config->Tree("aptwebserver::redirect::replace");
  540. if (Replaces != NULL)
  541. {
  542. std::string redirect = "/" + filename;
  543. for (::Configuration::Item *I = Replaces->Child; I != NULL; I = I->Next)
  544. redirect = SubstVar(redirect, I->Tag, I->Value);
  545. if (redirect.empty() == false && redirect[0] == '/')
  546. redirect.erase(0,1);
  547. if (redirect != filename)
  548. {
  549. sendRedirect(client, 301, redirect, *m, sendContent);
  550. continue;
  551. }
  552. }
  553. ::Configuration::Item const *Overwrite = _config->Tree("aptwebserver::overwrite");
  554. if (Overwrite != NULL)
  555. {
  556. for (::Configuration::Item *I = Overwrite->Child; I != NULL; I = I->Next)
  557. {
  558. regex_t *pattern = new regex_t;
  559. int const res = regcomp(pattern, I->Tag.c_str(), REG_EXTENDED | REG_ICASE | REG_NOSUB);
  560. if (res != 0)
  561. {
  562. char error[300];
  563. regerror(res, pattern, error, sizeof(error));
  564. sendError(client, 500, *m, sendContent, error, headers);
  565. continue;
  566. }
  567. if (regexec(pattern, filename.c_str(), 0, 0, 0) == 0)
  568. {
  569. filename = _config->Find("aptwebserver::overwrite::" + I->Tag + "::filename", filename);
  570. if (filename[0] == '/')
  571. filename.erase(0,1);
  572. regfree(pattern);
  573. break;
  574. }
  575. regfree(pattern);
  576. }
  577. }
  578. // deal with the request
  579. if (_config->FindB("aptwebserver::support::http", true) == false &&
  580. LookupTag(*m, "Host").find(":4433") == std::string::npos)
  581. {
  582. sendError(client, 400, *m, sendContent, "HTTP disabled, all requests must be HTTPS", headers);
  583. continue;
  584. }
  585. else if (RealFileExists(filename) == true)
  586. {
  587. FileFd data(filename, FileFd::ReadOnly);
  588. std::string condition = LookupTag(*m, "If-Modified-Since", "");
  589. if (_config->FindB("aptwebserver::support::modified-since", true) == true && condition.empty() == false)
  590. {
  591. time_t cache;
  592. if (RFC1123StrToTime(condition.c_str(), cache) == true &&
  593. cache >= data.ModificationTime())
  594. {
  595. sendHead(client, 304, headers);
  596. continue;
  597. }
  598. }
  599. if (_config->FindB("aptwebserver::support::range", true) == true)
  600. condition = LookupTag(*m, "Range", "");
  601. else
  602. condition.clear();
  603. if (condition.empty() == false && strncmp(condition.c_str(), "bytes=", 6) == 0)
  604. {
  605. time_t cache;
  606. std::string ifrange;
  607. if (_config->FindB("aptwebserver::support::if-range", true) == true)
  608. ifrange = LookupTag(*m, "If-Range", "");
  609. bool validrange = (ifrange.empty() == true ||
  610. (RFC1123StrToTime(ifrange.c_str(), cache) == true &&
  611. cache <= data.ModificationTime()));
  612. // FIXME: support multiple byte-ranges (APT clients do not do this)
  613. if (condition.find(',') == std::string::npos)
  614. {
  615. size_t start = 6;
  616. unsigned long long filestart = strtoull(condition.c_str() + start, NULL, 10);
  617. // FIXME: no support for last-byte-pos being not the end of the file (APT clients do not do this)
  618. size_t dash = condition.find('-') + 1;
  619. unsigned long long fileend = strtoull(condition.c_str() + dash, NULL, 10);
  620. unsigned long long filesize = data.FileSize();
  621. if ((fileend == 0 || (fileend == filesize && fileend >= filestart)) &&
  622. validrange == true)
  623. {
  624. if (filesize > filestart)
  625. {
  626. data.Skip(filestart);
  627. std::ostringstream contentlength;
  628. contentlength << "Content-Length: " << (filesize - filestart);
  629. headers.push_back(contentlength.str());
  630. std::ostringstream contentrange;
  631. contentrange << "Content-Range: bytes " << filestart << "-"
  632. << filesize - 1 << "/" << filesize;
  633. headers.push_back(contentrange.str());
  634. sendHead(client, 206, headers);
  635. if (sendContent == true)
  636. sendFile(client, headers, data);
  637. continue;
  638. }
  639. else
  640. {
  641. std::ostringstream contentrange;
  642. contentrange << "Content-Range: bytes */" << filesize;
  643. headers.push_back(contentrange.str());
  644. sendError(client, 416, *m, sendContent, "", headers);
  645. break;
  646. }
  647. }
  648. }
  649. }
  650. addFileHeaders(headers, data);
  651. sendHead(client, 200, headers);
  652. if (sendContent == true)
  653. sendFile(client, headers, data);
  654. }
  655. else if (DirectoryExists(filename) == true)
  656. {
  657. if (filename[filename.length()-1] == '/')
  658. sendDirectoryListing(client, filename, *m, sendContent, headers);
  659. else
  660. sendRedirect(client, 301, filename.append("/"), *m, sendContent);
  661. }
  662. else
  663. sendError(client, 404, *m, sendContent, "", headers);
  664. }
  665. _error->DumpErrors(std::cerr);
  666. messages.clear();
  667. }
  668. close(client);
  669. std::clog << "CLOSE client " << client << std::endl;
  670. return NULL;
  671. }
  672. /*}}}*/
  673. int main(int const argc, const char * argv[])
  674. {
  675. CommandLine::Args Args[] = {
  676. {0, "port", "aptwebserver::port", CommandLine::HasArg},
  677. {0, "request-absolute", "aptwebserver::request::absolute", CommandLine::HasArg},
  678. {'c',"config-file",0,CommandLine::ConfigFile},
  679. {'o',"option",0,CommandLine::ArbItem},
  680. {0,0,0,0}
  681. };
  682. CommandLine CmdL(Args, _config);
  683. if(CmdL.Parse(argc,argv) == false)
  684. {
  685. _error->DumpErrors();
  686. exit(1);
  687. }
  688. // create socket, bind and listen to it {{{
  689. // ignore SIGPIPE, this can happen on write() if the socket closes connection
  690. signal(SIGPIPE, SIG_IGN);
  691. // we don't care for our slaves, so ignore their death
  692. signal(SIGCHLD, SIG_IGN);
  693. int sock = socket(AF_INET6, SOCK_STREAM, 0);
  694. if(sock < 0)
  695. {
  696. _error->Errno("aptwerbserver", "Couldn't create socket");
  697. _error->DumpErrors(std::cerr);
  698. return 1;
  699. }
  700. int const port = _config->FindI("aptwebserver::port", 8080);
  701. // ensure that we accept all connections: v4 or v6
  702. int const iponly = 0;
  703. setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &iponly, sizeof(iponly));
  704. // to not linger on an address
  705. int const enable = 1;
  706. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
  707. struct sockaddr_in6 locAddr;
  708. memset(&locAddr, 0, sizeof(locAddr));
  709. locAddr.sin6_family = AF_INET6;
  710. locAddr.sin6_port = htons(port);
  711. locAddr.sin6_addr = in6addr_any;
  712. if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0)
  713. {
  714. _error->Errno("aptwerbserver", "Couldn't bind");
  715. _error->DumpErrors(std::cerr);
  716. return 2;
  717. }
  718. FileFd pidfile;
  719. if (_config->FindB("aptwebserver::fork", false) == true)
  720. {
  721. std::string const pidfilename = _config->Find("aptwebserver::pidfile", "aptwebserver.pid");
  722. int const pidfilefd = GetLock(pidfilename);
  723. if (pidfilefd < 0 || pidfile.OpenDescriptor(pidfilefd, FileFd::WriteOnly) == false)
  724. {
  725. _error->Errno("aptwebserver", "Couldn't acquire lock on pidfile '%s'", pidfilename.c_str());
  726. _error->DumpErrors(std::cerr);
  727. return 3;
  728. }
  729. pid_t child = fork();
  730. if (child < 0)
  731. {
  732. _error->Errno("aptwebserver", "Forking failed");
  733. _error->DumpErrors(std::cerr);
  734. return 4;
  735. }
  736. else if (child != 0)
  737. {
  738. // successfully forked: ready to serve!
  739. std::string pidcontent;
  740. strprintf(pidcontent, "%d", child);
  741. pidfile.Write(pidcontent.c_str(), pidcontent.size());
  742. if (_error->PendingError() == true)
  743. {
  744. _error->DumpErrors(std::cerr);
  745. return 5;
  746. }
  747. std::cout << "Successfully forked as " << child << std::endl;
  748. return 0;
  749. }
  750. }
  751. std::clog << "Serving ANY file on port: " << port << std::endl;
  752. int const slaves = _config->FindB("aptwebserver::slaves", SOMAXCONN);
  753. listen(sock, slaves);
  754. /*}}}*/
  755. _config->CndSet("aptwebserver::response-header::Server", "APT webserver");
  756. _config->CndSet("aptwebserver::response-header::Accept-Ranges", "bytes");
  757. _config->CndSet("aptwebserver::directoryindex", "index.html");
  758. std::list<int> accepted_clients;
  759. while (true)
  760. {
  761. int client = accept(sock, NULL, NULL);
  762. if (client == -1)
  763. {
  764. if (errno == EINTR)
  765. continue;
  766. _error->Errno("accept", "Couldn't accept client on socket %d", sock);
  767. _error->DumpErrors(std::cerr);
  768. return 6;
  769. }
  770. pthread_attr_t attr;
  771. if (pthread_attr_init(&attr) != 0 || pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0)
  772. {
  773. _error->Errno("pthread_attr", "Couldn't set detach attribute for a fresh thread to handle client %d on socket %d", client, sock);
  774. _error->DumpErrors(std::cerr);
  775. close(client);
  776. continue;
  777. }
  778. pthread_t tid;
  779. // thats rather dirty, but we need to store the client socket somewhere safe
  780. accepted_clients.push_front(client);
  781. if (pthread_create(&tid, &attr, &handleClient, &(*accepted_clients.begin())) != 0)
  782. {
  783. _error->Errno("pthread_create", "Couldn't create a fresh thread to handle client %d on socket %d", client, sock);
  784. _error->DumpErrors(std::cerr);
  785. close(client);
  786. continue;
  787. }
  788. }
  789. pidfile.Close();
  790. return 0;
  791. }