aptwebserver.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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/stat.h>
  14. #include <netinet/in.h>
  15. #include <unistd.h>
  16. #include <errno.h>
  17. #include <time.h>
  18. #include <stdlib.h>
  19. #include <signal.h>
  20. char const * const httpcodeToStr(int const httpcode) /*{{{*/
  21. {
  22. switch (httpcode)
  23. {
  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 Content";
  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. case 418: return "418 I'm a teapot";
  63. // Server error 5xx
  64. case 500: return "500 Internal Server Error";
  65. case 501: return "501 Not Implemented";
  66. case 502: return "502 Bad Gateway";
  67. case 503: return "503 Service Unavailable";
  68. case 504: return "504 Gateway Time-out";
  69. case 505: return "505 HTTP Version not supported";
  70. }
  71. return NULL;
  72. }
  73. /*}}}*/
  74. void addFileHeaders(std::list<std::string> &headers, FileFd &data) /*{{{*/
  75. {
  76. std::ostringstream contentlength;
  77. contentlength << "Content-Length: " << data.FileSize();
  78. headers.push_back(contentlength.str());
  79. std::string lastmodified("Last-Modified: ");
  80. lastmodified.append(TimeRFC1123(data.ModificationTime()));
  81. headers.push_back(lastmodified);
  82. }
  83. /*}}}*/
  84. void addDataHeaders(std::list<std::string> &headers, std::string &data) /*{{{*/
  85. {
  86. std::ostringstream contentlength;
  87. contentlength << "Content-Length: " << data.size();
  88. headers.push_back(contentlength.str());
  89. }
  90. /*}}}*/
  91. bool sendHead(int const client, int const httpcode, std::list<std::string> &headers)/*{{{*/
  92. {
  93. std::string response("HTTP/1.1 ");
  94. response.append(httpcodeToStr(httpcode));
  95. headers.push_front(response);
  96. headers.push_back("Server: APT webserver");
  97. std::string date("Date: ");
  98. date.append(TimeRFC1123(time(NULL)));
  99. headers.push_back(date);
  100. std::clog << ">>> RESPONSE >>>" << std::endl;
  101. bool Success = true;
  102. for (std::list<std::string>::const_iterator h = headers.begin();
  103. Success == true && h != headers.end(); ++h)
  104. {
  105. Success &= FileFd::Write(client, h->c_str(), h->size());
  106. if (Success == true)
  107. Success &= FileFd::Write(client, "\r\n", 2);
  108. std::clog << *h << std::endl;
  109. }
  110. if (Success == true)
  111. Success &= FileFd::Write(client, "\r\n", 2);
  112. std::clog << "<<<<<<<<<<<<<<<<" << std::endl;
  113. return Success;
  114. }
  115. /*}}}*/
  116. bool sendFile(int const client, FileFd &data) /*{{{*/
  117. {
  118. bool Success = true;
  119. char buffer[500];
  120. unsigned long long actual = 0;
  121. while ((Success &= data.Read(buffer, sizeof(buffer), &actual)) == true)
  122. {
  123. if (actual == 0)
  124. break;
  125. if (Success == true)
  126. Success &= FileFd::Write(client, buffer, actual);
  127. }
  128. if (Success == true)
  129. Success &= FileFd::Write(client, "\r\n", 2);
  130. return Success;
  131. }
  132. /*}}}*/
  133. bool sendData(int const client, std::string const &data) /*{{{*/
  134. {
  135. bool Success = true;
  136. Success &= FileFd::Write(client, data.c_str(), data.size());
  137. if (Success == true)
  138. Success &= FileFd::Write(client, "\r\n", 2);
  139. return Success;
  140. }
  141. /*}}}*/
  142. void sendError(int const client, int const httpcode, std::string const &request,/*{{{*/
  143. bool content, std::string const &error = "")
  144. {
  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. bool parseFirstLine(int const client, std::string const &request, /*{{{*/
  160. std::string &filename, bool &sendContent,
  161. bool &closeConnection)
  162. {
  163. if (strncmp(request.c_str(), "HEAD ", 5) == 0)
  164. sendContent = false;
  165. if (strncmp(request.c_str(), "GET ", 4) != 0)
  166. {
  167. sendError(client, 501, request, true);
  168. return false;
  169. }
  170. size_t const lineend = request.find('\n');
  171. size_t filestart = request.find(' ');
  172. for (; request[filestart] == ' '; ++filestart);
  173. size_t fileend = request.rfind(' ', lineend);
  174. if (lineend == std::string::npos || filestart == std::string::npos ||
  175. fileend == std::string::npos || filestart == fileend)
  176. {
  177. sendError(client, 500, request, sendContent, "Filename can't be extracted");
  178. return false;
  179. }
  180. size_t httpstart = fileend;
  181. for (; request[httpstart] == ' '; ++httpstart);
  182. if (strncmp(request.c_str() + httpstart, "HTTP/1.1\r", 9) == 0)
  183. closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "Keep-Alive") != 0;
  184. else if (strncmp(request.c_str() + httpstart, "HTTP/1.0\r", 9) == 0)
  185. closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "close") == 0;
  186. else
  187. {
  188. sendError(client, 500, request, sendContent, "Not a HTTP/1.{0,1} request");
  189. return false;
  190. }
  191. filename = request.substr(filestart, fileend - filestart);
  192. if (filename.find(' ') != std::string::npos)
  193. {
  194. sendError(client, 500, request, sendContent, "Filename contains an unencoded space");
  195. return false;
  196. }
  197. filename = DeQuoteString(filename);
  198. // this is not a secure server, but at least prevent the obvious …
  199. if (filename.empty() == true || filename[0] != '/' ||
  200. strncmp(filename.c_str(), "//", 2) == 0 ||
  201. filename.find_first_of("\r\n\t\f\v") != std::string::npos ||
  202. filename.find("/../") != std::string::npos)
  203. {
  204. sendError(client, 400, request, sendContent, "Filename contains illegal character (sequence)");
  205. return false;
  206. }
  207. // nuke the first character which is a / as we assured above
  208. filename.erase(0, 1);
  209. if (filename.empty() == true)
  210. filename = ".";
  211. return true;
  212. }
  213. /*}}}*/
  214. int main(int const argc, const char * argv[])
  215. {
  216. CommandLine::Args Args[] = {
  217. {0, "port", "aptwebserver::port", CommandLine::HasArg},
  218. {'c',"config-file",0,CommandLine::ConfigFile},
  219. {'o',"option",0,CommandLine::ArbItem},
  220. {0,0,0,0}
  221. };
  222. CommandLine CmdL(Args, _config);
  223. if(CmdL.Parse(argc,argv) == false)
  224. {
  225. _error->DumpErrors();
  226. exit(1);
  227. }
  228. // create socket, bind and listen to it {{{
  229. // ignore SIGPIPE, this can happen on write() if the socket closes connection
  230. signal(SIGPIPE, SIG_IGN);
  231. int sock = socket(AF_INET6, SOCK_STREAM, 0);
  232. if(sock < 0)
  233. {
  234. _error->Errno("aptwerbserver", "Couldn't create socket");
  235. _error->DumpErrors(std::cerr);
  236. return 1;
  237. }
  238. int const port = _config->FindI("aptwebserver::port", 8080);
  239. // ensure that we accept all connections: v4 or v6
  240. int const iponly = 0;
  241. setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &iponly, sizeof(iponly));
  242. // to not linger on an address
  243. int const enable = 1;
  244. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));
  245. struct sockaddr_in6 locAddr;
  246. memset(&locAddr, 0, sizeof(locAddr));
  247. locAddr.sin6_family = AF_INET6;
  248. locAddr.sin6_port = htons(port);
  249. locAddr.sin6_addr = in6addr_any;
  250. if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0)
  251. {
  252. _error->Errno("aptwerbserver", "Couldn't bind");
  253. _error->DumpErrors(std::cerr);
  254. return 2;
  255. }
  256. std::clog << "Serving ANY file on port: " << port << std::endl;
  257. listen(sock, 1);
  258. /*}}}*/
  259. std::vector<std::string> messages;
  260. int client;
  261. while ((client = accept(sock, NULL, NULL)) != -1)
  262. {
  263. std::clog << "ACCEPT client " << client
  264. << " on socket " << sock << std::endl;
  265. while (ReadMessages(client, messages))
  266. {
  267. bool closeConnection = false;
  268. for (std::vector<std::string>::const_iterator m = messages.begin();
  269. m != messages.end() && closeConnection == false; ++m) {
  270. std::clog << ">>> REQUEST >>>>" << std::endl << *m
  271. << std::endl << "<<<<<<<<<<<<<<<<" << std::endl;
  272. std::list<std::string> headers;
  273. std::string filename;
  274. bool sendContent = true;
  275. if (parseFirstLine(client, *m, filename, sendContent, closeConnection) == false)
  276. continue;
  277. std::string host = LookupTag(*m, "Host", "");
  278. if (host.empty() == true)
  279. {
  280. // RFC 2616 §14.23 requires Host
  281. sendError(client, 400, *m, sendContent, "Host header is required");
  282. continue;
  283. }
  284. if (RealFileExists(filename) == true)
  285. {
  286. FileFd data(filename, FileFd::ReadOnly);
  287. std::string condition = LookupTag(*m, "If-Modified-Since", "");
  288. if (condition.empty() == false)
  289. {
  290. time_t cache;
  291. if (RFC1123StrToTime(condition.c_str(), cache) == true &&
  292. cache >= data.ModificationTime())
  293. {
  294. sendHead(client, 304, headers);
  295. continue;
  296. }
  297. }
  298. addFileHeaders(headers, data);
  299. sendHead(client, 200, headers);
  300. if (sendContent == true)
  301. sendFile(client, data);
  302. }
  303. else
  304. sendError(client, 404, *m, sendContent);
  305. }
  306. _error->DumpErrors(std::cerr);
  307. messages.clear();
  308. if (closeConnection == true)
  309. break;
  310. }
  311. std::clog << "CLOSE client " << client
  312. << " on socket " << sock << std::endl;
  313. close(client);
  314. }
  315. return 0;
  316. }