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.
 
 
 
 
 
 

857 lines
29 KiB

  1. #include <config.h>
  2. #include <apt-pkg/cmndline.h>
  3. #include <apt-pkg/configuration.h>
  4. #include <apt-pkg/error.h>
  5. #include <apt-pkg/fileutl.h>
  6. #include <apt-pkg/strutl.h>
  7. #include <dirent.h>
  8. #include <errno.h>
  9. #include <netinet/in.h>
  10. #include <pthread.h>
  11. #include <regex.h>
  12. #include <signal.h>
  13. #include <stddef.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <sys/socket.h>
  17. #include <sys/stat.h>
  18. #include <time.h>
  19. #include <unistd.h>
  20. #include <iostream>
  21. #include <sstream>
  22. #include <list>
  23. #include <string>
  24. #include <vector>
  25. static char const * httpcodeToStr(int const httpcode) /*{{{*/
  26. {
  27. switch (httpcode)
  28. {
  29. // Informational 1xx
  30. case 100: return "100 Continue";
  31. case 101: return "101 Switching Protocols";
  32. // Successful 2xx
  33. case 200: return "200 OK";
  34. case 201: return "201 Created";
  35. case 202: return "202 Accepted";
  36. case 203: return "203 Non-Authoritative Information";
  37. case 204: return "204 No Content";
  38. case 205: return "205 Reset Content";
  39. case 206: return "206 Partial Content";
  40. // Redirections 3xx
  41. case 300: return "300 Multiple Choices";
  42. case 301: return "301 Moved Permanently";
  43. case 302: return "302 Found";
  44. case 303: return "303 See Other";
  45. case 304: return "304 Not Modified";
  46. case 305: return "304 Use Proxy";
  47. case 307: return "307 Temporary Redirect";
  48. // Client errors 4xx
  49. case 400: return "400 Bad Request";
  50. case 401: return "401 Unauthorized";
  51. case 402: return "402 Payment Required";
  52. case 403: return "403 Forbidden";
  53. case 404: return "404 Not Found";
  54. case 405: return "405 Method Not Allowed";
  55. case 406: return "406 Not Acceptable";
  56. case 407: return "407 Proxy Authentication Required";
  57. case 408: return "408 Request Time-out";
  58. case 409: return "409 Conflict";
  59. case 410: return "410 Gone";
  60. case 411: return "411 Length Required";
  61. case 412: return "412 Precondition Failed";
  62. case 413: return "413 Request Entity Too Large";
  63. case 414: return "414 Request-URI Too Large";
  64. case 415: return "415 Unsupported Media Type";
  65. case 416: return "416 Requested range not satisfiable";
  66. case 417: return "417 Expectation Failed";
  67. case 418: return "418 I'm a teapot";
  68. // Server error 5xx
  69. case 500: return "500 Internal Server Error";
  70. case 501: return "501 Not Implemented";
  71. case 502: return "502 Bad Gateway";
  72. case 503: return "503 Service Unavailable";
  73. case 504: return "504 Gateway Time-out";
  74. case 505: return "505 HTTP Version not supported";
  75. }
  76. return NULL;
  77. }
  78. /*}}}*/
  79. static void addFileHeaders(std::list<std::string> &headers, FileFd &data)/*{{{*/
  80. {
  81. std::ostringstream contentlength;
  82. contentlength << "Content-Length: " << data.FileSize();
  83. headers.push_back(contentlength.str());
  84. std::string lastmodified("Last-Modified: ");
  85. lastmodified.append(TimeRFC1123(data.ModificationTime()));
  86. headers.push_back(lastmodified);
  87. }
  88. /*}}}*/
  89. static void addDataHeaders(std::list<std::string> &headers, std::string &data)/*{{{*/
  90. {
  91. std::ostringstream contentlength;
  92. contentlength << "Content-Length: " << data.size();
  93. headers.push_back(contentlength.str());
  94. }
  95. /*}}}*/
  96. static bool sendHead(int const client, int const httpcode, std::list<std::string> &headers)/*{{{*/
  97. {
  98. std::string response("HTTP/1.1 ");
  99. response.append(httpcodeToStr(httpcode));
  100. headers.push_front(response);
  101. _config->Set("APTWebserver::Last-Status-Code", httpcode);
  102. std::stringstream buffer;
  103. _config->Dump(buffer, "aptwebserver::response-header", "%t: %v%n", false);
  104. std::vector<std::string> addheaders = VectorizeString(buffer.str(), '\n');
  105. for (std::vector<std::string>::const_iterator h = addheaders.begin(); h != addheaders.end(); ++h)
  106. headers.push_back(*h);
  107. std::string date("Date: ");
  108. date.append(TimeRFC1123(time(NULL)));
  109. headers.push_back(date);
  110. std::clog << ">>> RESPONSE to " << client << " >>>" << std::endl;
  111. bool Success = true;
  112. for (std::list<std::string>::const_iterator h = headers.begin();
  113. Success == true && h != headers.end(); ++h)
  114. {
  115. Success &= FileFd::Write(client, h->c_str(), h->size());
  116. if (Success == true)
  117. Success &= FileFd::Write(client, "\r\n", 2);
  118. std::clog << *h << std::endl;
  119. }
  120. if (Success == true)
  121. Success &= FileFd::Write(client, "\r\n", 2);
  122. std::clog << "<<<<<<<<<<<<<<<<" << std::endl;
  123. return Success;
  124. }
  125. /*}}}*/
  126. static bool sendFile(int const client, FileFd &data) /*{{{*/
  127. {
  128. bool Success = true;
  129. char buffer[500];
  130. unsigned long long actual = 0;
  131. while ((Success &= data.Read(buffer, sizeof(buffer), &actual)) == true)
  132. {
  133. if (actual == 0)
  134. break;
  135. Success &= FileFd::Write(client, buffer, actual);
  136. }
  137. if (Success == false)
  138. std::cerr << "SENDFILE: READ/WRITE ERROR to " << client << std::endl;
  139. return Success;
  140. }
  141. /*}}}*/
  142. static bool sendData(int const client, std::string const &data) /*{{{*/
  143. {
  144. if (FileFd::Write(client, data.c_str(), data.size()) == false)
  145. {
  146. std::cerr << "SENDDATA: WRITE ERROR to " << client << std::endl;
  147. return false;
  148. }
  149. return true;
  150. }
  151. /*}}}*/
  152. static void sendError(int const client, int const httpcode, std::string const &request,/*{{{*/
  153. bool content, std::string const &error = "", std::list<std::string> headers = std::list<std::string>())
  154. {
  155. std::string response("<html><head><title>");
  156. response.append(httpcodeToStr(httpcode)).append("</title></head>");
  157. response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1>");
  158. if (httpcode != 200)
  159. {
  160. if (error.empty() == false)
  161. response.append("<p><em>Error</em>: ").append(error).append("</p>");
  162. response.append("This error is a result of the request: <pre>");
  163. }
  164. else
  165. {
  166. if (error.empty() == false)
  167. response.append("<p><em>Success</em>: ").append(error).append("</p>");
  168. response.append("The successfully executed operation was requested by: <pre>");
  169. }
  170. response.append(request).append("</pre></body></html>");
  171. addDataHeaders(headers, response);
  172. sendHead(client, httpcode, headers);
  173. if (content == true)
  174. sendData(client, response);
  175. }
  176. static void sendSuccess(int const client, std::string const &request,
  177. bool content, std::string const &error = "")
  178. {
  179. sendError(client, 200, request, content, error);
  180. }
  181. /*}}}*/
  182. static void sendRedirect(int const client, int const httpcode, std::string const &uri,/*{{{*/
  183. std::string const &request, bool content)
  184. {
  185. std::list<std::string> headers;
  186. std::string response("<html><head><title>");
  187. response.append(httpcodeToStr(httpcode)).append("</title></head>");
  188. response.append("<body><h1>").append(httpcodeToStr(httpcode)).append("</h1");
  189. response.append("<p>You should be redirected to <em>").append(uri).append("</em></p>");
  190. response.append("This page is a result of the request: <pre>");
  191. response.append(request).append("</pre></body></html>");
  192. addDataHeaders(headers, response);
  193. std::string location("Location: ");
  194. if (strncmp(uri.c_str(), "http://", 7) != 0 && strncmp(uri.c_str(), "https://", 8) != 0)
  195. {
  196. std::string const host = LookupTag(request, "Host");
  197. if (host.find(":4433") != std::string::npos)
  198. location.append("https://");
  199. else
  200. location.append("http://");
  201. location.append(host).append("/");
  202. if (strncmp("/home/", uri.c_str(), strlen("/home/")) == 0 && uri.find("/public_html/") != std::string::npos)
  203. {
  204. std::string homeuri = SubstVar(uri, "/home/", "~");
  205. homeuri = SubstVar(homeuri, "/public_html/", "/");
  206. location.append(homeuri);
  207. }
  208. else
  209. location.append(uri);
  210. }
  211. else
  212. location.append(uri);
  213. headers.push_back(location);
  214. sendHead(client, httpcode, headers);
  215. if (content == true)
  216. sendData(client, response);
  217. }
  218. /*}}}*/
  219. static int filter_hidden_files(const struct dirent *a) /*{{{*/
  220. {
  221. if (a->d_name[0] == '.')
  222. return 0;
  223. #ifdef _DIRENT_HAVE_D_TYPE
  224. // if we have the d_type check that only files and dirs will be included
  225. if (a->d_type != DT_UNKNOWN &&
  226. a->d_type != DT_REG &&
  227. a->d_type != DT_LNK && // this includes links to regular files
  228. a->d_type != DT_DIR)
  229. return 0;
  230. #endif
  231. return 1;
  232. }
  233. static int grouped_alpha_case_sort(const struct dirent **a, const struct dirent **b) {
  234. #ifdef _DIRENT_HAVE_D_TYPE
  235. if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_DIR);
  236. else if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_REG)
  237. return -1;
  238. else if ((*b)->d_type == DT_DIR && (*a)->d_type == DT_REG)
  239. return 1;
  240. else
  241. #endif
  242. {
  243. struct stat f_prop; //File's property
  244. stat((*a)->d_name, &f_prop);
  245. int const amode = f_prop.st_mode;
  246. stat((*b)->d_name, &f_prop);
  247. int const bmode = f_prop.st_mode;
  248. if (S_ISDIR(amode) && S_ISDIR(bmode));
  249. else if (S_ISDIR(amode))
  250. return -1;
  251. else if (S_ISDIR(bmode))
  252. return 1;
  253. }
  254. return strcasecmp((*a)->d_name, (*b)->d_name);
  255. }
  256. /*}}}*/
  257. static void sendDirectoryListing(int const client, std::string const &dir,/*{{{*/
  258. std::string const &request, bool content)
  259. {
  260. std::list<std::string> headers;
  261. std::ostringstream listing;
  262. struct dirent **namelist;
  263. int const counter = scandir(dir.c_str(), &namelist, filter_hidden_files, grouped_alpha_case_sort);
  264. if (counter == -1)
  265. {
  266. sendError(client, 500, request, content);
  267. return;
  268. }
  269. listing << "<html><head><title>Index of " << dir << "</title>"
  270. << "<style type=\"text/css\"><!-- td {padding: 0.02em 0.5em 0.02em 0.5em;}"
  271. << "tr:nth-child(even){background-color:#dfdfdf;}"
  272. << "h1, td:nth-child(3){text-align:center;}"
  273. << "table {margin-left:auto;margin-right:auto;} --></style>"
  274. << "</head>" << std::endl
  275. << "<body><h1>Index of " << dir << "</h1>" << std::endl
  276. << "<table><tr><th>#</th><th>Name</th><th>Size</th><th>Last-Modified</th></tr>" << std::endl;
  277. if (dir != "./")
  278. listing << "<tr><td>d</td><td><a href=\"..\">Parent Directory</a></td><td>-</td><td>-</td></tr>";
  279. for (int i = 0; i < counter; ++i) {
  280. struct stat fs;
  281. std::string filename(dir);
  282. filename.append("/").append(namelist[i]->d_name);
  283. stat(filename.c_str(), &fs);
  284. if (S_ISDIR(fs.st_mode))
  285. {
  286. listing << "<tr><td>d</td>"
  287. << "<td><a href=\"" << namelist[i]->d_name << "/\">" << namelist[i]->d_name << "</a></td>"
  288. << "<td>-</td>";
  289. }
  290. else
  291. {
  292. listing << "<tr><td>f</td>"
  293. << "<td><a href=\"" << namelist[i]->d_name << "\">" << namelist[i]->d_name << "</a></td>"
  294. << "<td>" << SizeToStr(fs.st_size) << "B</td>";
  295. }
  296. listing << "<td>" << TimeRFC1123(fs.st_mtime) << "</td></tr>" << std::endl;
  297. }
  298. listing << "</table></body></html>" << std::endl;
  299. std::string response(listing.str());
  300. addDataHeaders(headers, response);
  301. sendHead(client, 200, headers);
  302. if (content == true)
  303. sendData(client, response);
  304. }
  305. /*}}}*/
  306. static bool parseFirstLine(int const client, std::string const &request,/*{{{*/
  307. std::string &filename, std::string &params, bool &sendContent,
  308. bool &closeConnection)
  309. {
  310. if (strncmp(request.c_str(), "HEAD ", 5) == 0)
  311. sendContent = false;
  312. if (strncmp(request.c_str(), "GET ", 4) != 0)
  313. {
  314. sendError(client, 501, request, true);
  315. return false;
  316. }
  317. size_t const lineend = request.find('\n');
  318. size_t filestart = request.find(' ');
  319. for (; request[filestart] == ' '; ++filestart);
  320. size_t fileend = request.rfind(' ', lineend);
  321. if (lineend == std::string::npos || filestart == std::string::npos ||
  322. fileend == std::string::npos || filestart == fileend)
  323. {
  324. sendError(client, 500, request, sendContent, "Filename can't be extracted");
  325. return false;
  326. }
  327. size_t httpstart = fileend;
  328. for (; request[httpstart] == ' '; ++httpstart);
  329. if (strncmp(request.c_str() + httpstart, "HTTP/1.1\r", 9) == 0)
  330. closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "Keep-Alive") != 0;
  331. else if (strncmp(request.c_str() + httpstart, "HTTP/1.0\r", 9) == 0)
  332. closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "close") == 0;
  333. else
  334. {
  335. sendError(client, 500, request, sendContent, "Not a HTTP/1.{0,1} request");
  336. return false;
  337. }
  338. filename = request.substr(filestart, fileend - filestart);
  339. if (filename.find(' ') != std::string::npos)
  340. {
  341. sendError(client, 500, request, sendContent, "Filename contains an unencoded space");
  342. return false;
  343. }
  344. std::string host = LookupTag(request, "Host", "");
  345. if (host.empty() == true)
  346. {
  347. // RFC 2616 §14.23 requires Host
  348. sendError(client, 400, request, sendContent, "Host header is required");
  349. return false;
  350. }
  351. host = "http://" + host;
  352. // Proxies require absolute uris, so this is a simple proxy-fake option
  353. std::string const absolute = _config->Find("aptwebserver::request::absolute", "uri,path");
  354. if (strncmp(host.c_str(), filename.c_str(), host.length()) == 0 && APT::String::Startswith(filename, "/_config/") == false)
  355. {
  356. if (absolute.find("uri") == std::string::npos)
  357. {
  358. sendError(client, 400, request, sendContent, "Request is absoluteURI, but configured to not accept that");
  359. return false;
  360. }
  361. // strip the host from the request to make it an absolute path
  362. filename.erase(0, host.length());
  363. std::string const authConf = _config->Find("aptwebserver::proxy-authorization", "");
  364. std::string auth = LookupTag(request, "Proxy-Authorization", "");
  365. if (authConf.empty() != auth.empty())
  366. {
  367. if (auth.empty())
  368. sendError(client, 407, request, sendContent, "Proxy requires authentication");
  369. else
  370. sendError(client, 407, request, sendContent, "Client wants to authenticate to proxy, but proxy doesn't need it");
  371. return false;
  372. }
  373. if (authConf.empty() == false)
  374. {
  375. char const * const basic = "Basic ";
  376. if (strncmp(auth.c_str(), basic, strlen(basic)) == 0)
  377. {
  378. auth.erase(0, strlen(basic));
  379. if (auth != authConf)
  380. {
  381. sendError(client, 407, request, sendContent, "Proxy-Authentication doesn't match");
  382. return false;
  383. }
  384. }
  385. else
  386. {
  387. std::list<std::string> headers;
  388. headers.push_back("Proxy-Authenticate: Basic");
  389. sendError(client, 407, request, sendContent, "Unsupported Proxy-Authentication Scheme", headers);
  390. return false;
  391. }
  392. }
  393. }
  394. else if (absolute.find("path") == std::string::npos && APT::String::Startswith(filename, "/_config/") == false)
  395. {
  396. sendError(client, 400, request, sendContent, "Request is absolutePath, but configured to not accept that");
  397. return false;
  398. }
  399. if (APT::String::Startswith(filename, "/_config/") == false)
  400. {
  401. std::string const authConf = _config->Find("aptwebserver::authorization", "");
  402. std::string auth = LookupTag(request, "Authorization", "");
  403. if (authConf.empty() != auth.empty())
  404. {
  405. if (auth.empty())
  406. sendError(client, 401, request, sendContent, "Server requires authentication");
  407. else
  408. sendError(client, 401, request, sendContent, "Client wants to authenticate to server, but server doesn't need it");
  409. return false;
  410. }
  411. if (authConf.empty() == false)
  412. {
  413. char const * const basic = "Basic ";
  414. if (strncmp(auth.c_str(), basic, strlen(basic)) == 0)
  415. {
  416. auth.erase(0, strlen(basic));
  417. if (auth != authConf)
  418. {
  419. sendError(client, 401, request, sendContent, "Authentication doesn't match");
  420. return false;
  421. }
  422. }
  423. else
  424. {
  425. std::list<std::string> headers;
  426. headers.push_back("WWW-Authenticate: Basic");
  427. sendError(client, 401, request, sendContent, "Unsupported Authentication Scheme", headers);
  428. return false;
  429. }
  430. }
  431. }
  432. size_t paramspos = filename.find('?');
  433. if (paramspos != std::string::npos)
  434. {
  435. params = filename.substr(paramspos + 1);
  436. filename.erase(paramspos);
  437. }
  438. filename = DeQuoteString(filename);
  439. // this is not a secure server, but at least prevent the obvious …
  440. if (filename.empty() == true || filename[0] != '/' ||
  441. strncmp(filename.c_str(), "//", 2) == 0 ||
  442. filename.find_first_of("\r\n\t\f\v") != std::string::npos ||
  443. filename.find("/../") != std::string::npos)
  444. {
  445. sendError(client, 400, request, sendContent, "Filename contains illegal character (sequence)");
  446. return false;
  447. }
  448. // nuke the first character which is a / as we assured above
  449. filename.erase(0, 1);
  450. if (filename.empty() == true)
  451. filename = "./";
  452. // support ~user/ uris to refer to /home/user/public_html/ as a kind-of special directory
  453. else if (filename[0] == '~')
  454. {
  455. // /home/user is actually not entirely correct, but good enough for now
  456. size_t dashpos = filename.find('/');
  457. if (dashpos != std::string::npos)
  458. {
  459. std::string home = filename.substr(1, filename.find('/') - 1);
  460. std::string pubhtml = filename.substr(filename.find('/') + 1);
  461. filename = "/home/" + home + "/public_html/" + pubhtml;
  462. }
  463. else
  464. filename = "/home/" + filename.substr(1) + "/public_html/";
  465. }
  466. // if no filename is given, but a valid directory see if we can use an index or
  467. // have to resort to a autogenerated directory listing later on
  468. if (DirectoryExists(filename) == true)
  469. {
  470. std::string const directoryIndex = _config->Find("aptwebserver::directoryindex");
  471. if (directoryIndex.empty() == false && directoryIndex == flNotDir(directoryIndex) &&
  472. RealFileExists(filename + directoryIndex) == true)
  473. filename += directoryIndex;
  474. }
  475. return true;
  476. }
  477. /*}}}*/
  478. static bool handleOnTheFlyReconfiguration(int const client, std::string const &request, std::vector<std::string> const &parts)/*{{{*/
  479. {
  480. size_t const pcount = parts.size();
  481. if (pcount == 4 && parts[1] == "set")
  482. {
  483. _config->Set(parts[2], parts[3]);
  484. sendSuccess(client, request, true, "Option '" + parts[2] + "' was set to '" + parts[3] + "'!");
  485. return true;
  486. }
  487. else if (pcount == 4 && parts[1] == "find")
  488. {
  489. std::list<std::string> headers;
  490. std::string response = _config->Find(parts[2], parts[3]);
  491. addDataHeaders(headers, response);
  492. sendHead(client, 200, headers);
  493. sendData(client, response);
  494. return true;
  495. }
  496. else if (pcount == 3 && parts[1] == "find")
  497. {
  498. std::list<std::string> headers;
  499. if (_config->Exists(parts[2]) == true)
  500. {
  501. std::string response = _config->Find(parts[2]);
  502. addDataHeaders(headers, response);
  503. sendHead(client, 200, headers);
  504. sendData(client, response);
  505. return true;
  506. }
  507. sendError(client, 404, request, "Requested Configuration option doesn't exist.");
  508. return false;
  509. }
  510. else if (pcount == 3 && parts[1] == "clear")
  511. {
  512. _config->Clear(parts[2]);
  513. sendSuccess(client, request, true, "Option '" + parts[2] + "' was cleared.");
  514. return true;
  515. }
  516. sendError(client, 400, request, true, "Unknown on-the-fly configuration request");
  517. return false;
  518. }
  519. /*}}}*/
  520. static void * handleClient(void * voidclient) /*{{{*/
  521. {
  522. int client = *((int*)(voidclient));
  523. std::clog << "ACCEPT client " << client << std::endl;
  524. std::vector<std::string> messages;
  525. while (ReadMessages(client, messages))
  526. {
  527. bool closeConnection = false;
  528. for (std::vector<std::string>::const_iterator m = messages.begin();
  529. m != messages.end() && closeConnection == false; ++m) {
  530. std::clog << ">>> REQUEST from " << client << " >>>" << std::endl << *m
  531. << std::endl << "<<<<<<<<<<<<<<<<" << std::endl;
  532. std::list<std::string> headers;
  533. std::string filename;
  534. std::string params;
  535. bool sendContent = true;
  536. if (parseFirstLine(client, *m, filename, params, sendContent, closeConnection) == false)
  537. continue;
  538. // special webserver command request
  539. if (filename.length() > 1 && filename[0] == '_')
  540. {
  541. std::vector<std::string> parts = VectorizeString(filename, '/');
  542. if (parts[0] == "_config")
  543. {
  544. handleOnTheFlyReconfiguration(client, *m, parts);
  545. continue;
  546. }
  547. }
  548. // string replacements in the requested filename
  549. ::Configuration::Item const *Replaces = _config->Tree("aptwebserver::redirect::replace");
  550. if (Replaces != NULL)
  551. {
  552. std::string redirect = "/" + filename;
  553. for (::Configuration::Item *I = Replaces->Child; I != NULL; I = I->Next)
  554. redirect = SubstVar(redirect, I->Tag, I->Value);
  555. if (redirect.empty() == false && redirect[0] == '/')
  556. redirect.erase(0,1);
  557. if (redirect != filename)
  558. {
  559. sendRedirect(client, 301, redirect, *m, sendContent);
  560. continue;
  561. }
  562. }
  563. ::Configuration::Item const *Overwrite = _config->Tree("aptwebserver::overwrite");
  564. if (Overwrite != NULL)
  565. {
  566. for (::Configuration::Item *I = Overwrite->Child; I != NULL; I = I->Next)
  567. {
  568. regex_t *pattern = new regex_t;
  569. int const res = regcomp(pattern, I->Tag.c_str(), REG_EXTENDED | REG_ICASE | REG_NOSUB);
  570. if (res != 0)
  571. {
  572. char error[300];
  573. regerror(res, pattern, error, sizeof(error));
  574. sendError(client, 500, *m, sendContent, error);
  575. continue;
  576. }
  577. if (regexec(pattern, filename.c_str(), 0, 0, 0) == 0)
  578. {
  579. filename = _config->Find("aptwebserver::overwrite::" + I->Tag + "::filename", filename);
  580. if (filename[0] == '/')
  581. filename.erase(0,1);
  582. regfree(pattern);
  583. break;
  584. }
  585. regfree(pattern);
  586. }
  587. }
  588. // deal with the request
  589. if (_config->FindB("aptwebserver::support::http", true) == false &&
  590. LookupTag(*m, "Host").find(":4433") == std::string::npos)
  591. {
  592. sendError(client, 400, *m, sendContent, "HTTP disabled, all requests must be HTTPS");
  593. continue;
  594. }
  595. else if (RealFileExists(filename) == true)
  596. {
  597. FileFd data(filename, FileFd::ReadOnly);
  598. std::string condition = LookupTag(*m, "If-Modified-Since", "");
  599. if (_config->FindB("aptwebserver::support::modified-since", true) == true && condition.empty() == false)
  600. {
  601. time_t cache;
  602. if (RFC1123StrToTime(condition.c_str(), cache) == true &&
  603. cache >= data.ModificationTime())
  604. {
  605. sendHead(client, 304, headers);
  606. continue;
  607. }
  608. }
  609. if (_config->FindB("aptwebserver::support::range", true) == true)
  610. condition = LookupTag(*m, "Range", "");
  611. else
  612. condition.clear();
  613. if (condition.empty() == false && strncmp(condition.c_str(), "bytes=", 6) == 0)
  614. {
  615. time_t cache;
  616. std::string ifrange;
  617. if (_config->FindB("aptwebserver::support::if-range", true) == true)
  618. ifrange = LookupTag(*m, "If-Range", "");
  619. bool validrange = (ifrange.empty() == true ||
  620. (RFC1123StrToTime(ifrange.c_str(), cache) == true &&
  621. cache <= data.ModificationTime()));
  622. // FIXME: support multiple byte-ranges (APT clients do not do this)
  623. if (condition.find(',') == std::string::npos)
  624. {
  625. size_t start = 6;
  626. unsigned long long filestart = strtoull(condition.c_str() + start, NULL, 10);
  627. // FIXME: no support for last-byte-pos being not the end of the file (APT clients do not do this)
  628. size_t dash = condition.find('-') + 1;
  629. unsigned long long fileend = strtoull(condition.c_str() + dash, NULL, 10);
  630. unsigned long long filesize = data.FileSize();
  631. if ((fileend == 0 || (fileend == filesize && fileend >= filestart)) &&
  632. validrange == true)
  633. {
  634. if (filesize > filestart)
  635. {
  636. data.Skip(filestart);
  637. std::ostringstream contentlength;
  638. contentlength << "Content-Length: " << (filesize - filestart);
  639. headers.push_back(contentlength.str());
  640. std::ostringstream contentrange;
  641. contentrange << "Content-Range: bytes " << filestart << "-"
  642. << filesize - 1 << "/" << filesize;
  643. headers.push_back(contentrange.str());
  644. sendHead(client, 206, headers);
  645. if (sendContent == true)
  646. sendFile(client, data);
  647. continue;
  648. }
  649. else
  650. {
  651. headers.push_back("Content-Length: 0");
  652. std::ostringstream contentrange;
  653. contentrange << "Content-Range: bytes */" << filesize;
  654. headers.push_back(contentrange.str());
  655. sendHead(client, 416, headers);
  656. continue;
  657. }
  658. }
  659. }
  660. }
  661. addFileHeaders(headers, data);
  662. sendHead(client, 200, headers);
  663. if (sendContent == true)
  664. sendFile(client, data);
  665. }
  666. else if (DirectoryExists(filename) == true)
  667. {
  668. if (filename[filename.length()-1] == '/')
  669. sendDirectoryListing(client, filename, *m, sendContent);
  670. else
  671. sendRedirect(client, 301, filename.append("/"), *m, sendContent);
  672. }
  673. else
  674. sendError(client, 404, *m, sendContent);
  675. }
  676. _error->DumpErrors(std::cerr);
  677. messages.clear();
  678. if (closeConnection == true)
  679. break;
  680. }
  681. close(client);
  682. std::clog << "CLOSE client " << client << std::endl;
  683. return NULL;
  684. }
  685. /*}}}*/
  686. int main(int const argc, const char * argv[])
  687. {
  688. CommandLine::Args Args[] = {
  689. {0, "port", "aptwebserver::port", CommandLine::HasArg},
  690. {0, "request-absolute", "aptwebserver::request::absolute", CommandLine::HasArg},
  691. {0, "authorization", "aptwebserver::authorization", CommandLine::HasArg},
  692. {0, "proxy-authorization", "aptwebserver::proxy-authorization", CommandLine::HasArg},
  693. {'c',"config-file",0,CommandLine::ConfigFile},
  694. {'o',"option",0,CommandLine::ArbItem},
  695. {0,0,0,0}
  696. };
  697. CommandLine CmdL(Args, _config);
  698. if(CmdL.Parse(argc,argv) == false)
  699. {
  700. _error->DumpErrors();
  701. exit(1);
  702. }
  703. // create socket, bind and listen to it {{{
  704. // ignore SIGPIPE, this can happen on write() if the socket closes connection
  705. signal(SIGPIPE, SIG_IGN);
  706. // we don't care for our slaves, so ignore their death
  707. signal(SIGCHLD, SIG_IGN);
  708. int sock = socket(AF_INET6, SOCK_STREAM, 0);
  709. if(sock < 0)
  710. {
  711. _error->Errno("aptwerbserver", "Couldn't create socket");
  712. _error->DumpErrors(std::cerr);
  713. return 1;
  714. }
  715. int const port = _config->FindI("aptwebserver::port", 8080);
  716. // ensure that we accept all connections: v4 or v6
  717. int const iponly = 0;
  718. setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &iponly, sizeof(iponly));
  719. // to not linger on an address
  720. int const enable = 1;
  721. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
  722. struct sockaddr_in6 locAddr;
  723. memset(&locAddr, 0, sizeof(locAddr));
  724. locAddr.sin6_family = AF_INET6;
  725. locAddr.sin6_port = htons(port);
  726. locAddr.sin6_addr = in6addr_any;
  727. if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0)
  728. {
  729. _error->Errno("aptwerbserver", "Couldn't bind");
  730. _error->DumpErrors(std::cerr);
  731. return 2;
  732. }
  733. FileFd pidfile;
  734. if (_config->FindB("aptwebserver::fork", false) == true)
  735. {
  736. std::string const pidfilename = _config->Find("aptwebserver::pidfile", "aptwebserver.pid");
  737. int const pidfilefd = GetLock(pidfilename);
  738. if (pidfilefd < 0 || pidfile.OpenDescriptor(pidfilefd, FileFd::WriteOnly) == false)
  739. {
  740. _error->Errno("aptwebserver", "Couldn't acquire lock on pidfile '%s'", pidfilename.c_str());
  741. _error->DumpErrors(std::cerr);
  742. return 3;
  743. }
  744. pid_t child = fork();
  745. if (child < 0)
  746. {
  747. _error->Errno("aptwebserver", "Forking failed");
  748. _error->DumpErrors(std::cerr);
  749. return 4;
  750. }
  751. else if (child != 0)
  752. {
  753. // successfully forked: ready to serve!
  754. std::string pidcontent;
  755. strprintf(pidcontent, "%d", child);
  756. pidfile.Write(pidcontent.c_str(), pidcontent.size());
  757. if (_error->PendingError() == true)
  758. {
  759. _error->DumpErrors(std::cerr);
  760. return 5;
  761. }
  762. std::cout << "Successfully forked as " << child << std::endl;
  763. return 0;
  764. }
  765. }
  766. std::clog << "Serving ANY file on port: " << port << std::endl;
  767. int const slaves = _config->FindB("aptwebserver::slaves", SOMAXCONN);
  768. listen(sock, slaves);
  769. /*}}}*/
  770. _config->CndSet("aptwebserver::response-header::Server", "APT webserver");
  771. _config->CndSet("aptwebserver::response-header::Accept-Ranges", "bytes");
  772. _config->CndSet("aptwebserver::directoryindex", "index.html");
  773. std::list<int> accepted_clients;
  774. while (true)
  775. {
  776. int client = accept(sock, NULL, NULL);
  777. if (client == -1)
  778. {
  779. if (errno == EINTR)
  780. continue;
  781. _error->Errno("accept", "Couldn't accept client on socket %d", sock);
  782. _error->DumpErrors(std::cerr);
  783. return 6;
  784. }
  785. pthread_attr_t attr;
  786. if (pthread_attr_init(&attr) != 0 || pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0)
  787. {
  788. _error->Errno("pthread_attr", "Couldn't set detach attribute for a fresh thread to handle client %d on socket %d", client, sock);
  789. _error->DumpErrors(std::cerr);
  790. close(client);
  791. continue;
  792. }
  793. pthread_t tid;
  794. // thats rather dirty, but we need to store the client socket somewhere safe
  795. accepted_clients.push_front(client);
  796. if (pthread_create(&tid, &attr, &handleClient, &(*accepted_clients.begin())) != 0)
  797. {
  798. _error->Errno("pthread_create", "Couldn't create a fresh thread to handle client %d on socket %d", client, sock);
  799. _error->DumpErrors(std::cerr);
  800. close(client);
  801. continue;
  802. }
  803. }
  804. pidfile.Close();
  805. return 0;
  806. }