1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
|
## ----------------------------------------------------------------------------
# Tools::HTTPParser.
# -----------------------------------------------------------------------------
# Mastering programmed by YAMASHINA Hio
#
# Copyright 2008 YAMASHINA Hio
# -----------------------------------------------------------------------------
# $Id: HTTPParser.pm 11016 2008-05-03 06:43:45Z hio $
# -----------------------------------------------------------------------------
package Tools::HTTPParser;
use strict;
use warnings;
#our $HAS_HTTP_PARSER ||= do{
# eval 'local($SIG{__DIE__})="DEFAULT";use HTTP::Parser; 1;';
# $@ and RunLoop->shared_loop->notify_msg(__PACKAGE__.", HTTP::Parser: $@");
# !$@;
#};
our $RE_REQUEST_GREETING = qr{
^
(\w+) # method:GET/POST/tec.
(?:\s+)
(\S+?) # path:/
(?:
(?:\s+)
(HTTP/.+?) # protocol:HTTP/1.0
)?
[ \t]*\r?\n
}ix;
our $RE_RESPONSE_GREETING = qr{
^
(HTTP/\d+\.\d+) # protocol:HTTP/1.0
(?:\s+)
(\d+) # status_code:200
(?:\s+)
(.+?) # message:OK.
[ \t]*\r?\n
}ix;
# constants.
our $RET_NEED_LINE_DATA = -2;
our $RET_NEED_MORE_DATA = -1;
our $RET_SUCCESS = 0;
our %HTTP_STATUS_MESSAGE = (
200 => 'OK',
302 => 'Found',
401 => 'Unauthorized',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
500 => 'Server Error',
503 => 'Temporary Unavailable',
);
our $DEBUG = 0;
1;
# -----------------------------------------------------------------------------
# $pkg->new().
# $pkg->new(request => 1).
# $pkg->new(response => 1).
#
sub new
{
my $pkg = shift;
my %opts = @_;
my $this = bless {}, $pkg;
$this->{parser} = undef;
$this->{recvbuf} = '';
$this->{prevkey} = undef;
$this->{rest} = undef;
$this->{reply} = {
StreamState => 'greeting', # greeting/header/body/parsed.
};
# [request] / [response] => [sample]
# Protocol / Protocol => "HTTP/1.0",
# Type / Type => request / response.
# StreamState / StreamState => greeting/header/body/parsed.
# Path / => "/path/to/?request",
# Method / => "GET",
# / Code => 200
# / Message => "OK",
# Header / Header => {},
# Content / Content => undef,
$this;
}
# -----------------------------------------------------------------------------
# $status = $pkg->add($packet).
#
sub add
{
my $this = shift;
my $packet = shift;
$this->{recvbuf} .= $packet;
$DEBUG and require Data::Dumper;
$DEBUG and print __PACKAGE__."#add, StreamState = $this->{reply}{StreamState}\n";
if( $this->{reply}{StreamState} eq 'greeting' )
{
my $taintness = substr($this->{recvbuf}, 0, 0);
if( $this->{recvbuf} =~ s/$RE_REQUEST_GREETING// )
{
my $method = $1 . $taintness;
my $path = $2 . $taintness;
my $proto = $3 . $taintness;
$this->{reply} = {
StreamState => 'header', # greeting/header/body/parsed.
Type => 'request',
Protocol => $proto,
Path => $path,
Method => $method,
Header => {},
Content => undef,
};
}elsif( $this->{recvbuf} =~ s/$RE_RESPONSE_GREETING// )
{
my $proto = $1 . $taintness;
my $code = $2 . $taintness;
my $msg = $3 . $taintness;
$this->{reply} = {
StreamState => 'header', # greeting/header/body/parsed.
Type => 'response',
Protocol => $proto,
Code => $code,
Message => $msg,
Header => {},
Content => undef,
};
}else
{
my $offs = index($this->{recvbuf}, "\n");
if( $offs >= 0 )
{
my $line = substr($this->{recvbuf}, 0, $offs+1);
$line =~ s/\r?\n\z//;
die "invalid greeting: $line";
}
return $RET_NEED_LINE_DATA;
}
$this->{prevkey} = undef;
$DEBUG and print __PACKAGE__."#add, got greeting, ".Data::Dumper->new([$this->{reply}],['reply'])->Indent(1)->Dump;
}
my $reply = $this->{reply};
if( $reply->{StreamState} eq 'header' )
{
for(;;)
{
my $offs = index($this->{recvbuf}, "\n");
if( $offs < 0 )
{
return $RET_NEED_LINE_DATA;
}
my $line = substr($this->{recvbuf}, 0, $offs+1, '');
$line =~ s/\r?\n\z//;
$DEBUG and print __PACKAGE__."#add, line> $line\n";
if( $line eq '' )
{
last;
}
if( $line =~ s/^\s+/ / )
{
my $prevkey= $this->{prevkey};
if( !defined($prevkey) )
{
die "invalid header(without previous key): $line";
}
$reply->{Header}{$prevkey} .= $line;
if( $reply->{ListedHeader}{$prevkey} )
{
$reply->{ListedHeader}{$prevkey}[-1] .= $line;
}
next;
}
my ($key, $val) = split(/:\s*/, $line, 2);
if( !defined($val) )
{
die "invalid header(no splitter): $line";
}
$key =~ s/(?:(?<=-)|^)([a-z])/\U$1/g;
if( exists($reply->{Header}{$key}) )
{
$reply->{ListedHeader}{$key} ||= [ $reply->{Header}{$key} ];
push(@{$reply->{ListedHeader}{$key}}, $val);
}
$reply->{Header}{$key} = $val;
$this->{prevkey} = $key;
}
$this->{rest} = $reply->{Header}{'Content-Length'};
my $read_body = 0;
if( defined($this->{rest}) )
{
# Content-Length で本文サイズが指定されているとき.
$read_body = 1;
}elsif( !$reply->{Method} )
{
# Response のとき.
$read_body = 1;
}elsif( $reply->{Method} eq 'POST' )
{
# Request/POST のとき.
$read_body = 1;
}else
{
# Request/POST以外 のとき.
$read_body = 0;
}
if( !$read_body )
{
$reply->{StreamState} = 'parsed';
return $RET_SUCCESS;
}
$reply->{StreamState} = 'body';
$DEBUG and print __PACKAGE__."#add, got header, ".Data::Dumper->new([$this->{reply}],['reply'])->Indent(1)->Dump;
}
if( $reply->{StreamState} eq 'body' )
{
if( !defined($reply->{Content}) && $this->{recvbuf} ne '' )
{
$reply->{Content} = '';
}
my $ret;
if( !defined($this->{rest}) )
{
$reply->{Content} .= $this->{recvbuf};
$this->{recvbuf} = '';
$ret = $RET_NEED_MORE_DATA;
}elsif( length($this->{recvbuf}) < $this->{rest} )
{
$this->{rest} -= length($this->{recvbuf});
$reply->{Content} .= $this->{recvbuf};
$this->{recvbuf} = '';
$ret = $this->{rest};
}else
{
$reply->{Content} .= substr($this->{recvbuf}, 0, $this->{rest}, '');
$this->{rest} = undef;
$reply->{StreamState} = 'parsed';
$ret = $RET_SUCCESS;
}
$DEBUG and print __PACKAGE__."#add, got body, rest=$ret, reply=".Data::Dumper->new([$this->{reply}])->Indent(1)->Terse(1)->Dump;
return $ret;
}
die "NOT REACH HERE: StreamState=$reply->{StreamState}";
}
# -----------------------------------------------------------------------------
# $obj->object().
#
sub object
{
my $this = shift;
$this->{reply};
}
# -----------------------------------------------------------------------------
# $len = $obj->extra().
# バッファに残っているデータサイズ(数値)を取得.
#
sub extra
{
my $this = shift;
length($this->{recvbuf});
}
# -----------------------------------------------------------------------------
# $str = $pkg->to_string($req).
# HTTPとして流せるテキストに変換.
# 要求行/ステータス行も含めた文字列を返します.
#
sub to_string
{
my $pkg = shift;
my $res = shift;
if( !ref($res) )
{
$res = {
Code => $res,
};
}
my $type = $res->{Type} || ($res->{Method} ? 'request' : 'response');
my $hdr = $res->{Header} || {};
my $cref = defined($res->{Content}) && \$res->{Content};
my $status_line;
if( $type eq 'response' )
{
my $code = $res->{Code} || 500;
my $proto = $res->{Protocol} || 'HTTP/1.0';
my $message = $res->{Message};
$message ||= $HTTP_STATUS_MESSAGE{$code} || "No message";
$status_line = "$proto $code $message\r\n";
if( !$cref && !$res->{Header}{Location} )
{
$cref = \"$code $message";
}
if( !defined($hdr->{'Content-Length'}) && $cref )
{
$hdr = {%$hdr}; # sharrow-copy.
$hdr->{'Content-Length'} = length($$cref);
}
}else
{
# request.
my $method = $res->{Method} || 'GET';
my $path = $res->{Path} || '/';
my $proto = $res->{Protocol} || 'HTTP/1.0';
$status_line = "$method $path $proto\r\n";
}
my $str = '';
$str .= $status_line;
foreach my $key (sort keys %$hdr)
{
$str .= "$key: $hdr->{$key}\r\n";
}
$str .= "\r\n";
if( $cref )
{
$str .= $$cref;
}
$str;
}
# -----------------------------------------------------------------------------
# $req = $pkg->from_lwp($lwp_http_request).
# $res = $pkg->from_lwp($lwp_http_response).
# LWPのHTTP::Request/HTTP::ResponseからTools::HTTPParser形式の
# オブジェクトを生成.
#
sub from_lwp
{
my $pkg = shift;
my $htreq = shift;
my $proto = $htreq->protocol;
if( my $ver = !$proto && $htreq->header('x-http-version') )
{
$proto = "HTTP/$ver";
}
my $type = $htreq->isa('HTTP::Request') ? 'request' : 'response';
my $obj = {
StreamState => 'parsed',
Type => $type,
Protocol => $proto,
Header => {
map{ $_ => scalar($htreq->header($_)) } $htreq->headers->header_field_names
},
Content => $htreq->content,
#_htreq => $htreq,
};
if( $type eq 'request' )
{
$obj->{Method} = $htreq->method;
$obj->{Path} = $htreq->uri->as_string;
}else
{
$obj->{Code} = $htreq->code;
$obj->{Message} = $htreq->message;
}
$obj;
}
# -----------------------------------------------------------------------------
# $bool = $pkg->extract_forwarded_for($req, \@allows).
# ReverseProxyによって生成されるX-Forwarded-Forヘッダを
# $req->{RemoteAddr}/$req->{Header}{Host} に展開.
# @allows: 展開を許可するIPアドレスの一覧(X-Forwarded-Forの逆順).
# 書き換えると真の値を, 書き換えなかった時はundefの値を返す.
# 途中までしか一致しなかった時は RemoteAddr="-$addr-" で書き換える.
#
sub extract_forwarded_for
{
my $pkg = shift;
my $req = shift;
my $allows = shift;
$DEBUG and $pkg->_debug(__PACKAGE__."#_extract_forwarded_for.");
$DEBUG and $pkg->_debug("- allow-chain has ".@$allows.(@$allows==1?" server":" servers"));
$DEBUG and map{ $pkg->_debug("- allow[$_] = $allows->[$_]") } 0..$#$allows;
my $hdr = $req->{Header};
if( !$req->{RemoteAddr} )
{
$DEBUG and $pkg->_debug("- no RemoteAddr field on request.");
return undef;
}
if( !$hdr->{'X-Forwarded-For'} )
{
$DEBUG and $pkg->_debug("- no X-Forwarded-For header.");
return undef;
}
if( !defined($hdr->{'X-Forwarded-Host'}) )
{
$DEBUG and $pkg->_debug("- no X-Forwarded-Host");
return undef;
}
if( !defined($hdr->{'X-Forwarded-Server'}) )
{
$DEBUG and $pkg->_debug("- no X-Forwarded-Server");
return undef;
}
my @copy_keys = qw(Host X-Forwarded-For X-Forwarded-Host X-Forwarded-Server);
my $orig = {
map{ exists($hdr->{$_}) ? ($_ => $hdr->{$_}) : () } @copy_keys
};
exists($req->{RemoteAddr}) and $orig->{RemoteAddr} = $req->{RemoteAddr};
$DEBUG and map{ $pkg->_debug("- + $_: ".(defined($orig->{$_}) ? $orig->{$_} : exists($orig->{$_}) ? "{undef}" : "{none}")) } sort keys %$orig;
# https://192.168.0.3/irc/
# ==> http://localhost:8668/irc/
# X-Forwarded-Server: fwd.example.com
# X-Forwarded-Host: 192.168.0.3
# X-Forwarded-For: 192.168.0.10
# https://192.168.0.3/irc/
# ==> https://fwd.example.com/irc2/ (fwd.example.com=10.0.0.4)
# ==> http://localhost:8668/irc/
# X-Forwarded-Server: fwd.example.com, fwd.example.com
# X-Forwarded-Host: 192.168.0.3, fwd.example.com
# X-Forwarded-For: 192.168.0.10, 10.0.0.4
my $cur = {%$orig};
my $is_success = 1;
while( @$allows )
{
my $allow = shift @$allows;
$DEBUG and $pkg->_debug("- next allow: $allow");
if( $cur->{RemoteAddr} ne $allow )
{
$DEBUG and $pkg->_debug("- next forwarder $cur->{RemoteAddr} does not match with next allow $allow");
$pkg->_debug(__PACKAGE__.", extract-forwarded-for is cancelled (not allowed, $cur->{RemoteAddr} for $allow)");
$is_success = 0;
last;
}
my $next = $cur;
# 転送前情報を末尾から取り出し.
my @fwd_keys = qw(X-Forwarded-For X-Forwarded-Host X-Forwarded-Server);
my @vals = map{
($next->{$_} =~ s/(?:^|\s*,)\s*(\S+)\s*\z//) ? $1 : undef;
} @fwd_keys;
if( grep{ !defined($_) } @vals )
{
my ($idx) = grep{ !defined($vals[$_]) } 0..$#vals;
my $key = $fwd_keys[$idx];
$DEBUG and $pkg->_debug("- invalid next $key [$next->{$key}]");
$pkg->_debug(__PACKAGE__.", extract-forwarded-for is cancelled (short $key)");
$is_success = 0;
last;
}
my ($addr, $host, $svr) = @vals;
$next->{RemoteAddr} = $addr;
$next->{Host} = $host;
$DEBUG and $pkg->_debug("- extract: RemoteAddr=$addr, Host=$host");
$cur = $next;
}
# $req に結果を反映.
# 変更前のデータもついでに保持.
$req->{_extract_orig} = $orig;
$req->{RemoteAddr} = delete $cur->{RemoteAddr};
%$hdr = ( %$hdr, %$cur );
if( !$is_success )
{
$req->{RemoteAddr} = "-$req->{RemoteAddr}-";
}
$DEBUG and $pkg->_debug("- extract: RemoteAddr=$req->{RemoteAddr}, Host=$req->{Header}{Host}");
1;
}
# -----------------------------------------------------------------------------
# $txt = $pkg->escapeHTML($html).
#
sub escapeHTML
{
my $pkg = shift;
my $html = shift;
$html =~ s/&/&/g;
$html =~ s/</</g;
$html =~ s/>/>/g;
$html =~ s/"/"/g;
$html =~ s/'/'/g;
$html;
}
# -----------------------------------------------------------------------------
# $pkg->_debug($msg).
# デバッグメッセージ送信用.
#
sub _debug
{
my $this = shift;
my $msg = shift;
RunLoop->shared_loop->notify_msg($msg);
}
# -----------------------------------------------------------------------------
# End of Module.
# -----------------------------------------------------------------------------
__END__
=encoding utf8
=for stopwords
YAMASHINA
Hio
ACKNOWLEDGEMENTS
AnnoCPAN
CPAN
RT
=head1 NAME
Tools::HTTPParser - HTTP/1.0 parser for tiarra-modules.
=head1 VERSION
Version 0.01
=head1 SYNOPSIS
use Tools::HTTPParser;
use Module::Use qw(Tools::HTTPParser);
my $parser = Tools::HTTPParser->new();
my $status = eval{ $parser->add($packet); }
$@ and die ...;
$status==0 or return; # in progress.
my $res = $parser->object();
my $req = $parser->object();
=head1 DESCRIPTION
HTTP::Parser と同様の HTTP パーサ.
tiarra モジュール Tools::HTTPClient と互換の動作.
結果の形式は以下の2種類.
$request = {
StreamState => 'parsed', # greeting/header/body/parsed.
Type => 'request',
Protocol => 'HTTP/1.0',
Path => '/path/to?request',
Method => 'GET',
Header => {},
Content => undef,
};
$response = {
StreamState => 'parsed', # greeting/header/body/parsed.
Type => 'request',
Protocol => 'HTTP/1.0',
Code => 200,
Message => 'OK',
Header => {},
Content => undef,
};
=head1 AUTHOR
YAMASHINA Hio, C<< <hio at cpan.org> >>
=head1 COPYRIGHT & LICENSE
Copyright 2008 YAMASHINA Hio, all rights reserved.
This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
=cut
|