aptwebserver.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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 Conent";
  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. }
  81. /*}}}*/
  82. void addDataHeaders(std::list<std::string> &headers, std::string &data) {/*{{{*/
  83. std::ostringstream contentlength;
  84. contentlength << "Content-Length: " << data.size();
  85. headers.push_back(contentlength.str());
  86. }
  87. /*}}}*/
  88. bool sendHead(int const client, int const httpcode, std::list<std::string> &headers) { /*{{{*/
  89. std::string response("HTTP/1.1 ");
  90. response.append(httpcodeToStr(httpcode));
  91. headers.push_front(response);
  92. headers.push_back("Server: APT webserver");
  93. std::string date("Date: ");
  94. date.append(TimeRFC1123(time(NULL)));
  95. headers.push_back(date);
  96. std::clog << ">>> RESPONSE >>>" << std::endl;
  97. bool Success = true;
  98. for (std::list<std::string>::const_iterator h = headers.begin();
  99. Success == true && h != headers.end(); ++h) {
  100. Success &= FileFd::Write(client, h->c_str(), h->size());
  101. if (Success == true)
  102. Success &= FileFd::Write(client, "\r\n", 2);
  103. std::clog << *h << std::endl;
  104. }
  105. if (Success == true)
  106. Success &= FileFd::Write(client, "\r\n", 2);
  107. std::clog << "<<<<<<<<<<<<<<<<" << std::endl;
  108. return Success;
  109. }
  110. /*}}}*/
  111. bool sendFile(int const client, FileFd &data) { /*{{{*/
  112. bool Success = true;
  113. char buffer[500];
  114. unsigned long long actual = 0;
  115. while ((Success &= data.Read(buffer, sizeof(buffer), &actual)) == true) {
  116. if (actual == 0)
  117. break;
  118. Success &= FileFd::Write(client, buffer, actual);
  119. }
  120. if (Success == true)
  121. Success &= FileFd::Write(client, "\r\n", 2);
  122. return Success;
  123. }
  124. /*}}}*/
  125. bool sendData(int const client, std::string const &data) { /*{{{*/
  126. bool Success = true;
  127. Success &= FileFd::Write(client, data.c_str(), data.size());
  128. if (Success == true)
  129. Success &= FileFd::Write(client, "\r\n", 2);
  130. return Success;
  131. }
  132. /*}}}*/
  133. void sendError(int const client, int const httpcode, std::string const &request, bool content, std::string const &error = "") { /*{{{*/
  134. std::list<std::string> headers;
  135. std::string response("<html><head><title>");
  136. response.append(httpcodeToStr(httpcode)).append("</title></head>");
  137. response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1>");
  138. if (error.empty() == false)
  139. response.append("<p><em>Error</em>: ").append(error).append("</p>");
  140. response.append("This error is a result of the request: <pre>");
  141. response.append(request).append("</pre></body></html>");
  142. addDataHeaders(headers, response);
  143. sendHead(client, httpcode, headers);
  144. if (content == true)
  145. sendData(client, response);
  146. }
  147. /*}}}*/
  148. void sendRedirect(int const client, int const httpcode, std::string const &uri, std::string const &request, bool content) { /*{{{*/
  149. std::list<std::string> headers;
  150. std::string response("<html><head><title>");
  151. response.append(httpcodeToStr(httpcode)).append("</title></head>");
  152. response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1");
  153. response.append("<p>You should be redirected to <em>").append(uri).append("</em></p>");
  154. response.append("This page is a result of the request: <pre>");
  155. response.append(request).append("</pre></body></html>");
  156. addDataHeaders(headers, response);
  157. std::string location("Location: ");
  158. if (strncmp(uri.c_str(), "http://", 7) != 0)
  159. location.append("http://").append(LookupTag(request, "Host")).append("/").append(uri);
  160. else
  161. location.append(uri);
  162. headers.push_back(location);
  163. sendHead(client, httpcode, headers);
  164. if (content == true)
  165. sendData(client, response);
  166. }
  167. /*}}}*/
  168. // sendDirectoryLisiting /*{{{*/
  169. int filter_hidden_files(const struct dirent *a) {
  170. if (a->d_name[0] == '.')
  171. return 0;
  172. #ifdef _DIRENT_HAVE_D_TYPE
  173. // if we have the d_type check that only files and dirs will be included
  174. if (a->d_type != DT_UNKNOWN &&
  175. a->d_type != DT_REG &&
  176. a->d_type != DT_LNK && // this includes links to regular files
  177. a->d_type != DT_DIR)
  178. return 0;
  179. #endif
  180. return 1;
  181. }
  182. int grouped_alpha_case_sort(const struct dirent **a, const struct dirent **b) {
  183. #ifdef _DIRENT_HAVE_D_TYPE
  184. if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_DIR);
  185. else if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_REG)
  186. return -1;
  187. else if ((*b)->d_type == DT_DIR && (*a)->d_type == DT_REG)
  188. return 1;
  189. else
  190. #endif
  191. {
  192. struct stat f_prop; //File's property
  193. stat((*a)->d_name, &f_prop);
  194. int const amode = f_prop.st_mode;
  195. stat((*b)->d_name, &f_prop);
  196. int const bmode = f_prop.st_mode;
  197. if (S_ISDIR(amode) && S_ISDIR(bmode));
  198. else if (S_ISDIR(amode))
  199. return -1;
  200. else if (S_ISDIR(bmode))
  201. return 1;
  202. }
  203. return strcasecmp((*a)->d_name, (*b)->d_name);
  204. }
  205. void sendDirectoryListing(int const client, std::string const &dir, std::string const &request, bool content) {
  206. std::list<std::string> headers;
  207. std::ostringstream listing;
  208. struct dirent **namelist;
  209. int const counter = scandir(dir.c_str(), &namelist, filter_hidden_files, grouped_alpha_case_sort);
  210. if (counter == -1) {
  211. sendError(client, 500, request, content);
  212. return;
  213. }
  214. listing << "<html><head><title>Index of " << dir << "</title>"
  215. << "<style type=\"text/css\"><!-- td {padding: 0.02em 0.5em 0.02em 0.5em;}"
  216. << "tr:nth-child(even){background-color:#dfdfdf;}"
  217. << "h1, td:nth-child(3){text-align:center;}"
  218. << "table {margin-left:auto;margin-right:auto;} --></style>"
  219. << "</head>" << std::endl
  220. << "<body><h1>Index of " << dir << "</h1>" << std::endl
  221. << "<table><tr><th>#</th><th>Name</th><th>Size</th><th>Last-Modified</th></tr>" << std::endl;
  222. if (dir != ".")
  223. listing << "<tr><td>d</td><td><a href=\"..\">Parent Directory</a></td><td>-</td><td>-</td></tr>";
  224. for (int i = 0; i < counter; ++i) {
  225. struct stat fs;
  226. std::string filename(dir);
  227. filename.append("/").append(namelist[i]->d_name);
  228. stat(filename.c_str(), &fs);
  229. if (S_ISDIR(fs.st_mode)) {
  230. listing << "<tr><td>d</td>"
  231. << "<td><a href=\"" << namelist[i]->d_name << "/\">" << namelist[i]->d_name << "</a></td>"
  232. << "<td>-</td>";
  233. } else {
  234. listing << "<tr><td>f</td>"
  235. << "<td><a href=\"" << namelist[i]->d_name << "\">" << namelist[i]->d_name << "</a></td>"
  236. << "<td>" << SizeToStr(fs.st_size) << "B</td>";
  237. }
  238. listing << "<td>" << TimeRFC1123(fs.st_mtime) << "</td></tr>" << std::endl;
  239. }
  240. listing << "</table></body></html>" << std::endl;
  241. std::string response(listing.str());
  242. addDataHeaders(headers, response);
  243. sendHead(client, 200, headers);
  244. if (content == true)
  245. sendData(client, response);
  246. }
  247. /*}}}*/
  248. bool parseFirstLine(int const client, std::string const &request, std::string &filename, bool &sendContent) { /*{{{*/
  249. if (strncmp(request.c_str(), "HEAD ", 5) == 0)
  250. sendContent = false;
  251. if (strncmp(request.c_str(), "GET ", 4) != 0)
  252. {
  253. sendError(client, 501, request, true);
  254. return false;
  255. }
  256. size_t const lineend = request.find('\n');
  257. size_t filestart = request.find(' ');
  258. for (; request[filestart] == ' '; ++filestart);
  259. size_t fileend = request.rfind(' ', lineend);
  260. if (lineend == std::string::npos || filestart == std::string::npos ||
  261. fileend == std::string::npos || filestart == fileend) {
  262. sendError(client, 500, request, sendContent, "Filename can't be extracted");
  263. return false;
  264. }
  265. size_t httpstart = fileend;
  266. for (; request[httpstart] == ' '; ++httpstart);
  267. if (strncmp(request.c_str() + httpstart, "HTTP/1.1\r", 9) != 0) {
  268. sendError(client, 500, request, sendContent, "Not an HTTP/1.1 request");
  269. return false;
  270. }
  271. filename = request.substr(filestart, fileend - filestart);
  272. if (filename.find(' ') != std::string::npos) {
  273. sendError(client, 500, request, sendContent, "Filename contains an unencoded space");
  274. return false;
  275. }
  276. filename = DeQuoteString(filename);
  277. // this is not a secure server, but at least prevent the obvious …
  278. if (filename.empty() == true || filename[0] != '/' ||
  279. strncmp(filename.c_str(), "//", 2) == 0 ||
  280. filename.find_first_of("\r\n\t\f\v") != std::string::npos ||
  281. filename.find("/../") != std::string::npos) {
  282. sendError(client, 400, request, sendContent, "Filename contains illegal character (sequence)");
  283. return false;
  284. }
  285. // nuke the first character which is a / as we assured above
  286. filename.erase(0, 1);
  287. if (filename.empty() == true)
  288. filename = ".";
  289. return true;
  290. }
  291. /*}}}*/
  292. int main(int const argc, const char * argv[])
  293. {
  294. CommandLine::Args Args[] = {
  295. {0, "simulate-paywall", "aptwebserver::Simulate-Paywall",
  296. CommandLine::Boolean},
  297. {0, "port", "aptwebserver::port", CommandLine::HasArg},
  298. {'c',"config-file",0,CommandLine::ConfigFile},
  299. {'o',"option",0,CommandLine::ArbItem},
  300. {0,0,0,0}
  301. };
  302. CommandLine CmdL(Args, _config);
  303. if(CmdL.Parse(argc,argv) == false) {
  304. _error->DumpErrors();
  305. exit(1);
  306. }
  307. // create socket, bind and listen to it {{{
  308. // ignore SIGPIPE, this can happen on write() if the socket closes connection
  309. signal(SIGPIPE, SIG_IGN);
  310. int sock = socket(AF_INET6, SOCK_STREAM, 0);
  311. if(sock < 0 ) {
  312. _error->Errno("aptwerbserver", "Couldn't create socket");
  313. _error->DumpErrors(std::cerr);
  314. return 1;
  315. }
  316. // get the port
  317. int const port = _config->FindI("aptwebserver::port", 8080);
  318. bool const simulate_broken_server = _config->FindB("aptwebserver::Simulate-Paywall", false);
  319. // ensure that we accept all connections: v4 or v6
  320. int const iponly = 0;
  321. setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &iponly, sizeof(iponly));
  322. // to not linger to an address
  323. int const enable = 1;
  324. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
  325. struct sockaddr_in6 locAddr;
  326. memset(&locAddr, 0, sizeof(locAddr));
  327. locAddr.sin6_family = AF_INET6;
  328. locAddr.sin6_port = htons(port);
  329. locAddr.sin6_addr = in6addr_any;
  330. if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0) {
  331. _error->Errno("aptwerbserver", "Couldn't bind");
  332. _error->DumpErrors(std::cerr);
  333. return 2;
  334. }
  335. if (simulate_broken_server) {
  336. std::clog << "Simulating a broken web server that return nonsense "
  337. "for all querries" << std::endl;
  338. } else {
  339. std::clog << "Serving ANY file on port: " << port << std::endl;
  340. }
  341. listen(sock, 1);
  342. /*}}}*/
  343. std::vector<std::string> messages;
  344. int client;
  345. while ((client = accept(sock, NULL, NULL)) != -1) {
  346. std::clog << "ACCEPT client " << client
  347. << " on socket " << sock << std::endl;
  348. while (ReadMessages(client, messages)) {
  349. for (std::vector<std::string>::const_iterator m = messages.begin();
  350. m != messages.end(); ++m) {
  351. std::clog << ">>> REQUEST >>>>" << std::endl << *m
  352. << std::endl << "<<<<<<<<<<<<<<<<" << std::endl;
  353. std::list<std::string> headers;
  354. std::string filename;
  355. bool sendContent = true;
  356. if (parseFirstLine(client, *m, filename, sendContent) == false)
  357. continue;
  358. std::string host = LookupTag(*m, "Host", "");
  359. if (host.empty() == true) {
  360. // RFC 2616 §14.23 requires Host
  361. sendError(client, 400, *m, sendContent, "Host header is required");
  362. continue;
  363. }
  364. if (simulate_broken_server == true) {
  365. std::string data("ni ni ni\n");
  366. addDataHeaders(headers, data);
  367. sendHead(client, 200, headers);
  368. sendData(client, data);
  369. }
  370. else if (RealFileExists(filename) == true) {
  371. FileFd data(filename, FileFd::ReadOnly);
  372. std::string condition = LookupTag(*m, "If-Modified-Since", "");
  373. if (condition.empty() == false) {
  374. time_t cache;
  375. if (RFC1123StrToTime(condition.c_str(), cache) == true &&
  376. cache >= data.ModificationTime()) {
  377. sendHead(client, 304, headers);
  378. continue;
  379. }
  380. }
  381. addFileHeaders(headers, data);
  382. sendHead(client, 200, headers);
  383. if (sendContent == true)
  384. sendFile(client, data);
  385. }
  386. else if (DirectoryExists(filename) == true) {
  387. if (filename == "." || filename[filename.length()-1] == '/')
  388. sendDirectoryListing(client, filename, *m, sendContent);
  389. else
  390. sendRedirect(client, 301, filename.append("/"), *m, sendContent);
  391. }
  392. else
  393. {
  394. ::Configuration::Item const *Replaces = _config->Tree("aptwebserver::redirect::replace");
  395. if (Replaces != NULL) {
  396. std::string redirect = "/" + filename;
  397. for (::Configuration::Item *I = Replaces->Child; I != NULL; I = I->Next)
  398. redirect = SubstVar(redirect, I->Tag, I->Value);
  399. redirect.erase(0,1);
  400. if (redirect != filename) {
  401. sendRedirect(client, 301, redirect, *m, sendContent);
  402. continue;
  403. }
  404. }
  405. sendError(client, 404, *m, sendContent);
  406. }
  407. }
  408. _error->DumpErrors(std::cerr);
  409. messages.clear();
  410. }
  411. std::clog << "CLOSE client " << client
  412. << " on socket " << sock << std::endl;
  413. close(client);
  414. }
  415. return 0;
  416. }