You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

544 lines
18 KiB

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