blib/lib/Net/WinRM.pm untested

filter: Statementstmt 0.0% 0 / 253 Branchbran 0.0% 0 / 102 Conditioncond 0.0% 0 / 47 MC/DCmcdc 0.0% 0 / 29 Subroutinesub 0.0% 0 / 39 Podpod 0.0% 0 / 28 totaltotal 0.0% 0 / 498 CC 52 SCAR 33.1
CC
52
Cov
0%
instances_add
90.0
enumerator
56.0
parse_http_response
42.0
CRAP 27.4
1 package Net::WinRM;
2 our $VERSION = '1.00';
3
4
5 # Tied hash, represents a single WinRM request. In order to be sent,
6 # needs to be converted into XML, and using in http POST request
7 package Net::WinRM::Request;
8
9 use strict;
10 use warnings;
11 use Data::UUID;
12 use XML::Simple;
13 use HTTP::Request;
14 use Encode;
15
16 # new dummy. all common request fields are initialzed here
17 sub new
18 {
19 my $self = bless {
20 'xmlns:s' => 'http://www.w3.org/2003/05/soap-envelope',
21 'xmlns:wsa' => 'http://schemas.xmlsoap.org/ws/2004/08/addressing',
22 'xmlns:wsman' => 'http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd',
23 's:Header' => { 'wsa:ReplyTo' => { 'wsa:Address' => {
24 content => 'http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous'
25 }}},
26 's:Body' => {},
27 }, shift;
28
29 $self-> uuid;
30
31 my %p = @_;
32 while ( my ($k, $v) = each %p) {
33 $self-> $k(( ref($v) and ref($v) eq 'ARRAY') ? @$v : $v);
34 }
35
36 return $self;
37 }
38
39 # external convertors
40 sub to_xml
41 {
42 '<?xml version="1.0" encoding="UTF-8"?>' .
43 "\n" .
44 XMLout( { 's:Envelope' => $_[0] }, KeepRoot => 1, KeyAttr => [])
45 }
46
47 sub xml { new(@_)-> to_xml }
48
49 sub to_http_request
50 {
51 my $self = shift;
52
53 my $content = $self-> to_xml;
54
55 Encode::_utf8_off($content);
56
57 my $req = HTTP::Request-> new( POST => $self->{'s:Header'}->{'wsa:To'}->{'content'});
58 $req-> header('Content-Type' => 'application/soap+xml;charset=UTF-8');
59 $req-> header('Content-Length' => length $content);
60 $req-> content( $content);
61
62 return $req;
63 }
64
65 sub uuid
66 {
67 my ( $self) = shift;
68
69 my $u = Data::UUID-> new;
70 my $ux = $u-> create;
71 $ux = $u-> to_string( $ux);
72
73 $self-> {'s:Header'}-> {'wsa:MessageID'} = {
74 's:mustUnderstand' => 'true',
75 'content' => "uuid:$ux"
76 };
77 }
78
79 # lower-level modificators
80 sub action
81 {
82 my ( $self, $action) = @_;
83
84 $self-> {'s:Header'}-> {'wsa:Action'} = {
85 's:mustUnderstand' => 'true',
86 'content' => "http://schemas.xmlsoap.org/ws/2004/09/$action"
87 };
88 }
89
90 sub to
91 {
92 my ( $self, $to) = @_;
93 $self-> {'s:Header'}-> {'wsa:To'} = {
94 's:mustUnderstand' => 'true',
95 'content' => "http://$to/wsman",
96 };
97 }
98
99 sub class_namespace
100 {
101 my ( $self, $class, $namespace) = @_;
102 $namespace = 'root/cimv2' unless defined $namespace;
103 $self-> {'s:Header'}-> {'wsman:ResourceURI'} = {
104 's:mustUnderstand' => 'true',
105 'content' => "http://schemas.microsoft.com/wbem/wsman/1/wmi/$namespace/$class",
106 };
107 }
108
109 # upper-level modificators
110 sub get
111 {
112 my ( $self, $selector) = @_;
113 $self-> action( 'transfer/Get');
114 $self-> {'s:Header'}-> {'wsman:SelectorSet'} = {
115 'wsman:Selector' => [ map {{
116 Name => $_,
117 content => $selector-> {$_},
118 }} keys %$selector ],
119 };
120 }
121
122 sub enumerate
123 {
124 my ( $self, $keysonly, $wql, $max_elements ) = @_;
125
126 $max_elements = 20 unless defined $max_elements;
127
128 $self-> action('enumeration/Enumerate');
129 $self->{'xmlns:wsen'} = 'http://schemas.xmlsoap.org/ws/2004/09/enumeration';
130 $self->{'s:Body'} = {
131 'wsen:Enumerate' => {
132 'wsman:EnumerationMode' => {
133 content => $keysonly ?
134 'EnumerateEPR' :
135 'EnumerateObjectAndEPR'
136 },
137 ( $max_elements ? (
138 'wsman:OptimizeEnumeration' => {},
139 'wsman:MaxElements' => { content => $max_elements },
140 ) : ())
141 }
142 };
143
144 $self->{'s:Body'}->{'wsen:Enumerate'}->{'wsman:Filter'} = {
145 Dialect => 'http://schemas.microsoft.com/wbem/wsman/1/WQL',
146 content => $wql,
147 } if defined $wql;
148 }
149
150 sub pull
151 {
152 my ( $self, $ec) = @_;
153 $self-> action( 'enumeration/Pull');
154 $self-> {'xmlns:wsen'} = 'http://schemas.xmlsoap.org/ws/2004/09/enumeration';
155 $self-> {'s:Body'} = {'wsen:Pull' => { 'wsen:EnumerationContext' => { content => $ec }}};
156 }
157
158 # Deciphers XML that is a response from a WinRM server, and stores the parsed
159 # data as a hash. Since WinRM may not return XML on occasions like
160 # authentication error, the class also accepts empty text to be initialized from
161 package Net::WinRM::Response;
162
163 use XML::Simple;
164
165 sub new
166 {
167 if ( $_[1] =~ /^</) {
168 # XMLin is stupid and treats anything not xmlish as a filename
169 my $s = {};
170 eval { $s = XMLin( $_[1], KeepRoot => 1); };
171
172 return bless $s->{'s:Envelope'}, $_[0] if
173 UNIVERSAL::isa($s,'HASH') and
174 exists $s->{'s:Envelope'};
175 }
176
177 # empty object
178 return bless {}, $_[0];
179 }
180
181 # traverses a path in the hash
182 sub fetch
183 {
184 my ( $self, $path, $subtree) = @_;
185
186 $subtree = $self unless defined $subtree;
187
188 my @p = split('/', $path);
189
190 while ( $subtree and UNIVERSAL::isa($subtree,'HASH')) {
191 $path = shift @p;
192 return unless exists $subtree-> {$path};
193 return $subtree-> {$path} unless @p;
194 $subtree = $subtree-> {$path};
195 }
196
197 return;
198 }
199
200 # returns WinRM error, if found
201 sub error
202 {
203 my ( $self) = @_;
204
205 my $r;
206
207 $r = $self-> fetch('s:Body/s:Fault');
208 return unless defined $r;
209
210 return $r-> {'XMLFault'} if defined $r->{'XMLFault'};
211
212 my $err = $self-> fetch(
213 's:Detail/f:WSManFault/f:Message/f:ProviderFault/f:WSManFault/f:Message',
214 $r
215 );
216 return $err if defined $err;
217
218 return $self-> fetch( 's:Reason/s:Text/content', $r );
219 }
220
221 sub empty { 0 == scalar keys %{$_[0]} }
222
223 sub deserialize_property
224 {
225 my ( $self, $v) = @_;
226 if (
227 ref($v) and
228 ref($v) eq 'HASH'
229 ) {
230 if (
231 1 == keys(%$v) and
232 $v->{'xsi:nil'}
233 ) {
234 $v = undef;
235 } elsif ( $v-> {'cim:Datetime'}) {
236 $v = $v-> {'cim:Datetime'};
237 } elsif ( $v-> {'a:ReferenceParameters'}) {
238 $v = $self-> fetch(
239 'a:ReferenceParameters/w:SelectorSet/w:Selector/content',
240 $v
241 );
242 }
243 }
244 return $v;
245 }
246
247 # parses get/enumerate record and returns the deciphered hash
248 sub parse_record
249 {
250 my ( $self, $h) = @_;
251
252 my %resp;
253 while ( my ( $k, $v) = each %$h) {
254 next unless $k =~ s/^p://;
255 $resp{$k} = $self-> deserialize_property($v);
256 }
257 return \%resp;
258 }
259
260 # parse XmlFragment returned by WQL queries
261 sub parse_fragment
262 {
263 my ( $self, $h) = @_;
264
265 my %resp;
266 while ( my ( $k, $v) = each %$h) {
267 next if $k =~ /^\w+:/;
268 $resp{$k} = $self-> deserialize_property($v);
269 }
270 return \%resp;
271 }
272
273 # parses enumeration response, gets either sub-tree or an error
274 sub get_enumeration_body
275 {
276 my $self = $_[0];
277 return
278 $self-> fetch('s:Body/n:EnumerateResponse') ||
279 $self-> fetch('s:Body/n:PullResponse') ||
280 "bad response: no Body/<Pull|Enumerate> response";
281 }
282
283 # collection of winrm actions - get, enumerate.
284 package Net::WinRM;
285
286 use Carp;
287 use LWP::ConnCache;
288 use IO::Lambda qw(:all);
289 use IO::Lambda::HTTP qw(http_request);
290
291 sub new
292 {
293 my ( $class, %opt) = @_;
294
295 for ( qw(host class)) {
296 croak "Net::WinRM::Protocol::new: option '$_' must be present"
297 unless exists $opt{$_};
298 }
299
300 my $self = bless {
301 conn_cache => ($opt{conn_cache} || LWP::ConnCache-> new()),
302 %opt
303 }, $class;
304
305 return $self;
306 }
307
308 # given an action, creates a http request and options to http_request lambda
309 sub create_http_request
310 {
311 my $self = shift;
312 my $req = Net::WinRM::Request-> new(
313 to => $self-> {host},
314 class_namespace => [ $self-> {class}, $self-> {namespace} ],
315 @_
316 )-> to_http_request;
317
318 $req-> protocol('HTTP/1.1');
319 $req-> header('Host' => $self-> {host});
320 $req-> header('Connection' => 'Keep-Alive');
321 $req-> header('Authorization' => $self-> {authorization})
322 if exists $self-> {authorization};
323
324 my %ret = (
325 max_redirect => 0,
326 conn_cache => $self-> {conn_cache},
327 timeout => $self-> {timeout},
328 deadline => $self-> {deadline},
329 ntlm_version => $self-> {ntlm_version} || 1,
330 );
331
332 if ( defined $self-> {username}) {
333 my $def_auth;
334 if ( $self-> {username} =~ m{^(.*?)/(.*)$}) {
335 $ret{domain} = $1;
336 $ret{username} = $2;
337 $def_auth = 'Negotiate';
338 } else {
339 $ret{username} = $self-> {username};
340 $def_auth = 'Basic';
341 }
342 $ret{password} = $self-> {password};
343 $ret{preferred_auth} = $self-> {preferred_auth} || $def_auth;
344 }
345
346 return $req, %ret;
347 }
348
349 # deals with http response from winrm server, but doesn't parse the winrm content
350 sub parse_http_response
351 {
352 my ( $self, $r) = @_;
353
354 return "communication error: $r" unless ref($r);
355
356 my $res = Net::WinRM::Response-> new( $r-> content);
357 my $code = $r-> code;
358
359 if ( $code !~ /^[25]/) {
360 # authentications, redirects etc
361 return defined($res-> error) ?
362 $res-> error :
363 "http error $code " . $r-> message
364 ;
365 } elsif ( $code !~ /^2/) {
366 # winrm 5XX errors
367 return defined($res-> error) ?
368 $res-> error :
369 'unknown winrm error'
370 ;
371 }
372
373 return $res;
374 }
375
376 # Creates a lambda that performs WinRM get request. Lambda returns either the instance hash,
377 # or error string
378 sub get
379 {
380 my ($class, %opt) = @_;
381 for ( qw(selector)) {
382 croak "Net::WinRM::Protocol::get: option '$_' must be present"
383 unless exists $opt{$_};
384 }
385 my $self = $class-> new( %opt);
386
387 lambda {
388 context $self-> create_http_request(
389 get => $self-> {selector}
390 );
391 http_request {
392 my $r = $self-> parse_http_response(shift);
393 return $r unless ref($r);
394
395 my $item = $r-> fetch("s:Body/p:" . $self->{class});
396 return "bad response: no Body/Get response" unless $item;
397
398 return $r-> parse_record( $item);
399 }}
400 }
401
402 sub instances_add
403 {
404 my ( $self, $r) = @_;
405
406 my $t = $r-> get_enumeration_body;
407 return $t unless ref($t);
408
409 my $items =
410 $r-> fetch('n:Items/a:EndpointReference', $t) ||
411 $r-> fetch('w:Items/a:EndpointReference', $t);
412 return unless $items;
413
414 $items = [ $items ] if ref($items) eq 'HASH';
415 for ( @$items) {
416 my $param = $r-> fetch( 'a:ReferenceParameters', $_ );
417 next unless $param;
418
419 my $item = $r-> fetch( 'w:SelectorSet/w:Selector', $param ) || [];
420 $item = [$item] unless ref($item) eq 'ARRAY';
421
422 my $class = $r-> fetch( 'w:ResourceURI', $param );
423 return 'pull: bad response - no ResourceURI'
424 unless defined $class;
425 return "pull: bad class($class)" unless $class =~ /\/(\w+)$/;
426 $class = $1;
427
428 my %keyset = ( _class => $class );
429 for my $x (@$item) {
430 next unless defined $x->{Name} and defined $x->{content};
431 $keyset{ $x->{Name} } = $x->{content};
432 }
433
434 push @{ $self->{enumeration} }, \%keyset;
435 }
436
437 return undef;
438 }
439
440 sub enumerate_add
441 {
442 my ( $self, $r) = @_;
443
444 my $t = $r-> get_enumeration_body;
445 return $t unless ref($t);
446
447 my $items =
448 $r-> fetch('n:Items/w:Item', $t) ||
449 $r-> fetch('w:Items/w:Item', $t);
450 return undef unless $items;
451
452 $items = [ $items ] if ref($items) eq 'HASH';
453
454 for my $item ( @$items) {
455 my @class = grep { /^p:/ } keys %$item;
456 return "pull: ambiguous class set: @class" if 1 < @class;
457
458 if (@class) {
459 $item = $r-> parse_record( $item->{ $class[0] } );
460 $class[0] =~ s/^p://;
461 $item->{_class} = $class[0];
462 } else {
463 $item = $item->{'w:XmlFragment'}
464 or return "pull: XmlFragment not present";
465 $item = $r-> parse_fragment($item);
466 }
467
468 push @{ $self->{enumeration} }, $item;
469 }
470
471 return undef;
472 }
473
474 # Creates a lambda that performs WinRM ENUMERATE request. Lambda returns either the array of instance hashes,
475 # or error string
476 sub enumerator
477 {
478 my ( $class, $instances, @opt) = @_;
479 my $self = $class-> new(@opt);
480
481 lambda {
482 $self->{enumeration} = [];
483 my ( $req, @options ) = $self-> create_http_request(
484 enumerate => [ $instances, $self->{wql}, $self->{max_elements} ]
485 );
486
487 context $req, @options;
488 http_request {
489 $self-> {authorization} = $req-> header('Authorization');
490
491 my $r = $self-> parse_http_response(shift);
492 return $r unless ref($r);
493
494 # negotiate enumeration, get the first enum uuid token
495 my $t = $r-> get_enumeration_body;
496 return $t unless ref $t;
497 my $ec = $t-> {'n:EnumerationContext'};
498 my $end =
499 $t-> {'w:EndOfSequence'} ||
500 $t-> {'n:EndOfSequence'};
501 return 'bad response - no EnumerationContext'
502 if not($end) and not($ec);
503
504 # have any instances to add?
505 my $err = $instances ?
506 $self-> instances_add( $r) :
507 $self-> enumerate_add( $r);
508 return $err if defined $err;
509
510 # is it all already?
511 return $self-> {enumeration} if $end;
512
513 context $self-> create_http_request( pull => $ec );
514 again;
515 }}
516 }
517
518 sub instances { shift-> enumerator( 1, @_ ) }
519 sub enumerate { shift-> enumerator( 0, @_ ) }
520
521 1;
522
523 __DATA__