blib/lib/App/Netdisco/Util/SNMPText.pm untested

filter: Statementstmt 0.0% 0 / 150 Branchbran 0.0% 0 / 78 Conditioncond 0.0% 0 / 25 MC/DCmcdc 0.0% 0 / 16 Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 304 CC 40 SCAR 32.6
CC
40
Cov
0%
_walk_config
56.0
_decode_octets
42.0
decode_snmp_data
42.0
CRAP 26.0
1 package App::Netdisco::Util::SNMPText;
2  
3 # DBD::Pg 3.3+ reads undecoded strings as Latin-1 under pg_enable_utf8, so SNMP text is decoded here first
4  
5 use Dancer qw/:syntax :script/;
6  
7 use App::Netdisco::Util::Permission 'acl_matches';
8 use App::Netdisco::Util::Configuration 'snmp_charset_maps';
9  
10 use Encode ();
11 use Try::Tiny;
12 use Scalar::Util 'blessed';
13  
14 use base 'Exporter';
15 our @EXPORT = ();
16 our @EXPORT_OK = qw/
17 decode_text_with
18 decode_snmp_text
19 decode_snmp_data
20 decode_cli_extra
21 snmp_charsets_for
22 reset_snmp_charsets_cache
23 looks_garbled
24 ungarble
25 scan_config_encoding
26 scan_stored_encoding
27 /;
28 our %EXPORT_TAGS = (all => \@EXPORT_OK);
29  
30 my %warned;
31 my %charsets_by_ip;
32 my $CHECK = Encode::FB_CROAK | Encode::LEAVE_SRC;
33  
34 =head1 NAME
35  
36 App::Netdisco::Util::SNMPText
37  
38 =head1 DESCRIPTION
39  
40 Helper functions to turn the octets of an SNMP text value into a character
41 string, without double encoding and without substituting U+FFFD.
42  
43 There are no default exports, however the C<:all> tag will export all
44 subroutines.
45  
46 =head1 EXPORT_OK
47  
48 =head2 snmp_charsets_for( $device )
49  
50 Returns an array reference of fallback charset names configured for the
51 device, without duplicates. The C<snmp_charset> setting is a list of maps
52 from ACL to charsets. Maps are read in list order; within a map, matching
53 ACL keys are read in alphabetical order, then C<group:__ANY__>.
54  
55 =cut
56  
57 sub snmp_charsets_for {
58 my ($device) = @_;
59 return [] unless $device;
60  
61 my (@charsets, %seen);
62 # a per-job override is merged in as written, after normalize_snmp_charset
63 foreach my $map (@{ snmp_charset_maps(setting('snmp_charset')) }) {
64 my @keys = ((sort { $a cmp $b } grep { $_ ne q{group:__ANY__} } keys %$map),
65 (exists $map->{'group:__ANY__'} ? 'group:__ANY__' : ()));
66 foreach my $key (@keys) {
67 next unless acl_matches($device, $key);
68 push @charsets, grep { not $seen{$_}++ } @{ $map->{$key} };
69 }
70 }
71 return \@charsets;
72 }
73  
74 =head2 reset_snmp_charsets_cache()
75  
76 Empties the cache by device IP which C<decode_snmp_text> keeps of
77 C<snmp_charsets_for>, so that one job walks the ACLs once per device. The
78 worker runner calls it at the start of every job, so a changed setting or
79 device applies to the next job.
80  
81 =cut
82  
83 sub reset_snmp_charsets_cache { %charsets_by_ip = () }
84  
85 sub _job_charsets_for {
86 my $device = shift;
87 return [] unless $device;
88 my $ip = $device->ip;
89 return snmp_charsets_for($device) unless defined $ip;
90 $charsets_by_ip{$ip} = snmp_charsets_for($device)
91 unless exists $charsets_by_ip{$ip};
92 return $charsets_by_ip{$ip};
93 }
94  
95 =head2 decode_text_with( $bytes, \@charsets )
96  
97 Returns the character string for C<$bytes>. Undef and empty values are
98 returned unchanged, as is a string which already holds characters above 0xFF.
99  
100 Plain ASCII is returned as is. Otherwise valid UTF-8 is tried first, then
101 each charset in the list (accepted only if encoding the result gives back
102 exactly C<$bytes> and it holds no private use or U+FFFD characters), and
103 lastly Latin-1, which accepts any octets. A charset name which L<Encode> does
104 not know is skipped, with one warning per process.
105  
106 In list context returns C<($text, $how)> where C<$how> is C<ascii>, C<UTF-8>,
107 the charset name, or C<latin1>.
108  
109 =cut
110  
111 sub decode_text_with {
112 my ($bytes, $charsets) = @_;
113 return (wantarray ? ($bytes, 'ascii') : $bytes)
114 if !defined $bytes or $bytes eq '';
115  
116 my ($text, $how) = _decode_octets($bytes, $charsets || []);
117 return wantarray ? ($text, $how) : $text;
118 }
119  
120 sub _decode_octets {
121 my ($bytes, $charsets) = @_;
122  
123 return ($bytes, 'UTF-8')
124 if utf8::is_utf8($bytes) and $bytes =~ m/[^\x00-\xFF]/;
125 return ($bytes, 'ascii') if $bytes !~ m/[^\x00-\x7F]/;
126  
127 my $utf8 = try { Encode::decode('UTF-8', $bytes, $CHECK) };
128 return ($utf8, 'UTF-8') if defined $utf8;
129  
130 # a code ref defers the per-device ACL walk until a fallback is needed
131 $charsets = $charsets->() if ref $charsets eq ref sub {};
132 foreach my $charset (@$charsets) {
133 my $text = _decode_round_trip($bytes, $charset);
134 return ($text, $charset) if defined $text;
135 }
136  
137 return (Encode::decode('iso-8859-1', $bytes), 'latin1');
138 }
139  
140 # A multi-byte charset can accept octets it does not mean, so only a result
141 # which encodes back to the same octets is trusted. Encode 3.21 also maps a
142 # lone 0xFF in GBK to private use U+F8F5, which round-trips, so those and
143 # U+FFFD are rejected too.
144 sub _decode_round_trip {
145 my ($bytes, $charset) = @_;
146  
147 if (not Encode::find_encoding($charset)) {
148 warning sprintf 'snmp_charset: unknown charset [%s], ignored', $charset
149 unless $warned{$charset}++;
150 return undef;
151 }
152  
153 return try {
154 my $text = Encode::decode($charset, $bytes, $CHECK);
155 ($text !~ m/[\p{Co}\x{FFFD}]/
156 and Encode::encode($charset, $text, $CHECK) eq $bytes) ? $text : undef;
157 } catch { undef };
158 }
159  
160 =head2 decode_snmp_text( $bytes, $device_or_undef, $field_label )
161  
162 Decodes as C<decode_text_with> does, using the charsets from
163 C<snmp_charsets_for> for the device, or none when the device is undef. The
164 charsets are looked up only when the value is neither ASCII nor UTF-8, and
165 once per device until C<reset_snmp_charsets_cache>. Returns the text. When
166 the value is neither UTF-8 nor in a configured charset, it is stored as
167 Latin-1 and a debug message names the device, C<$field_label> and the octets.
168  
169 =cut
170  
171 sub decode_snmp_text {
172 my ($bytes, $device, $field_label) = @_;
173 return $bytes if !defined $bytes or $bytes eq '';
174  
175 my ($text, $how) = _decode_octets($bytes,
176 sub { _job_charsets_for($device) });
177 debug sprintf ' [%s] %s bytes %s are not UTF-8 or a configured snmp_charset; stored as Latin-1',
178 ($device ? $device->ip : '-'), $field_label, unpack('H*', $bytes)
179 if $how eq 'latin1';
180  
181 return $text;
182 }
183  
184 =head2 decode_snmp_data( $data, $device_or_undef, $field_label )
185  
186 Returns a copy of C<$data> in which every defined plain scalar, in hashes and
187 arrays to any depth, has been through C<decode_snmp_text>. Hash keys are left
188 as they are, and blessed objects and code references pass through unchanged.
189 C<$field_label> defaults to C<data>. The argument is never modified.
190  
191 =cut
192  
193 sub decode_snmp_data {
194 my ($data, $device, $field_label) = @_;
195 $field_label = 'data' unless defined $field_label;
196  
197 return $data if blessed $data;
198 my $type = ref $data;
199 return [ map { decode_snmp_data($_, $device, $field_label) } @$data ]
200 if $type eq 'ARRAY';
201 return { map { $_ => decode_snmp_data($data->{$_}, $device, $field_label) } keys %$data }
202 if $type eq 'HASH';
203 return $data if $type;
204  
205 return decode_snmp_text($data, $device, $field_label);
206 }
207  
208 =head2 decode_cli_extra( $extra )
209  
210 Decodes the C<-e> text given to C<netdisco-do> for a C<cf_> action, which
211 arrives as raw octets, with no device charsets. Undef and empty values are
212 returned unchanged.
213  
214 =cut
215  
216 sub decode_cli_extra {
217 my ($extra) = @_;
218 return decode_text_with($extra, []);
219 }
220  
221 =head2 looks_garbled( $string )
222  
223 True when the string holds a character from U+00C2 to U+00F4 followed by one
224 from U+0080 to U+00BF, which is how UTF-8 octets look when read as Latin-1,
225 and its characters read as octets are valid UTF-8. Correct text such as an
226 accented letter before a non-breaking space or a closing guillemet fails the
227 second test.
228  
229 =cut
230  
231 sub looks_garbled {
232 my ($string) = @_;
233 return 0 unless defined $string and $string =~ m/[\x{C2}-\x{F4}][\x{80}-\x{BF}]/;
234 my $bytes = try { Encode::encode('iso-8859-1', $string, $CHECK) };
235 return 0 unless defined $bytes;
236 return (defined try { Encode::decode('UTF-8', $bytes, $CHECK) }) ? 1 : 0;
237 }
238  
239 =head2 ungarble( $string, \@charsets )
240  
241 Returns the text that C<$string> would have been had its characters been read
242 as octets, using C<decode_text_with>. Returns undef when the string holds a
243 character which Latin-1 cannot encode, so it cannot be garbled in that way.
244  
245 =cut
246  
247 sub ungarble {
248 my ($string, $charsets) = @_;
249 my $bytes = try { Encode::encode('iso-8859-1', $string, $CHECK) };
250 return undef unless defined $bytes;
251 return scalar decode_text_with($bytes, $charsets || []);
252 }
253  
254 =head2 scan_config_encoding( $config )
255  
256 Walks hashes (keys and values) and arrays in C<$config> and returns a list of
257 C<< { path => 'discover_no[2]', value => ..., suggestion => ... } >> for every
258 string which C<looks_garbled>. Other references are skipped. Reads only the
259 data it is given. Under the settings which hold device credentials
260 (C<device_auth>, C<snmp_auth>, C<community>, C<community_rw>) the value and
261 suggestion are C<(hidden)>.
262  
263 =cut
264  
265 my $CREDENTIAL_SETTINGS = qr/^(?:device_auth|snmp_auth|community|community_rw)\b/;
266  
267 sub scan_config_encoding {
268 my ($config) = @_;
269 my @findings;
270 _walk_config($config, '', \@findings);
271 foreach my $finding (grep { $_->{path} =~ $CREDENTIAL_SETTINGS } @findings) {
272 $finding->{$_} = '(hidden)' for qw/value suggestion/;
273 }
274 return @findings;
275 }
276  
277 sub _walk_config {
278 my ($node, $path, $findings) = @_;
279 my $type = ref $node;
280  
281 if (!$type) {
282 return unless looks_garbled($node);
283 push @$findings, { path => $path, value => $node,
284 suggestion => ungarble($node, []) };
285 }
286 elsif ($type eq 'ARRAY') {
287 _walk_config($node->[$_], "$path\[$_]", $findings) for 0 .. $#$node;
288 }
289 elsif ($type eq 'HASH') {
290 foreach my $key (sort keys %$node) {
291 my $child = length $path ? "$path.$key" : $key;
292 _walk_config($key, "$child (key)", $findings) if looks_garbled($key);
293 _walk_config($node->{$key}, $child, $findings);
294 }
295 }
296 }
297  
298 =head2 scan_stored_encoding( $schema, $limit )
299  
300 Reads the database only. Returns findings for stored text that looks garbled
301 or holds U+FFFD, in C<device.name>, C<description>, C<vendor>, C<os> and
302 C<os_ver>, C<device_port.descr>, C<device_vlan.description> and
303 C<device_port_ssid.ssid>. Each finding is
304 C<< { ip, column, value, suggestion } >> where C<suggestion> is undef for
305 U+FFFD, whose original octets are not recoverable. At most C<$limit>
306 findings are returned per column, followed by C<< { column, more => $count } >>
307 for the rest.
308  
309 =cut
310  
311 my @STORED_COLUMNS = (
312 [Device => 'device', 'name'], [Device => 'device', 'description'],
313 [Device => 'device', 'vendor'], [Device => 'device', 'os'],
314 [Device => 'device', 'os_ver'], [DevicePort => 'device_port', 'descr'],
315 [DeviceVlan => 'device_vlan', 'description'],
316 [DevicePortSsid => 'device_port_ssid', 'ssid'],
317 );
318  
319 sub scan_stored_encoding {
320 my ($schema, $limit) = @_;
321 # a character string, so DBD::Pg sends it as UTF-8; a non-ASCII byte literal
322 # would be upgraded as Latin-1, unless utf8.pm happened to be loaded first
323 my $pattern = "[\x{C2}-\x{F4}][\x{80}-\x{BF}]|\x{FFFD}";
324 my (@findings, %charsets);
325  
326 foreach my $spec (@STORED_COLUMNS) {
327 my ($source, $table, $column) = @$spec;
328 # the pattern also matches correct text, which looks_garbled then drops
329 my $rs = $schema->resultset($source)->search(
330 { $column => { '~' => $pattern } },
331 { columns => ['ip', $column], order_by => ['ip', $column] });
332 my ($shown, $more) = (0, 0);
333  
334 foreach my $row ($rs->all) {
335 my $value = $row->get_column($column);
336 my $garbled = looks_garbled($value);
337 next unless $garbled or $value =~ m/\x{FFFD}/;
338 if ($shown++ >= $limit) { $more++; next }
339  
340 my $ip = $row->get_column('ip');
341 $charsets{$ip} ||= do {
342 my $device = $schema->resultset('Device')->find($ip);
343 snmp_charsets_for($device);
344 };
345 push @findings, { ip => $ip, column => "$table.$column", value => $value,
346 suggestion => ($garbled ? ungarble($value, $charsets{$ip}) : undef) };
347 }
348 push @findings, { column => "$table.$column", more => $more } if $more;
349 }
350 return @findings;
351 }
352  
353 1;