]>
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> |
ed793a19 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 | /*}}}*/ | |
ed793a19 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 | { |
ed793a19 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 | { |
ed793a19 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 | ||
ed793a19 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 | /*}}}*/ | |
ed793a19 | 150 | static bool sendFile(int const client, std::list<std::string> const &headers, FileFd &data)/*{{{*/ |
fbd29dd6 DK |
151 | { |
152 | bool Success = true; | |
ed793a19 | 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; | |
ed793a19 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) |
ed793a19 | 178 | std::cerr << "SENDFILE:" << (chunked ? " CHUNKED" : "") << " READ/WRITE ERROR to " << client << std::endl; |
fbd29dd6 DK |
179 | return Success; |
180 | } | |
181 | /*}}}*/ | |
ed793a19 | 182 | static bool sendData(int const client, std::list<std::string> const &headers, std::string const &data)/*{{{*/ |
fbd29dd6 | 183 | { |
ed793a19 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,/*{{{*/ |
ed793a19 | 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) |
ed793a19 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>"); |
ed793a19 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) | |
ed793a19 | 233 | sendData(client, headers, response); |
6beca0eb | 234 | } |
c3ccac92 | 235 | static void sendSuccess(int const client, std::string const &request, |
ed793a19 | 236 | bool const content, std::string const &error, std::list<std::string> &headers) |
6beca0eb | 237 | { |
ed793a19 | 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) | |
ed793a19 | 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,/*{{{*/ |
ed793a19 | 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 | { | |
ed793a19 | 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) | |
ed793a19 | 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, |
ed793a19 | 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 | { | |
ed793a19 | 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 | { | |
ed793a19 | 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 | { | |
ed793a19 | 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 | { | |
ed793a19 | 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 | |
ed793a19 | 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"); | |
b0314abb | 420 | if (strncmp(host.c_str(), filename.c_str(), host.length()) == 0 && APT::String::Startswith(filename, "/_config/") == false) |
f2380a78 DK |
421 | { |
422 | if (absolute.find("uri") == std::string::npos) | |
423 | { | |
ed793a19 | 424 | sendError(client, 400, request, sendContent, "Request is absoluteURI, but configured to not accept that", headers); |
f2380a78 DK |
425 | return false; |
426 | } | |
b0314abb | 427 | |
f2380a78 DK |
428 | // strip the host from the request to make it an absolute path |
429 | filename.erase(0, host.length()); | |
b0314abb DK |
430 | |
431 | std::string const authConf = _config->Find("aptwebserver::proxy-authorization", ""); | |
432 | std::string auth = LookupTag(request, "Proxy-Authorization", ""); | |
433 | if (authConf.empty() != auth.empty()) | |
434 | { | |
435 | if (auth.empty()) | |
ed793a19 | 436 | sendError(client, 407, request, sendContent, "Proxy requires authentication", headers); |
b0314abb | 437 | else |
ed793a19 | 438 | sendError(client, 407, request, sendContent, "Client wants to authenticate to proxy, but proxy doesn't need it", headers); |
b0314abb DK |
439 | return false; |
440 | } | |
441 | if (authConf.empty() == false) | |
442 | { | |
443 | char const * const basic = "Basic "; | |
444 | if (strncmp(auth.c_str(), basic, strlen(basic)) == 0) | |
445 | { | |
446 | auth.erase(0, strlen(basic)); | |
447 | if (auth != authConf) | |
448 | { | |
ed793a19 | 449 | sendError(client, 407, request, sendContent, "Proxy-Authentication doesn't match", headers); |
b0314abb DK |
450 | return false; |
451 | } | |
452 | } | |
453 | else | |
454 | { | |
455 | std::list<std::string> headers; | |
456 | headers.push_back("Proxy-Authenticate: Basic"); | |
457 | sendError(client, 407, request, sendContent, "Unsupported Proxy-Authentication Scheme", headers); | |
458 | return false; | |
459 | } | |
460 | } | |
f2380a78 | 461 | } |
b0314abb | 462 | else if (absolute.find("path") == std::string::npos && APT::String::Startswith(filename, "/_config/") == false) |
f2380a78 | 463 | { |
ed793a19 | 464 | sendError(client, 400, request, sendContent, "Request is absolutePath, but configured to not accept that", headers); |
f2380a78 DK |
465 | return false; |
466 | } | |
d23bda42 | 467 | |
b0314abb DK |
468 | if (APT::String::Startswith(filename, "/_config/") == false) |
469 | { | |
470 | std::string const authConf = _config->Find("aptwebserver::authorization", ""); | |
471 | std::string auth = LookupTag(request, "Authorization", ""); | |
472 | if (authConf.empty() != auth.empty()) | |
473 | { | |
474 | if (auth.empty()) | |
ed793a19 | 475 | sendError(client, 401, request, sendContent, "Server requires authentication", headers); |
b0314abb | 476 | else |
ed793a19 | 477 | sendError(client, 401, request, sendContent, "Client wants to authenticate to server, but server doesn't need it", headers); |
b0314abb DK |
478 | return false; |
479 | } | |
480 | if (authConf.empty() == false) | |
481 | { | |
482 | char const * const basic = "Basic "; | |
483 | if (strncmp(auth.c_str(), basic, strlen(basic)) == 0) | |
484 | { | |
485 | auth.erase(0, strlen(basic)); | |
486 | if (auth != authConf) | |
487 | { | |
ed793a19 | 488 | sendError(client, 401, request, sendContent, "Authentication doesn't match", headers); |
b0314abb DK |
489 | return false; |
490 | } | |
491 | } | |
492 | else | |
493 | { | |
b0314abb DK |
494 | headers.push_back("WWW-Authenticate: Basic"); |
495 | sendError(client, 401, request, sendContent, "Unsupported Authentication Scheme", headers); | |
496 | return false; | |
497 | } | |
498 | } | |
499 | } | |
500 | ||
d23bda42 DK |
501 | size_t paramspos = filename.find('?'); |
502 | if (paramspos != std::string::npos) | |
503 | { | |
504 | params = filename.substr(paramspos + 1); | |
505 | filename.erase(paramspos); | |
506 | } | |
507 | ||
fbd29dd6 DK |
508 | filename = DeQuoteString(filename); |
509 | ||
510 | // this is not a secure server, but at least prevent the obvious … | |
511 | if (filename.empty() == true || filename[0] != '/' || | |
512 | strncmp(filename.c_str(), "//", 2) == 0 || | |
513 | filename.find_first_of("\r\n\t\f\v") != std::string::npos || | |
514 | filename.find("/../") != std::string::npos) | |
515 | { | |
ed793a19 DK |
516 | std::list<std::string> headers; |
517 | sendError(client, 400, request, sendContent, "Filename contains illegal character (sequence)", headers); | |
fbd29dd6 DK |
518 | return false; |
519 | } | |
520 | ||
521 | // nuke the first character which is a / as we assured above | |
522 | filename.erase(0, 1); | |
523 | if (filename.empty() == true) | |
3c16b5fe | 524 | filename = "./"; |
eab3a9b2 DK |
525 | // support ~user/ uris to refer to /home/user/public_html/ as a kind-of special directory |
526 | else if (filename[0] == '~') | |
527 | { | |
528 | // /home/user is actually not entirely correct, but good enough for now | |
529 | size_t dashpos = filename.find('/'); | |
530 | if (dashpos != std::string::npos) | |
531 | { | |
532 | std::string home = filename.substr(1, filename.find('/') - 1); | |
533 | std::string pubhtml = filename.substr(filename.find('/') + 1); | |
534 | filename = "/home/" + home + "/public_html/" + pubhtml; | |
535 | } | |
536 | else | |
537 | filename = "/home/" + filename.substr(1) + "/public_html/"; | |
538 | } | |
3c16b5fe DK |
539 | |
540 | // if no filename is given, but a valid directory see if we can use an index or | |
541 | // have to resort to a autogenerated directory listing later on | |
542 | if (DirectoryExists(filename) == true) | |
543 | { | |
544 | std::string const directoryIndex = _config->Find("aptwebserver::directoryindex"); | |
545 | if (directoryIndex.empty() == false && directoryIndex == flNotDir(directoryIndex) && | |
546 | RealFileExists(filename + directoryIndex) == true) | |
547 | filename += directoryIndex; | |
548 | } | |
549 | ||
fbd29dd6 DK |
550 | return true; |
551 | } | |
552 | /*}}}*/ | |
ed793a19 DK |
553 | static bool handleOnTheFlyReconfiguration(int const client, std::string const &request,/*{{{*/ |
554 | std::vector<std::string> parts, std::list<std::string> &headers) | |
6beca0eb DK |
555 | { |
556 | size_t const pcount = parts.size(); | |
23397c9d DK |
557 | for (size_t i = 0; i < pcount; ++i) |
558 | parts[i] = DeQuoteString(parts[i]); | |
6beca0eb DK |
559 | if (pcount == 4 && parts[1] == "set") |
560 | { | |
561 | _config->Set(parts[2], parts[3]); | |
ed793a19 | 562 | sendSuccess(client, request, true, "Option '" + parts[2] + "' was set to '" + parts[3] + "'!", headers); |
6beca0eb DK |
563 | return true; |
564 | } | |
565 | else if (pcount == 4 && parts[1] == "find") | |
566 | { | |
6beca0eb DK |
567 | std::string response = _config->Find(parts[2], parts[3]); |
568 | addDataHeaders(headers, response); | |
569 | sendHead(client, 200, headers); | |
ed793a19 | 570 | sendData(client, headers, response); |
6beca0eb DK |
571 | return true; |
572 | } | |
573 | else if (pcount == 3 && parts[1] == "find") | |
574 | { | |
6beca0eb DK |
575 | if (_config->Exists(parts[2]) == true) |
576 | { | |
577 | std::string response = _config->Find(parts[2]); | |
578 | addDataHeaders(headers, response); | |
579 | sendHead(client, 200, headers); | |
ed793a19 | 580 | sendData(client, headers, response); |
6beca0eb DK |
581 | return true; |
582 | } | |
ed793a19 | 583 | sendError(client, 404, request, true, "Requested Configuration option doesn't exist", headers); |
6beca0eb DK |
584 | return false; |
585 | } | |
586 | else if (pcount == 3 && parts[1] == "clear") | |
587 | { | |
588 | _config->Clear(parts[2]); | |
ed793a19 | 589 | sendSuccess(client, request, true, "Option '" + parts[2] + "' was cleared.", headers); |
6beca0eb DK |
590 | return true; |
591 | } | |
592 | ||
ed793a19 | 593 | sendError(client, 400, request, true, "Unknown on-the-fly configuration request", headers); |
6beca0eb DK |
594 | return false; |
595 | } | |
596 | /*}}}*/ | |
c3ccac92 | 597 | static void * handleClient(void * voidclient) /*{{{*/ |
575fe03e DK |
598 | { |
599 | int client = *((int*)(voidclient)); | |
600 | std::clog << "ACCEPT client " << client << std::endl; | |
601 | std::vector<std::string> messages; | |
ed793a19 DK |
602 | bool closeConnection = false; |
603 | std::list<std::string> headers; | |
604 | while (closeConnection == false && ReadMessages(client, messages)) | |
575fe03e | 605 | { |
ed793a19 DK |
606 | // if we announced a closing, do the close |
607 | if (std::find(headers.begin(), headers.end(), std::string("Connection: close")) != headers.end()) | |
608 | break; | |
609 | headers.clear(); | |
575fe03e DK |
610 | for (std::vector<std::string>::const_iterator m = messages.begin(); |
611 | m != messages.end() && closeConnection == false; ++m) { | |
612 | std::clog << ">>> REQUEST from " << client << " >>>" << std::endl << *m | |
613 | << std::endl << "<<<<<<<<<<<<<<<<" << std::endl; | |
575fe03e DK |
614 | std::string filename; |
615 | std::string params; | |
616 | bool sendContent = true; | |
ed793a19 | 617 | if (parseFirstLine(client, *m, filename, params, sendContent, closeConnection, headers) == false) |
575fe03e DK |
618 | continue; |
619 | ||
620 | // special webserver command request | |
621 | if (filename.length() > 1 && filename[0] == '_') | |
622 | { | |
623 | std::vector<std::string> parts = VectorizeString(filename, '/'); | |
624 | if (parts[0] == "_config") | |
625 | { | |
ed793a19 | 626 | handleOnTheFlyReconfiguration(client, *m, parts, headers); |
575fe03e DK |
627 | continue; |
628 | } | |
629 | } | |
630 | ||
631 | // string replacements in the requested filename | |
632 | ::Configuration::Item const *Replaces = _config->Tree("aptwebserver::redirect::replace"); | |
633 | if (Replaces != NULL) | |
634 | { | |
635 | std::string redirect = "/" + filename; | |
636 | for (::Configuration::Item *I = Replaces->Child; I != NULL; I = I->Next) | |
637 | redirect = SubstVar(redirect, I->Tag, I->Value); | |
f9b4f12d DK |
638 | if (redirect.empty() == false && redirect[0] == '/') |
639 | redirect.erase(0,1); | |
575fe03e DK |
640 | if (redirect != filename) |
641 | { | |
642 | sendRedirect(client, 301, redirect, *m, sendContent); | |
643 | continue; | |
644 | } | |
645 | } | |
646 | ||
647 | ::Configuration::Item const *Overwrite = _config->Tree("aptwebserver::overwrite"); | |
648 | if (Overwrite != NULL) | |
649 | { | |
650 | for (::Configuration::Item *I = Overwrite->Child; I != NULL; I = I->Next) | |
651 | { | |
652 | regex_t *pattern = new regex_t; | |
653 | int const res = regcomp(pattern, I->Tag.c_str(), REG_EXTENDED | REG_ICASE | REG_NOSUB); | |
654 | if (res != 0) | |
655 | { | |
656 | char error[300]; | |
657 | regerror(res, pattern, error, sizeof(error)); | |
ed793a19 | 658 | sendError(client, 500, *m, sendContent, error, headers); |
575fe03e DK |
659 | continue; |
660 | } | |
661 | if (regexec(pattern, filename.c_str(), 0, 0, 0) == 0) | |
662 | { | |
663 | filename = _config->Find("aptwebserver::overwrite::" + I->Tag + "::filename", filename); | |
664 | if (filename[0] == '/') | |
665 | filename.erase(0,1); | |
666 | regfree(pattern); | |
667 | break; | |
668 | } | |
669 | regfree(pattern); | |
670 | } | |
671 | } | |
672 | ||
673 | // deal with the request | |
f9b4f12d DK |
674 | if (_config->FindB("aptwebserver::support::http", true) == false && |
675 | LookupTag(*m, "Host").find(":4433") == std::string::npos) | |
676 | { | |
ed793a19 | 677 | sendError(client, 400, *m, sendContent, "HTTP disabled, all requests must be HTTPS", headers); |
f9b4f12d DK |
678 | continue; |
679 | } | |
680 | else if (RealFileExists(filename) == true) | |
575fe03e DK |
681 | { |
682 | FileFd data(filename, FileFd::ReadOnly); | |
683 | std::string condition = LookupTag(*m, "If-Modified-Since", ""); | |
f2c0ec8b | 684 | if (_config->FindB("aptwebserver::support::modified-since", true) == true && condition.empty() == false) |
575fe03e DK |
685 | { |
686 | time_t cache; | |
687 | if (RFC1123StrToTime(condition.c_str(), cache) == true && | |
688 | cache >= data.ModificationTime()) | |
689 | { | |
690 | sendHead(client, 304, headers); | |
691 | continue; | |
692 | } | |
693 | } | |
694 | ||
695 | if (_config->FindB("aptwebserver::support::range", true) == true) | |
696 | condition = LookupTag(*m, "Range", ""); | |
697 | else | |
698 | condition.clear(); | |
699 | if (condition.empty() == false && strncmp(condition.c_str(), "bytes=", 6) == 0) | |
700 | { | |
701 | time_t cache; | |
702 | std::string ifrange; | |
703 | if (_config->FindB("aptwebserver::support::if-range", true) == true) | |
704 | ifrange = LookupTag(*m, "If-Range", ""); | |
705 | bool validrange = (ifrange.empty() == true || | |
706 | (RFC1123StrToTime(ifrange.c_str(), cache) == true && | |
707 | cache <= data.ModificationTime())); | |
708 | ||
709 | // FIXME: support multiple byte-ranges (APT clients do not do this) | |
710 | if (condition.find(',') == std::string::npos) | |
711 | { | |
712 | size_t start = 6; | |
713 | unsigned long long filestart = strtoull(condition.c_str() + start, NULL, 10); | |
714 | // FIXME: no support for last-byte-pos being not the end of the file (APT clients do not do this) | |
715 | size_t dash = condition.find('-') + 1; | |
716 | unsigned long long fileend = strtoull(condition.c_str() + dash, NULL, 10); | |
717 | unsigned long long filesize = data.FileSize(); | |
718 | if ((fileend == 0 || (fileend == filesize && fileend >= filestart)) && | |
719 | validrange == true) | |
720 | { | |
721 | if (filesize > filestart) | |
722 | { | |
723 | data.Skip(filestart); | |
724 | std::ostringstream contentlength; | |
725 | contentlength << "Content-Length: " << (filesize - filestart); | |
726 | headers.push_back(contentlength.str()); | |
727 | std::ostringstream contentrange; | |
728 | contentrange << "Content-Range: bytes " << filestart << "-" | |
729 | << filesize - 1 << "/" << filesize; | |
730 | headers.push_back(contentrange.str()); | |
731 | sendHead(client, 206, headers); | |
732 | if (sendContent == true) | |
ed793a19 | 733 | sendFile(client, headers, data); |
575fe03e DK |
734 | continue; |
735 | } | |
736 | else | |
737 | { | |
575fe03e DK |
738 | std::ostringstream contentrange; |
739 | contentrange << "Content-Range: bytes */" << filesize; | |
740 | headers.push_back(contentrange.str()); | |
ed793a19 DK |
741 | sendError(client, 416, *m, sendContent, "", headers); |
742 | break; | |
575fe03e DK |
743 | } |
744 | } | |
745 | } | |
746 | } | |
747 | ||
748 | addFileHeaders(headers, data); | |
749 | sendHead(client, 200, headers); | |
750 | if (sendContent == true) | |
ed793a19 | 751 | sendFile(client, headers, data); |
575fe03e DK |
752 | } |
753 | else if (DirectoryExists(filename) == true) | |
754 | { | |
755 | if (filename[filename.length()-1] == '/') | |
ed793a19 | 756 | sendDirectoryListing(client, filename, *m, sendContent, headers); |
575fe03e DK |
757 | else |
758 | sendRedirect(client, 301, filename.append("/"), *m, sendContent); | |
759 | } | |
760 | else | |
ed793a19 | 761 | sendError(client, 404, *m, sendContent, "", headers); |
575fe03e DK |
762 | } |
763 | _error->DumpErrors(std::cerr); | |
764 | messages.clear(); | |
575fe03e DK |
765 | } |
766 | close(client); | |
767 | std::clog << "CLOSE client " << client << std::endl; | |
768 | return NULL; | |
769 | } | |
770 | /*}}}*/ | |
771 | ||
fbd29dd6 DK |
772 | int main(int const argc, const char * argv[]) |
773 | { | |
774 | CommandLine::Args Args[] = { | |
775 | {0, "port", "aptwebserver::port", CommandLine::HasArg}, | |
f2380a78 | 776 | {0, "request-absolute", "aptwebserver::request::absolute", CommandLine::HasArg}, |
b0314abb DK |
777 | {0, "authorization", "aptwebserver::authorization", CommandLine::HasArg}, |
778 | {0, "proxy-authorization", "aptwebserver::proxy-authorization", CommandLine::HasArg}, | |
fbd29dd6 DK |
779 | {'c',"config-file",0,CommandLine::ConfigFile}, |
780 | {'o',"option",0,CommandLine::ArbItem}, | |
781 | {0,0,0,0} | |
782 | }; | |
783 | ||
784 | CommandLine CmdL(Args, _config); | |
785 | if(CmdL.Parse(argc,argv) == false) | |
786 | { | |
787 | _error->DumpErrors(); | |
788 | exit(1); | |
789 | } | |
790 | ||
791 | // create socket, bind and listen to it {{{ | |
792 | // ignore SIGPIPE, this can happen on write() if the socket closes connection | |
793 | signal(SIGPIPE, SIG_IGN); | |
575fe03e DK |
794 | // we don't care for our slaves, so ignore their death |
795 | signal(SIGCHLD, SIG_IGN); | |
796 | ||
fbd29dd6 DK |
797 | int sock = socket(AF_INET6, SOCK_STREAM, 0); |
798 | if(sock < 0) | |
799 | { | |
800 | _error->Errno("aptwerbserver", "Couldn't create socket"); | |
801 | _error->DumpErrors(std::cerr); | |
802 | return 1; | |
803 | } | |
804 | ||
805 | int const port = _config->FindI("aptwebserver::port", 8080); | |
806 | ||
807 | // ensure that we accept all connections: v4 or v6 | |
808 | int const iponly = 0; | |
809 | setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &iponly, sizeof(iponly)); | |
810 | // to not linger on an address | |
811 | int const enable = 1; | |
812 | setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)); | |
813 | ||
814 | struct sockaddr_in6 locAddr; | |
815 | memset(&locAddr, 0, sizeof(locAddr)); | |
816 | locAddr.sin6_family = AF_INET6; | |
817 | locAddr.sin6_port = htons(port); | |
818 | locAddr.sin6_addr = in6addr_any; | |
819 | ||
820 | if (bind(sock, (struct sockaddr*) &locAddr, sizeof(locAddr)) < 0) | |
821 | { | |
822 | _error->Errno("aptwerbserver", "Couldn't bind"); | |
823 | _error->DumpErrors(std::cerr); | |
824 | return 2; | |
825 | } | |
826 | ||
e3c62328 DK |
827 | FileFd pidfile; |
828 | if (_config->FindB("aptwebserver::fork", false) == true) | |
829 | { | |
830 | std::string const pidfilename = _config->Find("aptwebserver::pidfile", "aptwebserver.pid"); | |
831 | int const pidfilefd = GetLock(pidfilename); | |
832 | if (pidfilefd < 0 || pidfile.OpenDescriptor(pidfilefd, FileFd::WriteOnly) == false) | |
833 | { | |
834 | _error->Errno("aptwebserver", "Couldn't acquire lock on pidfile '%s'", pidfilename.c_str()); | |
835 | _error->DumpErrors(std::cerr); | |
836 | return 3; | |
837 | } | |
838 | ||
839 | pid_t child = fork(); | |
840 | if (child < 0) | |
841 | { | |
842 | _error->Errno("aptwebserver", "Forking failed"); | |
843 | _error->DumpErrors(std::cerr); | |
844 | return 4; | |
845 | } | |
846 | else if (child != 0) | |
847 | { | |
848 | // successfully forked: ready to serve! | |
849 | std::string pidcontent; | |
850 | strprintf(pidcontent, "%d", child); | |
851 | pidfile.Write(pidcontent.c_str(), pidcontent.size()); | |
852 | if (_error->PendingError() == true) | |
853 | { | |
854 | _error->DumpErrors(std::cerr); | |
855 | return 5; | |
856 | } | |
857 | std::cout << "Successfully forked as " << child << std::endl; | |
858 | return 0; | |
859 | } | |
860 | } | |
861 | ||
fbd29dd6 DK |
862 | std::clog << "Serving ANY file on port: " << port << std::endl; |
863 | ||
575fe03e DK |
864 | int const slaves = _config->FindB("aptwebserver::slaves", SOMAXCONN); |
865 | listen(sock, slaves); | |
fbd29dd6 DK |
866 | /*}}}*/ |
867 | ||
14c84d02 DK |
868 | _config->CndSet("aptwebserver::response-header::Server", "APT webserver"); |
869 | _config->CndSet("aptwebserver::response-header::Accept-Ranges", "bytes"); | |
3c16b5fe | 870 | _config->CndSet("aptwebserver::directoryindex", "index.html"); |
14c84d02 | 871 | |
575fe03e | 872 | std::list<int> accepted_clients; |
fbd29dd6 | 873 | |
575fe03e DK |
874 | while (true) |
875 | { | |
876 | int client = accept(sock, NULL, NULL); | |
877 | if (client == -1) | |
fbd29dd6 | 878 | { |
575fe03e DK |
879 | if (errno == EINTR) |
880 | continue; | |
881 | _error->Errno("accept", "Couldn't accept client on socket %d", sock); | |
882 | _error->DumpErrors(std::cerr); | |
883 | return 6; | |
884 | } | |
14c84d02 | 885 | |
575fe03e DK |
886 | pthread_attr_t attr; |
887 | if (pthread_attr_init(&attr) != 0 || pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0) | |
888 | { | |
889 | _error->Errno("pthread_attr", "Couldn't set detach attribute for a fresh thread to handle client %d on socket %d", client, sock); | |
fbd29dd6 | 890 | _error->DumpErrors(std::cerr); |
575fe03e DK |
891 | close(client); |
892 | continue; | |
fbd29dd6 DK |
893 | } |
894 | ||
575fe03e DK |
895 | pthread_t tid; |
896 | // thats rather dirty, but we need to store the client socket somewhere safe | |
897 | accepted_clients.push_front(client); | |
898 | if (pthread_create(&tid, &attr, &handleClient, &(*accepted_clients.begin())) != 0) | |
899 | { | |
900 | _error->Errno("pthread_create", "Couldn't create a fresh thread to handle client %d on socket %d", client, sock); | |
901 | _error->DumpErrors(std::cerr); | |
902 | close(client); | |
903 | continue; | |
904 | } | |
fbd29dd6 | 905 | } |
e3c62328 DK |
906 | pidfile.Close(); |
907 | ||
fbd29dd6 DK |
908 | return 0; |
909 | } |