CAB/Socket.pm untested

filter: Statementstmt 0.0% 0 / 189 Branchbran 0.0% 0 / 90 Conditioncond 0.0% 0 / 57 MC/DCmcdc 0.0% 0 / 37 Subroutinesub 0.0% 0 / 46 Podpod 0.0% 0 / 33 totaltotal 0.0% 0 / 452 CC 46 SCAR 26.5
CC
46
Cov
0%
handleClient
42.0
put_data
30.0
put_str
30.0
CRAP 14.1
1 ## -*- Mode: CPerl -*-
2 ##
3 ## File: DTA::CAB::Socket.pm
4 ## Author: Bryan Jurish <moocow@cpan.org>
5 ## Description: UNIX-socket based queue: common utilities
6  
7 package DTA::CAB::Socket;
8 use DTA::CAB::Logger;
9 use DTA::CAB::Utils ':files';
10 use IO::Handle;
11 use IO::File;
12 use IO::Socket;
13 use Errno qw(EINTR);
14 use Fcntl ':DEFAULT';
15 use Storable;
16 use Carp;
17 use Exporter;
18 use strict;
19  
20 ##==============================================================================
21 ## Globals
22 ##==============================================================================
23 our @ISA = qw(Exporter DTA::CAB::Logger);
24  
25 our @EXPORT = qw();
26 our %EXPORT_TAGS =
27 (
28 'flags' => [qw($sf_eoq $sf_undef $sf_u8 $sf_ref)],
29 );
30 our @EXPORT_OK = map {@$_} values %EXPORT_TAGS;
31 $EXPORT_TAGS{all} = [@EXPORT_OK];
32  
33 ##==============================================================================
34 ## Constructors etc.
35 ##==============================================================================
36  
37 ## $s = DTA::CAB::Socket->new(%args)
38 ## + %$s, %args:
39 ## (
40 ## fh => $sockfh, ##-- an IO::Socket object for the socket
41 ## timeout => $secs, ##-- default timeout for select() (default=undef: none)
42 ## nonblocking => $bool, ##-- set O_NONBLOCK on open() if true (default=false)
43 ## logSocket => $level, ##-- log level for full socket trace (default=undef (none))
44 ## logRequest => $level, ##-- log level for client requests (default=undef (none))
45 ## )
46 sub new {
47 my ($that,%args) = @_;
48 my $s = bless({
49 #path =>undef,
50 timeout=>undef,
51 nonblocking => 0,
52 logSocket => undef,
53 logRequest => undef,
54 (ref($that) ? (%$that) : qw()),
55 fh =>undef,
56 %args,
57 }, ref($that)||$that);
58 return $s;
59 }
60  
61 ## undef = $s->DESTROY
62 ## + destructor calls close()
63 sub DESTROY {
64 $_[0]->close();
65 }
66  
67 ##==============================================================================
68 ## Debug
69  
70 ## undef = $s->vtrace(@msg)
71 ## + logs @msg at $s->{logSocket}
72 sub vtrace {
73 $_[0]->vlog($_[0]{logSocket}, join(' ', map {defined($_) ? $_ : '--undef--'} @_[1..$#_])) if (defined($_[0]{logSocket}));
74 }
75  
76 ##==============================================================================
77 ## Open/Close
78  
79 ## $bool = $s->opened()
80 sub opened {
81 return defined($_[0]{fh}) && $_[0]{fh}->opened();
82 }
83  
84 ## $s = $s->close()
85 ## + closes the socket and deletes $s->{fh}
86 sub close {
87 my $s = shift;
88 $s->{fh}->close() if ($s->opened);
89 delete($s->{fh});
90 return $s;
91 }
92  
93 ## $s_or_undef = $s->open(%args)
94 ## + default implementation just dies
95 sub open {
96 $_[0]->vtrace("open ", @_[1..$#_]);
97 $_[0]->logconfess("abstract open() method not implemented");
98 }
99  
100 ## $s = $s->reopen()
101 ## + wrapper just calls $s->open()
102 sub reopen {
103 $_[0]->open(@_[1..$#_]);
104 }
105  
106 ## $s = $s->connect()
107 ## + wrapper for $s->open()
108 sub connect {
109 return $_[0]->open(@_[1..$#_]);
110 }
111  
112  
113 ##==============================================================================
114 ## Select
115  
116 ## $flags = $s->flags()
117 ## + get fcntl flags
118 sub flags {
119 return fcntl($_[0]{fh}, F_GETFL, 0)
120 }
121  
122 ## $bool = $s->nonblocking()
123 ## $bool = $s->nonblocking($bool)
124 ## + get current value of O_NONBLOCK flag
125 sub nonblocking {
126 if (@_ > 1) {
127 fcntl($_[0]{fh}, F_SETFL, ($_[1] ? ($_[0]->flags | O_NONBLOCK) : ($_[0]->flags & ~O_NONBLOCK)))
128 or $_[0]->logconfess("canread(): could not set flags on socket fd ", fileno($_[0]{fh}), ": $!");
129 }
130 return $_[0]->flags & O_NONBLOCK;
131 }
132  
133 ## $bool = $s->canread()
134 ## $bool = $s->canread($timeout_secs)
135 ## + returns true iff there is readable data on the socket
136 ## + $timeout_secs defaults to $s->{timeout} (0 for none)
137 ## + temporarily sets O_NONBLOCK for the socket
138 ## + should return true for a server socket if at least one client is waiting to connect
139 sub canread {
140 #$_[0]->vtrace('canread');
141 my $s = shift;
142 my $timeout = @_ ? shift : $s->{timeout};
143 my $flags0 = $s->flags;
144 if (!($flags0 & O_NONBLOCK)) {
145 fcntl($s->{fh}, F_SETFL, $flags0 | O_NONBLOCK)
146 or $s->logconfess("canread(): could not set O_NOBLOCK on socket: $!");
147 }
148 my $rbits = fhbits($s->{fh});
149 my $nfound = select($rbits, undef, undef, $timeout);
150 if (!($flags0 & O_NONBLOCK)) {
151 fcntl($s->{fh}, F_SETFL, $flags0)
152 or $s->logconfess("canread(): could not reset socket flags: $!");
153 }
154 return $nfound;
155 }
156  
157 ## $bool = $s->canwrite()
158 ## $bool = $s->canwrite($timeout_secs)
159 ## + returns true iff data can be written to the socket
160 ## + $timeout_secs defaults to $s->{timeout} (0 for none)
161 ## + temporarily sets O_NONBLOCK for the socket
162 sub canwrite {
163 #$_[0]->vtrace('canwrite');
164 my $s = shift;
165 my $timeout = @_ ? shift : $s->{timeout};
166 my $flags0 = $s->flags;
167 if (!($flags0 & O_NONBLOCK)) {
168 fcntl($s->{fh}, F_SETFL, $flags0 | O_NONBLOCK)
169 or $s->logconfess("canwrite(): could not set O_NOBLOCK on socket: $!");
170 }
171 my $wbits = fhbits($s->{fh});
172 my $nfound = select(undef, $wbits, undef, $timeout);
173 if (!($flags0 & O_NONBLOCK)) {
174 fcntl($s->{fh}, F_SETFL, $flags0)
175 or $s->logconfess("canwrite(): could not reset socket flags: $!");
176 }
177 return $nfound;
178 }
179  
180 ## $s = $s->waitr()
181 ## + waits indefinitely for input; wrapper for $s->canread(undef)
182 sub waitr {
183 return $_[0]->canread(undef) ? $_[0] : undef;
184 }
185  
186 ## $bool = $s->waitw()
187 ## + wrapper for $s->canwrite(undef)
188 sub waitw {
189 return $_[0]->canwrite(undef) ? $_[0] : undef;
190 }
191  
192 ##==============================================================================
193 ## Server Methods
194  
195 ## $class = $CLASS_OR_OBJECT->clientClass()
196 ## + default client class, used by newClient()
197 sub clientClass {
198 return ref($_[0]) || $_[0];
199 }
200  
201 ## $client = $CLASS_OR_OBJECT->newClient(%args)
202 ## + wrapper for clients, called by $s->accept()
203 ## + default just calls $CLASS_OR_OBJECT->clientClass->new(%args)
204 sub newClient {
205 my $that = shift;
206 return $that->clientClass->new(@_);
207 }
208  
209 ## $cli_or_undef = $s->accept()
210 ## $cli_or_undef = $s->accept($timeout_secs)
211 ## + accept incoming client connections with optional timeout
212 ## + if a client connection is available, it will be returned with $s->newClient(fh=>$fh)
213 ## + otherwise, if no connection is available, undef will be returned
214 sub accept {
215 my $s = shift;
216 my $timeout = @_ ? shift : $s->{timeout};
217 if (!defined($timeout) || $s->canread($timeout)) {
218 my $cfh = $s->{fh}->accept();
219 return undef if (!defined($cfh));
220 return $s->newClient(fh=>$cfh);
221 }
222 return undef;
223 }
224  
225 ## $rc = $qs->handleClient($cli)
226 ## $rc = $qs->handleClient($cli, %callbacks)
227 ## + handle a single client request
228 ## + each client request is a STRING message (command)
229 ## - request arguments (if required) are sent as separate messages following the command request
230 ## - server response (if any) depends on command sent
231 ## + this method parses client request command $cmd and dispatches to
232 ## - the function $callbacks{lc($cmd)}->($qs,$cli,\$cmd), if defined
233 ## - the method $qs->can("handle_".lc($cmd))->($qs,$cli,\$cmd), if available
234 ## - the function $callbacks{DEFAULT}->($qs,$cli,\$cmd), if defined
235 ## - the method $qs->can("handle_DEFAULT")->($qs,$cli,\$cmd)
236 ## + returns whatever the handler subroutine does
237 sub handleClient {
238 my ($qs,$cli,%callbacks) = @_;
239 my $creq = $cli->get();
240 $qs->vlog($qs->{logRequest}, "client request: $$creq");
241 if (!ref($creq) || ref($creq) ne 'SCALAR' || ref($$creq)) {
242 $qs->logconfess("could not parse client request");
243 }
244 my $cmd = lc($$creq);
245 my ($sub);
246 if (defined($sub=$callbacks{$cmd})) {
247 return $sub->($qs,$cli,$creq);
248 }
249 elsif (defined($sub=$qs->can("handle_${cmd}"))) {
250 return $sub->($qs,$cli,$creq);
251 }
252 elsif (defined($sub=$callbacks{DEFAULT})) {
253 return $sub->($qs,$cli,$creq);
254 }
255 elsif (defined($sub=$qs->can("handle_DEFAULT"))) {
256 return $sub->($qs,$cli,$creq);
257 }
258 ##-- should never get here
259 $qs->logconfess("could not dispatch client request $$creq");
260 return undef;
261 }
262  
263 ##--------------------------------------------------------------
264 ## Server Methods: Request Handling
265  
266 ## undef = $qs->handle_DEFAULT($cli,\$cmd)
267 ## + default implementation just logcluck()s and returns undef
268 sub handle_DEFAULT {
269 $_[0]->logcluck("cannot handle client client request ${$_[2]}");
270 return undef;
271 }
272  
273 ##==============================================================================
274 ## Protocol
275 ## + all socket messages are of the form pack('NN/a*', $flags, $message_data)
276 ## + $flags is a bitmask of DTA::CAB::Socket flags ($sf_* constants)
277 ## + length element (second 'N' of pack format) is always 0 for serialized references
278 ## + $message_data is one of the following:
279 ## - if ($flags & $sf_ref) -> a reference written with nstore_fd(); will be decoded
280 ## - elsif ($flags & $sf_u8) -> a UTF-8 encoded string; will be decoded
281 ## - elsif ($flags & $sf_undef) -> a literal undef value
282 ## - elsif ($flags & $sf_eoq) -> undef as end-of-queue marker
283  
284 ##--------------------------------------------------------------
285 ## Protocol: Constants
286 our $sf_eoq = 0x1;
287 our $sf_undef = 0x2;
288 our $sf_u8 = 0x4;
289 our $sf_ref = 0x8;
290  
291 ##--------------------------------------------------------------
292 ## Protocol: Write
293  
294 ## $s = $s->put_header($flags,$len)
295 ## + write a message header to the socket
296 sub put_header {
297 $_[0]->vtrace("put_header", @_[1..$#_]);
298 syswrite($_[0]{fh}, pack('NN', @_[1,2]), 8)==8
299 or $_[0]->logconfess("put_header(): could not write message header to socket: $!");
300 return $_[0];
301 }
302  
303 ## $s = $s->put_data(\$data, $len)
304 ## $s = $s->put_data( $data, $len)
305 ## + write some raw data bytes to the socket (header should already have been sent)
306 sub put_data {
307 $_[0]->vtrace("put_data", @_[1..$#_]);
308 return if (!defined($_[0]));
309 use bytes;
310 my $ref = ref($_[1]) ? $_[1] : \$_[1];
311 my $len = defined($_[2]) ? $_[2] : length($$ref);
312 if ($len > 0) {
313 syswrite($_[0]{fh}, $$ref, $len)==$len
314 or $_[0]->logconfess("put_data(): could not write message data to socket: $!");
315 }
316 return $_[0];
317 }
318  
319 ## $s = $s->put_msg($flags,$len, $data)
320 ## $s = $s->put_msg($flags,$len,\$data)
321 ## + write a whole message to the socket
322 sub put_msg {
323 $_[0]->put_header(@_[1,2]) && $_[0]->put_data(@_[3,2]);
324 }
325  
326  
327 ## $s = $s->put_ref($ref)
328 ## + write a reference to the socket with Storable::nstore() (length written as 0)
329 sub put_ref {
330 $_[0]->vtrace("put_ref", @_[1..$#_]);
331 $_[0]->put_header( $sf_ref | (defined($_[1]) ? 0 : $sf_undef), 0 );
332 return $_[0] if (!defined($_[1]));
333 Storable::nstore_fd($_[1], $_[0]{fh})
334 or $_[0]->logconfess("put_ref(): nstore_fd() failed for $_[1]: $!");
335 return $_[0];
336 }
337  
338 ## $s = $s->put_str(\$str)
339 ## $s = $s->put_str( $str)
340 ## + write a raw string message to the socket
341 ## + auto-magically sets $sf_undef and $sf_u8 flags
342 sub put_str {
343 $_[0]->vtrace("put_str", @_[1..$#_]);
344 use bytes;
345 my $ref = ref($_[1]) ? $_[1] : \$_[1];
346 my $flags = (defined($$ref) ? (utf8::is_utf8($$ref) ? $sf_u8 : 0) : $sf_undef);
347 my $len = (defined($$ref) ? length($$ref) : 0);
348 $_[0]->put_msg($flags,$len,$ref);
349 }
350  
351 ## $s = $s->put_undef()
352 sub put_undef {
353 $_[0]->vtrace("put_undef", @_[1..$#_]);
354 $_[0]->put_msg( $sf_undef, 0, undef );
355 }
356  
357 ## $s = $s->put_eoq()
358 sub put_eoq {
359 $_[0]->vtrace("put_eoq", @_[1..$#_]);
360 $_[0]->put_msg( $sf_eoq|$sf_undef, 0, undef );
361 }
362  
363  
364 ## $s = $s->put( $thingy )
365 ## + write an arbitrary thingy to the socket
366 ## + if $thingy is a SCALAR or a reference to a bare SCALAR, calls $s->put_str($thingy)
367 ## + otherwise calls $s->put_ref($thingy)
368 sub put {
369 $_[0]->vtrace("put", @_[1..$#_]);
370 return $_[0]->put_undef() if (!defined($_[1]));
371 return $_[0]->put_str(\$_[1]) if (!ref($_[1]));
372 return $_[0]->put_str( $_[1]) if ( ref($_[1]) eq 'SCALAR' && !ref(${$_[1]}) );
373 return $_[0]->put_ref( $_[1]);
374 }
375  
376 ##--------------------------------------------------------------
377 ## Protocol: Read
378  
379 ## $nbytes_read = $s->safe_sysread(\$bufr, $nbytes)
380 ## + safe wrapper for CORE::sysread which avoids EINTR ("Interrupted system call") errors
381 sub safe_sysread {
382 my ($s,$bufr,$nbytes) = @_;
383 my ($rc);
384 my $nread = 0;
385 while ($nbytes > 0) {
386 if ( !($rc = CORE::sysread($s->{fh},$$bufr,$nbytes,$nread)) ) {
387 next if ($! == EINTR);
388 return undef; ##-- other error
389 }
390 $nbytes -= $rc;
391 $nread += $rc;
392 }
393 return $nread;
394 }
395  
396 ## ($flags,$len) = $s->get_header(); ##-- list context
397 ## $header_packed = $s->get_header(); ##-- scalar context
398 ## + gets header from socket
399 sub get_header {
400 $_[0]->vtrace("get_header", @_[1..$#_]);
401 my ($hdr);
402 #CORE::sysread($_[0]{fh}, $hdr, 8)==8
403 $_[0]->safe_sysread(\$hdr,8)==8
404 or $_[0]->logconfess("get_header(): could not read message header from socket: $!");
405 return wantarray ? unpack('NN',$hdr) : $hdr;
406 }
407  
408 ## \$buf = $s->get_data($len)
409 ## \$buf = $s->get_data($len,\$buf)
410 ## + reads $len bytes of data from the socket
411 sub get_data {
412 $_[0]->vtrace("get_data", @_[1..$#_]);
413 my ($s,$len,$bufr) = @_;
414 $bufr = \(my $buf) if (!defined($bufr));
415 $$bufr = undef;
416 if ($len > 0) {
417 #CORE::sysread($s->{fh}, $$bufr, $len)==$len
418 $s->safe_sysread($bufr, $len)==$len
419 or $s->logconfess("get_data(): could not read message of length=$len bytes from socket: $!");
420 }
421 return $bufr;
422 }
423  
424 ## $ref = $s->get_ref_data()
425 ## + reads reference data from the socket with Storable::fd_retrieve()
426 ## + header should already have been read
427 sub get_ref_data {
428 $_[0]->vtrace("get_ref_data", @_[1..$#_]);
429 return
430 Storable::fd_retrieve($_[0]{fh})
431 || $_[0]->logconfess("get_ref_data(): fd_retrieve() failed");
432 }
433  
434 ## \$str_or_undef = $s->get_str_data($flags, $len)
435 ## \$str_or_undef = $s->get_str_data($flags, $len, \$str)
436 ## + reads string bytes from the socket (header should already have been read)
437 ## + returned value is auto-magically decoded
438 sub get_str_data {
439 $_[0]->vtrace("get_str_data", @_[1..$#_]);
440 my $s = shift;
441 my $bufr = $s->get_data(@_[1,2]);
442 $$bufr = '' if (!defined($$bufr)); ##-- get_data() returns empty string as undef
443 utf8::decode($$bufr) if ($_[0] & $sf_u8);
444 return $bufr;
445 }
446  
447  
448 ## $ref_or_undef = $s->get( ); ##-- SCALAR context, local buffer
449 ## ($flags,$len,$ref) = $s->get( ); ##-- LIST context, local buffer
450 ## $ref_or_undef = $s->get( \$buf ); ##-- SCALAR context, user buffer
451 ## ($flags,$len,$ref) = $s->get( \$buf ); ##-- LIST context, user buffer
452 ## + gets next message from the buffer
453 ## + if passed, \$buf is used as a data buffer,
454 ## - it will hold the string data actually read from the socket
455 ## - in the case of string messages, \$buf is also the value returned
456 ## - in the case of ref messages, \$buf is the serialized (nfreeze()) reference
457 ## - for undef or end-of-queue messages, $$buf will be set to undef
458 sub get {
459 $_[0]->vtrace("get", @_[1..$#_]);
460 my ($s,$bufr) = @_;
461 my ($flags,$len) = $s->get_header();
462 if ($flags & ($sf_eoq | $sf_undef)) {
463 $bufr = \undef;
464 } elsif ($flags & $sf_ref) {
465 $bufr = $s->get_ref_data();
466 } else {
467 $bufr = $s->get_str_data($flags,$len,$bufr);
468 }
469 return wantarray ? ($flags,$len,$bufr) : $bufr;
470 }
471  
472  
473 1; ##-- be happy
474  
475 __END__