]>
Commit | Line | Data |
---|---|---|
35e83b7d DM |
1 | package PVE::HTTPServer; |
2 | ||
3 | use strict; | |
4 | use warnings; | |
519ea5b0 | 5 | use Time::HiRes qw(usleep ualarm gettimeofday tv_interval); |
35e83b7d DM |
6 | use Socket qw(IPPROTO_TCP TCP_NODELAY SOMAXCONN); |
7 | use POSIX qw(strftime EINTR EAGAIN); | |
8 | use Fcntl; | |
519ea5b0 | 9 | use IO::File; |
35e83b7d | 10 | use File::stat qw(); |
519ea5b0 | 11 | use Digest::MD5; |
82e3d509 | 12 | # use AnyEvent::Strict; # only use this for debugging |
35e83b7d | 13 | use AnyEvent::Util qw(guard fh_nonblocking WSAEWOULDBLOCK WSAEINPROGRESS); |
9c1493d4 | 14 | use AnyEvent::Socket; |
35e83b7d DM |
15 | use AnyEvent::Handle; |
16 | use AnyEvent::TLS; | |
17 | use AnyEvent::IO; | |
18 | use AnyEvent::HTTP; | |
19 | use Fcntl (); | |
20 | use Compress::Zlib; | |
21 | use PVE::SafeSyslog; | |
22 | use PVE::INotify; | |
23 | use PVE::RPCEnvironment; | |
24 | use PVE::REST; | |
25 | ||
81af3133 | 26 | use Net::IP; |
35e83b7d DM |
27 | use URI; |
28 | use HTTP::Status qw(:constants); | |
29 | use HTTP::Headers; | |
30 | use HTTP::Response; | |
cb39891f | 31 | use Data::Dumper; |
35e83b7d | 32 | |
562cd9a4 DM |
33 | my $limit_max_headers = 30; |
34 | my $limit_max_header_size = 8*1024; | |
35 | my $limit_max_post = 16*1024; | |
35e83b7d | 36 | |
35e83b7d DM |
37 | |
38 | my $known_methods = { | |
39 | GET => 1, | |
40 | POST => 1, | |
41 | PUT => 1, | |
42 | DELETE => 1, | |
43 | }; | |
44 | ||
519ea5b0 DM |
45 | my $baseuri = "/api2"; |
46 | ||
47 | sub split_abs_uri { | |
48 | my ($abs_uri) = @_; | |
49 | ||
09128602 | 50 | my ($format, $rel_uri) = $abs_uri =~ m/^\Q$baseuri\E\/+(html|text|json|extjs|png|htmljs|spiceconfig)(\/.*)?$/; |
519ea5b0 DM |
51 | $rel_uri = '/' if !$rel_uri; |
52 | ||
53 | return wantarray ? ($rel_uri, $format) : $rel_uri; | |
54 | } | |
55 | ||
35e83b7d DM |
56 | sub log_request { |
57 | my ($self, $reqstate) = @_; | |
58 | ||
35e83b7d DM |
59 | my $loginfo = $reqstate->{log}; |
60 | ||
61 | # like apache2 common log format | |
62 | # LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" | |
63 | ||
f3de8a0b DM |
64 | return if $loginfo->{written}; # avoid duplicate logs |
65 | $loginfo->{written} = 1; | |
66 | ||
35e83b7d DM |
67 | my $peerip = $reqstate->{peer_host} || '-'; |
68 | my $userid = $loginfo->{userid} || '-'; | |
69 | my $content_length = defined($loginfo->{content_length}) ? $loginfo->{content_length} : '-'; | |
70 | my $code = $loginfo->{code} || 500; | |
71 | my $requestline = $loginfo->{requestline} || '-'; | |
72 | my $timestr = strftime("%d/%b/%Y:%H:%M:%S %z", localtime()); | |
73 | ||
74 | my $msg = "$peerip - $userid [$timestr] \"$requestline\" $code $content_length\n"; | |
75 | ||
3cdd9dc4 | 76 | $self->write_log($msg); |
35e83b7d DM |
77 | } |
78 | ||
79 | sub log_aborted_request { | |
80 | my ($self, $reqstate, $error) = @_; | |
81 | ||
82 | my $r = $reqstate->{request}; | |
83 | return if !$r; # no active request | |
84 | ||
85 | if ($error) { | |
86 | syslog("err", "problem with client $reqstate->{peer_host}; $error"); | |
87 | } | |
f4defdaa | 88 | |
35e83b7d DM |
89 | $self->log_request($reqstate); |
90 | } | |
91 | ||
af5ed080 DM |
92 | sub cleanup_reqstate { |
93 | my ($reqstate) = @_; | |
94 | ||
95 | delete $reqstate->{log}; | |
96 | delete $reqstate->{request}; | |
97 | delete $reqstate->{proto}; | |
98 | delete $reqstate->{accept_gzip}; | |
35e83b7d | 99 | |
519ea5b0 DM |
100 | if ($reqstate->{tmpfilename}) { |
101 | unlink $reqstate->{tmpfilename}; | |
102 | delete $reqstate->{tmpfilename}; | |
103 | } | |
af5ed080 DM |
104 | } |
105 | ||
106 | sub client_do_disconnect { | |
107 | my ($self, $reqstate) = @_; | |
108 | ||
109 | cleanup_reqstate($reqstate); | |
519ea5b0 | 110 | |
23f5480e DM |
111 | my $shutdown_hdl = sub { |
112 | my $hdl = shift; | |
113 | ||
114 | shutdown($hdl->{fh}, 1); | |
115 | # clear all handlers | |
116 | $hdl->on_drain(undef); | |
117 | $hdl->on_read(undef); | |
118 | $hdl->on_eof(undef); | |
119 | }; | |
120 | ||
121 | if (my $proxyhdl = delete $reqstate->{proxyhdl}) { | |
122 | &$shutdown_hdl($proxyhdl); | |
123 | } | |
124 | ||
35e83b7d DM |
125 | my $hdl = delete $reqstate->{hdl}; |
126 | ||
127 | if (!$hdl) { | |
128 | syslog('err', "detected empty handle"); | |
129 | return; | |
130 | } | |
131 | ||
23f5480e DM |
132 | print "close connection $hdl\n" if $self->{debug}; |
133 | ||
134 | &$shutdown_hdl($hdl); | |
35e83b7d | 135 | |
35e83b7d DM |
136 | $self->{conn_count}--; |
137 | ||
f4defdaa | 138 | print "$$: CLOSE FH" . $hdl->{fh}->fileno() . " CONN$self->{conn_count}\n" if $self->{debug}; |
35e83b7d DM |
139 | } |
140 | ||
141 | sub finish_response { | |
142 | my ($self, $reqstate) = @_; | |
143 | ||
144 | my $hdl = $reqstate->{hdl}; | |
145 | ||
af5ed080 | 146 | cleanup_reqstate($reqstate); |
519ea5b0 | 147 | |
35e83b7d | 148 | if (!$self->{end_loop} && $reqstate->{keep_alive} > 0) { |
519ea5b0 | 149 | # print "KEEPALIVE $reqstate->{keep_alive}\n" if $self->{debug}; |
f4defdaa | 150 | $hdl->on_read(sub { |
35e83b7d DM |
151 | eval { $self->push_request_header($reqstate); }; |
152 | warn $@ if $@; | |
153 | }); | |
154 | } else { | |
155 | $hdl->on_drain (sub { | |
f4defdaa DM |
156 | eval { |
157 | $self->client_do_disconnect($reqstate); | |
158 | }; | |
35e83b7d DM |
159 | warn $@ if $@; |
160 | }); | |
161 | } | |
162 | } | |
163 | ||
164 | sub response { | |
165 | my ($self, $reqstate, $resp, $mtime, $nocomp) = @_; | |
166 | ||
167 | #print "$$: send response: " . Dumper($resp); | |
168 | ||
af5ed080 DM |
169 | # activate timeout |
170 | $reqstate->{hdl}->timeout_reset(); | |
171 | $reqstate->{hdl}->timeout($self->{timeout}); | |
172 | ||
c8e15d47 DM |
173 | $nocomp = 1 if !$reqstate->{accept_gzip}; |
174 | ||
35e83b7d DM |
175 | my $code = $resp->code; |
176 | my $msg = $resp->message || HTTP::Status::status_message($code); | |
177 | ($msg) = $msg =~m/^(.*)$/m; | |
178 | my $content = $resp->content; | |
179 | ||
180 | if ($code =~ /^(1\d\d|[23]04)$/) { | |
181 | # make sure content we have no content | |
182 | $content = ""; | |
183 | } | |
184 | ||
1d4dc6a0 | 185 | $reqstate->{keep_alive} = 0 if ($code >= 400) || $self->{end_loop}; |
35e83b7d DM |
186 | |
187 | $reqstate->{log}->{code} = $code; | |
188 | ||
66084986 DM |
189 | my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0'; |
190 | my $res = "$proto $code $msg\015\012"; | |
f4defdaa | 191 | |
35e83b7d DM |
192 | my $ctime = time(); |
193 | my $date = HTTP::Date::time2str($ctime); | |
194 | $resp->header('Date' => $date); | |
195 | if ($mtime) { | |
196 | $resp->header('Last-Modified' => HTTP::Date::time2str($mtime)); | |
197 | } else { | |
198 | $resp->header('Expires' => $date); | |
199 | $resp->header('Cache-Control' => "max-age=0"); | |
200 | $resp->header("Pragma", "no-cache"); | |
201 | } | |
202 | ||
203 | $resp->header('Server' => "pve-api-daemon/3.0"); | |
204 | ||
205 | my $content_length; | |
f4defdaa | 206 | if ($content) { |
35e83b7d DM |
207 | |
208 | $content_length = length($content); | |
209 | ||
210 | if (!$nocomp && ($content_length > 1024)) { | |
211 | my $comp = Compress::Zlib::memGzip($content); | |
212 | $resp->header('Content-Encoding', 'gzip'); | |
213 | $content = $comp; | |
214 | $content_length = length($content); | |
215 | } | |
216 | $resp->header("Content-Length" => $content_length); | |
217 | $reqstate->{log}->{content_length} = $content_length; | |
f4defdaa | 218 | |
35e83b7d DM |
219 | } else { |
220 | $resp->remove_header("Content-Length"); | |
221 | } | |
f4defdaa | 222 | |
35e83b7d DM |
223 | if ($reqstate->{keep_alive} > 0) { |
224 | $resp->push_header('Connection' => 'Keep-Alive'); | |
225 | } else { | |
226 | $resp->header('Connection' => 'close'); | |
227 | } | |
228 | ||
229 | $res .= $resp->headers_as_string("\015\012"); | |
f4defdaa | 230 | #print "SEND(without content) $res\n" if $self->{debug}; |
35e83b7d DM |
231 | |
232 | $res .= "\015\012"; | |
9c1493d4 | 233 | $res .= $content if $content; |
35e83b7d DM |
234 | |
235 | $self->log_request($reqstate, $reqstate->{request}); | |
236 | ||
237 | $reqstate->{hdl}->push_write($res); | |
238 | $self->finish_response($reqstate); | |
239 | } | |
240 | ||
241 | sub error { | |
242 | my ($self, $reqstate, $code, $msg, $hdr, $content) = @_; | |
243 | ||
244 | eval { | |
f4defdaa | 245 | my $resp = HTTP::Response->new($code, $msg, $hdr, $content); |
35e83b7d DM |
246 | $self->response($reqstate, $resp); |
247 | }; | |
248 | warn $@ if $@; | |
249 | } | |
250 | ||
251 | sub send_file_start { | |
252 | my ($self, $reqstate, $filename) = @_; | |
253 | ||
254 | eval { | |
255 | # print "SEND FILE $filename\n"; | |
f4defdaa | 256 | # Note: aio_load() this is not really async unless we use IO::AIO! |
35e83b7d DM |
257 | eval { |
258 | ||
1d4dc6a0 DM |
259 | my $r = $reqstate->{request}; |
260 | ||
35e83b7d DM |
261 | my $fh = IO::File->new($filename, '<') || |
262 | die "$!\n"; | |
263 | my $stat = File::stat::stat($fh) || | |
264 | die "$!\n"; | |
1d4dc6a0 DM |
265 | |
266 | my $mtime = $stat->mtime; | |
267 | ||
268 | if (my $ifmod = $r->header('if-modified-since')) { | |
269 | my $iftime = HTTP::Date::str2time($ifmod); | |
270 | if ($mtime <= $iftime) { | |
271 | my $resp = HTTP::Response->new(304, "NOT MODIFIED"); | |
272 | $self->response($reqstate, $resp, $mtime); | |
273 | return; | |
274 | } | |
275 | } | |
f4defdaa | 276 | |
35e83b7d DM |
277 | my $data; |
278 | my $len = sysread($fh, $data, $stat->size); | |
279 | die "got short file\n" if !defined($len) || $len != $stat->size; | |
280 | ||
281 | my $ct; | |
e4f2a5c5 | 282 | my $nocomp; |
35e83b7d DM |
283 | if ($filename =~ m/\.css$/) { |
284 | $ct = 'text/css'; | |
f4defdaa | 285 | } elsif ($filename =~ m/\.js$/) { |
35e83b7d | 286 | $ct = 'application/javascript'; |
f4defdaa | 287 | } elsif ($filename =~ m/\.png$/) { |
35e83b7d | 288 | $ct = 'image/png'; |
e4f2a5c5 | 289 | $nocomp = 1; |
dd28cbbd DM |
290 | } elsif ($filename =~ m/\.ico$/) { |
291 | $ct = 'image/x-icon'; | |
292 | $nocomp = 1; | |
f4defdaa | 293 | } elsif ($filename =~ m/\.gif$/) { |
35e83b7d | 294 | $ct = 'image/gif'; |
e4f2a5c5 | 295 | $nocomp = 1; |
f4defdaa | 296 | } elsif ($filename =~ m/\.jar$/) { |
35e83b7d | 297 | $ct = 'application/java-archive'; |
7bf2d98f | 298 | $nocomp = 1; |
35e83b7d DM |
299 | } else { |
300 | die "unable to detect content type"; | |
301 | } | |
302 | ||
303 | my $header = HTTP::Headers->new(Content_Type => $ct); | |
f4defdaa | 304 | my $resp = HTTP::Response->new(200, "OK", $header, $data); |
e4f2a5c5 | 305 | $self->response($reqstate, $resp, $mtime, $nocomp); |
35e83b7d DM |
306 | }; |
307 | if (my $err = $@) { | |
308 | $self->error($reqstate, 501, $err); | |
309 | } | |
310 | }; | |
f4defdaa | 311 | |
35e83b7d DM |
312 | warn $@ if $@; |
313 | } | |
314 | ||
315 | sub proxy_request { | |
519ea5b0 | 316 | my ($self, $reqstate, $clientip, $host, $method, $uri, $ticket, $token, $params) = @_; |
35e83b7d DM |
317 | |
318 | eval { | |
319 | my $target; | |
bc8f141b | 320 | my $keep_alive = 1; |
35e83b7d | 321 | if ($host eq 'localhost') { |
519ea5b0 | 322 | $target = "http://$host:85$uri"; |
bc8f141b DM |
323 | # keep alive for localhost is not worth (connection setup is about 0.2ms) |
324 | $keep_alive = 0; | |
35e83b7d | 325 | } else { |
519ea5b0 | 326 | $target = "https://$host:8006$uri"; |
35e83b7d DM |
327 | } |
328 | ||
329 | my $headers = { | |
330 | PVEDisableProxy => 'true', | |
331 | PVEClientIP => $clientip, | |
332 | }; | |
333 | ||
334 | my $cookie_name = 'PVEAuthCookie'; | |
335 | ||
336 | $headers->{'cookie'} = PVE::REST::create_auth_cookie($ticket) if $ticket; | |
337 | $headers->{'CSRFPreventionToken'} = $token if $token; | |
c8e15d47 | 338 | $headers->{'Accept-Encoding'} = 'gzip' if $reqstate->{accept_gzip}; |
35e83b7d DM |
339 | |
340 | my $content; | |
341 | ||
342 | if ($method eq 'POST' || $method eq 'PUT') { | |
343 | $headers->{'Content-Type'} = 'application/x-www-form-urlencoded'; | |
519ea5b0 | 344 | # use URI object to format application/x-www-form-urlencoded content. |
35e83b7d DM |
345 | my $url = URI->new('http:'); |
346 | $url->query_form(%$params); | |
347 | $content = $url->query; | |
348 | if (defined($content)) { | |
349 | $headers->{'Content-Length'} = length($content); | |
350 | } | |
351 | } | |
352 | ||
35e83b7d | 353 | my $w; $w = http_request( |
f4defdaa DM |
354 | $method => $target, |
355 | headers => $headers, | |
356 | timeout => 30, | |
4c06bd34 | 357 | recurse => 0, |
907c5316 | 358 | proxy => undef, # avoid use of $ENV{HTTP_PROXY} |
bc8f141b | 359 | keepalive => $keep_alive, |
f4defdaa | 360 | body => $content, |
4c06bd34 | 361 | tls_ctx => $self->{tls_ctx}, |
35e83b7d DM |
362 | sub { |
363 | my ($body, $hdr) = @_; | |
364 | ||
365 | undef $w; | |
f4defdaa | 366 | |
b51d83cb DM |
367 | if (!$reqstate->{hdl}) { |
368 | warn "proxy detected vanished client connection\n"; | |
369 | return; | |
370 | } | |
371 | ||
35e83b7d DM |
372 | eval { |
373 | my $code = delete $hdr->{Status}; | |
374 | my $msg = delete $hdr->{Reason}; | |
375 | delete $hdr->{URL}; | |
376 | delete $hdr->{HTTPVersion}; | |
377 | my $header = HTTP::Headers->new(%$hdr); | |
378 | my $resp = HTTP::Response->new($code, $msg, $header, $body); | |
c8e15d47 | 379 | # Note: disable compression, because body is already compressed |
35e83b7d DM |
380 | $self->response($reqstate, $resp, undef, 1); |
381 | }; | |
382 | warn $@ if $@; | |
383 | }); | |
384 | }; | |
385 | warn $@ if $@; | |
386 | } | |
387 | ||
519ea5b0 DM |
388 | # return arrays as \0 separated strings (like CGI.pm) |
389 | sub decode_urlencoded { | |
390 | my ($data) = @_; | |
391 | ||
392 | my $res = {}; | |
393 | ||
394 | return $res if !$data; | |
395 | ||
396 | foreach my $kv (split(/[\&\;]/, $data)) { | |
397 | my ($k, $v) = split(/=/, $kv); | |
398 | $k =~s/\+/ /g; | |
399 | $k =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg; | |
400 | $v =~s/\+/ /g; | |
401 | $v =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg; | |
402 | ||
403 | if (defined(my $old = $res->{$k})) { | |
404 | $res->{$k} = "$old\0$v"; | |
405 | } else { | |
406 | $res->{$k} = $v; | |
407 | } | |
408 | } | |
409 | return $res; | |
410 | } | |
411 | ||
cb39891f | 412 | sub extract_params { |
35e83b7d DM |
413 | my ($r, $method) = @_; |
414 | ||
519ea5b0 | 415 | my $params = {}; |
35e83b7d DM |
416 | |
417 | if ($method eq 'PUT' || $method eq 'POST') { | |
519ea5b0 | 418 | $params = decode_urlencoded($r->content); |
35e83b7d DM |
419 | } |
420 | ||
519ea5b0 | 421 | my $query_params = decode_urlencoded($r->url->query()); |
35e83b7d DM |
422 | |
423 | foreach my $k (keys %{$query_params}) { | |
424 | $params->{$k} = $query_params->{$k}; | |
425 | } | |
426 | ||
427 | return PVE::Tools::decode_utf8_parameters($params); | |
cb39891f | 428 | } |
35e83b7d DM |
429 | |
430 | sub handle_api2_request { | |
519ea5b0 | 431 | my ($self, $reqstate, $auth, $upload_state) = @_; |
35e83b7d DM |
432 | |
433 | eval { | |
434 | my $r = $reqstate->{request}; | |
435 | my $method = $r->method(); | |
436 | my $path = $r->uri->path(); | |
437 | ||
519ea5b0 | 438 | my ($rel_uri, $format) = split_abs_uri($path); |
35e83b7d DM |
439 | if (!$format) { |
440 | $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri"); | |
441 | return; | |
442 | } | |
443 | ||
697f0611 | 444 | #print Dumper($upload_state) if $upload_state; |
35e83b7d | 445 | |
519ea5b0 | 446 | my $rpcenv = $self->{rpcenv}; |
35e83b7d | 447 | |
519ea5b0 | 448 | my $params; |
35e83b7d | 449 | |
519ea5b0 DM |
450 | if ($upload_state) { |
451 | $params = $upload_state->{params}; | |
452 | } else { | |
cb39891f | 453 | $params = extract_params($r, $method); |
519ea5b0 | 454 | } |
35e83b7d | 455 | |
519ea5b0 | 456 | delete $params->{_dc}; # remove disable cache parameter |
35e83b7d | 457 | |
519ea5b0 | 458 | my $clientip = $reqstate->{peer_host}; |
35e83b7d | 459 | |
519ea5b0 | 460 | $rpcenv->init_request(); |
35e83b7d | 461 | |
519ea5b0 | 462 | my $res = PVE::REST::rest_handler($rpcenv, $clientip, $method, $rel_uri, $auth, $params); |
35e83b7d | 463 | |
af5ed080 DM |
464 | AnyEvent->now_update(); # in case somebody called sleep() |
465 | ||
35e83b7d DM |
466 | $rpcenv->set_user(undef); # clear after request |
467 | ||
42d8780f | 468 | if (my $host = $res->{proxy}) { |
35e83b7d DM |
469 | |
470 | if ($self->{trusted_env}) { | |
471 | $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy not allowed"); | |
472 | return; | |
f4defdaa | 473 | } |
35e83b7d | 474 | |
42d8780f | 475 | if ($host ne 'localhost' && $r->header('PVEDisableProxy')) { |
7c02a325 DM |
476 | $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy loop detected"); |
477 | return; | |
478 | } | |
479 | ||
519ea5b0 DM |
480 | $res->{proxy_params}->{tmpfilename} = $reqstate->{tmpfilename} if $upload_state; |
481 | ||
42d8780f | 482 | $self->proxy_request($reqstate, $clientip, $host, $method, |
519ea5b0 | 483 | $r->uri, $auth->{ticket}, $auth->{token}, $res->{proxy_params}); |
35e83b7d DM |
484 | return; |
485 | ||
486 | } | |
487 | ||
488 | PVE::REST::prepare_response_data($format, $res); | |
e4f2a5c5 | 489 | my ($raw, $ct, $nocomp) = PVE::REST::format_response_data($format, $res, $path); |
35e83b7d DM |
490 | |
491 | my $resp = HTTP::Response->new($res->{status}, $res->{message}); | |
492 | $resp->header("Content-Type" => $ct); | |
493 | $resp->content($raw); | |
e4f2a5c5 | 494 | $self->response($reqstate, $resp, $nocomp); |
35e83b7d | 495 | }; |
519ea5b0 DM |
496 | if (my $err = $@) { |
497 | $self->error($reqstate, 501, $err); | |
498 | } | |
35e83b7d DM |
499 | } |
500 | ||
9c1493d4 | 501 | sub handle_spice_proxy_request { |
23f5480e | 502 | my ($self, $reqstate, $connect_str, $vmid, $node, $spiceport) = @_; |
9c1493d4 DM |
503 | |
504 | eval { | |
505 | ||
2164733e AD |
506 | die "Port $spiceport is not allowed" if ($spiceport < 61000 || $spiceport > 61099); |
507 | ||
9dc5cbff DM |
508 | my $rpcenv = $self->{rpcenv}; |
509 | $rpcenv->init_request(); | |
510 | ||
7c02a325 DM |
511 | my $clientip = $reqstate->{peer_host}; |
512 | my $r = $reqstate->{request}; | |
513 | ||
9c1493d4 DM |
514 | my $remip; |
515 | ||
516 | if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) { | |
517 | $remip = PVE::Cluster::remote_node_ip($node); | |
23f5480e DM |
518 | die "unable to get remote IP address for node '$node'\n" if !$remip; |
519 | print "REMOTE CONNECT $vmid, $remip, $connect_str\n" if $self->{debug}; | |
520 | } else { | |
521 | print "$$: CONNECT $vmid, $node, $spiceport\n" if $self->{debug}; | |
522 | } | |
9c1493d4 | 523 | |
32e64173 | 524 | if ($remip && $r->header('PVEDisableProxy')) { |
7c02a325 DM |
525 | $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy loop detected"); |
526 | return; | |
527 | } | |
528 | ||
9c1493d4 | 529 | $reqstate->{hdl}->timeout(0); |
23f5480e | 530 | $reqstate->{hdl}->wbuf_max(64*10*1024); |
9c1493d4 | 531 | |
23f5480e DM |
532 | my $remhost = $remip ? $remip : "127.0.0.1"; |
533 | my $remport = $remip ? 3128 : $spiceport; | |
9c1493d4 | 534 | |
23f5480e | 535 | tcp_connect $remhost, $remport, sub { |
9c1493d4 | 536 | my ($fh) = @_ |
23f5480e | 537 | or die "connect to '$remhost:$remport' failed: $!"; |
9c1493d4 | 538 | |
23f5480e | 539 | print "$$: CONNECTed to '$remhost:$remport'\n" if $self->{debug}; |
9c1493d4 DM |
540 | $reqstate->{proxyhdl} = AnyEvent::Handle->new( |
541 | fh => $fh, | |
542 | rbuf_max => 64*1024, | |
543 | wbuf_max => 64*10*1024, | |
23f5480e | 544 | timeout => 5, |
9c1493d4 DM |
545 | on_eof => sub { |
546 | my ($hdl) = @_; | |
547 | eval { | |
548 | $self->log_aborted_request($reqstate); | |
549 | $self->client_do_disconnect($reqstate); | |
550 | }; | |
551 | if (my $err = $@) { syslog('err', $err); } | |
552 | }, | |
553 | on_error => sub { | |
554 | my ($hdl, $fatal, $message) = @_; | |
555 | eval { | |
556 | $self->log_aborted_request($reqstate, $message); | |
557 | $self->client_do_disconnect($reqstate); | |
558 | }; | |
559 | if (my $err = $@) { syslog('err', "$err"); } | |
7074e572 | 560 | }); |
9c1493d4 | 561 | |
23f5480e | 562 | |
7074e572 DM |
563 | my $proxyhdlreader = sub { |
564 | my ($hdl) = @_; | |
9c1493d4 | 565 | |
7074e572 DM |
566 | my $len = length($hdl->{rbuf}); |
567 | my $data = substr($hdl->{rbuf}, 0, $len, ''); | |
568 | ||
569 | #print "READ1 $len\n"; | |
570 | $reqstate->{hdl}->push_write($data) if $reqstate->{hdl}; | |
571 | }; | |
572 | ||
573 | my $hdlreader = sub { | |
9c1493d4 DM |
574 | my ($hdl) = @_; |
575 | ||
576 | my $len = length($hdl->{rbuf}); | |
577 | my $data = substr($hdl->{rbuf}, 0, $len, ''); | |
578 | ||
579 | #print "READ0 $len\n"; | |
580 | $reqstate->{proxyhdl}->push_write($data) if $reqstate->{proxyhdl}; | |
7074e572 DM |
581 | }; |
582 | ||
23f5480e | 583 | my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0'; |
9c1493d4 | 584 | |
23f5480e DM |
585 | my $startproxy = sub { |
586 | $reqstate->{proxyhdl}->timeout(0); | |
587 | $reqstate->{proxyhdl}->on_read($proxyhdlreader); | |
588 | $reqstate->{hdl}->on_read($hdlreader); | |
9c1493d4 | 589 | |
23f5480e | 590 | # todo: use stop_read/start_read if write buffer grows to much |
9c1493d4 | 591 | |
23f5480e DM |
592 | my $res = "$proto 200 OK\015\012"; # hope this is the right answer? |
593 | $reqstate->{hdl}->push_write($res); | |
594 | ||
595 | # log early | |
596 | $reqstate->{log}->{code} = 200; | |
597 | $self->log_request($reqstate); | |
598 | }; | |
599 | ||
600 | if ($remip) { | |
601 | my $header = "CONNECT ${connect_str} $proto\015\012" . | |
602 | "Host: ${connect_str}\015\012" . | |
603 | "Proxy-Connection: keep-alive\015\012" . | |
604 | "User-Agent: spiceproxy\015\012" . | |
7c02a325 DM |
605 | "PVEDisableProxy: true\015\012" . |
606 | "PVEClientIP: $clientip\015\012" . | |
23f5480e | 607 | "\015\012"; |
7c02a325 | 608 | |
23f5480e DM |
609 | $reqstate->{proxyhdl}->push_write($header); |
610 | $reqstate->{proxyhdl}->push_read(line => sub { | |
611 | my ($hdl, $line) = @_; | |
612 | ||
613 | if ($line =~ m!^$proto 200 OK$!) { | |
614 | &$startproxy(); | |
615 | } else { | |
616 | $reqstate->{hdl}->push_write($line); | |
617 | $self->client_do_disconnect($reqstate); | |
618 | } | |
619 | }); | |
620 | } else { | |
621 | &$startproxy(); | |
622 | } | |
f3de8a0b | 623 | |
9c1493d4 DM |
624 | }; |
625 | }; | |
626 | if (my $err = $@) { | |
c3e0b952 | 627 | warn $err; |
9c1493d4 DM |
628 | $self->log_aborted_request($reqstate, $err); |
629 | $self->client_do_disconnect($reqstate); | |
630 | } | |
631 | } | |
632 | ||
35e83b7d | 633 | sub handle_request { |
519ea5b0 | 634 | my ($self, $reqstate, $auth) = @_; |
35e83b7d DM |
635 | |
636 | eval { | |
637 | my $r = $reqstate->{request}; | |
638 | my $method = $r->method(); | |
639 | my $path = $r->uri->path(); | |
af5ed080 DM |
640 | |
641 | # disable timeout on handle (we already have all data we need) | |
642 | # we re-enable timeout in response() | |
643 | $reqstate->{hdl}->timeout(0); | |
35e83b7d | 644 | |
519ea5b0 DM |
645 | if ($path =~ m!$baseuri!) { |
646 | $self->handle_api2_request($reqstate, $auth); | |
35e83b7d DM |
647 | return; |
648 | } | |
649 | ||
650 | if ($self->{pages} && ($method eq 'GET') && (my $handler = $self->{pages}->{$path})) { | |
651 | if (ref($handler) eq 'CODE') { | |
519ea5b0 DM |
652 | my $params = decode_urlencoded($r->url->query()); |
653 | my ($resp, $userid) = &$handler($self, $reqstate->{request}, $params); | |
35e83b7d DM |
654 | $self->response($reqstate, $resp); |
655 | } elsif (ref($handler) eq 'HASH') { | |
656 | if (my $filename = $handler->{file}) { | |
657 | my $fh = IO::File->new($filename) || | |
658 | die "unable to open file '$filename' - $!\n"; | |
659 | send_file_start($self, $reqstate, $filename); | |
660 | } else { | |
661 | die "internal error - no handler"; | |
662 | } | |
663 | } else { | |
664 | die "internal error - no handler"; | |
665 | } | |
666 | return; | |
f4defdaa | 667 | } |
35e83b7d DM |
668 | |
669 | if ($self->{dirs} && ($method eq 'GET')) { | |
670 | # we only allow simple names | |
671 | if ($path =~ m!^(/\S+/)([a-zA-Z0-9\-\_\.]+)$!) { | |
672 | my ($subdir, $file) = ($1, $2); | |
673 | if (my $dir = $self->{dirs}->{$subdir}) { | |
674 | my $filename = "$dir$file"; | |
675 | my $fh = IO::File->new($filename) || | |
676 | die "unable to open file '$filename' - $!\n"; | |
677 | send_file_start($self, $reqstate, $filename); | |
678 | return; | |
679 | } | |
680 | } | |
681 | } | |
682 | ||
683 | die "no such file '$path'"; | |
684 | }; | |
685 | if (my $err = $@) { | |
686 | $self->error($reqstate, 501, $err); | |
687 | } | |
688 | } | |
689 | ||
519ea5b0 DM |
690 | sub file_upload_multipart { |
691 | my ($self, $reqstate, $auth, $rstate) = @_; | |
692 | ||
693 | eval { | |
694 | my $boundary = $rstate->{boundary}; | |
695 | my $hdl = $reqstate->{hdl}; | |
696 | ||
697 | my $startlen = length($hdl->{rbuf}); | |
698 | ||
699 | if ($rstate->{phase} == 0) { # skip everything until start | |
700 | if ($hdl->{rbuf} =~ s/^.*?--\Q$boundary\E \015?\012 | |
701 | ((?:[^\015]+\015\012)* ) \015?\012//xs) { | |
702 | my $header = $1; | |
703 | my ($ct, $disp, $name, $filename); | |
704 | foreach my $line (split(/\015?\012/, $header)) { | |
705 | # assume we have single line headers | |
706 | if ($line =~ m/^Content-Type\s*:\s*(.*)/i) { | |
707 | $ct = parse_content_type($1); | |
708 | } elsif ($line =~ m/^Content-Disposition\s*:\s*(.*)/i) { | |
709 | ($disp, $name, $filename) = parse_content_disposition($1); | |
710 | } | |
711 | } | |
712 | ||
713 | if (!($disp && $disp eq 'form-data' && $name)) { | |
a1375562 | 714 | syslog('err', "wrong content disposition in multipart - abort upload"); |
519ea5b0 DM |
715 | $rstate->{phase} = -1; |
716 | } else { | |
717 | ||
718 | $rstate->{fieldname} = $name; | |
719 | ||
a1375562 DM |
720 | if ($filename) { |
721 | if ($name eq 'filename') { | |
722 | # found file upload data | |
723 | $rstate->{phase} = 1; | |
724 | $rstate->{filename} = $filename; | |
725 | } else { | |
726 | syslog('err', "wrong field name for file upload - abort upload"); | |
727 | $rstate->{phase} = -1; | |
728 | } | |
729 | } else { | |
519ea5b0 DM |
730 | # found form data for field $name |
731 | $rstate->{phase} = 2; | |
519ea5b0 DM |
732 | } |
733 | } | |
734 | } else { | |
735 | my $len = length($hdl->{rbuf}); | |
736 | substr($hdl->{rbuf}, 0, $len - $rstate->{maxheader}, '') | |
737 | if $len > $rstate->{maxheader}; # skip garbage | |
738 | } | |
739 | } elsif ($rstate->{phase} == 1) { # inside file - dump until end marker | |
740 | if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) { | |
741 | my ($rest, $eof) = ($1, $3); | |
742 | my $len = length($rest); | |
743 | die "write to temporary file failed - $!" | |
744 | if syswrite($rstate->{outfh}, $rest) != $len; | |
745 | $rstate->{ctx}->add($rest); | |
746 | $rstate->{params}->{filename} = $rstate->{filename}; | |
747 | $rstate->{md5sum} = $rstate->{ctx}->hexdigest; | |
748 | $rstate->{bytes} += $len; | |
749 | $rstate->{phase} = $eof ? 100 : 0; | |
750 | } else { | |
751 | my $len = length($hdl->{rbuf}); | |
752 | my $wlen = $len - $rstate->{boundlen}; | |
753 | if ($wlen > 0) { | |
da342311 | 754 | my $data = substr($hdl->{rbuf}, 0, $wlen, ''); |
519ea5b0 DM |
755 | die "write to temporary file failed - $!" |
756 | if syswrite($rstate->{outfh}, $data) != $wlen; | |
757 | $rstate->{bytes} += $wlen; | |
758 | $rstate->{ctx}->add($data); | |
759 | } | |
760 | } | |
761 | } elsif ($rstate->{phase} == 2) { # inside normal field | |
762 | ||
763 | if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) { | |
764 | my ($rest, $eof) = ($1, $3); | |
765 | my $len = length($rest); | |
562cd9a4 DM |
766 | $rstate->{post_size} += $len; |
767 | if ($rstate->{post_size} < $limit_max_post) { | |
519ea5b0 DM |
768 | $rstate->{params}->{$rstate->{fieldname}} = $rest; |
769 | $rstate->{phase} = $eof ? 100 : 0; | |
770 | } else { | |
562cd9a4 | 771 | syslog('err', "form data to large - abort upload"); |
519ea5b0 DM |
772 | $rstate->{phase} = -1; # skip |
773 | } | |
774 | } | |
775 | } else { # skip | |
776 | my $len = length($hdl->{rbuf}); | |
777 | substr($hdl->{rbuf}, 0, $len, ''); # empty rbuf | |
778 | } | |
779 | ||
780 | $rstate->{read} += ($startlen - length($hdl->{rbuf})); | |
781 | ||
782 | if (!$rstate->{done} && ($rstate->{read} + length($hdl->{rbuf})) >= $rstate->{size}) { | |
783 | $rstate->{done} = 1; # make sure we dont get called twice | |
784 | if ($rstate->{phase} < 0 || !$rstate->{md5sum}) { | |
cb39891f | 785 | die "upload failed\n"; |
519ea5b0 DM |
786 | } else { |
787 | my $elapsed = tv_interval($rstate->{starttime}); | |
788 | ||
789 | my $rate = int($rstate->{bytes}/($elapsed*1024*1024)); | |
790 | syslog('info', "multipart upload complete " . | |
da342311 DM |
791 | "(size: %d time: %ds rate: %.2fMiB/s md5sum: $rstate->{md5sum})", |
792 | $rstate->{bytes}, $elapsed, $rate); | |
519ea5b0 DM |
793 | $self->handle_api2_request($reqstate, $auth, $rstate); |
794 | } | |
795 | } | |
796 | }; | |
797 | if (my $err = $@) { | |
da342311 | 798 | syslog('err', $err); |
519ea5b0 DM |
799 | $self->error($reqstate, 501, $err); |
800 | } | |
801 | } | |
802 | ||
803 | sub parse_content_type { | |
804 | my ($ctype) = @_; | |
805 | ||
806 | my ($ct, @params) = split(/\s*[;,]\s*/o, $ctype); | |
807 | ||
808 | foreach my $v (@params) { | |
809 | if ($v =~ m/^\s*boundary\s*=\s*(\S+?)\s*$/o) { | |
810 | return wantarray ? ($ct, $1) : $ct; | |
811 | } | |
812 | } | |
813 | ||
814 | return wantarray ? ($ct) : $ct; | |
815 | } | |
816 | ||
817 | sub parse_content_disposition { | |
818 | my ($line) = @_; | |
819 | ||
820 | my ($disp, @params) = split(/\s*[;,]\s*/o, $line); | |
821 | my $name; | |
822 | my $filename; | |
823 | ||
824 | foreach my $v (@params) { | |
825 | if ($v =~ m/^\s*name\s*=\s*(\S+?)\s*$/o) { | |
826 | $name = $1; | |
827 | $name =~ s/^"(.*)"$/$1/; | |
7f87932a | 828 | } elsif ($v =~ m/^\s*filename\s*=\s*(.+?)\s*$/o) { |
519ea5b0 DM |
829 | $filename = $1; |
830 | $filename =~ s/^"(.*)"$/$1/; | |
831 | } | |
832 | } | |
833 | ||
834 | return wantarray ? ($disp, $name, $filename) : $disp; | |
835 | } | |
836 | ||
837 | my $tmpfile_seq_no = 0; | |
838 | ||
839 | sub get_upload_filename { | |
840 | # choose unpredictable tmpfile name | |
841 | ||
842 | $tmpfile_seq_no++; | |
843 | return "/var/tmp/pveupload-" . Digest::MD5::md5_hex($tmpfile_seq_no . time() . $$); | |
844 | } | |
845 | ||
35e83b7d DM |
846 | sub unshift_read_header { |
847 | my ($self, $reqstate, $state) = @_; | |
848 | ||
562cd9a4 | 849 | $state = { size => 0, count => 0 } if !$state; |
35e83b7d DM |
850 | |
851 | $reqstate->{hdl}->unshift_read(line => sub { | |
852 | my ($hdl, $line) = @_; | |
853 | ||
854 | eval { | |
562cd9a4 DM |
855 | # print "$$: got header: $line\n" if $self->{debug}; |
856 | ||
857 | die "to many http header lines\n" if ++$state->{count} >= $limit_max_headers; | |
858 | die "http header too large\n" if ($state->{size} += length($line)) >= $limit_max_header_size; | |
35e83b7d DM |
859 | |
860 | my $r = $reqstate->{request}; | |
861 | if ($line eq '') { | |
862 | ||
519ea5b0 DM |
863 | my $path = $r->uri->path(); |
864 | my $method = $r->method(); | |
865 | ||
35e83b7d DM |
866 | $r->push_header($state->{key}, $state->{val}) |
867 | if $state->{key}; | |
868 | ||
519ea5b0 DM |
869 | if (!$known_methods->{$method}) { |
870 | my $resp = HTTP::Response->new(HTTP_NOT_IMPLEMENTED, "method '$method' not available"); | |
871 | $self->response($reqstate, $resp); | |
872 | return; | |
873 | } | |
874 | ||
35e83b7d | 875 | my $conn = $r->header('Connection'); |
c8e15d47 DM |
876 | my $accept_enc = $r->header('Accept-Encoding'); |
877 | $reqstate->{accept_gzip} = ($accept_enc && $accept_enc =~ m/gzip/) ? 1 : 0; | |
35e83b7d DM |
878 | |
879 | if ($conn) { | |
880 | $reqstate->{keep_alive} = 0 if $conn =~ m/close/oi; | |
881 | } else { | |
882 | if ($reqstate->{proto}->{ver} < 1001) { | |
883 | $reqstate->{keep_alive} = 0; | |
884 | } | |
885 | } | |
886 | ||
35e83b7d | 887 | my $te = $r->header('Transfer-Encoding'); |
519ea5b0 DM |
888 | if ($te && lc($te) eq 'chunked') { |
889 | # Handle chunked transfer encoding | |
890 | $self->error($reqstate, 501, "chunked transfer encoding not supported"); | |
891 | return; | |
892 | } elsif ($te) { | |
893 | $self->error($reqstate, 501, "Unknown transfer encoding '$te'"); | |
894 | return; | |
895 | } | |
896 | ||
35e83b7d DM |
897 | my $pveclientip = $r->header('PVEClientIP'); |
898 | ||
f4defdaa | 899 | # fixme: how can we make PVEClientIP header trusted? |
35e83b7d DM |
900 | if ($self->{trusted_env} && $pveclientip) { |
901 | $reqstate->{peer_host} = $pveclientip; | |
902 | } else { | |
903 | $r->header('PVEClientIP', $reqstate->{peer_host}); | |
904 | } | |
905 | ||
519ea5b0 DM |
906 | my $len = $r->header('Content-Length'); |
907 | ||
908 | # header processing complete - authenticate now | |
909 | ||
910 | my $auth = {}; | |
9c1493d4 DM |
911 | if ($self->{spiceproxy}) { |
912 | my $connect_str = $r->header('Host'); | |
c4d6e4bb DM |
913 | my ($vmid, $node, $port) = PVE::AccessControl::verify_spice_connect_url($connect_str); |
914 | if (!($vmid && $node && $port)) { | |
9c1493d4 DM |
915 | $self->error($reqstate, HTTP_UNAUTHORIZED, "invalid ticket"); |
916 | return; | |
917 | } | |
23f5480e | 918 | $self->handle_spice_proxy_request($reqstate, $connect_str, $vmid, $node, $port); |
9c1493d4 DM |
919 | return; |
920 | } elsif ($path =~ m!$baseuri!) { | |
519ea5b0 DM |
921 | my $token = $r->header('CSRFPreventionToken'); |
922 | my $cookie = $r->header('Cookie'); | |
923 | my $ticket = PVE::REST::extract_auth_cookie($cookie); | |
924 | ||
925 | my ($rel_uri, $format) = split_abs_uri($path); | |
926 | if (!$format) { | |
927 | $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri"); | |
928 | return; | |
929 | } | |
930 | ||
931 | eval { | |
932 | $auth = PVE::REST::auth_handler($self->{rpcenv}, $reqstate->{peer_host}, $method, | |
933 | $rel_uri, $ticket, $token); | |
934 | }; | |
935 | if (my $err = $@) { | |
936 | $self->error($reqstate, HTTP_UNAUTHORIZED, $err); | |
937 | return; | |
938 | } | |
939 | } | |
940 | ||
941 | $reqstate->{log}->{userid} = $auth->{userid}; | |
942 | ||
67637d3a | 943 | if ($len) { |
519ea5b0 DM |
944 | |
945 | if (!($method eq 'PUT' || $method eq 'POST')) { | |
946 | $self->error($reqstate, 501, "Unexpected content for method '$method'"); | |
947 | return; | |
948 | } | |
949 | ||
950 | my $ctype = $r->header('Content-Type'); | |
697f0611 | 951 | my ($ct, $boundary) = parse_content_type($ctype) if $ctype; |
519ea5b0 DM |
952 | |
953 | if ($auth->{isUpload} && !$self->{trusted_env}) { | |
954 | die "upload 'Content-Type '$ctype' not implemented\n" | |
697f0611 | 955 | if !($boundary && $ct && ($ct eq 'multipart/form-data')); |
519ea5b0 DM |
956 | |
957 | die "upload without content length header not supported" if !$len; | |
958 | ||
959 | die "upload without content length header not supported" if !$len; | |
960 | ||
961 | print "start upload $path $ct $boundary\n" if $self->{debug}; | |
962 | ||
963 | my $tmpfilename = get_upload_filename(); | |
964 | my $outfh = IO::File->new($tmpfilename, O_RDWR|O_CREAT|O_EXCL, 0600) || | |
965 | die "unable to create temporary upload file '$tmpfilename'"; | |
966 | ||
967 | $reqstate->{keep_alive} = 0; | |
968 | ||
969 | my $boundlen = length($boundary) + 8; # \015?\012--$boundary--\015?\012 | |
970 | ||
971 | my $state = { | |
972 | size => $len, | |
973 | boundary => $boundary, | |
974 | ctx => Digest::MD5->new, | |
975 | boundlen => $boundlen, | |
976 | maxheader => 2048 + $boundlen, # should be large enough | |
977 | params => decode_urlencoded($r->url->query()), | |
978 | phase => 0, | |
979 | read => 0, | |
562cd9a4 | 980 | post_size => 0, |
519ea5b0 DM |
981 | starttime => [gettimeofday], |
982 | outfh => $outfh, | |
983 | }; | |
984 | $reqstate->{tmpfilename} = $tmpfilename; | |
985 | $reqstate->{hdl}->on_read(sub { $self->file_upload_multipart($reqstate, $auth, $state); }); | |
986 | return; | |
987 | } | |
988 | ||
562cd9a4 DM |
989 | if ($len > $limit_max_post) { |
990 | $self->error($reqstate, 501, "for data too large"); | |
991 | return; | |
992 | } | |
993 | ||
519ea5b0 DM |
994 | if (!$ct || $ct eq 'application/x-www-form-urlencoded') { |
995 | $reqstate->{hdl}->unshift_read(chunk => $len, sub { | |
996 | my ($hdl, $data) = @_; | |
997 | $r->content($data); | |
998 | $self->handle_request($reqstate, $auth); | |
999 | }); | |
1000 | } else { | |
1001 | $self->error($reqstate, 506, "upload 'Content-Type '$ctype' not implemented"); | |
1002 | } | |
35e83b7d | 1003 | } else { |
519ea5b0 | 1004 | $self->handle_request($reqstate, $auth); |
35e83b7d DM |
1005 | } |
1006 | } elsif ($line =~ /^([^:\s]+)\s*:\s*(.*)/) { | |
1007 | $r->push_header($state->{key}, $state->{val}) if $state->{key}; | |
1008 | ($state->{key}, $state->{val}) = ($1, $2); | |
1009 | $self->unshift_read_header($reqstate, $state); | |
1010 | } elsif ($line =~ /^\s+(.*)/) { | |
1011 | $state->{val} .= " $1"; | |
1012 | $self->unshift_read_header($reqstate, $state); | |
1013 | } else { | |
1014 | $self->error($reqstate, 506, "unable to parse request header"); | |
1015 | } | |
1016 | }; | |
1017 | warn $@ if $@; | |
1018 | }); | |
1019 | }; | |
1020 | ||
1021 | sub push_request_header { | |
1022 | my ($self, $reqstate) = @_; | |
1023 | ||
1024 | eval { | |
1025 | $reqstate->{hdl}->push_read(line => sub { | |
1026 | my ($hdl, $line) = @_; | |
1027 | ||
1028 | eval { | |
23f5480e | 1029 | # print "got request header: $line\n" if $self->{debug}; |
f4defdaa | 1030 | |
35e83b7d DM |
1031 | $reqstate->{keep_alive}--; |
1032 | ||
1033 | if ($line =~ /(\S+)\040(\S+)\040HTTP\/(\d+)\.(\d+)/o) { | |
1034 | my ($method, $uri, $maj, $min) = ($1, $2, $3, $4); | |
1035 | ||
1036 | if ($maj != 1) { | |
1037 | $self->error($reqstate, 506, "http protocol version $maj.$min not supported"); | |
1038 | return; | |
1039 | } | |
1040 | ||
1041 | $self->{request_count}++; # only count valid request headers | |
1042 | if ($self->{request_count} >= $self->{max_requests}) { | |
f4defdaa | 1043 | $self->{end_loop} = 1; |
35e83b7d DM |
1044 | } |
1045 | $reqstate->{log} = { requestline => $line }; | |
697f0611 | 1046 | $reqstate->{proto}->{str} = "HTTP/$maj.$min"; |
35e83b7d DM |
1047 | $reqstate->{proto}->{maj} = $maj; |
1048 | $reqstate->{proto}->{min} = $min; | |
1049 | $reqstate->{proto}->{ver} = $maj*1000+$min; | |
1050 | $reqstate->{request} = HTTP::Request->new($method, $uri); | |
1051 | ||
1052 | $self->unshift_read_header($reqstate); | |
1053 | } elsif ($line eq '') { | |
1054 | # ignore empty lines before requests (browser bugs?) | |
1055 | $self->push_request_header($reqstate); | |
1056 | } else { | |
1057 | $self->error($reqstate, 400, 'bad request'); | |
1058 | } | |
1059 | }; | |
1060 | warn $@ if $@; | |
1061 | }); | |
1062 | }; | |
1063 | warn $@ if $@; | |
1064 | } | |
1065 | ||
1066 | sub accept { | |
1067 | my ($self) = @_; | |
1068 | ||
1069 | my $clientfh; | |
1070 | ||
1071 | return if $self->{end_loop}; | |
1072 | ||
1073 | # we need to m make sure that only one process calls accept | |
1074 | while (!flock($self->{lockfh}, Fcntl::LOCK_EX())) { | |
1075 | next if $! == EINTR; | |
1076 | die "could not get lock on file '$self->{lockfile}' - $!\n"; | |
1077 | } | |
1078 | ||
1079 | my $again = 0; | |
1080 | my $errmsg; | |
1081 | eval { | |
1082 | while (!$self->{end_loop} && | |
1083 | !defined($clientfh = $self->{socket}->accept()) && | |
1084 | ($! == EINTR)) {}; | |
1085 | ||
1086 | if ($self->{end_loop}) { | |
1087 | $again = 0; | |
1088 | } else { | |
1089 | $again = ($! == EAGAIN || $! == WSAEWOULDBLOCK); | |
1090 | if (!defined($clientfh)) { | |
1091 | $errmsg = "failed to accept connection: $!\n"; | |
1092 | } | |
1093 | } | |
1094 | }; | |
1095 | warn $@ if $@; | |
1096 | ||
1097 | flock($self->{lockfh}, Fcntl::LOCK_UN()); | |
1098 | ||
1099 | if (!defined($clientfh)) { | |
1100 | return if $again; | |
1101 | die $errmsg if $errmsg; | |
1102 | } | |
1103 | ||
f4defdaa | 1104 | fh_nonblocking $clientfh, 1; |
35e83b7d DM |
1105 | |
1106 | $self->{conn_count}++; | |
1107 | ||
35e83b7d DM |
1108 | return $clientfh; |
1109 | } | |
1110 | ||
1111 | sub wait_end_loop { | |
1112 | my ($self) = @_; | |
1113 | ||
1114 | $self->{end_loop} = 1; | |
1115 | ||
1116 | undef $self->{socket_watch}; | |
f4defdaa | 1117 | |
35e83b7d DM |
1118 | if ($self->{conn_count} <= 0) { |
1119 | $self->{end_cond}->send(1); | |
1120 | return; | |
1121 | } | |
1122 | ||
1123 | # else we need to wait until all open connections gets closed | |
1124 | my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub { | |
1125 | eval { | |
f4defdaa | 1126 | # todo: test for active connections instead (we can abort idle connections) |
35e83b7d DM |
1127 | if ($self->{conn_count} <= 0) { |
1128 | undef $w; | |
1129 | $self->{end_cond}->send(1); | |
1130 | } | |
1131 | }; | |
1132 | warn $@ if $@; | |
1133 | }); | |
1134 | } | |
f4defdaa | 1135 | |
81af3133 DM |
1136 | |
1137 | sub check_host_access { | |
1138 | my ($self, $clientip) = @_; | |
1139 | ||
1140 | my $cip = Net::IP->new($clientip); | |
1141 | ||
1142 | my $match_allow = 0; | |
1143 | my $match_deny = 0; | |
1144 | ||
1145 | if ($self->{allow_from}) { | |
1146 | foreach my $t (@{$self->{allow_from}}) { | |
1147 | if ($t->overlaps($cip)) { | |
1148 | $match_allow = 1; | |
1149 | last; | |
1150 | } | |
1151 | } | |
1152 | } | |
1153 | ||
1154 | if ($self->{deny_from}) { | |
1155 | foreach my $t (@{$self->{deny_from}}) { | |
1156 | if ($t->overlaps($cip)) { | |
1157 | $match_deny = 1; | |
1158 | last; | |
1159 | } | |
1160 | } | |
1161 | } | |
1162 | ||
1163 | if ($match_allow == $match_deny) { | |
1164 | # match both allow and deny, or no match | |
1165 | return $self->{policy} && $self->{policy} eq 'allow' ? 1 : 0; | |
1166 | } | |
1167 | ||
1168 | return $match_allow; | |
1169 | } | |
1170 | ||
35e83b7d DM |
1171 | sub accept_connections { |
1172 | my ($self) = @_; | |
1173 | ||
1174 | eval { | |
1175 | ||
1176 | while (my $clientfh = $self->accept()) { | |
1177 | ||
1178 | my $reqstate = { keep_alive => $self->{keep_alive} }; | |
1179 | ||
cc422b33 DM |
1180 | # stop keep-alive when there are many open connections |
1181 | if ($self->{conn_count} >= $self->{max_conn_soft_limit}) { | |
1182 | $reqstate->{keep_alive} = 0; | |
1183 | } | |
1184 | ||
35e83b7d DM |
1185 | if (my $sin = getpeername($clientfh)) { |
1186 | my ($pport, $phost) = Socket::unpack_sockaddr_in($sin); | |
1187 | ($reqstate->{peer_port}, $reqstate->{peer_host}) = ($pport, Socket::inet_ntoa($phost)); | |
1188 | } | |
1189 | ||
81af3133 DM |
1190 | if (!$self->{trusted_env} && !$self->check_host_access($reqstate->{peer_host})) { |
1191 | print "$$: ABORT request from $reqstate->{peer_host} - access denied\n" if $self->{debug}; | |
1192 | $reqstate->{log}->{code} = 403; | |
1193 | $self->log_request($reqstate); | |
1194 | next; | |
1195 | } | |
1196 | ||
35e83b7d DM |
1197 | $reqstate->{hdl} = AnyEvent::Handle->new( |
1198 | fh => $clientfh, | |
519ea5b0 | 1199 | rbuf_max => 64*1024, |
35e83b7d DM |
1200 | timeout => $self->{timeout}, |
1201 | linger => 0, # avoid problems with ssh - really needed ? | |
1202 | on_eof => sub { | |
1203 | my ($hdl) = @_; | |
1204 | eval { | |
1205 | $self->log_aborted_request($reqstate); | |
1206 | $self->client_do_disconnect($reqstate); | |
1207 | }; | |
1208 | if (my $err = $@) { syslog('err', $err); } | |
1209 | }, | |
f4defdaa | 1210 | on_error => sub { |
35e83b7d DM |
1211 | my ($hdl, $fatal, $message) = @_; |
1212 | eval { | |
1213 | $self->log_aborted_request($reqstate, $message); | |
1214 | $self->client_do_disconnect($reqstate); | |
1215 | }; | |
1216 | if (my $err = $@) { syslog('err', "$err"); } | |
1217 | }, | |
1218 | ($self->{tls_ctx} ? (tls => "accept", tls_ctx => $self->{tls_ctx}) : ())); | |
1219 | ||
f4defdaa | 1220 | print "$$: ACCEPT FH" . $clientfh->fileno() . " CONN$self->{conn_count}\n" if $self->{debug}; |
35e83b7d DM |
1221 | |
1222 | $self->push_request_header($reqstate); | |
1223 | } | |
1224 | }; | |
1225 | ||
1226 | if (my $err = $@) { | |
1227 | syslog('err', $err); | |
1228 | $self->{end_loop} = 1; | |
1229 | } | |
1230 | ||
1231 | $self->wait_end_loop() if $self->{end_loop}; | |
1232 | } | |
1233 | ||
3cdd9dc4 DM |
1234 | # Note: We can't open log file in non-blocking mode and use AnyEvent::Handle, |
1235 | # because we write from multiple processes, and that would arbitrarily mix output | |
f4defdaa | 1236 | # of all processes. |
35e83b7d DM |
1237 | sub open_access_log { |
1238 | my ($self, $filename) = @_; | |
1239 | ||
1240 | my $old_mask = umask(0137);; | |
1241 | my $logfh = IO::File->new($filename, ">>") || | |
1242 | die "unable to open log file '$filename' - $!\n"; | |
1243 | umask($old_mask); | |
1244 | ||
3cdd9dc4 DM |
1245 | $logfh->autoflush(1); |
1246 | ||
1247 | $self->{logfh} = $logfh; | |
1248 | } | |
1249 | ||
1250 | sub write_log { | |
1251 | my ($self, $data) = @_; | |
1252 | ||
1253 | return if !defined($self->{logfh}) || !$data; | |
1254 | ||
1255 | my $res = $self->{logfh}->print($data); | |
1256 | ||
1257 | if (!$res) { | |
1258 | delete $self->{logfh}; | |
1259 | syslog('err', "error writing access log"); | |
1260 | $self->{end_loop} = 1; # terminate asap | |
1261 | } | |
35e83b7d DM |
1262 | } |
1263 | ||
4c06bd34 DM |
1264 | sub atfork_handler { |
1265 | my ($self) = @_; | |
1266 | ||
1267 | eval { | |
1268 | # something else do to ? | |
1269 | close($self->{socket}); | |
1270 | }; | |
1271 | warn $@ if $@; | |
1272 | } | |
1273 | ||
35e83b7d DM |
1274 | sub new { |
1275 | my ($this, %args) = @_; | |
1276 | ||
1277 | my $class = ref($this) || $this; | |
1278 | ||
f4defdaa | 1279 | foreach my $req (qw(socket lockfh lockfile)) { |
35e83b7d DM |
1280 | die "misssing required argument '$req'" if !defined($args{$req}); |
1281 | } | |
1282 | ||
1283 | my $self = bless { %args }, $class; | |
1284 | ||
f4defdaa DM |
1285 | # init inotify |
1286 | PVE::INotify::inotify_init(); | |
1287 | ||
f4defdaa | 1288 | $self->{rpcenv} = PVE::RPCEnvironment->init( |
4c06bd34 | 1289 | $self->{trusted_env} ? 'priv' : 'pub', atfork => sub { $self-> atfork_handler() }); |
f4defdaa | 1290 | |
35e83b7d DM |
1291 | fh_nonblocking($self->{socket}, 1); |
1292 | ||
1293 | $self->{end_loop} = 0; | |
1294 | $self->{conn_count} = 0; | |
1295 | $self->{request_count} = 0; | |
1296 | $self->{timeout} = 5 if !$self->{timeout}; | |
1297 | $self->{keep_alive} = 0 if !defined($self->{keep_alive}); | |
1298 | $self->{max_conn} = 800 if !$self->{max_conn}; | |
1299 | $self->{max_requests} = 8000 if !$self->{max_requests}; | |
1300 | ||
81af3133 DM |
1301 | $self->{policy} = 'allow' if !$self->{policy}; |
1302 | ||
35e83b7d DM |
1303 | $self->{end_cond} = AnyEvent->condvar; |
1304 | ||
1305 | if ($self->{ssl}) { | |
f4defdaa | 1306 | $self->{tls_ctx} = AnyEvent::TLS->new(%{$self->{ssl}}); |
35e83b7d DM |
1307 | } |
1308 | ||
9c1493d4 DM |
1309 | if ($self->{spiceproxy}) { |
1310 | $known_methods = { CONNECT => 1 }; | |
1311 | } | |
1312 | ||
35e83b7d | 1313 | $self->open_access_log($self->{logfile}) if $self->{logfile}; |
f4defdaa | 1314 | |
cc422b33 DM |
1315 | $self->{max_conn_soft_limit} = $self->{max_conn} > 100 ? $self->{max_conn} - 20 : $self->{max_conn}; |
1316 | ||
35e83b7d DM |
1317 | $self->{socket_watch} = AnyEvent->io(fh => $self->{socket}, poll => 'r', cb => sub { |
1318 | eval { | |
1319 | if ($self->{conn_count} >= $self->{max_conn}) { | |
1320 | my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub { | |
1321 | if ($self->{conn_count} < $self->{max_conn}) { | |
1322 | undef $w; | |
1323 | $self->accept_connections(); | |
1324 | } | |
1325 | }); | |
1326 | } else { | |
1327 | $self->accept_connections(); | |
f4defdaa | 1328 | } |
35e83b7d DM |
1329 | }; |
1330 | warn $@ if $@; | |
1331 | }); | |
1332 | ||
1333 | $self->{term_watch} = AnyEvent->signal(signal => "TERM", cb => sub { | |
1334 | undef $self->{term_watch}; | |
1335 | $self->wait_end_loop(); | |
1336 | }); | |
1337 | ||
f4defdaa | 1338 | $self->{quit_watch} = AnyEvent->signal(signal => "QUIT", cb => sub { |
35e83b7d DM |
1339 | undef $self->{quit_watch}; |
1340 | $self->wait_end_loop(); | |
1341 | }); | |
1342 | ||
f4defdaa DM |
1343 | $self->{inotify_poll} = AnyEvent->timer(after => 5, interval => 5, cb => sub { |
1344 | PVE::INotify::poll(); # read inotify events | |
1345 | }); | |
1346 | ||
35e83b7d DM |
1347 | return $self; |
1348 | } | |
1349 | ||
1350 | sub run { | |
1351 | my ($self) = @_; | |
1352 | ||
1353 | $self->{end_cond}->recv; | |
1354 | } | |
1355 | ||
1356 | 1; |