aptwebserver.cc 16 KB

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