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