SecureSocket.pm untested

filter: Statementstmt 0.0% 0 / 144 Branchbran 0.0% 0 / 42 Conditioncond 0.0% 0 / 28 MC/DCmcdc 0.0% 0 / 18 Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 272 CC 21 SCAR 30.4
CC
21
Cov
0%
write
72.0
connect
30.0
_getaddress
20.0
CRAP 21.0
1 # $Id: SecureSocket.pm,v 1.3 1998/01/26 11:13:29 aas Exp $
2 #
3 # Derived by Joshua Kronengold from Socket.pm and SSLeay
4 #
5  
6  
7 require Socket;
8 require Net::SSLeay;
9  
10  
11 package LWP::SecureSocket;
12  
13 =head1 NAME
14  
15 LWP::SecureSocket - SSL TCP/IP socket interface
16  
17 =head1 SYNOPSIS
18  
19 $socket = new LWP::SecureSocket;
20 $socket->connect('localhost', 7); # echo
21 $quote = 'I dunno, I dream in Perl sometimes...';
22 $socket->write("$quote\n");
23 $socket->read_until("\n", \$buffer);
24 $socket->read(\$buffer);
25 $socket = undef; # close
26  
27 =head1 DESCRIPTION
28  
29 B<Beware:> New code should not use this depreciated module.
30  
31 This class implements SSL TCP/IP sockets. It groups socket
32 generation, TCP address manipulation and buffered reading. Errors are
33 handled by dying (throws exceptions).
34  
35 The following methods are provided:
36  
37 =over 4
38  
39 =cut
40  
41  
42 $VERSION = sprintf("%d.%02d", q$Revision: 1.3 $ =~ /(\d+)\.(\d+)/);
43 sub Version { $VERSION; }
44  
45 use Socket qw(pack_sockaddr_in unpack_sockaddr_in
46 PF_INET SOCK_STREAM INADDR_ANY
47 inet_ntoa inet_aton);
48 Socket->require_version(1.5);
49  
50 use Carp ();
51 use Symbol qw(gensym);
52  
53 use LWP::Debug ();
54 use LWP::IO ();
55 # use Socket;
56 use Net::SSLeay;
57  
58  
59 my $tcp_proto = (getprotobyname('tcp'))[2];
60  
61  
62 =item $sock = new LWP::SecureSocket()
63  
64 Constructs a new socket object.
65  
66 =cut
67  
68 sub new
69 {
70 my($class, $socket, $host, $port) = @_;
71  
72 unless ($socket) {
73 $socket = gensym();
74 LWP::Debug::debug("SecureSocket $socket");
75  
76 socket($socket, PF_INET, SOCK_STREAM, $tcp_proto) or
77 Carp::croak("socket: $!");
78 }
79  
80 my $self = bless {
81 'socket' => $socket,
82 'host' => $host,
83 'port' => $port,
84 'buffer' => '',
85 'size' => 4096,
86 }, $class;
87  
88 $self;
89 }
90  
91 sub DESTROY
92 {
93 my $socket = shift->{'socket'};
94 close($socket);
95 }
96  
97 sub host { shift->{'host'}; }
98 sub port { shift->{'port'}; }
99  
100  
101 =item $sock->connect($host, $port)
102  
103 Connect the socket to given host and port.
104  
105 =cut
106  
107 sub connect
108 {
109 my($self, $host, $port) = @_;
110 Carp::croak("no host") unless defined $host && length $host;
111 Carp::croak("no port") unless defined $port && $port > 0;
112  
113 LWP::Debug::trace("($host, $port)");
114  
115 $self->{'host'} = $host;
116 $self->{'port'} = $port;
117  
118 my @addr = $self->_getaddress($host, $port);
119 Carp::croak("Can't resolv address for $host")
120 unless @addr;
121 $socket=$self->{'socket'};
122 LWP::Debug::debug("Connecting to host '$host' on port '$port'...");
123 for (@addr) {
124 if (connect($self->{'socket'}, $_))
125 {
126 # print STDERR "\nCreating context....".
127 # "(connected socket($self->{'socket'}) to \n$host, $port, and ".
128 # "socket is ".."\n";
129 my $ctx= Net::SSLeay::CTX_new() or
130 Carp::croak "Failed to create SSL_CTX $!";
131 $self->{'context'}=$ctx;
132 $self->{SSL} = Net::SSLeay::new($ctx) or
133 Carp::croak "Failed to create SSL $!";
134 ($err=Net::SSLeay::set_fd($self->{SSL}, ($fn=fileno($socket)))) or
135 (Carp::croak "Can't set_fd somehow $!");
136 # print STDERR "\nConnecting....fileno=($fn)\n";
137 my $res= Net::SSLeay::connect($self->{SSL});
138 # print STDERR "result of connect: ($res)\n";
139 return;
140 }
141 }
142 Carp::croak("Could not connect to $host:$port");
143 }
144  
145  
146 =item $sock->shutdown()
147  
148 Shuts down the connection.
149  
150 =cut
151  
152 sub shutdown
153 {
154 my($self, $how) = @_;
155 $how = 2 unless defined $how;
156 shutdown($self->{'socket'}, $how);
157 delete $self->{'host'};
158 delete $self->{'port'};
159 }
160  
161  
162 =item $sock->bind($host, $port)
163  
164 Binds a name to the socket.
165  
166 =cut
167  
168 sub bind
169 {
170 my($self, $host, $port) = @_;
171 my $name = $self->_getaddress($host, $port);
172 bind($self->{'socket'}, $name);
173 }
174  
175  
176 =item $sock->listen($queuesize)
177  
178 Set up listen queue for socket.
179  
180 =cut
181  
182 sub listen
183 {
184 listen(shift->{'socket'}, @_);
185 }
186  
187  
188 =item $sock->accept($timeout)
189  
190 Accepts a new connection. Returns a new LWP::SecureSocket object if successful.
191 Timeout not implemented yet. would require modifying new, and not
192 necessary for app, so I\'m not bothering to modify. Might work
193 anyways, though.
194  
195 =cut
196  
197 sub accept
198 {
199 my $self = shift;
200 my $timeout = shift;
201 my $ns = gensym();
202 my $addr = accept($ns, $self->{'socket'});
203 if ($addr) {
204 my($port, $addr) = unpack_sockaddr_in($addr);
205 return new LWP::SecureSocket $ns, inet_ntoa($addr), $port;
206 } else {
207 Carp::croak("Can't accept: $!");
208 }
209 }
210  
211  
212 =item $sock->getsockname()
213  
214 Returns a 2 element array ($host, $port)
215  
216 =cut
217  
218 sub getsockname
219 {
220 my($port, $addr) = unpack_sockaddr_in(getsockname(shift->{'socket'}));
221 (inet_ntoa($addr), $port);
222 }
223  
224  
225 =item $sock->read_until($delim, $data_ref, $size, $timeout)
226  
227 Reads data from the socket, up to a delimiter specified by a regular
228 expression. If $delim is undefined all data is read. If $size is
229 defined, data will be read internally in chunks of $size bytes. This
230 does not mean that we will return the data when size bytes are read.
231  
232 Note that $delim is discarded from the data returned.
233  
234 =cut
235  
236 sub read_until
237 {
238 my ($self, $delim, $data_ref, $size, $timeout) = @_;
239  
240 {
241 my $d = $delim;
242 $d =~ s/\r/\\r/g;
243 $d =~ s/\n/\\n/g;
244 LWP::Debug::trace("('$d',...)");
245 }
246  
247 my $socket = $self->{'socket'};
248 my $ssl = $self->{SSL};
249 $delim = '' unless defined $delim;
250 $size ||= $self->{'size'};
251  
252 my $buf = \$self->{'buffer'};
253  
254 if (length $delim) {
255 while ($$buf !~ /$delim/) {
256 my $data=Net::SSLeay::read($ssl) or die "Unexpected EOF 1";
257 $$buf .=$data;
258
259 # LWP::IO::read($socket, $$buf, $size, length($$buf), $timeout)
260 # or die "Unexpected EOF";
261 }
262 ($$data_ref, $self->{'buffer'}) = split(/$delim/, $$buf, 2);
263 } else {
264 $data_ref = $buf;
265 $self->{'buffer'} = '';
266 }
267  
268 1;
269 }
270  
271  
272 =item $sock->read($bufref, [$size, $timeout])
273  
274 Reads data of the socket. Not more than $size bytes. Might return
275 less if the data is available. Dies on timeout.
276  
277 =cut
278  
279 sub read
280 {
281 my($self, $data_ref, $size, $timeout) = @_;
282 $size ||= $self->{'size'};
283  
284 LWP::Debug::trace('(...)');
285 if (length $self->{'buffer'}) {
286 # return data from buffer until it is empty
287 #print "Returning data from buffer...$self->{'buffer'}\n";
288 $$data_ref = substr($self->{'buffer'}, 0, $size);
289 substr($self->{'buffer'}, 0, $size) = '';
290 return length $$data_ref;
291 }
292
293 my $ssl = $self->{SSL};
294 # print STDERR "reading...";
295 (my $data=Net::SSLeay::read($ssl));
296 # print STDERR "read ($data)\n";
297 $$data_ref.=$data;
298 return(length $data);
299 }
300  
301  
302 =item $sock->pushback($data)
303  
304 Put data back into the socket. Data will returned next time you
305 read(). Can be used if you find out that you have read too much.
306  
307 =cut
308  
309 sub pushback
310 {
311 LWP::Debug::trace('(' . length($_[1]) . ' bytes)');
312 my $self = shift;
313 substr($self->{'buffer'}, 0, 0) = shift;
314 }
315  
316  
317 =item $sock->write($data, [$timeout])
318  
319 Write data to socket. The $data argument might be a scalar or code.
320  
321 If data is a reference to a subroutine, then we will call this routine
322 to obtain the data to be written. The routine will be called until it
323 returns undef or empty data. Data might be returned from the callback
324 as a scalar or as a reference to a scalar.
325  
326 Write returns the number of bytes written to the socket.
327  
328 =cut
329  
330 sub write
331 {
332 my $self = shift;
333 my $ssl = $self->{SSL};
334  
335 my $timeout = $_[1]; # we don't want to copy data in $_[0]
336 LWP::Debug::trace('()');
337 my $bytes_written = 0;
338 if (!ref $_[0]) {
339 my $got = Net::SSLeay::write($ssl, $_[0]);
340 $bytes_written=length $_[0] if $got;
341 # $bytes_written = LWP::IO::write($self->{'socket'}, $_[0], $timeout);
342 } elsif (ref($_[0]) eq 'CODE') {
343 # write data until $callback returns empty data '';
344 my $callback = shift;
345 while (1) {
346 my $data = &$callback;
347 last unless defined $data;
348 my $dataRef = ref($data) ? $data : \$data;
349 my $len = length $$dataRef;
350 last unless $len;
351 my $n = $self->write($$dataRef, $timeout);
352 $bytes_written += $n;
353 last if $n != $len;
354 }
355 } else {
356 Carp::croak('Illegal LWP::SecureSocket->write() argument');
357 }
358 $bytes_written;
359 }
360  
361  
362  
363 =item $sock->_getaddress($h, $p)
364  
365 Given a host and a port, it will return the address (sockaddr_in)
366 suitable as the C<name> argument for connect() or bind(). Might return
367 several addresses in array context if the hostname is bound to several
368 IP addresses.
369  
370 =cut
371  
372  
373 sub _getaddress
374 {
375 my($self, $host, $port) = @_;
376  
377 my(@addr);
378 if (!defined $host) {
379 # INADDR_ANY
380 $addr[0] = pack_sockaddr_in($port, INADDR_ANY);
381 }
382 elsif ($host =~ /^(\d+\.\d+\.\d+\.\d+)$/) {
383 # numeric IP address
384 $addr[0] = pack_sockaddr_in($port, inet_aton($1));
385 } else {
386 # hostname
387 LWP::Debug::debug("resolving host '$host'...");
388 (undef,undef,undef,undef,@addr) = gethostbyname($host);
389 for (@addr) {
390 LWP::Debug::debug(" ..." . inet_ntoa($_));
391 $_ = pack_sockaddr_in($port, $_);
392 }
393 }
394 wantarray ? @addr : $addr[0];
395 }
396  
397  
398 #####################################################################
399  
400 package main;
401  
402 eval join('',<DATA>) || die $@ unless caller();
403  
404 =back
405  
406 =head1 AUTHOR
407  
408 Derived by Joshua Kronengold from Socket.pm and SSLeay
409  
410 =cut
411  
412 1;
413  
414 __END__