File Coverage

blib/lib/IO/Socket/Netlink.pm
Criterion Covered Total %
statement 255 287 88.8
branch 77 116 66.3
condition 33 44 75.0
subroutine 74 82 90.2
pod 10 14 71.4
total 449 543 82.6


line stmt bran cond sub pod time code
1             # You may distribute under the terms of either the GNU General Public License
2             # or the Artistic License (the same terms as Perl itself)
3             #
4             # (C) Paul Evans, 2010-2016 -- leonerd@leonerd.org.uk
5              
6             package IO::Socket::Netlink;
7              
8 8     8   83817 use strict;
  8         18  
  8         270  
9 8     8   42 use warnings;
  8         14  
  8         279  
10 8     8   45 use base qw( IO::Socket );
  8         15  
  8         5758  
11              
12             our $VERSION = '0.05';
13              
14 8     8   194352 use Carp;
  8         48  
  8         606  
15              
16 8     8   47 use Socket qw( SOCK_RAW );
  8         13  
  8         1576  
17              
18 8         7230 use Socket::Netlink qw(
19             PF_NETLINK AF_NETLINK
20             NLMSG_NOOP NLMSG_DONE NLMSG_ERROR
21             NLM_F_REQUEST NLM_F_MULTI
22             pack_sockaddr_nl unpack_sockaddr_nl
23 8     8   1944 );
  8         14  
24              
25             __PACKAGE__->register_domain( AF_NETLINK );
26              
27             =head1 NAME
28              
29             C - Object interface to C domain sockets
30              
31             =head1 SYNOPSIS
32              
33             use Socket::Netlink;
34             use IO::Socket::Netlink;
35            
36             my $sock = IO::Socket::Netlink->new( Protocol => 0 ) or die "socket: $!";
37            
38             $sock->send_nlmsg( $sock->new_request(
39             nlmsg_type => 18,
40             nlmsg_flags => NLM_F_DUMP,
41             nlmsg => "\0\0\0\0\0\0\0\0",
42             ) ) or die "send: $!";
43            
44             $sock->recv_nlmsg( my $message, 65536 ) or die "recv: $!";
45            
46             printf "Received type=%d flags=%x:\n%v02x\n",
47             $message->nlmsg_type, $message->nlmsg_flags, $message->nlmsg;
48              
49             =head1 DESCRIPTION
50              
51             This module provides an object interface to C sockets on Linux, by
52             building on top of the L class. While useful on its own, it is
53             intended itself to serve as a base class, for particular netlink protocols to
54             extend.
55              
56             =cut
57              
58             =head1 CLASS METHODS
59              
60             =head2 register_protocol
61              
62             $class->register_protocol( $proto )
63              
64             May be called by a subclass implementing a Netlink protocol. If so, then any
65             object constructed using a known protocol on this base class will be
66             automatically reblessed into the appropriate package.
67              
68             =cut
69              
70             my %protocol2pkg;
71              
72             sub register_protocol
73             {
74 3     3 1 22 my ( $pkg, $proto ) = @_;
75 3         15 $protocol2pkg{$proto} = $pkg;
76             }
77              
78             =head1 CONSTRUCTOR
79              
80             =cut
81              
82             =head2 new
83              
84             $sock = IO::Socket::Netlink->new( %args )
85              
86             Creates a new C object.
87              
88             The recognised arguments are:
89              
90             =over 8
91              
92             =item Protocol => INT
93              
94             The netlink protocol. This is a required argument.
95              
96             =item Pid => INT
97              
98             Socket identifier (usually the process identifier)
99              
100             =item Groups => INT
101              
102             32bit bitmask of multicast groups to join
103              
104             =back
105              
106             =cut
107              
108             sub new
109             {
110 7     7 1 81 my $class = shift;
111 7         85 $class->SUPER::new( Domain => PF_NETLINK, @_ );
112             }
113              
114             sub configure
115             {
116 7     7 0 725 my $self = shift;
117 7         16 my ( $arg ) = @_;
118              
119 7   50     64 my $type = $arg->{Type} || SOCK_RAW;
120              
121 7 50       32 if( !exists $arg->{Protocol} ) {
122 0         0 croak "Require a Protocol for a Netlink socket";
123             }
124              
125 7 50       69 $self->socket( AF_NETLINK, $type, $arg->{Protocol} ) or return undef;
126              
127 7 50 50     586 $self->bind( pack_sockaddr_nl( $arg->{Pid} || 0, $arg->{Groups} || 0 ) ) or return undef;
      50        
128              
129 7 100       162 if( ref($self) eq __PACKAGE__ ) {
130 3 100       43 my $class = $protocol2pkg{$arg->{Protocol}} or return $self;
131 1         3 bless $self, $class;
132              
133 1         5 return $self->configure( $arg );
134             }
135             else {
136 4         27 return $self;
137             }
138             }
139              
140             =head1 METHODS
141              
142             =cut
143              
144             =head2 sockpid
145              
146             $pid = $sock->sockpid
147              
148             Returns the socket identifier
149              
150             =cut
151              
152             sub sockpid
153             {
154 1     1 1 2833 my $self = shift;
155 1         8 ( unpack_sockaddr_nl( $self->sockname ) )[0];
156             }
157              
158             =head2 sockgroups
159              
160             $groups = $sock->sockgroups
161              
162             Returns the 32bit bitmask of multicast groups
163              
164             =cut
165              
166             sub sockgroups
167             {
168 1     1 1 523 my $self = shift;
169 1         4 ( unpack_sockaddr_nl( $self->sockname ) )[1];
170             }
171              
172             # It is intended subclasses override this
173             sub message_class
174             {
175 6     6 0 35 return "IO::Socket::Netlink::_Message";
176             }
177              
178             # And possibly this
179             sub command_class
180             {
181 0     0 0 0 return shift->message_class;
182             }
183              
184             =head2 new_message
185              
186             $msg = $sock->new_message( %args )
187              
188             Returns a new message object containing the given arguments. The named
189             arguments are in fact read as an list of key/value pairs, not a hash, so order
190             is significant. The basic C keys should come first, followed by any
191             required by the inner level header.
192              
193             For more detail, see the L section below.
194              
195             =cut
196              
197             sub new_message
198             {
199 10     10 1 50 my $self = shift;
200 10         36 return $self->message_class->new( @_ );
201             }
202              
203             =head2 new_request
204              
205             $msg = $sock->new_request( %args )
206              
207             A convenience wrapper around C which sets the C
208             flag on the returned message.
209              
210             =cut
211              
212             sub new_request
213             {
214 3     3 1 5 my $self = shift;
215 3         11 my $message = $self->new_message( @_ );
216 3   50     12 $message->nlmsg_flags( ($message->nlmsg_flags||0) | NLM_F_REQUEST );
217 3         9 return $message;
218             }
219              
220             =head2 new_command
221              
222             $sock->new_command( %args )
223              
224             As C, but may use a different class for messages. This is for
225             such netlink protocols as C, which uses a different set of message
226             attributes for userland-to-kernel commands, as for kernel-to-userland event
227             messages.
228              
229             =cut
230              
231             sub new_command
232             {
233 0     0 1 0 my $self = shift;
234 0         0 my $message = $self->command_class->new( @_ );
235 0   0     0 $message->nlmsg_flags( ($message->nlmsg_flags||0) | NLM_F_REQUEST );
236 0         0 return $message;
237             }
238              
239             # undoc'ed for now
240             sub unpack_message
241             {
242 7     7 0 1502 my $self = shift;
243 7         34 return $self->message_class->unpack( @_ );
244             }
245              
246             =head2 send_nlmsg
247              
248             $sock->send_nlmsg( $message )
249              
250             Sends the given message object to the kernel. C<$message> should be a message
251             object, constructed using the socket's C factory method.
252              
253             =cut
254              
255             sub send_nlmsg
256             {
257 2     2 1 3 my $self = shift;
258 2         4 my ( $message ) = @_;
259              
260 2         8 $self->send( $message->pack );
261             }
262              
263             =head2 recv_nlmsg
264              
265             $sock->recv_nlmsg( $message, $maxlen )
266              
267             Receives a single message from the kernel. The C<$message> parameter should be
268             a variable, which will contain the new message object when this method returns
269             successfully.
270              
271             Sometimes the kernel will respond multiple messages in reply to just one. If
272             this may be the case, see instead C.
273              
274             This method returns success or failure depending only on the result of the
275             underlying socket C call. If a message was successfully received it
276             returns true, even if that message contains an error. To detect the error, see
277             the C accessor.
278              
279             =cut
280              
281             sub recv_nlmsg
282             {
283 2     2 1 4 my $self = shift;
284 2         4 my ( undef, $maxlen ) = @_;
285             # Holes in @_ because we'll unpack to here
286              
287 2         2 my $ret;
288              
289 2         3 do {
290 2         8 $ret = $self->recv( my $buffer, $maxlen );
291 2 50       44 defined $ret or return undef;
292              
293 2         7 $_[0] = $self->unpack_message( $buffer );
294             # Ignore NLMSG_NOOP and try again
295             } while( $_[0]->nlmsg_type == NLMSG_NOOP );
296              
297 2         7 return $ret;
298             }
299              
300             =head2 recv_nlmsgs
301              
302             $sock->recv_nlmsgs( \@messages, $maxlen )
303              
304             Receives message from the kernel. If the first message received has the
305             C flag, then messages will be collected up until the final
306             C which indicates the end of the list. Each message is pushed
307             into the C<@messages> array (which is I cleared initially), excluding
308             the final C.
309              
310             This method returns success or failure depending only on the result of the
311             underlying socket C call or calls. If any calls fails then the method
312             will return false. If messages were successfully received it returns true,
313             even if a message contains an error. To detect the error, see the
314             C accessor.
315              
316             =cut
317              
318             sub recv_nlmsgs
319             {
320 0     0 1 0 my $self = shift;
321 0         0 my ( $msgs, $maxlen ) = @_;
322              
323 0         0 my $buffer;
324             my $message;
325              
326 0         0 do {
327 0 0       0 defined $self->recv( $buffer, $maxlen ) or return;
328              
329 0         0 $message = $self->unpack_message( $buffer );
330             # Ignore NLMSG_NOOP and try again
331             } while( $message->nlmsg_type == NLMSG_NOOP );
332              
333 0         0 push @$msgs, $message;
334 0 0       0 return scalar @$msgs unless $message->nlmsg_flags & NLM_F_MULTI;
335              
336             # We may still have to make more recv calls:
337 0         0 while(1) {
338 0         0 while( defined $buffer ) {
339 0         0 $message = $self->message_class->unpack( $buffer );
340              
341 0 0       0 return scalar @$msgs if $message->nlmsg_type == NLMSG_DONE;
342              
343 0 0       0 push @$msgs, $message if $message->nlmsg_type != NLMSG_NOOP;
344             }
345              
346 0 0       0 defined $self->recv( $buffer, $maxlen ) or return;
347             }
348             }
349              
350             package IO::Socket::Netlink::_Message;
351              
352 8     8   51 use Carp;
  8         11  
  8         591  
353              
354 8         2731 use Socket::Netlink qw(
355             :DEFAULT
356             pack_nlmsghdr unpack_nlmsghdr pack_nlattrs unpack_nlattrs
357 8     8   64 );
  8         13  
358              
359             # Don't hard-depend on Sub::Name or Sub::Util since it's only a niceness for stack traces
360             BEGIN {
361 8 50   8   36 if( eval { require Sub::Name } ) {
  8 50       1972  
362 0         0 *subname = \&Sub::Name::subname;
363             }
364 8         4547 elsif( eval { require Sub::Util } ) {
365 8         6713 *subname = \&Sub::Util::set_subname;
366             }
367             else {
368             # Ignore the name, return the CODEref
369 0         0 *subname = sub { return $_[1] };
  0         0  
370             }
371             }
372              
373             =head1 MESSAGE OBJECTS
374              
375             Netlink messages are passed in to C and returned by C
376             and C in the form of objects, which wrap the protocol headers.
377             These objects are not directly constructed; instead you should use the
378             C method on the socket to build a new message to send.
379              
380             These objects exist also to wrap higher-level protocol fields, for messages in
381             some particular netlink protocol. A subclass of C would
382             likely use its own subclass of message object; extra fields may exist on these
383             objects.
384              
385             The following accessors may be used to set or obtain the fields in the
386             toplevel C structure:
387              
388             =cut
389              
390             sub new
391             {
392 17     17   51 my $class = shift;
393              
394 17         47 my $self = bless {}, $class;
395              
396             # Important that these happen in order
397 17         84 for ( my $i=0; $i<@_; $i+=2 ) {
398 50         62 my $method = $_[$i];
399 50         139 $self->$method( $_[$i+1] );
400             }
401              
402 17         51 return $self;
403             }
404              
405             sub pack : method
406             {
407 8     8   747 my $self = shift;
408              
409 8   100     35 return pack_nlmsghdr(
      100        
      100        
      100        
410             $self->nlmsg_type || 0,
411             $self->nlmsg_flags || 0,
412             $self->nlmsg_seq || 0,
413             $self->nlmsg_pid || 0,
414             $self->nlmsg
415             );
416             }
417              
418             sub unpack : method
419             {
420 7     7   33 my $class = shift;
421              
422 7         48 ( my ( $type, $flags, $seq, $pid, $body ), $_[0] ) = unpack_nlmsghdr( $_[0] );
423              
424 7         36 return $class->new(
425             nlmsg_type => $type,
426             nlmsg_flags => $flags,
427             nlmsg_seq => $seq,
428             nlmsg_pid => $pid,
429              
430             nlmsg => $body,
431             );
432             }
433              
434             =over 4
435              
436             =item * $message->nlmsg_type
437              
438             =item * $message->nlmsg_flags
439              
440             =item * $message->nlmsg_seq
441              
442             =item * $message->nlmsg_pid
443              
444             Set or obtain the fields in the C structure.
445              
446             =item * $message->nlmsg
447              
448             Set or obtain the packed message body. This method is intended to be
449             overridden by specific protocol implementations, to pack or unpack their own
450             structure type.
451              
452             =back
453              
454             Many Netlink-based protocols use standard message headers with attribute
455             bodies. Messages may start with structure layouts containing standard fields,
456             optionally followed by a sequence of one or more attributes in a standard
457             format. Each attribute is an ID number and a value.
458              
459             Because this class is intended to be subclassed by specific Netlink protocol
460             implementations, a number of class methods exist to declare metadata about the
461             protocol to assist generating the code required to support it. A message class
462             can declare its header format, which defines what extra accessor fields will be
463             created, and functions to pack and unpack the fields to or from the message
464             body. It can also declare its mapping of attribute names, ID numbers, and data
465             types. The message class will then support automatic encoding and decoding of
466             named attributes to or from the buffer.
467              
468             =cut
469              
470             sub nlmsg_type
471             {
472 32     32   1941 my $self = shift;
473 32 100       207 $self->{nlmsg_type} = $_[0] if @_;
474 32 100 100     148 if( @_ and $self->{nlmsg_type} == NLMSG_ERROR ) {
475 2         9 bless $self, "IO::Socket::Netlink::_ErrorMessage";
476             }
477 32 100       211 $self->{nlmsg_type} || 0;
478             }
479              
480             __PACKAGE__->is_header(
481             no_data => 1,
482             fields => [
483             [ nlmsg_type => "decimal", no_accessor => 1 ],
484             [ nlmsg_flags => "hex" ],
485             [ nlmsg_seq => "decimal" ],
486             [ nlmsg_pid => "decimal" ],
487             [ nlmsg => "bytes" ],
488             ],
489             );
490              
491 0     0   0 sub nlerr_error { 0 }
492              
493             =head2 $messageclass->is_header( %args )
494              
495             Called by a subclass of the message class, this class method declares that
496             messages of this particular type contain a message header. The four required
497             fields of C<%args> define how this behaves:
498              
499             =over 4
500              
501             =item * data => STRING
502              
503             Gives the name of the accessor method on its parent class which contains the
504             data buffer for the header. Normally this would be C for direct
505             subclasses of the base message class, but further subclasses would need to use
506             the trailing data buffer accessor of their parent class.
507              
508             =item * fields => ARRAY
509              
510             Reference to an array of definitions for the fields, in the order returned by
511             the pack function or expected by the unpack function. A new accessor method
512             will be created for each.
513              
514             Each field item should either be an ARRAY reference containing the following
515             structure, or a plain scalar denoting simply its name
516              
517             [ $name, $type, %opts ]
518              
519             The C<$type> defines the default value of the attribute, and determines how
520             it will be printed by the C method:
521              
522             =over 4
523              
524             =item * decimal
525              
526             Default 0, printed with printf "%d"
527              
528             =item * hex
529              
530             Default 0, printed with printf "%x"
531              
532             =item * bytes
533              
534             Default "", printed with printf "%v02x"
535              
536             =item * string
537              
538             Default "", printed with printf "%s"
539              
540             =back
541              
542             The following options are recognised:
543              
544             =over 8
545              
546             =item default => SCALAR
547              
548             A value to set for the field when the message header is packed, if no other
549             value has been provided.
550              
551             =back
552              
553             Fields defined simply by name are given the type of C with a default
554             value of 0, and no other options.
555              
556             =item * pack => CODE
557              
558             =item * unpack => CODE
559              
560             References to code that, respectively, packs a list of field values into a
561             packed string value, or unpacks a packed string value back out into a list of
562             values.
563              
564             =back
565              
566             When the header is declared, the base class's method named by C will be
567             overridden by generated code. This overridden method unpacks the values of the
568             fields into accessors when it is set, or packs the accessors into a value when
569             queried.
570              
571             This arrangement can be continued by further subclasses which implement
572             further levels of wrapping, if the pack and unpack functions implement a data
573             tail area; that is, the pack function takes an extra string buffer and the
574             unpack function returns one, for extra bytes after the header itself. The last
575             named field will then contain this buffer.
576              
577             =cut
578              
579             sub is_header
580             {
581 19     19   73 my $class = shift;
582 19         83 my %args = @_;
583              
584             # This function is also used internally to bootstrap the bottom layer. It
585             # contains a number of undocumented features.
586              
587 19         35 my $no_data = $args{no_data};
588              
589 19 50 66     128 my $datafield = $args{data} or $no_data or croak "Expected 'data'";
590              
591 19 50       82 ref( my $fields = $args{fields} ) eq "ARRAY" or croak "Expected 'fields' as ARRAY ref";
592              
593 19 50 66     110 $no_data or ref( my $packfunc = $args{pack} ) eq "CODE" or croak "Expected 'pack' as CODE ref";
594 19 50 66     106 $no_data or ref( my $unpackfunc = $args{unpack} ) eq "CODE" or croak "Expected 'unpack' as CODE ref";
595              
596 19         26 my @fieldnames;
597             my @formats;
598              
599 19         44 foreach my $f ( @$fields ) {
600 64 100       208 my ( $name, $type, %opts ) = ref $f eq "ARRAY" ? @$f
601             : ( $f, "decimal" );
602 64         94 push @fieldnames, $name;
603              
604 64         49 my $default;
605             my $format;
606 64 100       160 if( $type eq "decimal" ) {
    100          
    50          
    0          
607 38         41 $default = 0;
608 38         46 $format = "%d";
609             }
610             elsif( $type eq "hex" ) {
611 8         13 $default = 0;
612 8         10 $format = "%x";
613             }
614             elsif( $type eq "bytes" ) {
615 18         117 $default = "";
616 18         24 $format = "%v02x";
617             }
618             elsif( $type eq "string" ) {
619 0         0 $default = "";
620 0         0 $format = "%s";
621             }
622             else {
623 0         0 croak "Unrecognised field type '$type'";
624             }
625              
626 64 50       134 $default = $opts{default} if defined $opts{default};
627              
628 8     8   49 no strict 'refs';
  8         12  
  8         1004  
629              
630 56         352 *{"${class}::$name"} = subname $name => sub {
631 156     156   3786 my $self = shift;
        54      
        54      
        156      
        156      
        156      
        156      
        156      
        156      
        54      
        21      
        21      
632 156 100       486 $self->{$name} = shift if @_;
633 156 100       763 defined $self->{$name} ? $self->{$name} : $default;
634 64 100       449 } unless $opts{no_accessor};
635              
636 64         191 push @formats, "$name=$format";
637             }
638              
639 8     8   37 no strict 'refs';
  8         11  
  8         3819  
640 11         66 *{"${class}::$datafield"} = subname $datafield => sub {
641 9     9   12 my $self = shift;
        9      
        7      
642 9 100       21 if( @_ ) {
643 4         24 my @values = $unpackfunc->( shift );
644 4         25 $self->${ \$fieldnames[$_] }( $values[$_] ) for 0 .. $#fieldnames;
  10         31  
645             }
646              
647 9         22 return $packfunc->( map { $self->${ \$fieldnames[$_] }() } 0 .. $#fieldnames );
  23         32  
  23         57  
648 19 100       159 } unless $no_data;
649              
650             # Debugging support
651 19 100 100     123 if( defined $datafield and !defined &{"${class}::${datafield}_string"} ) {
  11         95  
652 8         27 my $formatstring = join ",", @formats;
653 8         60 *{"${class}::${datafield}_string"} = subname "${datafield}_string" => sub {
654 0     0   0 my $self = shift;
        0      
655 0         0 sprintf "${datafield}={$formatstring}", map $self->$_, @fieldnames;
656 8         61 };
657             }
658             }
659              
660             =head2 $messageclass->is_subclassed_by_type
661              
662             Called by a subclass of the message class, this class method declares that
663             messages are further subclassed according to the value of their C.
664             This will override the C accessor to re-C the object into
665             its declared subclass according to the types declared to the generated
666             C method.
667              
668             For example
669              
670             package IO::Socket::Netlink::SomeProto::_Message;
671             use base qw( IO::Socket::Netlink::_Message );
672              
673             __PACKAGE__->is_subclassed_by_type;
674              
675             package IO::Socket::Netlink::SomeProto::_InfoMessage;
676              
677             __PACKAGE__->register_nlmsg_type( 123 );
678              
679             ...
680              
681             At this point, if a message is constructed with this type number, either by
682             code calling C, or received from the socket, it will be
683             automatically reblessed to the appropriate class.
684              
685             This feature is intended for use by netlink protocols where different message
686             types have different stucture types.
687              
688             =cut
689              
690             sub is_subclassed_by_type
691             {
692 3     3   27 my $class = shift;
693              
694 3         5 my %type2pkg;
695              
696 8     8   49 no strict 'refs';
  8         10  
  8         2236  
697              
698 3         24 *{"${class}::register_nlmsg_type"} = subname "register_nlmsg_type" => sub {
699 4     4   17 my $pkg = shift;
        4      
700 4         6 my ( $type ) = @_;
701              
702 4         12 $type2pkg{$type} = $pkg;
703 3         30 };
704              
705             # SUPER:: happens in the context of the current package. So we need some
706             # massive hackery to make this work
707 3         288 my $SUPER_nlmsg_type = eval "
708             package $class;
709             sub { shift->SUPER::nlmsg_type( \@_ ) }
710             ";
711              
712 3         22 *{"${class}::nlmsg_type"} = subname "nlmsg_type" => sub {
713 15     15   1343 my $self = shift;
        15      
714 15         393 my $nlmsg_type = $SUPER_nlmsg_type->( $self, @_ );
715              
716 15 100       47 return $nlmsg_type unless @_;
717 7 50       19 return unless defined $nlmsg_type;
718              
719 7 100       24 my $pkg = $type2pkg{$nlmsg_type} or return; # no known type
720 6 100       30 return if ref $self eq $pkg; # already right type
721              
722             # Only rebless upwards or downwards, not sideways
723 2 50 33     6 if( ref $self eq $class or $pkg eq $class ) {
724 2         10 bless $self, $pkg;
725             }
726 3         24 };
727             }
728              
729             =head2 $messageclass->has_nlattrs( $fieldname, %attrs )
730              
731             Called by a subclass of the message class, this class method is intended to be
732             used by subclass authors to declare the attributes the message protocol
733             understands. The data declared here is used by the C method.
734              
735             C<$fieldname> should be the name of an existing method on the object class;
736             this method will be used to obtain or set the data field containing the
737             attributes (typically this will be the trailing message body). C<%attrs>
738             should be a hash, mapping symbolic names of fields into their typeid and
739             data format. Each entry should be of the form
740              
741             $name => [ $typeid, $datatype ]
742              
743             When the C method is packing attributes into the message body, it will
744             read attributes by C<$name> and encode them using the given C<$datatype> to
745             store in the body by C<$typeid>. When it is unpacking attributes from the
746             body, it will use the C<$typeid> to decode the data, and return it in a hash
747             key of the given C<$name>.
748              
749             =cut
750              
751             my %attr_bytype; # typeid => [ name, unpacker ]
752             my %attr_byname; # name => [ typeid, packer ]
753              
754             sub has_nlattrs
755             {
756 3     3   39 my $class = shift;
757 3         17 my ( $fieldname, %attrs ) = @_;
758              
759 3 50       36 my $fieldfunc = $class->can( $fieldname )
760             or croak "$class cannot $fieldname";
761              
762             {
763 8     8   44 no strict 'refs';
  8         11  
  8         10256  
  3         7  
764 3         5 *{"${class}::nlattrdata"} = $fieldfunc;
  3         18  
765             }
766              
767 3         13 foreach my $name ( keys %attrs ) {
768 16         15 my ( $typeid, $datatype ) = @{ $attrs{$name} };
  16         26  
769              
770 16 50       94 my $packer = $class->can( "pack_nlattr_$datatype" ) or
771             croak "$class cannot pack_nlattr_$datatype";
772 16 50       84 my $unpacker = $class->can( "unpack_nlattr_$datatype" ) or
773             croak "$class cannot unpack_nlattr_$datatype";
774              
775 16         38 $attr_bytype{$class}{$typeid} = [ $name, $unpacker ];
776 16         46 $attr_byname{$class}{$name} = [ $typeid, $packer ];
777             }
778             }
779              
780             =pod
781              
782             The following standard definitions exist for C<$datatype>:
783              
784             =over 4
785              
786             =cut
787              
788             =item * u8
789              
790             An unsigned 8-bit number
791              
792             =cut
793              
794 2     2   14 sub pack_nlattr_u8 { pack "C", $_[1] }
795 6     6   14 sub unpack_nlattr_u8 { unpack "C", $_[1] }
796              
797             =item * u16
798              
799             An unsigned 16-bit number
800              
801             =cut
802              
803 2     2   14 sub pack_nlattr_u16 { pack "S", $_[1] }
804 5     5   18 sub unpack_nlattr_u16 { unpack "S", $_[1] }
805              
806             =item * u32
807              
808             An unsigned 32-bit number
809              
810             =cut
811              
812 2     2   9 sub pack_nlattr_u32 { pack "L", $_[1] }
813 9     9   23 sub unpack_nlattr_u32 { unpack "L", $_[1] }
814              
815             =item * u64
816              
817             An unsigned 64-bit number
818              
819             =cut
820              
821 0     0   0 sub pack_nlattr_u64 { pack "Q", $_[1] }
822 0     0   0 sub unpack_nlattr_u64 { unpack "Q", $_[1] }
823              
824             =item * asciiz
825              
826             A NULL-terminated string of ASCII text
827              
828             =cut
829              
830 3     3   25 sub pack_nlattr_asciiz { pack "Z*", $_[1] }
831 5     5   14 sub unpack_nlattr_asciiz { unpack "Z*", $_[1] }
832              
833             =item * raw
834              
835             No encoding or decoding will take place; the value contains the raw byte
836             buffer
837              
838             =cut
839              
840 1     1   4 sub pack_nlattr_raw { $_[1] }
841 3     3   5 sub unpack_nlattr_raw { $_[1] }
842              
843             =item * nested
844              
845             The buffer itself contains more attributes in the same schema. These will be
846             taken or returned in a HASH reference.
847              
848             =cut
849              
850 1     1   11 sub pack_nlattr_nested { $_[0]->_pack_nlattrs( $_[1] ) }
851 3     3   16 sub unpack_nlattr_nested { $_[0]->_unpack_nlattrs( $_[1] ) }
852              
853             =back
854              
855             A subclass can define new data types by providing methods called
856             C and C which will be used to
857             encode or decode the attribute value into a string buffer.
858              
859             =cut
860              
861             =head2 $message->nlattrs( \%newattrs )
862              
863             Sets the message body field by encoding the attributes given by C<%newattrs>,
864             keyed by name, into Netlink attribute values, by using the definitions
865             declared by the subclass's C method.
866              
867             =head2 \%attrs = $message->nlattrs
868              
869             Returns the decoded attributes from the message body field.
870              
871             =cut
872              
873             sub _pack_nlattrs
874             {
875 10     10   9 my $self = shift;
876 10         16 my $class = ref $self;
877 10         12 my ( $values ) = @_;
878              
879 10 50       27 my $attrmap = $attr_byname{$class} or
880             croak "No attribute defintions for $class have been declared";
881              
882 10         9 my %attrs;
883 10         30 foreach my $name ( keys %$values ) {
884 9 50       19 $attrmap->{$name} or croak "Unknown netlink message attribute $name";
885 9         9 my ( $typeid, $packer ) = @{ $attrmap->{$name} };
  9         29  
886 9         23 $attrs{$typeid} = $packer->( $self, $values->{$name} );
887             }
888              
889 10         67 return pack_nlattrs( %attrs );
890             }
891              
892             sub _unpack_nlattrs
893             {
894 8     8   9 my $self = shift;
895 8         12 my $class = ref $self;
896 8         9 my ( $data ) = @_;
897              
898 8 50       19 my $attrmap = $attr_bytype{$class} or
899             croak "No attribute definitions for $class have been declared";
900              
901 8         43 my %attrs = unpack_nlattrs( $data );
902              
903 8         12 my %values;
904 8         18 foreach my $typeid ( keys %attrs ) {
905 34 100       58 $attrmap->{$typeid} or next;
906 30         24 my ( $name, $unpacker ) = @{ $attrmap->{$typeid} };
  30         37  
907 30         43 $values{$name} = $unpacker->( $self, $attrs{$typeid} );
908             }
909              
910 8         88 return \%values;
911             }
912              
913             sub nlattrs
914             {
915 14     14   3952 my $self = shift;
916              
917 14 100       30 if( @_ ) {
918 9         31 $self->nlattrdata( $self->_pack_nlattrs( @_ ) );
919             }
920             else {
921 5         12 return $self->_unpack_nlattrs( $self->nlattrdata );
922             }
923             }
924              
925             =head2 $value = $message->get_nlattr( $name )
926              
927             Returns the decoded value of a single attribute from the message body field.
928             Similar to
929              
930             $value = $message->nlattrs->{$name}
931              
932             except it does not incur the extra cost of decoding the other attribute values
933             that remain unused.
934              
935             =cut
936              
937             sub get_nlattr
938             {
939 1     1   2 my $self = shift;
940 1         3 my $class = ref $self;
941 1         2 my ( $wantname ) = @_;
942              
943 1 50       5 my $attrmap = $attr_bytype{$class} or
944             croak "No attribute definitions for $class have been declared";
945              
946 1         3 my %attrs = unpack_nlattrs( $self->nlattrdata );
947              
948 1         5 foreach my $typeid ( keys %attrs ) {
949 6 50       10 $attrmap->{$typeid} or next;
950 6         6 my ( $name, $unpacker ) = @{ $attrmap->{$typeid} };
  6         7  
951 6 100       21 return $unpacker->( $self, $attrs{$typeid} ) if $name eq $wantname;
952             }
953              
954 0         0 return undef;
955             }
956              
957             =head2 $message->change_nlattrs( %newvalues )
958              
959             Changes the stored values of the given attributes in the message body field.
960             Similar to
961              
962             $message->nlattrs( { %{ $message->nlattrs }, %newvalues } );
963              
964             except it does not incur the extra cost of decoding and reencoding the
965             unmodified attribute values.
966              
967             A value of C may be assigned to delete an attribute.
968              
969             =cut
970              
971             sub change_nlattrs
972             {
973 2     2   4 my $self = shift;
974 2         4 my $class = ref $self;
975 2         5 my %newvalues = @_;
976              
977 2 50       8 my $attrmap = $attr_byname{$class} or
978             croak "No attribute definitions for $class have been declared";
979              
980 2         4 my %attrs = unpack_nlattrs( $self->nlattrdata );
981              
982 2         8 foreach my $name ( keys %newvalues ) {
983 3 50       8 $attrmap->{$name} or croak "Unknown netlink message attribute $name";
984 3         4 my ( $typeid, $packer ) = @{ $attrmap->{$name} };
  3         5  
985 3 100       7 if( defined( my $value = $newvalues{$name} ) ) {
986 2         4 $attrs{$typeid} = $packer->( $self, $newvalues{$name} );
987             }
988             else {
989 1         3 delete $attrs{$typeid};
990             }
991             }
992              
993 2         13 $self->nlattrdata( pack_nlattrs( %attrs ) );
994             }
995              
996             =pod
997              
998             The following accessors are provided for debugging purposes
999              
1000             =cut
1001              
1002             =head2 $str = $message->nlmsg_type_string
1003              
1004             Renders the message type into a readable string form. Subclasses may wish to
1005             override this method to return other strings they recognise, or call to
1006             C if they don't.
1007              
1008             =cut
1009              
1010             # Some useful debugging accessors
1011             sub nlmsg_type_string
1012             {
1013 4     4   6 my $self = shift;
1014 4   100     13 my $type = $self->nlmsg_type || 0;
1015 4 50       56 return $type == NLMSG_NOOP ? "NLMSG_NOOP" :
    100          
    50          
1016             $type == NLMSG_DONE ? "NLMSG_DONE" :
1017             $type == NLMSG_ERROR ? "NLMSG_ERROR" :
1018             "$type";
1019             }
1020              
1021             =head2 $str = $message->nlmsg_flags_string
1022              
1023             Renders the flags into a readable string form. Each flag present is named,
1024             joined by C<|> characters.
1025              
1026             =cut
1027              
1028             sub nlmsg_flags_string
1029             {
1030 4     4   9 my $self = shift;
1031 4   100     10 my $flags = $self->nlmsg_flags || 0;
1032 4         9 my @flags;
1033              
1034 4         22 foreach my $f (qw(
1035             NLM_F_REQUEST NLM_F_MULTI NLM_F_ACK NLM_F_ECHO
1036             NLM_F_ROOT NLM_F_MATCH NLM_F_ATOMIC NLM_F_DUMP
1037             NLM_F_REPLACE NLM_F_EXCL NLM_F_CREATE NLM_F_APPEND
1038             )) {
1039 6         21 my $val = __PACKAGE__->$f;
1040 6 100       18 push @flags, $f if $flags & $val;
1041 6         12 $flags &= ~$val;
1042              
1043 6 100       24 last unless $flags;
1044             }
1045              
1046 4 50       11 push @flags, sprintf "0x%x", $flags if $flags;
1047              
1048 4 100       30 return @flags ? join "|", @flags : "0";
1049             }
1050              
1051             =head2 $str = $message->nlmsg_string
1052              
1053             Intended for subclasses to override, to include more of their own information
1054             about nested headers.
1055              
1056             =cut
1057              
1058             sub nlmsg_string
1059             {
1060 2     2   3 my $self = shift;
1061 2         4 return sprintf "nlmsg={%d bytes}", length $self->nlmsg;
1062             }
1063              
1064             =head2 $str = $message->STRING
1065              
1066             =head2 $str = "$message"
1067              
1068             Returns a human-readable string form of the message, giving details of the
1069             values of the fields. Provided primarily for debugging purposes.
1070              
1071             =cut
1072              
1073 8     8   9581 use overload '""' => "STRING";
  8         7401  
  8         62  
1074             sub STRING
1075             {
1076 4     4   1244 my $self = shift;
1077 4   100     26 return sprintf "%s(type=%s,flags=%s,seq=%d,pid=%d,%s)",
      100        
1078             ref $self,
1079             $self->nlmsg_type_string,
1080             $self->nlmsg_flags_string,
1081             $self->nlmsg_seq || 0,
1082             $self->nlmsg_pid || 0,
1083             $self->nlmsg_string;
1084             }
1085              
1086             package IO::Socket::Netlink::_ErrorMessage;
1087              
1088 8     8   1302 use base qw( IO::Socket::Netlink::_Message );
  8         12  
  8         3200  
1089 8         997 use Socket::Netlink qw(
1090             pack_nlmsgerr unpack_nlmsgerr
1091 8     8   57 );
  8         12  
1092              
1093             =head1 ERROR MESSAGE OBJECTS
1094              
1095             If a message object has its C field set to C then the
1096             object will be reblessed into a subclass that encapsulates the error message.
1097              
1098             =head2 $message->nlerr_error
1099              
1100             Accessor for the error value from the kernel. This will be a system error
1101             value such used by C<$!>. This accessor also exists on non-error messages, but
1102             returns false. This makes it easy to test for an error after C:
1103              
1104             $sock->recv_nlmsg( my $message, 2**15 ) or die "Cannot recv - $!";
1105             ( $! = $message->nlerr_error ) and die "Received NLMSG_ERROR - $!";
1106              
1107             =head2 $message->nlerr_msg
1108              
1109             Accessor for the original netlink message header that invoked the error. This
1110             value may be unpacked using C.
1111              
1112             =cut
1113              
1114             __PACKAGE__->is_header(
1115             data => "nlmsg",
1116             fields => [
1117             [ nlerr_error => "decimal" ],
1118             [ nlerr_msg => "bytes" ],
1119             ],
1120             pack => \&pack_nlmsgerr,
1121             unpack => \&unpack_nlmsgerr,
1122             );
1123              
1124             =head1 SEE ALSO
1125              
1126             =over 4
1127              
1128             =item *
1129              
1130             L - interface to Linux's C socket family
1131              
1132             =back
1133              
1134             =head1 AUTHOR
1135              
1136             Paul Evans
1137              
1138             =cut
1139              
1140             0x55AA;