/
XML.pm
2140 lines (1746 loc) · 64.6 KB
/
XML.pm
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
###############################################################################
#
# This file copyright (c) 2001-2014 Randy J. Ray, all rights reserved
#
# Copying and distribution are permitted under the terms of the Artistic
# License 2.0 (http://www.opensource.org/licenses/artistic-license-2.0.php) or
# the GNU LGPL (http://www.opensource.org/licenses/lgpl-2.1.php).
#
###############################################################################
#
# Description: This module provides the core XML <-> RPC conversion and
# structural management.
#
# Functions: This module contains many, many subclasses. Better to
# examine them individually.
#
# Libraries: RPC::XML::base64 uses MIME::Base64
# DateTime::Format::ISO8601 is used if available
#
# Global Consts: $VERSION
#
###############################################################################
package RPC::XML;
use 5.008008;
use strict;
use warnings;
use vars qw(@EXPORT_OK %EXPORT_TAGS $VERSION $ERROR
%XMLMAP $XMLRE $ENCODING $FORCE_STRING_ENCODING $ALLOW_NIL
$DATETIME_REGEXP $DATETIME_ISO8601_AVAILABLE);
use subs qw(time2iso8601 smart_encode);
use base 'Exporter';
use Module::Load;
use Scalar::Util qw(blessed reftype);
# The RPC_* convenience-encoders need prototypes:
## no critic (ProhibitSubroutinePrototypes)
# This module declares all the data-type packages:
## no critic (ProhibitMultiplePackages)
# The data-type package names trigger this one:
## no critic (Capitalization)
# The XML escape map now has CR in it but I don't want to use charnames:
## no critic (ProhibitEscapedCharacters)
BEGIN
{
# Default encoding:
$ENCODING = 'us-ascii';
# force strings?
$FORCE_STRING_ENCODING = 0;
# Allow the <nil /> extension?
$ALLOW_NIL = 0;
# Determine if the DateTime::Format::ISO8601 module is available for
# RPC::XML::datetime_iso8601 to use:
$DATETIME_ISO8601_AVAILABLE = eval { load DateTime::Format::ISO8601; 1; };
}
@EXPORT_OK = qw(time2iso8601 smart_encode
RPC_BOOLEAN RPC_INT RPC_I4 RPC_I8 RPC_DOUBLE
RPC_DATETIME_ISO8601 RPC_BASE64 RPC_STRING RPC_NIL
$ENCODING $FORCE_STRING_ENCODING $ALLOW_NIL);
%EXPORT_TAGS = (types => [ qw(RPC_BOOLEAN RPC_INT RPC_I4 RPC_I8 RPC_DOUBLE
RPC_STRING RPC_DATETIME_ISO8601 RPC_BASE64
RPC_NIL) ],
all => [ @EXPORT_OK ]);
$VERSION = '1.61';
$VERSION = eval $VERSION; ## no critic (ProhibitStringyEval)
# Global error string
$ERROR = q{};
# These are used for stringifying XML-sensitive characters that may appear
# in struct keys:
%XMLMAP = (
q{>} => '>',
q{<} => '<',
q{&} => '&',
q{"} => '"',
q{'} => ''',
"\x0d" => '
',
);
$XMLRE = join q{} => keys %XMLMAP; $XMLRE = qr/([$XMLRE])/;
# The XMLRPC spec only allows for the incorrect iso8601 format
# without dashes, but dashes are part of the standard so we include
# them. Note that the actual RPC::XML::datetime_iso8601 class will strip
# them out if present.
my $date_re =
qr{
(\d{4})-?
([01]\d)-?
([0123]\d)
}x;
my $time_re =
qr{
([012]\d):
([0-5]\d):
([0-5]\d)([.,]\d+)?
(Z|[-+]\d\d:\d\d)?
}x;
$DATETIME_REGEXP = qr{^${date_re}T?${time_re}$};
# All of the RPC_* functions are convenience-encoders
sub RPC_STRING ($)
{
return RPC::XML::string->new(shift);
}
sub RPC_BOOLEAN ($)
{
return RPC::XML::boolean->new(shift);
}
sub RPC_INT ($)
{
return RPC::XML::int->new(shift);
}
sub RPC_I4 ($)
{
return RPC::XML::i4->new(shift);
}
sub RPC_I8 ($)
{
return RPC::XML::i8->new(shift);
}
sub RPC_DOUBLE ($)
{
return RPC::XML::double->new(shift);
}
sub RPC_DATETIME_ISO8601 ($)
{
return RPC::XML::datetime_iso8601->new(shift);
}
sub RPC_BASE64 ($;$)
{
return RPC::XML::base64->new(shift, shift);
}
sub RPC_NIL ()
{
return RPC::XML::nil->new();
}
# This is a dead-simple ISO8601-from-UNIX-time stringifier. Always expresses
# time in UTC. The format isn't strictly ISO8601, though, as the XML-RPC spec
# fucked it up.
sub time2iso8601
{
my $time = shift || time;
my @time = gmtime $time;
$time = sprintf '%4d%02d%02dT%02d:%02d:%02dZ',
$time[5] + 1900, $time[4] + 1, @time[3, 2, 1, 0];
return $time;
}
# This is a (futile?) attempt to provide a "smart" encoding method that will
# take a Perl scalar and promote it to the appropriate RPC::XML::_type_.
{
# The regex for ints and floats uses [0-9] instead of \d on purpose, to
# only match ASCII digits.
## no critic (ProhibitEnumeratedClasses)
# The regex for floats is long, but I don't feel like factoring it out
# right now.
## no critic (ProhibitComplexRegexes)
my $MAX_INT = 2_147_483_647;
my $MIN_INT = -2_147_483_648;
my $MAX_BIG_INT = 9_223_372_036_854_775_807;
my $MIN_BIG_INT = -9_223_372_036_854_775_808;
my $MAX_DOUBLE = 1e37;
my $MIN_DOUBLE = $MAX_DOUBLE * -1;
sub smart_encode ## no critic (ProhibitExcessComplexity)
{
my @values = @_;
my ($type, $seenrefs, @newvalues);
# Look for sooper-sekrit pseudo-blessed hashref as first argument.
# It means this is a recursive call, and it contains a map of any
# references we've already seen.
if ((blessed $values[0]) && ($values[0]->isa('RPC::XML::refmap')))
{
# Peel it off of the list
$seenrefs = shift @values;
}
else
{
# Create one just in case we need it
$seenrefs = bless {}, 'RPC::XML::refmap';
}
for my $value (@values)
{
if (! defined $value)
{
$type = $ALLOW_NIL ?
RPC::XML::nil->new() : RPC::XML::string->new(q{});
}
elsif (ref $value)
{
# Skip any that we've already seen
next if $seenrefs->{$value}++;
if (blessed($value) &&
($value->isa('RPC::XML::datatype') || $value->isa('DateTime')))
{
# Only if the reference is a datatype or a DateTime
# instance, do we short-cut here...
if ($value->isa('RPC::XML::datatype'))
{
# Pass through any that have already been encoded
$type = $value;
}
else
{
# Must be a DateTime object, convert to ISO8601
$type = RPC::XML::datetime_iso8601
->new($value->clone->set_time_zone('UTC'));
}
}
elsif (reftype($value) eq 'HASH')
{
# Per RT 41063, to catch circular refs I can't delegate
# to the struct constructor, I have to create my own
# copy of the hash with locally-recursively-encoded
# values
my %newhash;
for my $key (keys %{$value})
{
# Forcing this into a list-context *should* make the
# test be true even if the return value is a hard
# undef. Only if the return value is an empty list
# should this evaluate as false...
if (my @value = smart_encode($seenrefs, $value->{$key}))
{
$newhash{$key} = $value[0];
}
}
$type = RPC::XML::struct->new(\%newhash);
}
elsif (reftype($value) eq 'ARRAY')
{
# This is a somewhat-ugly approach, but I don't want to
# dereference @$value, but I also want people to be able to
# pass array-refs in to this constructor and have them
# be treated as single elements, as one would expect
# (see RT 35106)
# Per RT 41063, looks like I get to deref $value after all...
$type = RPC::XML::array->new(
from => [ smart_encode($seenrefs, @{$value}) ]
);
}
elsif (reftype($value) eq 'SCALAR')
{
# This is a rare excursion into recursion, since the scalar
# nature (de-refed from the object, so no longer magic)
# will prevent further recursing.
$type = smart_encode($seenrefs, ${$value});
}
else
{
# If the user passed in a reference that didn't pass one
# of the above tests, we can't do anything with it:
$type = reftype $value;
die "Un-convertable reference: $type, cannot use\n";
}
$seenrefs->{$value}--;
}
# You have to check ints first, because they match the
# next pattern (for doubles) too
elsif (! $FORCE_STRING_ENCODING &&
$value =~ /^[-+]?[0-9]+$/ &&
$value >= $MIN_BIG_INT &&
$value <= $MAX_BIG_INT)
{
if (($value > $MAX_INT) || ($value < $MIN_INT))
{
$type = RPC::XML::i8->new($value);
}
else
{
$type = RPC::XML::int->new($value);
}
}
# Pattern taken from perldata(1)
elsif (! $FORCE_STRING_ENCODING &&
$value =~ m{
^
[+-]?
(?=[0-9]|[.][0-9])
[0-9]*
(?:[.][0-9]*)?
(?:[Ee](?:[+-]?[0-9]+))?
$
}x &&
$value > $MIN_DOUBLE &&
$value < $MAX_DOUBLE)
{
$type = RPC::XML::double->new($value);
}
elsif ($value =~ /$DATETIME_REGEXP/)
{
$type = RPC::XML::datetime_iso8601->new($value);
}
else
{
$type = RPC::XML::string->new($value);
}
push @newvalues, $type;
}
return (wantarray ? @newvalues : $newvalues[0]);
}
}
# This is a (mostly) empty class used as a common superclass for simple and
# complex types, so that their derivatives may be universally type-checked.
package RPC::XML::datatype;
sub type
{
my $self = shift;
my $class = ref($self) || $self;
$class =~ s/.*://;
return $class;
}
sub is_fault { return 0; }
###############################################################################
#
# Package: RPC::XML::simple_type
#
# Description: A base class for the simpler type-classes to inherit from,
# for default constructor, stringification, etc.
#
###############################################################################
package RPC::XML::simple_type;
use strict;
use base 'RPC::XML::datatype';
use Scalar::Util 'reftype';
# new - a generic constructor that presumes the value being stored is scalar
sub new
{
my $class = shift;
my $value = shift;
$RPC::XML::ERROR = q{};
$class = ref($class) || $class;
if ($class eq 'RPC::XML::simple_type')
{
$RPC::XML::ERROR = 'RPC::XML::simple_type::new: Cannot instantiate ' .
'this class directly';
return;
}
if (ref $value)
{
# If it is a scalar reference, just deref
if (reftype($value) eq 'SCALAR')
{
$value = ${$value};
}
else
{
# We can only manage scalar references (or blessed scalar refs)
$RPC::XML::ERROR = "${class}::new: Cannot instantiate from a " .
'reference not derived from scalar';
return;
}
}
return bless \$value, $class;
}
# value - a generic accessor
sub value
{
my $self = shift;
if (! ref $self)
{
$RPC::XML::ERROR =
"{$self}::value: Cannot be called as a static method";
return;
}
return ${$self};
}
# as_string - return the value as an XML snippet
sub as_string
{
my $self = shift;
my $class = ref $self;
if (! $class)
{
$RPC::XML::ERROR =
"{$self}::as_string: Cannot be called as a static method";
return;
}
$class =~ s/^.*\://;
$class =~ s/_/./g;
if (substr($class, 0, 8) eq 'datetime')
{
substr $class, 0, 8, 'dateTime';
}
return "<$class>${$self}</$class>";
}
# Serialization for simple types is just a matter of sending as_string over
sub serialize
{
my ($self, $fh) = @_;
utf8::encode(my $str = $self->as_string);
print {$fh} $str;
return;
}
# The switch to serialization instead of in-memory strings means having to
# calculate total size in bytes for Content-Length headers:
sub length ## no critic (ProhibitBuiltinHomonyms)
{
my $self = shift;
utf8::encode(my $str = $self->as_string);
return length $str;
}
###############################################################################
#
# Package: RPC::XML::int
#
# Description: Data-type class for integers
#
###############################################################################
package RPC::XML::int;
use strict;
use base 'RPC::XML::simple_type';
###############################################################################
#
# Package: RPC::XML::i4
#
# Description: Data-type class for i4. Forces data into an int object.
#
###############################################################################
package RPC::XML::i4;
use strict;
use base 'RPC::XML::simple_type';
###############################################################################
#
# Package: RPC::XML::i8
#
# Description: Data-type class for i8. Forces data into a 8-byte int.
#
###############################################################################
package RPC::XML::i8;
use strict;
use base 'RPC::XML::simple_type';
###############################################################################
#
# Package: RPC::XML::double
#
# Description: The "double" type-class
#
###############################################################################
package RPC::XML::double;
use strict;
use base 'RPC::XML::simple_type';
sub as_string
{
my $self = shift;
if (! ref $self)
{
$RPC::XML::ERROR =
"{$self}::as_string: Cannot be called as a static method";
return;
}
my $class = $self->type;
(my $value = sprintf '%.20f', ${$self}) =~ s/([.]\d+?)0+$/$1/;
return "<$class>$value</$class>";
}
###############################################################################
#
# Package: RPC::XML::string
#
# Description: The "string" type-class
#
###############################################################################
package RPC::XML::string;
use strict;
use base 'RPC::XML::simple_type';
# as_string - return the value as an XML snippet
sub as_string
{
my $self = shift;
my ($class, $value);
if (! ref $self)
{
$RPC::XML::ERROR =
"{$self}::as_string: Cannot be called as a static method";
return;
}
$class = $self->type;
($value = defined ${$self} ? ${$self} : q{} )
=~ s/$RPC::XML::XMLRE/$RPC::XML::XMLMAP{$1}/ge;
return "<$class>$value</$class>";
}
###############################################################################
#
# Package: RPC::XML::boolean
#
# Description: The type-class for boolean data. Handles some "extra" cases
#
###############################################################################
package RPC::XML::boolean;
use strict;
use base 'RPC::XML::simple_type';
# This constructor allows any of true, false, yes or no to be specified
sub new
{
my $class = shift;
my $value = shift || 0;
$RPC::XML::ERROR = q{};
if ($value =~ /true|yes|1/i)
{
$value = 1;
}
elsif ($value =~ /false|no|0/i)
{
$value = 0;
}
else
{
$class = ref($class) || $class;
$RPC::XML::ERROR = "${class}::new: Value must be one of yes, no, " .
'true, false, 1, 0 (case-insensitive)';
return;
}
return bless \$value, $class;
}
###############################################################################
#
# Package: RPC::XML::datetime_iso8601
#
# Description: This is the class to manage ISO8601-style date/time values
#
###############################################################################
package RPC::XML::datetime_iso8601;
use strict;
use base 'RPC::XML::simple_type';
use Scalar::Util 'reftype';
sub type { return 'dateTime.iso8601'; };
# Check the value passed in for sanity, and normalize the string representation
sub new
{
my ($class, $value) = @_;
my $newvalue;
if (ref($value) && reftype($value) eq 'SCALAR')
{
$value = ${$value};
}
if (defined $value)
{
if ($value =~ /$RPC::XML::DATETIME_REGEXP/)
{
# This is *not* a valid ISO 8601 format, but it's the way it is
# given in the spec, so assume that other implementations can only
# accept this form. Also, this should match the form that
# time2iso8601 produces.
$newvalue = $7 ? "$1$2$3T$4:$5:$6$7" : "$1$2$3T$4:$5:$6";
if ($8) {
$newvalue .= $8;
}
}
elsif ($RPC::XML::DATETIME_ISO8601_AVAILABLE)
{
$newvalue =
eval { DateTime::Format::ISO8601->parse_datetime($value) };
if ($newvalue)
{
# This both removes the dashes (*sigh*) and forces it from an
# object to an ordinary string:
$newvalue =~ s/-//g;
}
}
if (! $newvalue)
{
$RPC::XML::ERROR = "${class}::new: Malformed data ($value) " .
'passed as dateTime.iso8601';
return;
}
}
else
{
$RPC::XML::ERROR = "${class}::new: Value required in constructor";
return;
}
return bless \$newvalue, $class;
}
###############################################################################
#
# Package: RPC::XML::nil
#
# Description: The "nil" type-class extension
#
###############################################################################
package RPC::XML::nil;
use strict;
use base 'RPC::XML::simple_type';
# no value need be passed to this method
sub new
{
my ($class, $value, $flag) = @_;
# We need $value so we can bless a reference to it. But regardless of
# what was passed, it needs to be undef to be a proper "nil".
undef $value;
if (! $RPC::XML::ALLOW_NIL && ! $flag)
{
$RPC::XML::ERROR = "${class}::new: \$RPC::XML::ALLOW_NIL must be set" .
' for RPC::XML::nil objects to be supported';
return;
}
return bless \$value, $class;
}
# Stringification and serialsation are trivial..
sub as_string
{
return '<nil/>';
}
sub serialize
{
my ($self, $fh) = @_;
print {$fh} $self->as_string; # In case someone sub-classes this
return;
}
###############################################################################
#
# Package: RPC::XML::array
#
# Description: This class encapsulates the array data type. Each element
# within the array should be one of the datatype classes.
#
###############################################################################
package RPC::XML::array;
use strict;
use base 'RPC::XML::datatype';
use Scalar::Util qw(blessed reftype);
# The constructor for this class mainly needs to sanity-check the value data
sub new
{
my ($class, @args) = @_;
# Special-case time: If the args-list has exactly two elements, and the
# first element is "from" and the second element is an array-ref (or a
# type derived from), then copy the ref's contents into @args.
if ((2 == @args) && ($args[0] eq 'from') && (reftype($args[1]) eq 'ARRAY'))
{
@args = @{$args[1]};
}
# Ensure that each argument passed in is itself one of the data-type
# class instances.
return bless [ RPC::XML::smart_encode(@args) ], $class;
}
# This became more complex once it was shown that there may be a need to fetch
# the value while preserving the underlying objects.
sub value
{
my $self = shift;
my $no_recurse = shift || 0;
my $ret;
if ($no_recurse)
{
$ret = [ @{$self} ];
}
else
{
$ret = [ map { $_->value } @{$self} ];
}
return $ret;
}
sub as_string
{
my $self = shift;
return join q{},
'<array><data>',
(map { ('<value>', $_->as_string(), '</value>') } (@{$self})),
'</data></array>';
}
# Serialization for arrays is not as straight-forward as it is for simple
# types. One or more of the elements may be a base64 object, which has a
# non-trivial serialize() method. Thus, rather than just sending the data from
# as_string down the pipe, instead call serialize() recursively on all of the
# elements.
sub serialize
{
my ($self, $fh) = @_;
print {$fh} '<array><data>';
for (@{$self})
{
print {$fh} '<value>';
$_->serialize($fh);
print {$fh} '</value>';
}
print {$fh} '</data></array>';
return;
}
# Length calculation starts to get messy here, due to recursion
sub length ## no critic (ProhibitBuiltinHomonyms)
{
my $self = shift;
# Start with the constant components in the text
my $len = 28; # That the <array><data></data></array> part
for (@{$self}) { $len += (15 + $_->length) } # 15 is for <value></value>
return $len;
}
###############################################################################
#
# Package: RPC::XML::struct
#
# Description: This is the "struct" data class. The struct is like Perl's
# hash, with the constraint that all values are instances
# of the datatype classes.
#
###############################################################################
package RPC::XML::struct;
use strict;
use base 'RPC::XML::datatype';
use Scalar::Util qw(blessed reftype);
# The constructor for this class mainly needs to sanity-check the value data
sub new
{
my ($class, @args) = @_;
my %args = (ref $args[0] and reftype($args[0]) eq 'HASH') ?
%{$args[0]} : @args;
# RT 41063: If all the values are datatype objects, either they came in
# that way or we've already laundered them through smart_encode(). If there
# is even one that isn't, then we have to pass the whole mess to be
# encoded.
my $ref =
(grep { ! (blessed($_) && $_->isa('RPC::XML::datatype')) } values %args)
? RPC::XML::smart_encode(\%args) : \%args;
return bless $ref, $class;
}
# This became more complex once it was shown that there may be a need to fetch
# the value while preserving the underlying objects.
sub value
{
my $self = shift;
my $no_recurse = shift || 0;
my %value;
if ($no_recurse)
{
%value = map { ($_, $self->{$_}) } (keys %{$self});
}
else
{
%value = map { ($_, $self->{$_}->value) } (keys %{$self});
}
return \%value;
}
sub as_string
{
my $self = shift;
my $key;
# Clean the keys of $self, in case they have any HTML-special characters
my %clean;
for (keys %{$self})
{
($key = $_) =~ s/$RPC::XML::XMLRE/$RPC::XML::XMLMAP{$1}/ge;
$clean{$key} = $self->{$_}->as_string;
}
return join q{},
'<struct>',
(map {
("<member><name>$_</name><value>",
$clean{$_},
'</value></member>')
} (keys %clean)),
'</struct>';
}
# As with the array type, serialization here isn't cut and dried, since one or
# more values may be base64.
sub serialize
{
my ($self, $fh) = @_;
my $key;
print {$fh} '<struct>';
for (keys %{$self})
{
($key = $_) =~ s/$RPC::XML::XMLRE/$RPC::XML::XMLMAP{$1}/ge;
utf8::encode($key);
print {$fh} "<member><name>$key</name><value>";
$self->{$_}->serialize($fh);
print {$fh} '</value></member>';
}
print {$fh} '</struct>';
return;
}
# Length calculation is a real pain here. But not as bad as base64 promises
sub length ## no critic (ProhibitBuiltinHomonyms)
{
my $self = shift;
my $len = 17; # <struct></struct>
for my $key (keys %{$self})
{
$len += 45; # For all the constant XML presence
$len += $self->{$key}->length;
utf8::encode($key);
$len += length $key;
}
return $len;
}
###############################################################################
#
# Package: RPC::XML::base64
#
# Description: This is the base64-encoding type. Plain data is passed in,
# plain data is returned. Plain is always returned. All the
# encoding/decoding is done behind the scenes.
#
###############################################################################
package RPC::XML::base64;
use strict;
use base 'RPC::XML::datatype';
use Scalar::Util 'reftype';
sub new
{
my ($class, $value, $encoded) = @_;
require MIME::Base64;
my $self = {};
$RPC::XML::ERROR = q{};
$self->{encoded} = $encoded ? 1 : 0; # Is this already Base-64?
$self->{inmem} = 0; # To signal in-memory vs. filehandle
# First, determine if the call sent actual data, a reference to actual
# data, or an open filehandle.
if (ref $value and reftype($value) eq 'GLOB')
{
# This is a seekable filehandle (or acceptable substitute thereof).
# This assignment increments the ref-count, and prevents destruction
# in other scopes.
binmode $value;
$self->{value_fh} = $value;
$self->{fh_pos} = tell $value;
}
else
{
# Not a filehandle. Might be a scalar ref, but other than that it's
# in-memory data.
$self->{inmem}++;
$self->{value} = ref($value) ? ${$value} : ($value || q{});
# We want in-memory data to always be in the clear, to reduce the tests
# needed in value(), below.
if ($self->{encoded})
{
local $^W = 0; # Disable warnings in case the data is underpadded
$self->{value} = MIME::Base64::decode_base64($self->{value});
$self->{encoded} = 0;
}
}
return bless $self, $class;
}
sub value
{
my ($self, $flag) = @_;
my $as_base64 = (defined $flag and $flag) ? 1 : 0;
# There are six cases here, based on whether or not the data exists in
# Base-64 or clear form, and whether the data is in-memory or needs to be
# read from a filehandle.
if ($self->{inmem})
{
# This is simplified into two cases (rather than four) since we always
# keep in-memory data as cleartext
return $as_base64 ?
MIME::Base64::encode_base64($self->{value}, q{}) : $self->{value};
}
else
{
# This is trickier with filehandle-based data, since we chose not to
# change the state of the data. Thus, the behavior is dependant not
# only on $as_base64, but also on $self->{encoded}. This is why we
# took pains to explicitly set $as_base64 to either 0 or 1, rather than
# just accept whatever non-false value the caller sent. It makes this
# first test possible.
my ($accum, $pos, $res);
$accum = q{};
$self->{fh_pos} = tell $self->{value_fh};
seek $self->{value_fh}, 0, 0;
if ($as_base64 == $self->{encoded})
{
$pos = 0;
while ($res = read $self->{value_fh}, $accum, 1024, $pos)