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