aptwebserver.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. char const * const httpcodeToStr(int const httpcode) { /*{{{*/
  22. switch (httpcode) {
  23. // Informational 1xx
  24. case 100: return "100 Continue";
  25. case 101: return "101 Switching Protocols";
  26. // Successful 2xx
  27. case 200: return "200 OK";
  28. case 201: return "201 Created";
  29. case 202: return "202 Accepted";
  30. case 203: return "203 Non-Authoritative Information";
  31. case 204: return "204 No Content";
  32. case 205: return "205 Reset Content";
  33. case 206: return "206 Partial Conent";
  34. // Redirections 3xx
  35. case 300: return "300 Multiple Choices";
  36. case 301: return "301 Moved Permanently";
  37. case 302: return "302 Found";
  38. case 303: return "303 See Other";
  39. case 304: return "304 Not Modified";
  40. case 305: return "304 Use Proxy";
  41. case 307: return "307 Temporary Redirect";
  42. // Client errors 4xx
  43. case 400: return "400 Bad Request";
  44. case 401: return "401 Unauthorized";
  45. case 402: return "402 Payment Required";
  46. case 403: return "403 Forbidden";
  47. case 404: return "404 Not Found";
  48. case 405: return "405 Method Not Allowed";
  49. case 406: return "406 Not Acceptable";
  50. case 407: return "Proxy Authentication Required";
  51. case 408: return "Request Time-out";
  52. case 409: return "Conflict";
  53. case 410: return "Gone";
  54. case 411: return "Length Required";
  55. case 412: return "Precondition Failed";
  56. case 413: return "Request Entity Too Large";
  57. case 414: return "Request-URI Too Large";
  58. case 415: return "Unsupported Media Type";
  59. case 416: return "Requested range not satisfiable";
  60. case 417: return "Expectation Failed";
  61. // Server error 5xx
  62. case 500: return "Internal Server Error";
  63. case 501: return "Not Implemented";
  64. case 502: return "Bad Gateway";
  65. case 503: return "Service Unavailable";
  66. case 504: return "Gateway Time-out";
  67. case 505: return "HTTP Version not supported";
  68. }
  69. return NULL;
  70. }
  71. /*}}}*/
  72. void addFileHeaders(std::list<std::string> &headers, FileFd &data) { /*{{{*/
  73. std::ostringstream contentlength;
  74. contentlength << "Content-Length: " << data.FileSize();
  75. headers.push_back(contentlength.str());
  76. std::string lastmodified("Last-Modified: ");
  77. lastmodified.append(TimeRFC1123(data.ModificationTime()));
  78. headers.push_back(lastmodified);
  79. }
  80. /*}}}*/
  81. void addDataHeaders(std::list<std::string> &headers, std::string &data) {/*{{{*/
  82. std::ostringstream contentlength;
  83. contentlength << "Content-Length: " << data.size();
  84. headers.push_back(contentlength.str());
  85. }
  86. /*}}}*/
  87. bool sendHead(int const client, int const httpcode, std::list<std::string> &headers) { /*{{{*/
  88. std::string response("HTTP/1.1 ");
  89. response.append(httpcodeToStr(httpcode));
  90. headers.push_front(response);
  91. headers.push_back("Server: APT webserver");
  92. std::string date("Date: ");
  93. date.append(TimeRFC1123(time(NULL)));
  94. headers.push_back(date);
  95. std::clog << ">>> RESPONSE >>>" << std::endl;
  96. bool Success = true;
  97. for (std::list<std::string>::const_iterator h = headers.begin();
  98. Success == true && h != headers.end(); ++h) {
  99. Success &= FileFd::Write(client, h->c_str(), h->size());
  100. Success &= FileFd::Write(client, "\r\n", 2);
  101. std::clog << *h << std::endl;
  102. }
  103. Success &= FileFd::Write(client, "\r\n", 2);
  104. std::clog << "<<<<<<<<<<<<<<<<" << std::endl;
  105. return Success;
  106. }
  107. /*}}}*/
  108. bool sendFile(int const client, FileFd &data) { /*{{{*/
  109. bool Success = true;
  110. char buffer[500];
  111. unsigned long long actual = 0;
  112. while ((Success &= data.Read(buffer, sizeof(buffer), &actual)) == true) {
  113. if (actual == 0)
  114. break;
  115. Success &= FileFd::Write(client, buffer, actual);
  116. }
  117. Success &= FileFd::Write(client, "\r\n", 2);
  118. return Success;
  119. }
  120. /*}}}*/
  121. bool sendData(int const client, std::string const &data) { /*{{{*/
  122. bool Success = true;
  123. Success &= FileFd::Write(client, data.c_str(), data.size());
  124. Success &= FileFd::Write(client, "\r\n", 2);
  125. return Success;
  126. }
  127. /*}}}*/
  128. void sendError(int const client, int const httpcode, std::string const &request, bool content) { /*{{{*/
  129. std::list<std::string> headers;
  130. std::string response("<html><head><title>");
  131. response.append(httpcodeToStr(httpcode)).append("</title></head>");
  132. response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1");
  133. response.append("This error is a result of the request: <pre>");
  134. response.append(request).append("</pre></body></html>");
  135. addDataHeaders(headers, response);
  136. sendHead(client, httpcode, headers);
  137. if (content == true)
  138. sendData(client, response);
  139. }
  140. /*}}}*/
  141. // sendDirectoryLisiting /*{{{*/
  142. int filter_hidden_files(const struct dirent *a) {
  143. if (a->d_name[0] == '.')
  144. return 0;
  145. #ifdef _DIRENT_HAVE_D_TYPE
  146. // if we have the d_type check that only files and dirs will be included
  147. if (a->d_type != DT_UNKNOWN &&
  148. a->d_type != DT_REG &&
  149. a->d_type != DT_LNK && // this includes links to regular files
  150. a->d_type != DT_DIR)
  151. return 0;
  152. #endif
  153. return 1;
  154. }
  155. int grouped_alpha_case_sort(const struct dirent **a, const struct dirent **b) {
  156. #ifdef _DIRENT_HAVE_D_TYPE
  157. if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_DIR);
  158. else if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_REG)
  159. return -1;
  160. else if ((*b)->d_type == DT_DIR && (*a)->d_type == DT_REG)
  161. return 1;
  162. else
  163. #endif
  164. {
  165. struct stat f_prop; //File's property
  166. stat((*a)->d_name, &f_prop);
  167. int const amode = f_prop.st_mode;
  168. stat((*b)->d_name, &f_prop);
  169. int const bmode = f_prop.st_mode;
  170. if (S_ISDIR(amode) && S_ISDIR(bmode));
  171. else if (S_ISDIR(amode))
  172. return -1;
  173. else if (S_ISDIR(bmode))
  174. return 1;
  175. }
  176. return strcasecmp((*a)->d_name, (*b)->d_name);
  177. }
  178. void sendDirectoryListing(int const client, std::string const &dir, std::string const &request, bool content) {
  179. std::list<std::string> headers;
  180. std::ostringstream listing;
  181. struct dirent **namelist;
  182. int const counter = scandir(dir.c_str(), &namelist, filter_hidden_files, grouped_alpha_case_sort);
  183. if (counter == -1) {
  184. sendError(client, 500, request, content);
  185. return;
  186. }
  187. listing << "<html><head><title>Index of " << dir << "</title>"
  188. << "<style type=\"text/css\"><!-- td {padding: 0.02em 0.5em 0.02em 0.5em;}"
  189. << "tr:nth-child(even){background-color:#dfdfdf;}"
  190. << "h1, td:nth-child(3){text-align:center;}"
  191. << "table {margin-left:auto;margin-right:auto;} --></style>"
  192. << "</head>" << std::endl
  193. << "<body><h1>Index of " << dir << "</h1>" << std::endl
  194. << "<table><tr><th>#</th><th>Name</th><th>Size</th><th>Last-Modified</th></tr>" << std::endl;
  195. if (dir != ".")
  196. listing << "<tr><td>d</td><td><a href=\"..\">Parent Directory</a></td><td>-</td><td>-</td></tr>";
  197. for (int i = 0; i < counter; ++i) {
  198. struct stat fs;
  199. std::string filename(dir);
  200. filename.append("/").append(namelist[i]->d_name);
  201. stat(filename.c_str(), &fs);
  202. listing << "<tr><td>" << ((S_ISDIR(fs.st_mode)) ? 'd' : 'f') << "</td>"
  203. << "<td><a href=\"" << namelist[i]->d_name << "\">" << namelist[i]->d_name << "</a></td>";
  204. if (S_ISDIR(fs.st_mode))
  205. listing << "<td>-</td>";
  206. else
  207. listing << "<td>" << SizeToStr(fs.st_size) << "B</td>";
  208. listing << "<td>" << TimeRFC1123(fs.st_mtime) << "</td></tr>" << std::endl;
  209. }
  210. listing << "</table></body></html>" << std::endl;
  211. std::string response(listing.str());
  212. addDataHeaders(headers, response);
  213. sendHead(client, 200, headers);
  214. if (content == true)
  215. sendData(client, response);
  216. }
  217. /*}}}*/
  218. int main(int const argc, const char * argv[])
  219. {
  220. CommandLine::Args Args[] = {
  221. {0, "simulate-paywall", "aptwebserver::Simulate-Paywall",
  222. CommandLine::Boolean},
  223. {0, "port", "aptwebserver::port", CommandLine::HasArg},
  224. {0,0,0,0}
  225. };
  226. CommandLine CmdL(Args, _config);
  227. if(CmdL.Parse(argc,argv) == false) {
  228. _error->DumpErrors();
  229. exit(1);
  230. }
  231. // create socket, bind and listen to it {{{
  232. int sock = socket(AF_INET6, SOCK_STREAM, 0);
  233. if(sock < 0 ) {
  234. _error->Errno("aptwerbserver", "Couldn't create socket");
  235. _error->DumpErrors(std::cerr);
  236. return 1;
  237. }
  238. // get the port
  239. int const port = _config->FindI("aptwebserver::port", 8080);
  240. bool const simulate_broken_server = _config->FindB("aptwebserver::Simulate-Paywall", false);
  241. // ensure that we accept all connections: v4 or v6
  242. int const iponly = 0;
  243. setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &iponly, sizeof(iponly));
  244. // to not linger to an address
  245. int const enable = 1;
  246. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
  247. struct sockaddr_in6 locAddr;
  248. memset(&locAddr, 0, sizeof(locAddr));
  249. locAddr.sin6_family = AF_INET6;
  250. locAddr.sin6_port = htons(port);
  251. locAddr.sin6_addr = in6addr_any;
  252. if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0) {
  253. _error->Errno("aptwerbserver", "Couldn't bind");
  254. _error->DumpErrors(std::cerr);
  255. return 2;
  256. }
  257. if (simulate_broken_server) {
  258. std::clog << "Simulating a broken web server that return nonsense "
  259. "for all querries" << std::endl;
  260. } else {
  261. std::clog << "Serving ANY file on port: " << port << std::endl;
  262. }
  263. listen(sock, 1);
  264. /*}}}*/
  265. std::vector<std::string> messages;
  266. int client;
  267. while ((client = accept(sock, NULL, NULL)) != -1) {
  268. std::clog << "ACCEPT client " << client
  269. << " on socket " << sock << std::endl;
  270. while (ReadMessages(client, messages)) {
  271. for (std::vector<std::string>::const_iterator m = messages.begin();
  272. m != messages.end(); ++m) {
  273. std::clog << ">>> REQUEST >>>>" << std::endl << *m
  274. << std::endl << "<<<<<<<<<<<<<<<<" << std::endl;
  275. std::list<std::string> headers;
  276. bool sendContent = true;
  277. if (strncmp(m->c_str(), "HEAD ", 5) == 0)
  278. sendContent = false;
  279. if (strncmp(m->c_str(), "GET ", 4) != 0)
  280. sendError(client, 501, *m, true);
  281. std::string host = LookupTag(*m, "Host", "");
  282. if (host.empty() == true) {
  283. // RFC 2616 §14.23 Host
  284. sendError(client, 400, *m, sendContent);
  285. continue;
  286. }
  287. size_t const filestart = m->find(' ', 5);
  288. std::string filename = m->substr(5, filestart - 5);
  289. if (filename.empty() == true)
  290. filename = ".";
  291. else
  292. filename = DeQuoteString(filename);
  293. if (simulate_broken_server == true) {
  294. std::string data("ni ni ni\n");
  295. addDataHeaders(headers, data);
  296. sendHead(client, 200, headers);
  297. sendData(client, data);
  298. }
  299. else if (RealFileExists(filename) == true) {
  300. FileFd data(filename, FileFd::ReadOnly);
  301. std::string condition = LookupTag(*m, "If-Modified-Since", "");
  302. if (condition.empty() == false) {
  303. time_t cache;
  304. if (RFC1123StrToTime(condition.c_str(), cache) == true &&
  305. cache >= data.ModificationTime()) {
  306. sendHead(client, 304, headers);
  307. continue;
  308. }
  309. }
  310. addFileHeaders(headers, data);
  311. sendHead(client, 200, headers);
  312. if (sendContent == true)
  313. sendFile(client, data);
  314. }
  315. else if (DirectoryExists(filename) == true) {
  316. sendDirectoryListing(client, filename, *m, sendContent);
  317. }
  318. else
  319. sendError(client, 404, *m, false);
  320. }
  321. _error->DumpErrors(std::cerr);
  322. messages.clear();
  323. }
  324. std::clog << "CLOSE client " << client
  325. << " on socket " << sock << std::endl;
  326. close(client);
  327. }
  328. return 0;
  329. }