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