Analysis/Listener/HTTPPipelining.pm untested

filter: Statementstmt 0.0% 0 / 172 Branchbran 0.0% 0 / 32 Conditioncond 0.0% 0 / 8 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 258 CC 17 SCAR 23.3
CC
17
Cov
0%
_unchunk_response
30.0
http_transaction
20.0
_unpipeline_data
20.0
CRAP 10.2
1 package Net::Analysis::Listener::HTTPPipelining;
2 # $Id: HTTP.pm 140 2005-10-21 16:31:29Z abworrall $
3  
4 # {{{ Boilerplate
5  
6 use 5.008000;
7 our $VERSION = '0.02';
8 use strict;
9 use warnings;
10  
11 use Carp qw(carp croak confess);
12  
13 use Params::Validate qw(:all);
14  
15 use base qw(Net::Analysis::Listener::Base);
16  
17 # }}}
18  
19 use Net::Analysis::Packet qw(:pktslots :func);
20 use Net::Analysis::TCPMonologue;
21  
22 use HTTP::Response;
23 use HTTP::Request;
24  
25 #### Callbacks
26 #
27 # {{{ validate_configuration
28  
29 sub validate_configuration {
30 my $self = shift;
31  
32 my %h = validate (@_, { v => {type => SCALAR,
33 default => 0} });
34  
35 return \%h;
36 }
37  
38 # }}}
39  
40 # {{{ setup
41  
42 # A chance to setup stuff for our listener
43 sub setup {
44 my ($self) = shift;
45  
46 $self->{sesh} = {}; # TCP sessions
47 }
48  
49 # }}}
50 # {{{ teardown
51  
52 sub teardown {
53 my ($self) = shift;
54 }
55  
56 # }}}
57  
58 # {{{ tcp_session_start
59  
60 sub tcp_session_start {
61 my ($self, $args) = @_;
62 my $pkt = $args->{pkt}; # Might well be undef
63 my $k = $args->{socketpair_key};
64  
65 if ($self->{v} & 0x04) {
66 $self->trace (" ==== tcp session start [$pkt->{from} -> $pkt->{to}]");
67 }
68 }
69  
70 # }}}
71 # {{{ tcp_session_end
72  
73 sub tcp_session_end {
74 my ($self, $args) = @_;
75 my $pkt = $args->{pkt}; # Might well be undef
76 my $k = $args->{socketpair_key};
77  
78 $self->trace(" ==== tcp session end [$k]") if ($self->{v} & 0x04);
79  
80 my $sesh = $self->_remove_sesh ($k);
81 return if (! defined $sesh);
82  
83 $self->_unpipeline_data($sesh);
84 }
85  
86 # }}}
87 # {{{ tcp_monologue
88  
89 # In a pipelined request, the concept of orderly back-and-forth
90 # monologues breaks down. Conceptually, all the requests are
91 # glued together into one big monologue, and then all the responses
92 # are returned in another big monologue.
93 # These jumbo monlogues may be transmitted simultaneusly (that is
94 # kinda the point of pipelining ;), so from the perspective of our
95 # pcap files, the divisions between monologues are arbitrary.
96 # So, we assign no meaning to the monologues that arrive; all we do
97 # is steal the packets from them.
98 # All the hard work - breaking apart the jumbo monologues into separate
99 # requests and responses, pairing them up, and generating synthetic
100 # monologues, is done in tcp_session_end.
101  
102 sub tcp_monologue {
103 my ($self, $args) = @_;
104 my $k = $args->{socketpair_key};
105 my $mono = $args->{monologue};
106 my $sesh = $self->_get_sesh ($k);
107  
108 # Decide which jumbo monologue to place these pkts in
109 my $socketpair_from = $mono->first_packet()->[PKT_SLOT_FROM];
110  
111 my $pkts = $sesh->{$socketpair_from} ||= [];
112 push (@$pkts, @{ $mono->_data_packets }); # POTENTIAL MEM LEAK !! TAKE CARE
113 }
114  
115 # }}}
116 # {{{ http_transaction
117  
118 # Listen to our own event and print very basic report, if asked
119 sub http_transaction {
120 my ($self, $args) = @_;
121 return if (! $self->{v});
122  
123 my $req = $args->{req};
124 my $uri = (defined $req) ? $req->uri() : "(no uri)";
125 my $method = (defined $req) ? $req->method() : "(no method)";
126 my $t = $args->{t_elapsed} || -1.0;
127 printf "%8.4fs : $method %s\n", $t, $uri;
128 }
129  
130 # }}}
131  
132 # {{{ as_string
133  
134 sub as_string {
135 my ($self) = @_;
136 my $s = '';
137  
138 $s .= "[".ref($self)."]";
139  
140 return $s;
141 }
142  
143 # }}}
144  
145 #### Support funcs
146 #
147 # {{{ _trace
148  
149 # This may become more clever ...
150  
151 our $TRACE=0;
152  
153 sub _trace {
154 my ($self) = shift;
155  
156 return if (! $TRACE);
157  
158 foreach (@_) {
159 my $l = $_; # Skip 'Modification of a read-only value' errors
160 chomp ($l);
161 print "$l\n";
162 }
163 }
164  
165 # }}}
166 # {{{ _{get|remove}_sesh
167  
168 sub _get_sesh {
169 my ($self, $sesh_key) = @_;
170  
171 if (! exists $self->{sesh}{$sesh_key}) {
172 $self->{sesh}{$sesh_key} = {};
173 }
174  
175 return $self->{sesh}{$sesh_key};
176 }
177  
178 sub _remove_sesh {
179 my ($self, $sesh_key) = @_;
180  
181 return delete ($self->{sesh}{$sesh_key});
182 }
183  
184 # }}}
185 # {{{ _printable
186  
187 sub _printable {
188 my $raw = shift;
189 $raw =~ s {([^\x20-\x7e])} {.}g;
190 return $raw;
191 }
192  
193 # }}}
194 # {{{ _unchunk_response
195  
196 sub _unchunk_response {
197 my ($resp) = @_;
198  
199 my $transfer_encoding = $resp->header('transfer-encoding');
200  
201 return if (!$transfer_encoding);
202  
203 # http://www.jmarshall.com/easy/http/#http1.1c2
204 if ($transfer_encoding eq 'chunked') {
205 my $chunked_data = $resp->content();
206 my $unchunked_data = '';
207  
208 my ($chunk_size_hex, $chunk_size, $chunk);
209 while ($chunked_data) {
210 # Read chunk size. Discard chunking comments.
211 ($chunk_size_hex, $chunked_data) = ($chunked_data =~ /^([0-9a-fA-F]+)(?:;.*)?\r\n(.*)/s);
212 last if (!defined $chunk_size_hex);
213 $chunk_size = oct("0x$chunk_size_hex");
214  
215 last if ($chunk_size == 0); # Sod trailing headers!
216  
217 # allow for \r\n trailing the chunk
218 $chunk = substr ($chunked_data, 0, $chunk_size+2, '');
219 substr ($chunk, -2, 2, '');
220  
221 $unchunked_data .= $chunk;
222 }
223  
224 $resp->content($unchunked_data);
225 }
226 }
227  
228 # }}}
229  
230 # {{{ _unpipeline_data
231  
232 sub _unpipeline_data {
233 my $self = shift;
234 my ($sesh) = @_;
235  
236 my @jumbo_monos;
237 foreach my $k (keys %$sesh) {
238 my $mono = Net::Analysis::TCPMonologue->new();
239 foreach my $pkt (@{ $sesh->{$k} }) {
240 $mono->add_packet ($pkt);
241 }
242 push (@jumbo_monos, $mono);
243 }
244  
245 my ($req_mono, $resp_mono);
246 if ($jumbo_monos[0]->data =~ m!^(get|post|head)\s+([^ ]+)(HTTP/\d.\d)?!i) {
247 ($req_mono, $resp_mono) = @jumbo_monos;
248 } elsif ($jumbo_monos[1]->data =~ m!^(get|post|head)\s+([^ ]+)(HTTP/\d.\d)?!i) {
249 ($resp_mono, $req_mono) = @jumbo_monos;
250 } else {
251 carp ("This TCP session doesn't look very HTTPish");
252 }
253  
254 my (@reqs) = $self->_unpipeline_http_requests ($req_mono);
255 my (@resps) = $self->_unpipeline_http_responses ($resp_mono);
256 if (@reqs != @resps) {
257 carp ("found ".scalar(@reqs)." reqs but ".scalar(@resps).
258 " resps in pipelined HTTP");
259 return;
260 }
261  
262 while (@reqs) {
263 my ($req_data, $req_mono) = @{ shift (@reqs) };
264 my ($resp_data, $resp_mono) = @{ shift (@resps) };
265  
266 my ($http_req) = HTTP::Request->parse($req_data);
267 my ($http_resp) = HTTP::Response->parse($resp_data);
268 _unchunk_response ($http_resp); # Should port this to HTTP::Message
269  
270 my $host = $http_req->header('host') || '(nohost)';
271 my $uri = $http_req->uri() || '/noURI';
272 $self->_trace (">>>> $host$uri <<\n");
273  
274 $self->_trace (" << ".$http_resp->code().", ".
275 length($http_resp->content())." bytes");
276  
277 my $args = {socketpair_key => $req_mono->socketpair_key(),
278 req => $http_req,
279 req_mono => $req_mono,
280 resp => $http_resp,
281 resp_mono => $resp_mono,
282 t_end => $resp_mono->t_end()->clone()};
283  
284 $args->{t_start} = $req_mono->t_start()->clone();
285 $args->{t_elapsed} = $args->{t_end} - $args->{t_start};
286  
287 $self->emit (name => 'http_transaction', args => $args);
288 }
289 }
290  
291 # }}}
292 # {{{ _unpipeline_http_requests
293  
294 sub _unpipeline_http_requests {
295 my $self = shift;
296 my ($mono) = @_;
297  
298 # rfc 2612/8.1.2.2 : "Clients SHOULD NOT pipeline requests using
299 # non-idempotent methods"
300 # rfc 2612/9.1.2 : (GET, HEAD, PUT, DELETE) are idempotent.
301 # But, PUT may contain a data block (like POST), so we need to take care
302  
303 my @ret;
304 my ($n_start,$n_end) = (0,0);
305 my @blocks = (map {$_."\r\n\r\n"} split ("\r\n\r\n", $mono->data()));
306 while (@blocks) {
307 $_ = shift(@blocks);
308  
309 # PUT and POST requests have data after the request/header block;
310 # snarf it if needed
311 $_ .= shift(@blocks) if (/^(put|post) /i);
312  
313 $n_end = $n_start + length($_) - 1;
314  
315 #print " >> [$n_start, $n_end] ".(split("\n",$_))[0]."\n";
316  
317 # Now build a mono from the packets that made up this block
318 my $sub_mono = Net::Analysis::TCPMonologue->new();
319 foreach my $pkt (@{ $mono->which_pkts($n_start,$n_end) }) {
320 $sub_mono->add_packet ($pkt);
321 }
322  
323 push (@ret, [$_, $sub_mono]);
324  
325 $n_start = $n_end+1;
326 }
327  
328 #print ">>>>[".($n_end+1)." / ".$mono->length()." ]>>>>\n";
329 return @ret;
330 }
331  
332 # }}}
333 # {{{ _unpipeline_http_responses
334  
335 # This is knottier than it looks.
336  
337 # I just split on what looks like the start of a response. But if a response
338 # just so happened to contain a string that matched "HTTP/1.1 200 OK", this
339 # breaks.
340 # Ideally, I'd parse the Content-Length header instead, and only read the
341 # right amount of data. But, a HEAD request generates a response with no
342 # body data, but a content-length that indicates what the response *would*
343 # have been (for a GET).
344 # So: I need to know the request method in order to know whether to trust
345 # the Content-Length header, which is altogether too much irritation for now.
346  
347 sub _unpipeline_http_responses {
348 my $self = shift;
349 my ($mono) = @_;
350 my (@ret);
351  
352 my @bits = split (qr{(HTTP/\d\.\d \d\d\d)}, $mono->data());
353 shift (@bits); # Grr, empty field to the left of first "HTTP/1.1..."
354  
355 my ($n_start,$n_end) = (0,0);
356 while (@bits) {
357 $_ = shift (@bits);
358 $_ .= shift (@bits);
359  
360 $n_end = $n_start + length($_) - 1;
361  
362 # print " << [$n_start, $n_end] ".(split("\n",$_))[0]."\n";
363  
364 # Now build a mono from the packets that made up this block
365 my $sub_mono = Net::Analysis::TCPMonologue->new();
366 foreach my $pkt (@{ $mono->which_pkts($n_start,$n_end) }) {
367 $sub_mono->add_packet ($pkt);
368 }
369  
370 push (@ret, [$_, $sub_mono]);
371  
372 $n_start = $n_end+1;
373 }
374  
375 #print "<<<<[".($n_end+1)." / ".$mono->length()." ]<<<<\n";
376 return @ret;
377 }
378  
379 # }}}
380  
381 1;
382 __END__