]>
Commit | Line | Data |
---|---|---|
fbd29dd6 DK |
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> | |
bf3daa15 | 16 | #include <sys/types.h> |
fbd29dd6 DK |
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> | |
bf3daa15 | 23 | #include <dirent.h> |
fbd29dd6 DK |
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); | |
14c84d02 | 103 | _config->Set("APTWebserver::Last-Status-Code", httpcode); |
fbd29dd6 | 104 | |
14c84d02 DK |
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); | |
fbd29dd6 DK |
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; | |
93a99dac | 140 | Success &= FileFd::Write(client, buffer, actual); |
fbd29dd6 | 141 | } |
93a99dac DK |
142 | if (Success == false) |
143 | std::cerr << "SENDFILE: READ/WRITE ERROR to " << client << std::endl; | |
fbd29dd6 DK |
144 | return Success; |
145 | } | |
146 | /*}}}*/ | |
147 | bool sendData(int const client, std::string const &data) /*{{{*/ | |
148 | { | |
93a99dac DK |
149 | if (FileFd::Write(client, data.c_str(), data.size()) == false) |
150 | { | |
151 | std::cerr << "SENDDATA: WRITE ERROR to " << client << std::endl; | |
152 | return false; | |
153 | } | |
154 | return true; | |
fbd29dd6 DK |
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>"); | |
6beca0eb DK |
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 | } | |
fbd29dd6 DK |
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); | |
6beca0eb DK |
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); | |
fbd29dd6 DK |
186 | } |
187 | /*}}}*/ | |
bf3daa15 DK |
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) | |
eab3a9b2 DK |
201 | { |
202 | location.append("http://").append(LookupTag(request, "Host")).append("/"); | |
203 | if (strncmp("/home/", uri.c_str(), strlen("/home/")) == 0 && uri.find("/public_html/") != std::string::npos) | |
204 | { | |
205 | std::string homeuri = SubstVar(uri, "/home/", "~"); | |
206 | homeuri = SubstVar(homeuri, "/public_html/", "/"); | |
207 | location.append(homeuri); | |
208 | } | |
209 | else | |
210 | location.append(uri); | |
211 | } | |
bf3daa15 DK |
212 | else |
213 | location.append(uri); | |
214 | headers.push_back(location); | |
215 | sendHead(client, httpcode, headers); | |
216 | if (content == true) | |
217 | sendData(client, response); | |
218 | } | |
219 | /*}}}*/ | |
220 | int filter_hidden_files(const struct dirent *a) /*{{{*/ | |
221 | { | |
222 | if (a->d_name[0] == '.') | |
223 | return 0; | |
224 | #ifdef _DIRENT_HAVE_D_TYPE | |
225 | // if we have the d_type check that only files and dirs will be included | |
226 | if (a->d_type != DT_UNKNOWN && | |
227 | a->d_type != DT_REG && | |
228 | a->d_type != DT_LNK && // this includes links to regular files | |
229 | a->d_type != DT_DIR) | |
230 | return 0; | |
231 | #endif | |
232 | return 1; | |
233 | } | |
234 | int grouped_alpha_case_sort(const struct dirent **a, const struct dirent **b) { | |
235 | #ifdef _DIRENT_HAVE_D_TYPE | |
236 | if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_DIR); | |
237 | else if ((*a)->d_type == DT_DIR && (*b)->d_type == DT_REG) | |
238 | return -1; | |
239 | else if ((*b)->d_type == DT_DIR && (*a)->d_type == DT_REG) | |
240 | return 1; | |
241 | else | |
242 | #endif | |
243 | { | |
244 | struct stat f_prop; //File's property | |
245 | stat((*a)->d_name, &f_prop); | |
246 | int const amode = f_prop.st_mode; | |
247 | stat((*b)->d_name, &f_prop); | |
248 | int const bmode = f_prop.st_mode; | |
249 | if (S_ISDIR(amode) && S_ISDIR(bmode)); | |
250 | else if (S_ISDIR(amode)) | |
251 | return -1; | |
252 | else if (S_ISDIR(bmode)) | |
253 | return 1; | |
254 | } | |
255 | return strcasecmp((*a)->d_name, (*b)->d_name); | |
256 | } | |
257 | /*}}}*/ | |
258 | void sendDirectoryListing(int const client, std::string const &dir, /*{{{*/ | |
259 | std::string const &request, bool content) | |
260 | { | |
261 | std::list<std::string> headers; | |
262 | std::ostringstream listing; | |
263 | ||
264 | struct dirent **namelist; | |
265 | int const counter = scandir(dir.c_str(), &namelist, filter_hidden_files, grouped_alpha_case_sort); | |
266 | if (counter == -1) | |
267 | { | |
268 | sendError(client, 500, request, content); | |
269 | return; | |
270 | } | |
271 | ||
272 | listing << "<html><head><title>Index of " << dir << "</title>" | |
273 | << "<style type=\"text/css\"><!-- td {padding: 0.02em 0.5em 0.02em 0.5em;}" | |
274 | << "tr:nth-child(even){background-color:#dfdfdf;}" | |
275 | << "h1, td:nth-child(3){text-align:center;}" | |
276 | << "table {margin-left:auto;margin-right:auto;} --></style>" | |
277 | << "</head>" << std::endl | |
278 | << "<body><h1>Index of " << dir << "</h1>" << std::endl | |
279 | << "<table><tr><th>#</th><th>Name</th><th>Size</th><th>Last-Modified</th></tr>" << std::endl; | |
280 | if (dir != ".") | |
281 | listing << "<tr><td>d</td><td><a href=\"..\">Parent Directory</a></td><td>-</td><td>-</td></tr>"; | |
282 | for (int i = 0; i < counter; ++i) { | |
283 | struct stat fs; | |
284 | std::string filename(dir); | |
285 | filename.append("/").append(namelist[i]->d_name); | |
286 | stat(filename.c_str(), &fs); | |
287 | if (S_ISDIR(fs.st_mode)) | |
288 | { | |
289 | listing << "<tr><td>d</td>" | |
290 | << "<td><a href=\"" << namelist[i]->d_name << "/\">" << namelist[i]->d_name << "</a></td>" | |
291 | << "<td>-</td>"; | |
292 | } | |
293 | else | |
294 | { | |
295 | listing << "<tr><td>f</td>" | |
296 | << "<td><a href=\"" << namelist[i]->d_name << "\">" << namelist[i]->d_name << "</a></td>" | |
297 | << "<td>" << SizeToStr(fs.st_size) << "B</td>"; | |
298 | } | |
299 | listing << "<td>" << TimeRFC1123(fs.st_mtime) << "</td></tr>" << std::endl; | |
300 | } | |
301 | listing << "</table></body></html>" << std::endl; | |
302 | ||
303 | std::string response(listing.str()); | |
304 | addDataHeaders(headers, response); | |
305 | sendHead(client, 200, headers); | |
306 | if (content == true) | |
307 | sendData(client, response); | |
308 | } | |
309 | /*}}}*/ | |
fbd29dd6 DK |
310 | bool parseFirstLine(int const client, std::string const &request, /*{{{*/ |
311 | std::string &filename, bool &sendContent, | |
312 | bool &closeConnection) | |
313 | { | |
314 | if (strncmp(request.c_str(), "HEAD ", 5) == 0) | |
315 | sendContent = false; | |
316 | if (strncmp(request.c_str(), "GET ", 4) != 0) | |
317 | { | |
318 | sendError(client, 501, request, true); | |
319 | return false; | |
320 | } | |
321 | ||
322 | size_t const lineend = request.find('\n'); | |
323 | size_t filestart = request.find(' '); | |
324 | for (; request[filestart] == ' '; ++filestart); | |
325 | size_t fileend = request.rfind(' ', lineend); | |
326 | if (lineend == std::string::npos || filestart == std::string::npos || | |
327 | fileend == std::string::npos || filestart == fileend) | |
328 | { | |
329 | sendError(client, 500, request, sendContent, "Filename can't be extracted"); | |
330 | return false; | |
331 | } | |
332 | ||
333 | size_t httpstart = fileend; | |
334 | for (; request[httpstart] == ' '; ++httpstart); | |
335 | if (strncmp(request.c_str() + httpstart, "HTTP/1.1\r", 9) == 0) | |
336 | closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "Keep-Alive") != 0; | |
337 | else if (strncmp(request.c_str() + httpstart, "HTTP/1.0\r", 9) == 0) | |
338 | closeConnection = strcasecmp(LookupTag(request, "Connection", "Keep-Alive").c_str(), "close") == 0; | |
339 | else | |
340 | { | |
341 | sendError(client, 500, request, sendContent, "Not a HTTP/1.{0,1} request"); | |
342 | return false; | |
343 | } | |
344 | ||
345 | filename = request.substr(filestart, fileend - filestart); | |
346 | if (filename.find(' ') != std::string::npos) | |
347 | { | |
348 | sendError(client, 500, request, sendContent, "Filename contains an unencoded space"); | |
349 | return false; | |
350 | } | |
f2380a78 DK |
351 | |
352 | std::string host = LookupTag(request, "Host", ""); | |
353 | if (host.empty() == true) | |
354 | { | |
355 | // RFC 2616 §14.23 requires Host | |
356 | sendError(client, 400, request, sendContent, "Host header is required"); | |
357 | return false; | |
358 | } | |
359 | host = "http://" + host; | |
360 | ||
361 | // Proxies require absolute uris, so this is a simple proxy-fake option | |
362 | std::string const absolute = _config->Find("aptwebserver::request::absolute", "uri,path"); | |
363 | if (strncmp(host.c_str(), filename.c_str(), host.length()) == 0) | |
364 | { | |
365 | if (absolute.find("uri") == std::string::npos) | |
366 | { | |
367 | sendError(client, 400, request, sendContent, "Request is absoluteURI, but configured to not accept that"); | |
368 | return false; | |
369 | } | |
370 | // strip the host from the request to make it an absolute path | |
371 | filename.erase(0, host.length()); | |
372 | } | |
373 | else if (absolute.find("path") == std::string::npos) | |
374 | { | |
375 | sendError(client, 400, request, sendContent, "Request is absolutePath, but configured to not accept that"); | |
376 | return false; | |
377 | } | |
fbd29dd6 DK |
378 | filename = DeQuoteString(filename); |
379 | ||
380 | // this is not a secure server, but at least prevent the obvious … | |
381 | if (filename.empty() == true || filename[0] != '/' || | |
382 | strncmp(filename.c_str(), "//", 2) == 0 || | |
383 | filename.find_first_of("\r\n\t\f\v") != std::string::npos || | |
384 | filename.find("/../") != std::string::npos) | |
385 | { | |
386 | sendError(client, 400, request, sendContent, "Filename contains illegal character (sequence)"); | |
387 | return false; | |
388 | } | |
389 | ||
390 | // nuke the first character which is a / as we assured above | |
391 | filename.erase(0, 1); | |
392 | if (filename.empty() == true) | |
393 | filename = "."; | |
eab3a9b2 DK |
394 | // support ~user/ uris to refer to /home/user/public_html/ as a kind-of special directory |
395 | else if (filename[0] == '~') | |
396 | { | |
397 | // /home/user is actually not entirely correct, but good enough for now | |
398 | size_t dashpos = filename.find('/'); | |
399 | if (dashpos != std::string::npos) | |
400 | { | |
401 | std::string home = filename.substr(1, filename.find('/') - 1); | |
402 | std::string pubhtml = filename.substr(filename.find('/') + 1); | |
403 | filename = "/home/" + home + "/public_html/" + pubhtml; | |
404 | } | |
405 | else | |
406 | filename = "/home/" + filename.substr(1) + "/public_html/"; | |
407 | } | |
fbd29dd6 DK |
408 | return true; |
409 | } | |
410 | /*}}}*/ | |
6beca0eb DK |
411 | bool handleOnTheFlyReconfiguration(int const client, std::string const &request, std::vector<std::string> const &parts)/*{{{*/ |
412 | { | |
413 | size_t const pcount = parts.size(); | |
414 | if (pcount == 4 && parts[1] == "set") | |
415 | { | |
416 | _config->Set(parts[2], parts[3]); | |
417 | sendSuccess(client, request, true, "Option '" + parts[2] + "' was set to '" + parts[3] + "'!"); | |
418 | return true; | |
419 | } | |
420 | else if (pcount == 4 && parts[1] == "find") | |
421 | { | |
422 | std::list<std::string> headers; | |
423 | std::string response = _config->Find(parts[2], parts[3]); | |
424 | addDataHeaders(headers, response); | |
425 | sendHead(client, 200, headers); | |
426 | sendData(client, response); | |
427 | return true; | |
428 | } | |
429 | else if (pcount == 3 && parts[1] == "find") | |
430 | { | |
431 | std::list<std::string> headers; | |
432 | if (_config->Exists(parts[2]) == true) | |
433 | { | |
434 | std::string response = _config->Find(parts[2]); | |
435 | addDataHeaders(headers, response); | |
436 | sendHead(client, 200, headers); | |
437 | sendData(client, response); | |
438 | return true; | |
439 | } | |
440 | sendError(client, 404, request, "Requested Configuration option doesn't exist."); | |
441 | return false; | |
442 | } | |
443 | else if (pcount == 3 && parts[1] == "clear") | |
444 | { | |
445 | _config->Clear(parts[2]); | |
446 | sendSuccess(client, request, true, "Option '" + parts[2] + "' was cleared."); | |
447 | return true; | |
448 | } | |
449 | ||
450 | sendError(client, 400, request, true, "Unknown on-the-fly configuration request"); | |
451 | return false; | |
452 | } | |
453 | /*}}}*/ | |
fbd29dd6 DK |
454 | int main(int const argc, const char * argv[]) |
455 | { | |
456 | CommandLine::Args Args[] = { | |
457 | {0, "port", "aptwebserver::port", CommandLine::HasArg}, | |
f2380a78 | 458 | {0, "request-absolute", "aptwebserver::request::absolute", CommandLine::HasArg}, |
fbd29dd6 DK |
459 | {'c',"config-file",0,CommandLine::ConfigFile}, |
460 | {'o',"option",0,CommandLine::ArbItem}, | |
461 | {0,0,0,0} | |
462 | }; | |
463 | ||
464 | CommandLine CmdL(Args, _config); | |
465 | if(CmdL.Parse(argc,argv) == false) | |
466 | { | |
467 | _error->DumpErrors(); | |
468 | exit(1); | |
469 | } | |
470 | ||
471 | // create socket, bind and listen to it {{{ | |
472 | // ignore SIGPIPE, this can happen on write() if the socket closes connection | |
473 | signal(SIGPIPE, SIG_IGN); | |
474 | int sock = socket(AF_INET6, SOCK_STREAM, 0); | |
475 | if(sock < 0) | |
476 | { | |
477 | _error->Errno("aptwerbserver", "Couldn't create socket"); | |
478 | _error->DumpErrors(std::cerr); | |
479 | return 1; | |
480 | } | |
481 | ||
482 | int const port = _config->FindI("aptwebserver::port", 8080); | |
483 | ||
484 | // ensure that we accept all connections: v4 or v6 | |
485 | int const iponly = 0; | |
486 | setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &iponly, sizeof(iponly)); | |
487 | // to not linger on an address | |
488 | int const enable = 1; | |
489 | setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)); | |
490 | ||
491 | struct sockaddr_in6 locAddr; | |
492 | memset(&locAddr, 0, sizeof(locAddr)); | |
493 | locAddr.sin6_family = AF_INET6; | |
494 | locAddr.sin6_port = htons(port); | |
495 | locAddr.sin6_addr = in6addr_any; | |
496 | ||
497 | if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0) | |
498 | { | |
499 | _error->Errno("aptwerbserver", "Couldn't bind"); | |
500 | _error->DumpErrors(std::cerr); | |
501 | return 2; | |
502 | } | |
503 | ||
e3c62328 DK |
504 | FileFd pidfile; |
505 | if (_config->FindB("aptwebserver::fork", false) == true) | |
506 | { | |
507 | std::string const pidfilename = _config->Find("aptwebserver::pidfile", "aptwebserver.pid"); | |
508 | int const pidfilefd = GetLock(pidfilename); | |
509 | if (pidfilefd < 0 || pidfile.OpenDescriptor(pidfilefd, FileFd::WriteOnly) == false) | |
510 | { | |
511 | _error->Errno("aptwebserver", "Couldn't acquire lock on pidfile '%s'", pidfilename.c_str()); | |
512 | _error->DumpErrors(std::cerr); | |
513 | return 3; | |
514 | } | |
515 | ||
516 | pid_t child = fork(); | |
517 | if (child < 0) | |
518 | { | |
519 | _error->Errno("aptwebserver", "Forking failed"); | |
520 | _error->DumpErrors(std::cerr); | |
521 | return 4; | |
522 | } | |
523 | else if (child != 0) | |
524 | { | |
525 | // successfully forked: ready to serve! | |
526 | std::string pidcontent; | |
527 | strprintf(pidcontent, "%d", child); | |
528 | pidfile.Write(pidcontent.c_str(), pidcontent.size()); | |
529 | if (_error->PendingError() == true) | |
530 | { | |
531 | _error->DumpErrors(std::cerr); | |
532 | return 5; | |
533 | } | |
534 | std::cout << "Successfully forked as " << child << std::endl; | |
535 | return 0; | |
536 | } | |
537 | } | |
538 | ||
fbd29dd6 DK |
539 | std::clog << "Serving ANY file on port: " << port << std::endl; |
540 | ||
541 | listen(sock, 1); | |
542 | /*}}}*/ | |
543 | ||
14c84d02 DK |
544 | _config->CndSet("aptwebserver::response-header::Server", "APT webserver"); |
545 | _config->CndSet("aptwebserver::response-header::Accept-Ranges", "bytes"); | |
546 | ||
fbd29dd6 DK |
547 | std::vector<std::string> messages; |
548 | int client; | |
549 | while ((client = accept(sock, NULL, NULL)) != -1) | |
550 | { | |
551 | std::clog << "ACCEPT client " << client | |
552 | << " on socket " << sock << std::endl; | |
553 | ||
554 | while (ReadMessages(client, messages)) | |
555 | { | |
556 | bool closeConnection = false; | |
557 | for (std::vector<std::string>::const_iterator m = messages.begin(); | |
558 | m != messages.end() && closeConnection == false; ++m) { | |
559 | std::clog << ">>> REQUEST >>>>" << std::endl << *m | |
560 | << std::endl << "<<<<<<<<<<<<<<<<" << std::endl; | |
561 | std::list<std::string> headers; | |
562 | std::string filename; | |
563 | bool sendContent = true; | |
564 | if (parseFirstLine(client, *m, filename, sendContent, closeConnection) == false) | |
565 | continue; | |
566 | ||
6beca0eb DK |
567 | // special webserver command request |
568 | if (filename.length() > 1 && filename[0] == '_') | |
569 | { | |
570 | std::vector<std::string> parts = VectorizeString(filename, '/'); | |
571 | if (parts[0] == "_config") | |
572 | { | |
573 | handleOnTheFlyReconfiguration(client, *m, parts); | |
574 | continue; | |
575 | } | |
576 | } | |
577 | ||
7ea27d2a DK |
578 | // string replacements in the requested filename |
579 | ::Configuration::Item const *Replaces = _config->Tree("aptwebserver::redirect::replace"); | |
580 | if (Replaces != NULL) | |
581 | { | |
582 | std::string redirect = "/" + filename; | |
583 | for (::Configuration::Item *I = Replaces->Child; I != NULL; I = I->Next) | |
584 | redirect = SubstVar(redirect, I->Tag, I->Value); | |
585 | redirect.erase(0,1); | |
586 | if (redirect != filename) | |
587 | { | |
588 | sendRedirect(client, 301, redirect, *m, sendContent); | |
589 | continue; | |
590 | } | |
591 | } | |
592 | ||
ae99ce2e DK |
593 | ::Configuration::Item const *Overwrite = _config->Tree("aptwebserver::overwrite"); |
594 | if (Overwrite != NULL) | |
595 | { | |
596 | for (::Configuration::Item *I = Overwrite->Child; I != NULL; I = I->Next) | |
597 | { | |
598 | regex_t *pattern = new regex_t; | |
599 | int const res = regcomp(pattern, I->Tag.c_str(), REG_EXTENDED | REG_ICASE | REG_NOSUB); | |
600 | if (res != 0) | |
601 | { | |
602 | char error[300]; | |
603 | regerror(res, pattern, error, sizeof(error)); | |
604 | sendError(client, 500, *m, sendContent, error); | |
605 | continue; | |
606 | } | |
607 | if (regexec(pattern, filename.c_str(), 0, 0, 0) == 0) | |
608 | { | |
609 | filename = _config->Find("aptwebserver::overwrite::" + I->Tag + "::filename", filename); | |
610 | if (filename[0] == '/') | |
611 | filename.erase(0,1); | |
612 | regfree(pattern); | |
613 | break; | |
614 | } | |
615 | regfree(pattern); | |
616 | } | |
617 | } | |
618 | ||
7ea27d2a | 619 | // deal with the request |
fbd29dd6 DK |
620 | if (RealFileExists(filename) == true) |
621 | { | |
622 | FileFd data(filename, FileFd::ReadOnly); | |
623 | std::string condition = LookupTag(*m, "If-Modified-Since", ""); | |
624 | if (condition.empty() == false) | |
625 | { | |
626 | time_t cache; | |
627 | if (RFC1123StrToTime(condition.c_str(), cache) == true && | |
628 | cache >= data.ModificationTime()) | |
629 | { | |
630 | sendHead(client, 304, headers); | |
631 | continue; | |
632 | } | |
633 | } | |
634 | ||
14c84d02 DK |
635 | if (_config->FindB("aptwebserver::support::range", true) == true) |
636 | condition = LookupTag(*m, "Range", ""); | |
637 | else | |
638 | condition.clear(); | |
639 | if (condition.empty() == false && strncmp(condition.c_str(), "bytes=", 6) == 0) | |
640 | { | |
641 | time_t cache; | |
642 | std::string ifrange; | |
643 | if (_config->FindB("aptwebserver::support::if-range", true) == true) | |
644 | ifrange = LookupTag(*m, "If-Range", ""); | |
645 | bool validrange = (ifrange.empty() == true || | |
646 | (RFC1123StrToTime(ifrange.c_str(), cache) == true && | |
647 | cache <= data.ModificationTime())); | |
648 | ||
649 | // FIXME: support multiple byte-ranges (APT clients do not do this) | |
650 | if (condition.find(',') == std::string::npos) | |
651 | { | |
652 | size_t start = 6; | |
653 | unsigned long long filestart = strtoull(condition.c_str() + start, NULL, 10); | |
654 | // FIXME: no support for last-byte-pos being not the end of the file (APT clients do not do this) | |
655 | size_t dash = condition.find('-') + 1; | |
656 | unsigned long long fileend = strtoull(condition.c_str() + dash, NULL, 10); | |
657 | unsigned long long filesize = data.FileSize(); | |
658 | if ((fileend == 0 || (fileend == filesize && fileend >= filestart)) && | |
659 | validrange == true) | |
660 | { | |
661 | if (filesize > filestart) | |
662 | { | |
663 | data.Skip(filestart); | |
664 | std::ostringstream contentlength; | |
665 | contentlength << "Content-Length: " << (filesize - filestart); | |
666 | headers.push_back(contentlength.str()); | |
667 | std::ostringstream contentrange; | |
668 | contentrange << "Content-Range: bytes " << filestart << "-" | |
669 | << filesize - 1 << "/" << filesize; | |
670 | headers.push_back(contentrange.str()); | |
671 | sendHead(client, 206, headers); | |
672 | if (sendContent == true) | |
673 | sendFile(client, data); | |
674 | continue; | |
675 | } | |
676 | else | |
677 | { | |
678 | headers.push_back("Content-Length: 0"); | |
679 | std::ostringstream contentrange; | |
680 | contentrange << "Content-Range: bytes */" << filesize; | |
681 | headers.push_back(contentrange.str()); | |
682 | sendHead(client, 416, headers); | |
683 | continue; | |
684 | } | |
685 | } | |
686 | } | |
687 | } | |
688 | ||
fbd29dd6 DK |
689 | addFileHeaders(headers, data); |
690 | sendHead(client, 200, headers); | |
691 | if (sendContent == true) | |
692 | sendFile(client, data); | |
693 | } | |
bf3daa15 DK |
694 | else if (DirectoryExists(filename) == true) |
695 | { | |
696 | if (filename == "." || filename[filename.length()-1] == '/') | |
697 | sendDirectoryListing(client, filename, *m, sendContent); | |
698 | else | |
699 | sendRedirect(client, 301, filename.append("/"), *m, sendContent); | |
700 | } | |
fbd29dd6 DK |
701 | else |
702 | sendError(client, 404, *m, sendContent); | |
703 | } | |
704 | _error->DumpErrors(std::cerr); | |
705 | messages.clear(); | |
706 | if (closeConnection == true) | |
707 | break; | |
708 | } | |
709 | ||
710 | std::clog << "CLOSE client " << client | |
711 | << " on socket " << sock << std::endl; | |
712 | close(client); | |
713 | } | |
e3c62328 DK |
714 | pidfile.Close(); |
715 | ||
fbd29dd6 DK |
716 | return 0; |
717 | } |