| 1 | package App::Netdisco::Util::Web; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use Dancer ':syntax'; | ||
| 7 | use Dancer::Plugin::DBIC 'schema'; | ||
| 8 | |||
| 9 | use App::Netdisco::Util::Permission 'check_acl'; | ||
| 10 | |||
| 11 | use Time::Piece; | ||
| 12 | use Time::Seconds; | ||
| 13 | use HTML::Entities (); | ||
| 14 | use URI (); | ||
| 15 | use URI::QueryParam (); | ||
| 16 | use Try::Tiny; | ||
| 17 | |||
| 18 | use base 'Exporter'; | ||
| 19 | our @EXPORT = (); | ||
| 20 | our @EXPORT_OK = qw/ | ||
| 21 | sort_port sort_modules | ||
| 22 | interval_to_daterange | ||
| 23 | sql_match | ||
| 24 | request_is_device | ||
| 25 | request_is_api | ||
| 26 | request_is_api_report | ||
| 27 | request_is_api_search | ||
| 28 | trusted_client_address | ||
| 29 | warn_forwarded_address_ignored | ||
| 30 | device_display_name | ||
| 31 | page_title | ||
| 32 | pane_chrome | ||
| 33 | pane_history_header | ||
| 34 | escape_for_script_context | ||
| 35 | escape_results_token | ||
| 36 | omit_empty_columns | ||
| 37 | tacacs_configured | ||
| 38 | tacacs_unavailable | ||
| 39 | tacacs_startup_warning | ||
| 40 | /; | ||
| 41 | our %EXPORT_TAGS = (all => \@EXPORT_OK); | ||
| 42 | |||
| 43 | =head1 NAME | ||
| 44 | |||
| 45 | App::Netdisco::Util::Web | ||
| 46 | |||
| 47 | =head1 DESCRIPTION | ||
| 48 | |||
| 49 | A set of helper subroutines to support parts of the Netdisco application. | ||
| 50 | |||
| 51 | There are no default exports, however the C<:all> tag will export all | ||
| 52 | subroutines. | ||
| 53 | |||
| 54 | =head1 EXPORT_OK | ||
| 55 | |||
| 56 | =head2 request_is_device | ||
| 57 | |||
| 58 | Client has requested device content under C<.../device> or C<.../device/ports>. | ||
| 59 | |||
| 60 | =cut | ||
| 61 | |||
| 62 | sub request_is_device { | ||
| 63 | return ( | ||
| 64 | index(request->path, uri_for('/device')->path) == 0 | ||
| 65 | or | ||
| 66 | index(request->path, uri_for('/ajax/content/device/details')->path) == 0 | ||
| 67 | or | ||
| 68 | index(request->path, uri_for('/ajax/content/device/ports')->path) == 0 | ||
| 69 | ); | ||
| 70 | } | ||
| 71 | |||
| 72 | =head2 request_is_api | ||
| 73 | |||
| 74 | Client has requested JSON format data and an endpoint under C</api>. | ||
| 75 | |||
| 76 | =cut | ||
| 77 | |||
| 78 | sub request_is_api { | ||
| 79 | # /api/ paths are always API endpoints regardless of Accept header | ||
| 80 | return 1 if index(request->path, uri_for('/api/')->path) == 0; | ||
| 81 | # for other paths, require Accept: json and a return_url pointing to /api/ | ||
| 82 | return ((request->accept and request->accept =~ m/(?:json|javascript)/) | ||
| 83 | and param('return_url') | ||
| 84 | and index(param('return_url'), uri_for('/api/')->path) == 0); | ||
| 85 | } | ||
| 86 | |||
| 87 | =head2 request_is_api_report | ||
| 88 | |||
| 89 | Same as C<request_is_api> but also requires path to start "C</api/v1/report/...>". | ||
| 90 | |||
| 91 | =cut | ||
| 92 | |||
| 93 | sub request_is_api_report { | ||
| 94 | return (request_is_api and ( | ||
| 95 | index(request->path, uri_for('/api/v1/report/')->path) == 0 | ||
| 96 | or | ||
| 97 | (param('return_url') | ||
| 98 | and index(param('return_url'), uri_for('/api/v1/report/')->path) == 0) | ||
| 99 | )); | ||
| 100 | } | ||
| 101 | |||
| 102 | =head2 request_is_api_search | ||
| 103 | |||
| 104 | Same as C<request_is_api> but also requires path to start "C</api/v1/search/...>". | ||
| 105 | |||
| 106 | =cut | ||
| 107 | |||
| 108 | sub request_is_api_search { | ||
| 109 | return (request_is_api and ( | ||
| 110 | index(request->path, uri_for('/api/v1/search/')->path) == 0 | ||
| 111 | or | ||
| 112 | (param('return_url') | ||
| 113 | and index(param('return_url'), uri_for('/api/v1/search/')->path) == 0) | ||
| 114 | )); | ||
| 115 | } | ||
| 116 | |||
| 117 | =head2 trusted_client_address | ||
| 118 | |||
| 119 | The client address to make a security decision with. | ||
| 120 | |||
| 121 | This is the peer that opened the connection, unless that peer is named in the | ||
| 122 | C<trusted_proxies> setting, in which case it is the client named in the | ||
| 123 | C<X-Forwarded-For> chain that peer forwarded. The chain is read from its | ||
| 124 | nearest hop leftwards, stepping over any address which is itself a trusted | ||
| 125 | proxy, so a deployment two proxies deep resolves to the visitor rather than to | ||
| 126 | the inner proxy. | ||
| 127 | |||
| 128 | C<trusted_proxies> takes the usual access control list forms, so a Host Group | ||
| 129 | name works as well as a literal list. | ||
| 130 | |||
| 131 | A client on a UNIX socket is treated as the loopback address. | ||
| 132 | |||
| 133 | =cut | ||
| 134 | |||
| 135 | sub trusted_client_address { | ||
| 136 | my $peer = _socket_peer_address(); | ||
| 137 | |||
| 138 | return $peer unless _is_trusted_proxy($peer); | ||
| 139 | |||
| 140 | my @chain = map { _unmapped($_) } grep { length } split m/\s*,\s*/, | ||
| 141 | (request->env->{HTTP_X_FORWARDED_FOR} || ''); | ||
| 142 | return $peer unless scalar @chain; | ||
| 143 | |||
| 144 | while (scalar @chain > 1 and _is_trusted_proxy($chain[-1])) { | ||
| 145 | pop @chain; | ||
| 146 | } | ||
| 147 | |||
| 148 | return $chain[-1]; | ||
| 149 | } | ||
| 150 | |||
| 151 | sub _socket_peer_address { | ||
| 152 | my $env = request->env; | ||
| 153 | |||
| 154 | # bin/netdisco-web-fg keeps the socket peer here. | ||
| 155 | # A UNIX socket client can only be local. | ||
| 156 | if (exists $env->{'netdisco.peer_address'}) { | ||
| 157 | return '127.0.0.1' if not defined $env->{'netdisco.peer_address'}; | ||
| 158 | return _unmapped($env->{'netdisco.peer_address'}); | ||
| 159 | } | ||
| 160 | |||
| 161 | # without that entry, nothing overwrote REMOTE_ADDR | ||
| 162 | return _unmapped($env->{REMOTE_ADDR}); | ||
| 163 | } | ||
| 164 | |||
| 165 | # dual-stack listeners report an IPv4 peer in its IPv4-mapped IPv6 form | ||
| 166 | sub _unmapped { | ||
| 167 | my $address = shift; | ||
| 168 | return $address unless defined $address; | ||
| 169 | (my $plain = $address) =~ s/^::ffff:(?=\d+(?:\.\d+){3}$)//i; | ||
| 170 | return $plain; | ||
| 171 | } | ||
| 172 | |||
| 173 | sub _is_trusted_proxy { | ||
| 174 | my $address = shift; | ||
| 175 | return false unless $address; | ||
| 176 | |||
| 177 | # check_acl, not the acl_matches wrappers: both answer true for an absent or | ||
| 178 | # empty list, which here would trust every peer. | ||
| 179 | return check_acl($address, setting('trusted_proxies')) ? true : false; | ||
| 180 | } | ||
| 181 | |||
| 182 | =head2 warn_forwarded_address_ignored( $what ) | ||
| 183 | |||
| 184 | Log that C<$what> refused a client whose request carried a forwarded header | ||
| 185 | that C<trusted_proxies> keeps out of the decision, because it did not arrive | ||
| 186 | from a listed proxy. | ||
| 187 | |||
| 188 | =cut | ||
| 189 | |||
| 190 | sub warn_forwarded_address_ignored { | ||
| 191 | my $what = shift; | ||
| 192 | return unless request->forwarded_for_address; | ||
| 193 | return if _is_trusted_proxy(_socket_peer_address()); | ||
| 194 | |||
| 195 | # The refusal is otherwise silent, and nothing else names the setting that | ||
| 196 | # governs it. No addresses: this reaches the normal log. | ||
| 197 | warning "$what refused a client whose X-Forwarded-For was not used," | ||
| 198 | . " because the request did not arrive from an address named in" | ||
| 199 | . " trusted_proxies; list the proxy there if one is in front" | ||
| 200 | . " of the web server"; | ||
| 201 | } | ||
| 202 | |||
| 203 | =head2 sql_match( $value, $exact? ) | ||
| 204 | |||
| 205 | Convert wildcard characters "C<*>" and "C<?>" to "C<%>" and "C<_>" | ||
| 206 | respectively. | ||
| 207 | |||
| 208 | Pass a true value to C<$exact> to only substitute the existing wildcards, and | ||
| 209 | not also add "C<*>" to each end of the value. | ||
| 210 | |||
| 211 | In list context, returns two values, the translated value, and also an | ||
| 212 | L<SQL::Abstract> LIKE clause. | ||
| 213 | |||
| 214 | =cut | ||
| 215 | |||
| 216 | sub sql_match { | ||
| 217 | my ($text, $exact) = @_; | ||
| 218 | return unless $text; | ||
| 219 | |||
| 220 | $text =~ s/^\s+//; | ||
| 221 | $text =~ s/\s+$//; | ||
| 222 | |||
| 223 | $text =~ s/[*]+/%/g; | ||
| 224 | $text =~ s/[?]/_/g; | ||
| 225 | |||
| 226 | $text = '%'. $text . '%' unless $exact; | ||
| 227 | $text =~ s/\%+/%/g; | ||
| 228 | |||
| 229 | return ( wantarray ? ($text, {-ilike => $text}) : $text ); | ||
| 230 | } | ||
| 231 | |||
| 232 | =head2 sort_port( $a, $b ) | ||
| 233 | |||
| 234 | Sort port names of various types used by device vendors. Interface is as | ||
| 235 | Perl's own C<sort> - two input args and an integer return value. | ||
| 236 | |||
| 237 | =cut | ||
| 238 | |||
| 239 | sub sort_port { | ||
| 240 | my ($aval, $bval) = @_; | ||
| 241 | |||
| 242 | # hack for foundry "10GigabitEthernet" -> cisco-like "TenGigabitEthernet" | ||
| 243 | $aval = $1 if $aval =~ qr/^10(GigabitEthernet.+)$/; | ||
| 244 | $bval = $1 if $bval =~ qr/^10(GigabitEthernet.+)$/; | ||
| 245 | |||
| 246 | my $numbers = qr{^(\d+)$}; | ||
| 247 | my $numeric = qr{^([\d\.]+)$}; | ||
| 248 | my $dotted_numeric = qr{^(\d+)[:.](\d+)$}; | ||
| 249 | my $letter_number = qr{^([a-zA-Z]+)(\d+)$}; | ||
| 250 | my $wordcharword = qr{^([^:\/.]+)[-\ :\/\.]+([^:\/.0-9]+)(\d+)?$}; #port-channel45 | ||
| 251 | my $netgear = qr{^Slot: (\d+) Port: (\d+) }; # "Slot: 0 Port: 15 Gigabit - Level" | ||
| 252 | my $ciscofast = qr{^ | ||
| 253 | # Word Number slash (Gigabit0/) | ||
| 254 | (\D+)(\d+)[\/:] | ||
| 255 | # Groups of symbol float (/5.5/5.5/5.5), separated by slash or colon | ||
| 256 | ([\/:\.\d]+) | ||
| 257 | # Optional dash (-Bearer Channel) | ||
| 258 | (-.*)? | ||
| 259 | $}x; | ||
| 260 | |||
| 261 | my @a = (); my @b = (); | ||
| 262 | |||
| 263 | if ($aval =~ $dotted_numeric) { | ||
| 264 | @a = ($1,$2); | ||
| 265 | } elsif ($aval =~ $letter_number) { | ||
| 266 | @a = ($1,$2); | ||
| 267 | } elsif ($aval =~ $netgear) { | ||
| 268 | @a = ($1,$2); | ||
| 269 | } elsif ($aval =~ $numbers) { | ||
| 270 | @a = ($1); | ||
| 271 | } elsif ($aval =~ $ciscofast) { | ||
| 272 | @a = ($1,$2); | ||
| 273 | push @a, split(/[:\/]/,$3); | ||
| 274 | push @a, $4 if defined $4; | ||
| 275 | } elsif ($aval =~ $wordcharword) { | ||
| 276 | @a = ($1,$2,$3); | ||
| 277 | } else { | ||
| 278 | @a = ($aval); | ||
| 279 | } | ||
| 280 | |||
| 281 | if ($bval =~ $dotted_numeric) { | ||
| 282 | @b = ($1,$2); | ||
| 283 | } elsif ($bval =~ $letter_number) { | ||
| 284 | @b = ($1,$2); | ||
| 285 | } elsif ($bval =~ $netgear) { | ||
| 286 | @b = ($1,$2); | ||
| 287 | } elsif ($bval =~ $numbers) { | ||
| 288 | @b = ($1); | ||
| 289 | } elsif ($bval =~ $ciscofast) { | ||
| 290 | @b = ($1,$2); | ||
| 291 | push @b, split(/[:\/]/,$3); | ||
| 292 | push @b, $4 if defined $4; | ||
| 293 | } elsif ($bval =~ $wordcharword) { | ||
| 294 | @b = ($1,$2,$3); | ||
| 295 | } else { | ||
| 296 | @b = ($bval); | ||
| 297 | } | ||
| 298 | |||
| 299 | # Equal until proven otherwise | ||
| 300 | my $val = 0; | ||
| 301 | while (scalar(@a) or scalar(@b)){ | ||
| 302 | # carried around from the last find. | ||
| 303 | last if $val != 0; | ||
| 304 | |||
| 305 | my $a1 = shift @a; | ||
| 306 | my $b1 = shift @b; | ||
| 307 | |||
| 308 | # A has more components - loses | ||
| 309 | unless (defined $b1){ | ||
| 310 | $val = 1; | ||
| 311 | last; | ||
| 312 | } | ||
| 313 | |||
| 314 | # A has less components - wins | ||
| 315 | unless (defined $a1) { | ||
| 316 | $val = -1; | ||
| 317 | last; | ||
| 318 | } | ||
| 319 | |||
| 320 | if ($a1 =~ $numeric and $b1 =~ $numeric){ | ||
| 321 | $val = $a1 <=> $b1; | ||
| 322 | } elsif ($a1 ne $b1) { | ||
| 323 | $val = $a1 cmp $b1; | ||
| 324 | } | ||
| 325 | } | ||
| 326 | |||
| 327 | return $val; | ||
| 328 | } | ||
| 329 | |||
| 330 | =head2 sort_modules( $modules ) | ||
| 331 | |||
| 332 | Sort devices modules into tree hierarchy based upon position and parent - | ||
| 333 | input arg is module list. | ||
| 334 | |||
| 335 | =cut | ||
| 336 | |||
| 337 | sub sort_modules { | ||
| 338 | my $input = shift; | ||
| 339 | my %modules; | ||
| 340 | |||
| 341 | foreach my $module (@$input) { | ||
| 342 | $modules{$module->index}{module} = $module; | ||
| 343 | if ($module->parent) { | ||
| 344 | # Example | ||
| 345 | # index | description | type | parent | class | pos | ||
| 346 | #-------+----------------------------------------+---------------------+--------+---------+----- | ||
| 347 | # 1 | Cisco Aironet 1200 Series Access Point | cevChassisAIRAP1210 | 0 | chassis | -1 | ||
| 348 | # 3 | PowerPC405GP Ethernet | cevPortFEIP | 1 | port | -1 | ||
| 349 | # 2 | 802.11G Radio | cevPortUnknown | 1 | port | 0 | ||
| 350 | |||
| 351 | # Some devices do not implement correctly, so given parent | ||
| 352 | # can have multiple items within the same class at a single pos | ||
| 353 | # value. However, the database results are sorted by 1) parent | ||
| 354 | # 2) class 3) pos 4) index so we should just be able to push onto | ||
| 355 | # the array and ordering be preserved. | ||
| 356 | { | ||
| 357 | no warnings 'uninitialized'; | ||
| 358 | push(@{$modules{$module->parent}{children}{$module->class}}, $module->index); | ||
| 359 | } | ||
| 360 | } else { | ||
| 361 | push(@{$modules{root}}, $module->index); | ||
| 362 | } | ||
| 363 | } | ||
| 364 | return \%modules; | ||
| 365 | } | ||
| 366 | |||
| 367 | =head2 interval_to_daterange( $interval ) | ||
| 368 | |||
| 369 | Takes an interval in days, weeks, months, or years in a format like '7 days' | ||
| 370 | and returns a date range in the format 'YYYY-MM-DD to YYYY-MM-DD' by | ||
| 371 | subtracting the interval from the current date. | ||
| 372 | |||
| 373 | If C<$interval> is not passed, epoch zero (1970-01-01) is used as the start. | ||
| 374 | |||
| 375 | =cut | ||
| 376 | |||
| 377 | sub interval_to_daterange { | ||
| 378 | my $interval = shift; | ||
| 379 | |||
| 380 | unless ($interval | ||
| 381 | and $interval =~ m/^(?:\d+)\s+(?:day|week|month|year)s?$/) { | ||
| 382 | |||
| 383 | return "1970-01-01 to " . Time::Piece->new->ymd; | ||
| 384 | } | ||
| 385 | |||
| 386 | my %const = ( | ||
| 387 | day => ONE_DAY, | ||
| 388 | week => ONE_WEEK, | ||
| 389 | month => ONE_MONTH, | ||
| 390 | year => ONE_YEAR | ||
| 391 | ); | ||
| 392 | |||
| 393 | my ( $amt, $factor ) | ||
| 394 | = $interval =~ /^(\d+)\s+(day|week|month|year)s?$/gmx; | ||
| 395 | |||
| 396 | $amt-- if $factor eq 'day'; | ||
| 397 | |||
| 398 | my $start = Time::Piece->new - $const{$factor} * $amt; | ||
| 399 | |||
| 400 | return $start->ymd . " to " . Time::Piece->new->ymd; | ||
| 401 | } | ||
| 402 | |||
| 403 | =head2 device_display_name( $device ) | ||
| 404 | |||
| 405 | The name shown for a Device row in the web interface: its DNS name, or its IP | ||
| 406 | when another device answers to the same DNS name. | ||
| 407 | |||
| 408 | =cut | ||
| 409 | |||
| 410 | sub device_display_name { | ||
| 411 | my $device = shift or return undef; | ||
| 412 | |||
| 413 | my $others = schema(vars->{'tenant'})->resultset('Device') | ||
| 414 | ->search({ dns => $device->dns })->count() - 1; | ||
| 415 | |||
| 416 | return ($others ? $device->ip : ($device->dns || $device->ip)); | ||
| 417 | } | ||
| 418 | |||
| 419 | =head2 page_title( $page, $tab ) | ||
| 420 | |||
| 421 | The browser title for the C<$tab> pane of C<$page>, where C<$page> is one of | ||
| 422 | C<device>, C<search>, C<report> or C<admin>. | ||
| 423 | |||
| 424 | Returns undef where the interface has no title for the tab, so that a caller | ||
| 425 | emitting this into a response leaves the current title alone rather than | ||
| 426 | replacing it with something wrong. | ||
| 427 | |||
| 428 | =cut | ||
| 429 | |||
| 430 | sub page_title { | ||
| 431 | my ($page, $tab) = @_; | ||
| 432 | $tab ||= ''; | ||
| 433 | |||
| 434 | if ($page eq 'device') { | ||
| 435 | # before the device lookup, so an unknown tag costs no query | ||
| 436 | my $config = _tab_config('device', $tab) or return undef; | ||
| 437 | my $device = _device_for_query( param('q') ) or return undef; | ||
| 438 | return device_display_name($device) .' - '. $config->{'label'}; | ||
| 439 | } | ||
| 440 | |||
| 441 | # the port log is the one report naming its subject beside the tab | ||
| 442 | my $report = (($page eq 'report' and $tab eq 'portlog') | ||
| 443 | ? setting('_reports')->{ $tab } : undef); | ||
| 444 | |||
| 445 | if ($report) { | ||
| 446 | return _one_line(join ' ', (param('q') || ''), '-', (param('f') || '')) | ||
| 447 | .' - '. $report->{'label'}; | ||
| 448 | } | ||
| 449 | |||
| 450 | return setting('branding_text'); | ||
| 451 | } | ||
| 452 | |||
| 453 | # the registry entry a web plugin made for this tab, or undef when nothing | ||
| 454 | # registered the name. Reports and admin tasks are keyed by tag; device and | ||
| 455 | # search tabs are an ordered list, because the page renders them in that order. | ||
| 456 | sub _tab_config { | ||
| 457 | my ($page, $tab) = @_; | ||
| 458 | return undef unless defined $tab and length $tab; | ||
| 459 | |||
| 460 | return setting('_reports')->{ $tab } if $page eq 'report'; | ||
| 461 | return setting('_admin_tasks')->{ $tab } if $page eq 'admin'; | ||
| 462 | |||
| 463 | foreach my $item (@{ setting("_${page}_tabs") || [] }) { | ||
| 464 | return $item if $item->{'tag'} eq $tab; | ||
| 465 | } | ||
| 466 | return undef; | ||
| 467 | } | ||
| 468 | |||
| 469 | sub _device_for_query { | ||
| 470 | my $q = shift or return undef; | ||
| 471 | |||
| 472 | # the same lookup the /device page makes, so that the title matches the name | ||
| 473 | # that page rendered, which is what the browser reads today | ||
| 474 | return schema(vars->{'tenant'})->resultset('Device')->search({ | ||
| 475 | -or => [ | ||
| 476 | \[ 'host(me.ip) = ?' => [ bind_value => $q ] ], | ||
| 477 | 'me.dns' => $q, | ||
| 478 | ], | ||
| 479 | })->first; | ||
| 480 | } | ||
| 481 | |||
| 482 | # report.tt lays the port log's parts out over several lines, which the | ||
| 483 | # browser would otherwise carry into the tab | ||
| 484 | sub _one_line { | ||
| 485 | my $text = shift; | ||
| 486 | $text = '' unless defined $text; | ||
| 487 | |||
| 488 | $text =~ s/\s+/ /g; | ||
| 489 | $text =~ s/^\s+|\s+$//g; | ||
| 490 | return $text; | ||
| 491 | } | ||
| 492 | |||
| 493 | =head2 pane_history_header( $page, $tab ) | ||
| 494 | |||
| 495 | The C<HX-Push-Url> or C<HX-Replace-Url> header for the C<$tab> pane of | ||
| 496 | C<$page>, as a name and value pair for L<Dancer::Response/header>. htmx puts | ||
| 497 | the value in the address bar, and reads the value C<false> as an instruction | ||
| 498 | to leave the history alone. | ||
| 499 | |||
| 500 | The value is the address of the page the pane belongs to, carrying the query | ||
| 501 | the sidebar form submitted, so that opening it fresh renders the same tab with | ||
| 502 | the same results. | ||
| 503 | |||
| 504 | =cut | ||
| 505 | |||
| 506 | sub pane_history_header { | ||
| 507 | my ($page, $tab) = @_; | ||
| 508 | |||
| 509 | # an admin task has never had an address of its own for its options, and the | ||
| 510 | # job queue refetches on a timer, which would be a history entry every few | ||
| 511 | # seconds. "false" rather than no header at all, because htmx reads the | ||
| 512 | # header before any hx-push-url attribute and nothing else can overrule one. | ||
| 513 | return ('HX-Push-Url' => 'false') if $page eq 'admin'; | ||
| 514 | |||
| 515 | # the query the form serialized, rather than the my_query token, which | ||
| 516 | # stringifies a repeated parameter as an array reference | ||
| 517 | my $query = request->env->{'QUERY_STRING'} || ''; | ||
| 518 | my $path = uri_for(($page eq 'report') ? "/report/$tab" : "/$page")->path; | ||
| 519 | my $url = $path . (length $query ? ('?'. $query) : ''); | ||
| 520 | |||
| 521 | my $leaving = _htmx_current_url(); | ||
| 522 | |||
| 523 | if ($page eq 'report') { | ||
| 524 | # a report with no options submits an empty query, and repeating the | ||
| 525 | # address it is already showing would be an entry that the Back button | ||
| 526 | # appears to ignore | ||
| 527 | return ('HX-Push-Url' => 'false') | ||
| 528 | if (not length $query) and $leaving and $leaving->path eq $path; | ||
| 529 | |||
| 530 | return ('HX-Push-Url' => $url); | ||
| 531 | } | ||
| 532 | |||
| 533 | # a device or search tab change is a new page in the history but a change to | ||
| 534 | # the options of the tab already shown is not, which here is the difference | ||
| 535 | # between the tab asked for and the tab of the page htmx is leaving | ||
| 536 | my $leaving_tab = $leaving ? $leaving->query_param('tab') : undef; | ||
| 537 | |||
| 538 | return ('HX-Push-Url' => $url) | ||
| 539 | if defined $leaving_tab and $leaving_tab ne $tab; | ||
| 540 | |||
| 541 | return ('HX-Replace-Url' => $url); | ||
| 542 | } | ||
| 543 | |||
| 544 | # htmx sends the address bar contents with every request it makes | ||
| 545 | sub _htmx_current_url { | ||
| 546 | my $current = request->env->{'HTTP_HX_CURRENT_URL'} or return undef; | ||
| 547 | return URI->new($current); | ||
| 548 | } | ||
| 549 | |||
| 550 | =head2 pane_chrome( $page, $tab ) | ||
| 551 | |||
| 552 | The chrome around the C<$tab> pane of C<$page> that changes with the tab: the | ||
| 553 | CSV download link, and on the device page the sidebar reset link. Returned as | ||
| 554 | C<hx-swap-oob> markup for the same response that carries the pane, so that one | ||
| 555 | answer paints the pane and everything around it. | ||
| 556 | |||
| 557 | Returns the empty string where the page shell carries neither, which is also | ||
| 558 | what an unregistered tag gets. That is not tidiness: htmx drops an out-of-band | ||
| 559 | element naming an id the page does not have, and says nothing at all about it, | ||
| 560 | so C<netdisco.js> reports the shortfall as a script error. | ||
| 561 | |||
| 562 | The sidebar itself is deliberately absent. Whether a tab has one is declared by | ||
| 563 | the sidebar templates, both by which of them exist on an include path that | ||
| 564 | site-local plugins extend and by two of them reporting that they carry only | ||
| 565 | hidden fields, so no route can answer it without duplicating template text. | ||
| 566 | |||
| 567 | =cut | ||
| 568 | |||
| 569 | sub pane_chrome { | ||
| 570 | my ($page, $tab) = @_; | ||
| 571 | my $config = _tab_config($page, $tab) or return ''; | ||
| 572 | |||
| 573 | return join '', _csv_download_link($page, $tab, $config), | ||
| 574 | _sidebar_reset_link($page, $tab); | ||
| 575 | } | ||
| 576 | |||
| 577 | # The device and search shells render the anchor for every tab and show or hide | ||
| 578 | # it per tab; the report and admin shells render it only where the tab offers a | ||
| 579 | # download, and give the job queue and the port log a different set of controls | ||
| 580 | # in the same corner. | ||
| 581 | sub _csv_download_link { | ||
| 582 | my ($page, $tab, $config) = @_; | ||
| 583 | |||
| 584 | if ($page eq 'report' or $page eq 'admin') { | ||
| 585 | return '' unless $config->{'provides_csv'}; | ||
| 586 | return '' if $tab eq 'portlog' or $tab eq 'jobqueue'; | ||
| 587 | } | ||
| 588 | |||
| 589 | my $query = request->env->{'QUERY_STRING'} || ''; | ||
| 590 | my $href = uri_for("/ajax/content/$page/$tab")->path | ||
| 591 | . (length $query ? ('?'. $query) : ''); | ||
| 592 | |||
| 593 | return _oob_anchor('nd_csv-download', $href, | ||
| 594 | ($config->{'provides_csv'} ? '' : ' hidden'), | ||
| 595 | ' download="'. _escape_attr("netdisco-$page-$tab.csv") .'"', | ||
| 596 | '<i id="nd_csv-download-icon" class="text-info far fa-file-lines fa-lg"' | ||
| 597 | .' rel="tooltip" data-bs-placement="left" data-bs-title="Download as CSV"></i>'); | ||
| 598 | } | ||
| 599 | |||
| 600 | # the fields each device tab offers, in the order the sidebar renders them, so | ||
| 601 | # that the reset address reads the way it did when the browser built it | ||
| 602 | my %RESET_FIELDS = ( | ||
| 603 | ports => [qw/q f partial invert/], | ||
| 604 | netmap => [qw/q/], | ||
| 605 | ); | ||
| 606 | |||
| 607 | # only the device page has a reset anchor, and only for the two tabs whose | ||
| 608 | # sidebar has anything to reset. Nothing is emitted for the others, which is | ||
| 609 | # what the shell does today: the anchor keeps the address it last had, behind a | ||
| 610 | # sidebar those tabs hide anyway. | ||
| 611 | sub _sidebar_reset_link { | ||
| 612 | my ($page, $tab) = @_; | ||
| 613 | return '' unless $page eq 'device'; | ||
| 614 | |||
| 615 | my $fields = $RESET_FIELDS{ $tab } or return ''; | ||
| 616 | |||
| 617 | my $uri = URI->new( uri_for('/device')->path ); | ||
| 618 | $uri->query_form(tab => $tab, reset => 'on', firstsearch => 'on', | ||
| 619 | map {; ($_ => scalar param($_)) } | ||
| 620 | grep {; defined scalar param($_) } @$fields); | ||
| 621 | |||
| 622 | return _oob_anchor('nd_sidebar-reset-link', $uri->as_string, '', '', | ||
| 623 | '<i class="nd_sidebar-reset fas fa-arrow-rotate-left"' | ||
| 624 | .' rel="tooltip" data-bs-placement="left" data-bs-title="Reset to Defaults"' | ||
| 625 | .' data-bs-container="body"></i>'); | ||
| 626 | } | ||
| 627 | |||
| 628 | sub _oob_anchor { | ||
| 629 | my ($id, $href, $hidden, $extra, $content) = @_; | ||
| 630 | |||
| 631 | return '<a id="'. $id .'" hx-swap-oob="true"'. $hidden | ||
| 632 | .' href="'. _escape_attr($href) .'"'. $extra .'>'. $content .'</a>'; | ||
| 633 | } | ||
| 634 | |||
| 635 | sub _escape_attr { | ||
| 636 | return HTML::Entities::encode_entities(shift, q{<>&"'}); | ||
| 637 | } | ||
| 638 | |||
| 639 | =head2 escape_for_script_context( $json ) | ||
| 640 | |||
| 641 | Makes a JSON string safe to embed as a JavaScript literal inside an HTML | ||
| 642 | C<< <script> >> element, which is how the report and search templates ship | ||
| 643 | their result sets. Returns anything that is not a defined plain scalar | ||
| 644 | unchanged, so a resultset or an arrayref passed to a CSV or API template is | ||
| 645 | left alone. | ||
| 646 | |||
| 647 | =cut | ||
| 648 | |||
| 649 | sub escape_for_script_context { | ||
| 650 | my $json = shift; | ||
| 651 | return $json if (not defined $json) or ref $json; | ||
| 652 | |||
| 653 | # Inside a script element the HTML parser ends the element at "</" and | ||
| 654 | # changes state at "<!--" and "<script", none of which it stops doing just | ||
| 655 | # because the sequence sits inside a JavaScript string. Escaping every "<" | ||
| 656 | # covers all three. Both JSON.parse and the JavaScript parser read the | ||
| 657 | # escape back as "<", so the data the page receives is unchanged. | ||
| 658 | $json =~ s/</\\u003C/g; | ||
| 659 | |||
| 660 | # Not an HTML concern. This JSON is emitted as JavaScript source rather than | ||
| 661 | # parsed from a string, and these two characters are line terminators there. | ||
| 662 | $json =~ s/\x{2028}/\\u2028/g; | ||
| 663 | $json =~ s/\x{2029}/\\u2029/g; | ||
| 664 | |||
| 665 | return $json; | ||
| 666 | } | ||
| 667 | |||
| 668 | =head2 escape_results_token( $tokens ) | ||
| 669 | |||
| 670 | Applies C<escape_for_script_context> to the C<results> token of a template | ||
| 671 | token hash, in place, and returns the hash. | ||
| 672 | |||
| 673 | Only when the key is already there. The API serializer chooses between | ||
| 674 | emitting C<results> alone and walking the whole token hash on C<exists | ||
| 675 | $tokens-E<gt>{results}>, and a handler that renders without that token, as | ||
| 676 | node search does, needs the second. Assigning unconditionally would | ||
| 677 | autovivify the key and silently move such a handler onto the first branch. | ||
| 678 | |||
| 679 | =cut | ||
| 680 | |||
| 681 | sub escape_results_token { | ||
| 682 | my $tokens = shift; | ||
| 683 | return $tokens unless (ref {} eq ref $tokens) and exists $tokens->{results}; | ||
| 684 | |||
| 685 | $tokens->{results} = escape_for_script_context( $tokens->{results} ); | ||
| 686 | return $tokens; | ||
| 687 | } | ||
| 688 | |||
| 689 | =head2 omit_empty_columns( \@rows, \@column_order, \%column_config ) | ||
| 690 | |||
| 691 | Applies two column options of a configured report and returns the columns to | ||
| 692 | show, in order. C<_omit_if_empty> leaves a column out when no row has a value | ||
| 693 | for it, and deletes its key from every row. C<_empty_as> gives the text an empty | ||
| 694 | cell shows when the column is kept. A missing key counts as empty. Rows are | ||
| 695 | changed in place. | ||
| 696 | |||
| 697 | =cut | ||
| 698 | |||
| 699 | # Compares a copy: reading a number as a string in place would make the JSON | ||
| 700 | # encoder serialize it as a string. | ||
| 701 | sub _is_empty { my $value = shift; return (not defined $value or "$value" eq '') } | ||
| 702 | |||
| 703 | sub omit_empty_columns { | ||
| 704 | my ($rows, $column_order, $column_config) = @_; | ||
| 705 | my @kept; | ||
| 706 | foreach my $col (@$column_order) { | ||
| 707 | my $options = $column_config->{$col} || {}; | ||
| 708 | if ($options->{_omit_if_empty} and not grep { not _is_empty($_->{$col}) } @$rows) { | ||
| 709 | delete $_->{$col} for @$rows; | ||
| 710 | next; | ||
| 711 | } | ||
| 712 | if (defined $options->{_empty_as}) { | ||
| 713 | $_->{$col} = $options->{_empty_as} for grep { _is_empty($_->{$col}) } @$rows; | ||
| 714 | } | ||
| 715 | push @kept, $col; | ||
| 716 | } | ||
| 717 | return @kept; | ||
| 718 | } | ||
| 719 | |||
| 720 | =head2 tacacs_configured | ||
| 721 | |||
| 722 | Returns true when the C<tacacs> setting lists at least one server. The shipped | ||
| 723 | default C<{}>, and an empty list, are not a configuration. | ||
| 724 | |||
| 725 | =cut | ||
| 726 | |||
| 727 | sub tacacs_configured { | ||
| 728 | my $tacacs = setting('tacacs'); | ||
| 729 | return (ref [] eq ref $tacacs and scalar @$tacacs) ? 1 : 0; | ||
| 730 | } | ||
| 731 | |||
| 732 | =head2 tacacs_unavailable | ||
| 733 | |||
| 734 | Returns undef when Authen::TacacsPlus loads, otherwise advice naming the | ||
| 735 | commands that install it, or that rebuild it when it is installed but will not | ||
| 736 | load. | ||
| 737 | |||
| 738 | Loaded here, not with C<use>, because Netdisco no longer installs it: it does | ||
| 739 | not compile under GCC 15, and only sites using TACACS+ need it. | ||
| 740 | |||
| 741 | A copy that is found but will not load is told apart from a missing one, | ||
| 742 | because an OS upgrade leaves exactly that behind, and the plain install | ||
| 743 | command then answers "up to date" and changes nothing. | ||
| 744 | |||
| 745 | =cut | ||
| 746 | |||
| 747 | sub tacacs_unavailable { | ||
| 748 | return try { require Authen::TacacsPlus; undef } | ||
| 749 | catch { | ||
| 750 | my $error = $_; | ||
| 751 | return 'Authen::TacacsPlus is not installed. Install it with: ' | ||
| 752 | . _tacacs_install_commands('') | ||
| 753 | if $error =~ m{^Can't locate Authen/TacacsPlus\.pm}; | ||
| 754 | |||
| 755 | my ($first_line) = split /\n/, $error; | ||
| 756 | return "Authen::TacacsPlus is installed but cannot be loaded ($first_line). Rebuild it with: " | ||
| 757 | . _tacacs_install_commands('--reinstall '); | ||
| 758 | }; | ||
| 759 | } | ||
| 760 | |||
| 761 | sub _tacacs_install_commands { | ||
| 762 | my $flags = shift; | ||
| 763 | return "~/bin/localenv cpanm --notest ${flags}Authen::TacacsPlus " | ||
| 764 | ."(with GCC 15 or newer: CFLAGS=\"-std=gnu17\" ~/bin/localenv cpanm --notest ${flags}Authen::TacacsPlus)"; | ||
| 765 | } | ||
| 766 | |||
| 767 | =head2 tacacs_startup_warning | ||
| 768 | |||
| 769 | Returns the warning the web application logs at startup when TACACS+ is | ||
| 770 | configured but Authen::TacacsPlus cannot be loaded, otherwise undef. | ||
| 771 | |||
| 772 | =cut | ||
| 773 | |||
| 774 | sub tacacs_startup_warning { | ||
| 775 | return undef unless tacacs_configured(); | ||
| 776 | my $advice = tacacs_unavailable() or return undef; | ||
| 777 | return "TACACS+ is configured, but $advice"; | ||
| 778 | } | ||
| 779 | |||
| 780 | 1; |