aptwebserver.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. #include <config.h>
  2. #include <apt-pkg/strutl.h>
  3. #include <apt-pkg/fileutl.h>
  4. #include <apt-pkg/error.h>
  5. #include <apt-pkg/cmndline.h>
  6. #include <apt-pkg/configuration.h>
  7. #include <apt-pkg/init.h>
  8. #include <vector>
  9. #include <string>
  10. #include <list>
  11. #include <sstream>
  12. #include <sys/socket.h>
  13. #include <sys/types.h>
  14. #include <sys/stat.h>
  15. #include <netinet/in.h>
  16. #include <unistd.h>
  17. #include <errno.h>
  18. #include <time.h>
  19. #include <stdlib.h>
  20. #include <dirent.h>
  21. #include <signal.h>
  22. char const * const httpcodeToStr(int const httpcode) { /*{{{*/
  23. switch (httpcode) {
  24. // Informational 1xx
  25. case 100: return "100 Continue";
  26. case 101: return "101 Switching Protocols";
  27. // Successful 2xx
  28. case 200: return "200 OK";
  29. case 201: return "201 Created";
  30. case 202: return "202 Accepted";
  31. case 203: return "203 Non-Authoritative Information";
  32. case 204: return "204 No Content";
  33. case 205: return "205 Reset Content";
  34. case 206: return "206 Partial Content";
  35. // Redirections 3xx
  36. case 300: return "300 Multiple Choices";
  37. case 301: return "301 Moved Permanently";
  38. case 302: return "302 Found";
  39. case 303: return "303 See Other";
  40. case 304: return "304 Not Modified";
  41. case 305: return "304 Use Proxy";
  42. case 307: return "307 Temporary Redirect";
  43. // Client errors 4xx
  44. case 400: return "400 Bad Request";
  45. case 401: return "401 Unauthorized";
  46. case 402: return "402 Payment Required";
  47. case 403: return "403 Forbidden";
  48. case 404: return "404 Not Found";
  49. case 405: return "405 Method Not Allowed";
  50. case 406: return "406 Not Acceptable";
  51. case 407: return "407 Proxy Authentication Required";
  52. case 408: return "408 Request Time-out";
  53. case 409: return "409 Conflict";
  54. case 410: return "410 Gone";
  55. case 411: return "411 Length Required";
  56. case 412: return "412 Precondition Failed";
  57. case 413: return "413 Request Entity Too Large";
  58. case 414: return "414 Request-URI Too Large";
  59. case 415: return "415 Unsupported Media Type";
  60. case 416: return "416 Requested range not satisfiable";
  61. case 417: return "417 Expectation Failed";
  62. // Server error 5xx
  63. case 500: return "500 Internal Server Error";
  64. case 501: return "501 Not Implemented";
  65. case 502: return "502 Bad Gateway";
  66. case 503: return "503 Service Unavailable";
  67. case 504: return "504 Gateway Time-out";
  68. case 505: return "505 HTTP Version not supported";
  69. }
  70. return NULL;
  71. }
  72. /*}}}*/
  73. void addFileHeaders(std::list<std::string> &headers, FileFd &data) { /*{{{*/
  74. std::ostringstream contentlength;
  75. contentlength << "Content-Length: " << data.FileSize();
  76. headers.push_back(contentlength.str());
  77. std::string lastmodified("Last-Modified: ");
  78. lastmodified.append(TimeRFC1123(data.ModificationTime()));
  79. headers.push_back(lastmodified);
  80. std::string const fileext = flExtension(data.Name());
  81. if (fileext.empty() == false && fileext != data.Name()) {
  82. std::string confcontenttype("aptwebserver::ContentType::");
  83. confcontenttype.append(fileext);
  84. std::string const contenttype = _config->Find(confcontenttype);
  85. if (contenttype.empty() == false) {
  86. std::string header("Content-Type: ");
  87. header.append(contenttype);
  88. headers.push_back(header);
  89. }
  90. }
  91. }
  92. /*}}}*/
  93. void addDataHeaders(std::list<std::string> &headers, std::string &data) {/*{{{*/
  94. std::ostringstream contentlength;
  95. contentlength << "Content-Length: " << data.size();
  96. headers.push_back(contentlength.str());
  97. }
  98. /*}}}*/
  99. bool sendHead(int const client, int const httpcode, std::list<std::string> &headers) { /*{{{*/
  100. std::string response("HTTP/1.1 ");
  101. response.append(httpcodeToStr(httpcode));
  102. headers.push_front(response);
  103. headers.push_back("Server: APT webserver");
  104. std::string date("Date: ");
  105. date.append(TimeRFC1123(time(NULL)));
  106. headers.push_back(date);
  107. headers.push_back("Accept-Ranges: bytes");
  108. std::clog << ">>> RESPONSE >>>" << std::endl;
  109. bool Success = true;
  110. for (std::list<std::string>::const_iterator h = headers.begin();
  111. Success == true && h != headers.end(); ++h) {
  112. Success &= FileFd::Write(client, h->c_str(), h->size());
  113. if (Success == true)
  114. Success &= FileFd::Write(client, "\r\n", 2);
  115. std::clog << *h << std::endl;
  116. }
  117. if (Success == true)
  118. Success &= FileFd::Write(client, "\r\n", 2);
  119. std::clog << "<<<<<<<<<<<<<<<<" << std::endl;
  120. return Success;
  121. }
  122. /*}}}*/
  123. bool sendFile(int const client, FileFd &data) { /*{{{*/
  124. bool Success = true;
  125. char buffer[500];
  126. unsigned long long actual = 0;
  127. while ((Success &= data.Read(buffer, sizeof(buffer), &actual)) == true) {
  128. if (actual == 0)
  129. break;
  130. if (Success == true)
  131. Success &= FileFd::Write(client, buffer, actual);
  132. }
  133. if (Success == true)
  134. Success &= FileFd::Write(client, "\r\n", 2);
  135. return Success;
  136. }
  137. /*}}}*/
  138. bool sendData(int const client, std::string const &data) { /*{{{*/
  139. bool Success = true;
  140. Success &= FileFd::Write(client, data.c_str(), data.size());
  141. if (Success == true)
  142. Success &= FileFd::Write(client, "\r\n", 2);
  143. return Success;
  144. }
  145. /*}}}*/
  146. void sendError(int const client, int const httpcode, std::string const &request, bool content, std::string const &error = "") { /*{{{*/
  147. std::list<std::string> headers;
  148. std::string response("<html><head><title>");
  149. response.append(httpcodeToStr(httpcode)).append("</title></head>");
  150. response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1>");
  151. if (error.empty() == false)
  152. response.append("<p><em>Error</em>: ").append(error).append("</p>");
  153. response.append("This error is a result of the request: <pre>");
  154. response.append(request).append("</pre></body></html>");
  155. addDataHeaders(headers, response);
  156. sendHead(client, httpcode, headers);
  157. if (content == true)
  158. sendData(client, response);
  159. }
  160. /*}}}*/
  161. void sendRedirect(int const client, int const httpcode, std::string const &uri, std::string const &request, bool content) { /*{{{*/
  162. std::list<std::string> headers;
  163. std::string response("<html><head><title>");
  164. response.append(httpcodeToStr(httpcode)).append("</title></head>");
  165. response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1");
  166. response.append("<p>You should be redirected to <em>").append(uri).append("</em></p>");
  167. response.append("This page is a result of the request: <pre>");
  168. response.append(request).append("</pre></body></html>");
  169. addDataHeaders(headers, response);
  170. std::string location("Location: ");
  171. if (strncmp(uri.c_str(), "http://", 7) != 0)
  172. location.append("http://").append(LookupTag(request, "Host")).append("/").append(uri);
  173. else
  174. location.append(uri);
  175. headers.push_back(location);
  176. sendHead(client, httpcode, headers);
  177. if (content == true)
  178. sendData(client, response);
  179. }
  180. /*}}}*/
  181. // sendDirectoryLisiting /*{{{*/
  182. int filter_hidden_files(const struct dirent *a) {
  183. if (a->d_name[0] == '.')
  184. return 0;
  185. #ifdef _DIRENT_HAVE_D_TYPE
  186. // if we have the d_type check that only files and dirs will be included
  187. if (a->d_type != DT_UNKNOWN &&
  188. a->d_type != DT_REG &&
  189. a->d_type != DT_LNK && // this includes links to regular files
  190. a->d_type != DT_DIR)
  191. return 0;
  192. #endif
  193. return 1;
  194. }
  195. int grouped_alpha_case_sort(const struct dirent **a, const struct dirent **b) {
  196. #ifdef _DIRENT_HAVE_D_TYPE
  197. if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_DIR);
  198. else if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_REG)
  199. return -1;
  200. else if ((*b)->d_type == DT_DIR && (*a)->d_type == DT_REG)
  201. return 1;
  202. else
  203. #endif
  204. {
  205. struct stat f_prop; //File's property
  206. stat((*a)->d_name, &f_prop);
  207. int const amode = f_prop.st_mode;
  208. stat((*b)->d_name, &f_prop);
  209. int const bmode = f_prop.st_mode;
  210. if (S_ISDIR(amode) && S_ISDIR(bmode));
  211. else if (S_ISDIR(amode))
  212. return -1;
  213. else if (S_ISDIR(bmode))
  214. return 1;
  215. }
  216. return strcasecmp((*a)->d_name, (*b)->d_name);
  217. }
  218. void sendDirectoryListing(int const client, std::string const &dir, std::string const &request, bool content) {
  219. std::list<std::string> headers;
  220. std::ostringstream listing;
  221. struct dirent **namelist;
  222. int const counter = scandir(dir.c_str(), &namelist, filter_hidden_files, grouped_alpha_case_sort);
  223. if (counter == -1) {
  224. sendError(client, 500, request, content);
  225. return;
  226. }
  227. listing << "<html><head><title>Index of " << dir << "</title>"
  228. << "<style type=\"text/css\"><!-- td {padding: 0.02em 0.5em 0.02em 0.5em;}"
  229. << "tr:nth-child(even){background-color:#dfdfdf;}"
  230. << "h1, td:nth-child(3){text-align:center;}"
  231. << "table {margin-left:auto;margin-right:auto;} --></style>"
  232. << "</head>" << std::endl
  233. << "<body><h1>Index of " << dir << "</h1>" << std::endl
  234. << "<table><tr><th>#</th><th>Name</th><th>Size</th><th>Last-Modified</th></tr>" << std::endl;
  235. if (dir != ".")
  236. listing << "<tr><td>d</td><td><a href=\"..\">Parent Directory</a></td><td>-</td><td>-</td></tr>";
  237. for (int i = 0; i < counter; ++i) {
  238. struct stat fs;
  239. std::string filename(dir);
  240. filename.append("/").append(namelist[i]->d_name);
  241. stat(filename.c_str(), &fs);
  242. if (S_ISDIR(fs.st_mode)) {
  243. listing << "<tr><td>d</td>"
  244. << "<td><a href=\"" << namelist[i]->d_name << "/\">" << namelist[i]->d_name << "</a></td>"
  245. << "<td>-</td>";
  246. } else {
  247. listing << "<tr><td>f</td>"
  248. << "<td><a href=\"" << namelist[i]->d_name << "\">" << namelist[i]->d_name << "</a></td>"
  249. << "<td>" << SizeToStr(fs.st_size) << "B</td>";
  250. }
  251. listing << "<td>" << TimeRFC1123(fs.st_mtime) << "</td></tr>" << std::endl;
  252. }
  253. listing << "</table></body></html>" << std::endl;
  254. std::string response(listing.str());
  255. addDataHeaders(headers, response);
  256. sendHead(client, 200, headers);
  257. if (content == true)
  258. sendData(client, response);
  259. }
  260. /*}}}*/
  261. bool parseFirstLine(int const client, std::string const &request, std::string &filename, bool &sendContent, bool &closeConnection) { /*{{{*/
  262. if (strncmp(request.c_str(), "HEAD ", 5) == 0)
  263. sendContent = false;
  264. if (strncmp(request.c_str(), "GET ", 4) != 0)
  265. {
  266. sendError(client, 501, request, true);
  267. return false;
  268. }
  269. size_t const lineend = request.find('\n');
  270. size_t filestart = request.find(' ');
  271. for (; request[filestart] == ' '; ++filestart);
  272. size_t fileend = request.rfind(' ', lineend);
  273. if (lineend == std::string::npos || filestart == std::string::npos ||
  274. fileend == std::string::npos || filestart == fileend) {
  275. sendError(client, 500, request, sendContent, "Filename can't be extracted");
  276. return false;
  277. }
  278. size_t httpstart = fileend;
  279. for (; request[httpstart] == ' '; ++httpstart);
  280. if (strncmp(request.c_str() + httpstart, "HTTP/1.1\r", 9) == 0)
  281. closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "Keep-Alive") != 0;
  282. else if (strncmp(request.c_str() + httpstart, "HTTP/1.0\r", 9) == 0)
  283. closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "close") == 0;
  284. else {
  285. sendError(client, 500, request, sendContent, "Not an HTTP/1.{0,1} request");
  286. return false;
  287. }
  288. filename = request.substr(filestart, fileend - filestart);
  289. if (filename.find(' ') != std::string::npos) {
  290. sendError(client, 500, request, sendContent, "Filename contains an unencoded space");
  291. return false;
  292. }
  293. filename = DeQuoteString(filename);
  294. // this is not a secure server, but at least prevent the obvious …
  295. if (filename.empty() == true || filename[0] != '/' ||
  296. strncmp(filename.c_str(), "//", 2) == 0 ||
  297. filename.find_first_of("\r\n\t\f\v") != std::string::npos ||
  298. filename.find("/../") != std::string::npos) {
  299. sendError(client, 400, request, sendContent, "Filename contains illegal character (sequence)");
  300. return false;
  301. }
  302. // nuke the first character which is a / as we assured above
  303. filename.erase(0, 1);
  304. if (filename.empty() == true)
  305. filename = ".";
  306. return true;
  307. }
  308. /*}}}*/
  309. int main(int const argc, const char * argv[])
  310. {
  311. CommandLine::Args Args[] = {
  312. {0, "simulate-paywall", "aptwebserver::Simulate-Paywall",
  313. CommandLine::Boolean},
  314. {0, "port", "aptwebserver::port", CommandLine::HasArg},
  315. {'c',"config-file",0,CommandLine::ConfigFile},
  316. {'o',"option",0,CommandLine::ArbItem},
  317. {0,0,0,0}
  318. };
  319. CommandLine CmdL(Args, _config);
  320. if(CmdL.Parse(argc,argv) == false) {
  321. _error->DumpErrors();
  322. exit(1);
  323. }
  324. // create socket, bind and listen to it {{{
  325. // ignore SIGPIPE, this can happen on write() if the socket closes connection
  326. signal(SIGPIPE, SIG_IGN);
  327. int sock = socket(AF_INET6, SOCK_STREAM, 0);
  328. if(sock < 0 ) {
  329. _error->Errno("aptwerbserver", "Couldn't create socket");
  330. _error->DumpErrors(std::cerr);
  331. return 1;
  332. }
  333. // get the port
  334. int const port = _config->FindI("aptwebserver::port", 8080);
  335. bool const simulate_broken_server = _config->FindB("aptwebserver::Simulate-Paywall", false);
  336. // ensure that we accept all connections: v4 or v6
  337. int const iponly = 0;
  338. setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &iponly, sizeof(iponly));
  339. // to not linger to an address
  340. int const enable = 1;
  341. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
  342. struct sockaddr_in6 locAddr;
  343. memset(&locAddr, 0, sizeof(locAddr));
  344. locAddr.sin6_family = AF_INET6;
  345. locAddr.sin6_port = htons(port);
  346. locAddr.sin6_addr = in6addr_any;
  347. if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0) {
  348. _error->Errno("aptwerbserver", "Couldn't bind");
  349. _error->DumpErrors(std::cerr);
  350. return 2;
  351. }
  352. if (simulate_broken_server) {
  353. std::clog << "Simulating a broken web server that return nonsense "
  354. "for all querries" << std::endl;
  355. } else {
  356. std::clog << "Serving ANY file on port: " << port << std::endl;
  357. }
  358. listen(sock, 1);
  359. /*}}}*/
  360. std::vector<std::string> messages;
  361. int client;
  362. while ((client = accept(sock, NULL, NULL)) != -1) {
  363. std::clog << "ACCEPT client " << client
  364. << " on socket " << sock << std::endl;
  365. while (ReadMessages(client, messages)) {
  366. bool closeConnection = false;
  367. for (std::vector<std::string>::const_iterator m = messages.begin();
  368. m != messages.end() && closeConnection == false; ++m) {
  369. std::clog << ">>> REQUEST >>>>" << std::endl << *m
  370. << std::endl << "<<<<<<<<<<<<<<<<" << std::endl;
  371. std::list<std::string> headers;
  372. std::string filename;
  373. bool sendContent = true;
  374. if (parseFirstLine(client, *m, filename, sendContent, closeConnection) == false)
  375. continue;
  376. std::string host = LookupTag(*m, "Host", "");
  377. if (host.empty() == true) {
  378. // RFC 2616 §14.23 requires Host
  379. sendError(client, 400, *m, sendContent, "Host header is required");
  380. continue;
  381. }
  382. if (simulate_broken_server == true) {
  383. std::string data("ni ni ni\n");
  384. addDataHeaders(headers, data);
  385. sendHead(client, 200, headers);
  386. sendData(client, data);
  387. }
  388. else if (RealFileExists(filename) == true) {
  389. FileFd data(filename, FileFd::ReadOnly);
  390. std::string condition = LookupTag(*m, "If-Modified-Since", "");
  391. if (condition.empty() == false) {
  392. time_t cache;
  393. if (RFC1123StrToTime(condition.c_str(), cache) == true &&
  394. cache >= data.ModificationTime()) {
  395. sendHead(client, 304, headers);
  396. continue;
  397. }
  398. }
  399. condition = LookupTag(*m, "If-Range", "");
  400. bool ignoreRange = false;
  401. if (condition.empty() == false) {
  402. time_t cache;
  403. if (RFC1123StrToTime(condition.c_str(), cache) == false ||
  404. cache < data.ModificationTime())
  405. ignoreRange = true;
  406. }
  407. condition = LookupTag(*m, "Range", "");
  408. if (ignoreRange == false && condition.empty() == false &&
  409. strncmp(condition.c_str(), "bytes=", 6) == 0) {
  410. size_t end = condition.find(',');
  411. // FIXME: support multiple byte-ranges
  412. if (end == std::string::npos) {
  413. size_t start = 6;
  414. unsigned long long filestart = strtoull(condition.c_str() + start, NULL, 10);
  415. // FIXME: no fileend support
  416. size_t dash = condition.find('-') + 1;
  417. unsigned long long fileend = strtoull(condition.c_str() + dash, NULL, 10);
  418. unsigned long long filesize = data.FileSize();
  419. if (fileend == 0 || fileend == filesize) {
  420. if (filesize > filestart) {
  421. data.Skip(filestart);
  422. std::ostringstream contentlength;
  423. contentlength << "Content-Length: " << (filesize - filestart);
  424. headers.push_back(contentlength.str());
  425. std::ostringstream contentrange;
  426. contentrange << "Content-Range: bytes " << filestart << "-"
  427. << filesize - 1 << "/" << filesize;
  428. headers.push_back(contentrange.str());
  429. sendHead(client, 206, headers);
  430. if (sendContent == true)
  431. sendFile(client, data);
  432. continue;
  433. } else {
  434. headers.push_back("Content-Length: 0");
  435. std::ostringstream contentrange;
  436. contentrange << "Content-Range: bytes 0-0/" << filesize;
  437. headers.push_back(contentrange.str());
  438. sendHead(client, 416, headers);
  439. continue;
  440. }
  441. }
  442. }
  443. }
  444. addFileHeaders(headers, data);
  445. sendHead(client, 200, headers);
  446. if (sendContent == true)
  447. sendFile(client, data);
  448. }
  449. else if (DirectoryExists(filename) == true) {
  450. if (filename == "." || filename[filename.length()-1] == '/')
  451. sendDirectoryListing(client, filename, *m, sendContent);
  452. else
  453. sendRedirect(client, 301, filename.append("/"), *m, sendContent);
  454. }
  455. else
  456. {
  457. ::Configuration::Item const *Replaces = _config->Tree("aptwebserver::redirect::replace");
  458. if (Replaces != NULL) {
  459. std::string redirect = "/" + filename;
  460. for (::Configuration::Item *I = Replaces->Child; I != NULL; I = I->Next)
  461. redirect = SubstVar(redirect, I->Tag, I->Value);
  462. redirect.erase(0,1);
  463. if (redirect != filename) {
  464. sendRedirect(client, 301, redirect, *m, sendContent);
  465. continue;
  466. }
  467. }
  468. sendError(client, 404, *m, sendContent);
  469. }
  470. }
  471. _error->DumpErrors(std::cerr);
  472. messages.clear();
  473. if (closeConnection == true)
  474. break;
  475. }
  476. std::clog << "CLOSE client " << client
  477. << " on socket " << sock << std::endl;
  478. close(client);
  479. }
  480. return 0;
  481. }