You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

niclist.pl 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. #!/usr/bin/env perl
  2. #
  3. # Generates list of supported NICs with PCI vendor/device IDs, driver name
  4. # and other useful things.
  5. #
  6. # Initial version by Robin Smidsrød <robin@smidsrod.no>
  7. #
  8. use strict;
  9. use warnings;
  10. use autodie;
  11. use v5.10;
  12. use File::stat;
  13. use File::Basename qw(basename);
  14. use File::Find ();
  15. use Getopt::Long qw(GetOptions);
  16. GetOptions(
  17. 'help' => \( my $help = 0 ),
  18. 'format=s' => \( my $format = 'text' ),
  19. 'sort=s' => \( my $sort = 'bus,ipxe_driver,ipxe_name' ),
  20. 'columns=s' => \( my $columns = 'bus,vendor_id,device_id,'
  21. . 'vendor_name,device_name,ipxe_driver,'
  22. . 'ipxe_name,ipxe_description,file,legacy_api'
  23. ),
  24. 'pci-url=s' => \( my $pci_url = 'http://pciids.sourceforge.net/v2.2/pci.ids' ),
  25. 'pci-file=s' => \( my $pci_file = '/tmp/pci.ids' ),
  26. 'output=s' => \( my $output = '' ),
  27. );
  28. die(<<"EOM") if $help;
  29. Usage: $0 [options] [<directory>]
  30. Options:
  31. --help This page
  32. --format Set output format
  33. --sort Set output sort order (comma-separated)
  34. --columns Set output columns (comma-separated)
  35. --pci-url URL to pci.ids file
  36. --pci-file Cache file for downloaded pci.ids
  37. --output Output file (not specified is STDOUT)
  38. Output formats:
  39. text, csv, json, html, dokuwiki
  40. Column names (default order):
  41. bus, vendor_id, device_id, vendor_name, device_name,
  42. ipxe_driver, ipxe_name, ipxe_description, file, legacy_api
  43. EOM
  44. # Only load runtime requirements if actually in use
  45. given($format) {
  46. when( /csv/ ) {
  47. eval { require Text::CSV; };
  48. die("Please install Text::CSV CPAN module to use this feature.\n")
  49. if $@;
  50. }
  51. when( /json/ ) {
  52. eval { require JSON; };
  53. die("Please install JSON CPAN module to use this feature.\n")
  54. if $@;
  55. }
  56. when( /html/ ) {
  57. eval { require HTML::Entities; };
  58. die("Please install HTML::Entities CPAN module to use this feature.\n")
  59. if $@;
  60. }
  61. default { }
  62. }
  63. # Scan source dir and build NIC list
  64. my $ipxe_src_dir = shift || '.'; # Default to current directory
  65. my $ipxe_nic_list = build_ipxe_nic_list( $ipxe_src_dir );
  66. # Download pci.ids file and parse it
  67. fetch_pci_ids_file($pci_url, $pci_file);
  68. my $pci_id_map = build_pci_id_map($pci_file);
  69. # Merge 'official' vendor/device names and sort list
  70. update_ipxe_nic_names($ipxe_nic_list, $pci_id_map);
  71. my $sorted_list = sort_ipxe_nic_list($ipxe_nic_list, $sort);
  72. # Run specified formatter
  73. my $column_names = parse_columns_param($columns);
  74. say STDERR "Formatting NIC list in format '$format' with columns: "
  75. . join(", ", @$column_names);
  76. my $formatter = \&{ "format_nic_list_$format" };
  77. my $report = $formatter->( $sorted_list, $column_names );
  78. # Print final report
  79. if ( $output and $output ne '-' ) {
  80. say STDERR "Printing report to '$output'...";
  81. open( my $out_fh, ">", $output );
  82. print $out_fh $report;
  83. close($out_fh);
  84. }
  85. else {
  86. print STDOUT $report;
  87. }
  88. exit;
  89. # fetch URL into specified filename
  90. sub fetch_pci_ids_file {
  91. my ($url, $filename) = @_;
  92. my @cmd = ( "wget", "--quiet", "-O", $filename, $url );
  93. my @touch = ( "touch", $filename );
  94. if ( -r $filename ) {
  95. my $age = time - stat($filename)->mtime;
  96. # Refresh if older than 1 day
  97. if ( $age > 86400 ) {
  98. say STDERR "Refreshing $filename from $url...";
  99. system(@cmd);
  100. system(@touch);
  101. }
  102. }
  103. else {
  104. say STDERR "Fetching $url into $filename...";
  105. system(@cmd);
  106. system(@touch);
  107. }
  108. return $filename;
  109. }
  110. sub build_pci_id_map {
  111. my ($filename) = @_;
  112. say STDERR "Building PCI ID map...";
  113. my $devices = {};
  114. my $classes = {};
  115. my $pci_id = qr/[[:xdigit:]]{4}/;
  116. my $c_id = qr/[[:xdigit:]]{2}/;
  117. my $non_space = qr/[^\s]/;
  118. # open pci.ids file specified
  119. open( my $fh, "<", $filename );
  120. # For devices
  121. my $vendor_id = "";
  122. my $vendor_name = "";
  123. my $device_id = "";
  124. my $device_name = "";
  125. # For classes
  126. my $class_id = "";
  127. my $class_name = "";
  128. my $subclass_id = "";
  129. my $subclass_name = "";
  130. while(<$fh>) {
  131. # skip # and blank lines
  132. next if m/^$/;
  133. next if m/^\s*#/;
  134. # Vendors, devices and subsystems. Please keep sorted.
  135. # Syntax:
  136. # vendor vendor_name
  137. # device device_name <-- single tab
  138. # subvendor subdevice subsystem_name <-- two tabs
  139. if ( m/^ ($pci_id) \s+ ( $non_space .* ) /x ) {
  140. $vendor_id = lc $1;
  141. $vendor_name = $2;
  142. $devices->{$vendor_id} = { name => $vendor_name };
  143. next;
  144. }
  145. if ( $vendor_id and m/^ \t ($pci_id) \s+ ( $non_space .* ) /x ) {
  146. $device_id = lc $1;
  147. $device_name = $2;
  148. $devices->{$vendor_id}->{'devices'} //= {};
  149. $devices->{$vendor_id}->{'devices'}->{$device_id} = { name => $device_name };
  150. next;
  151. }
  152. if ( $vendor_id and $device_id and m/^ \t{2} ($pci_id) \s+ ($pci_id) \s+ ( $non_space .* ) /x ) {
  153. my $subvendor_id = lc $1;
  154. my $subdevice_id = lc $2;
  155. my $subsystem_name = $3;
  156. $devices->{$vendor_id}->{'devices'}->{$device_id}->{'subvendor'} //= {};
  157. $devices->{$vendor_id}->{'devices'}->{$device_id}->{'subvendor'}->{$subvendor_id} //= {};
  158. $devices->{$vendor_id}->{'devices'}->{$device_id}->{'subvendor'}->{$subvendor_id}->{'devices'} //= {};
  159. $devices->{$vendor_id}->{'devices'}->{$device_id}->{'subvendor'}->{$subvendor_id}->{'devices'}->{$subdevice_id} = { name => $subsystem_name };
  160. next;
  161. }
  162. # List of known device classes, subclasses and programming interfaces
  163. # Syntax:
  164. # C class class_name
  165. # subclass subclass_name <-- single tab
  166. # prog-if prog-if_name <-- two tabs
  167. if ( m/^C \s+ ($c_id) \s+ ( $non_space .* ) /x ) {
  168. $class_id = lc $1;
  169. $class_name = $2;
  170. $classes->{$class_id} = { name => $class_name };
  171. next;
  172. }
  173. if ( $class_id and m/^ \t ($c_id) \s+ ( $non_space .* ) /x ) {
  174. $subclass_id = lc $1;
  175. $subclass_name = $2;
  176. $classes->{$class_id}->{'subclasses'} //= {};
  177. $classes->{$class_id}->{'subclasses'}->{$subclass_id} = { name => $subclass_name };
  178. next;
  179. }
  180. if ( $class_id and $subclass_id and m/^ \t{2} ($c_id) \s+ ( $non_space .* ) /x ) {
  181. my $prog_if_id = lc $1;
  182. my $prog_if_name = $2;
  183. $classes->{$class_id}->{'subclasses'}->{$subclass_id}->{'programming_interfaces'} //= {};
  184. $classes->{$class_id}->{'subclasses'}->{$subclass_id}->{'programming_interfaces'}->{$prog_if_id} = { name => $prog_if_name };
  185. next;
  186. }
  187. }
  188. close($fh);
  189. # Populate subvendor names
  190. foreach my $vendor_id ( keys %$devices ) {
  191. my $device_map = $devices->{$vendor_id}->{'devices'};
  192. foreach my $device_id ( keys %$device_map ) {
  193. my $subvendor_map = $device_map->{$device_id}->{'subvendor'};
  194. foreach my $subvendor_id ( keys %$subvendor_map ) {
  195. $subvendor_map->{$subvendor_id}->{'name'} = $devices->{$subvendor_id}->{'name'} || "";
  196. }
  197. }
  198. }
  199. return {
  200. 'devices' => $devices,
  201. 'classes' => $classes,
  202. };
  203. }
  204. # Scan through C code and parse ISA_ROM and PCI_ROM lines
  205. sub build_ipxe_nic_list {
  206. my ($dir) = @_;
  207. say STDERR "Building iPXE NIC list from " . ( $dir eq '.' ? 'current directory' : $dir ) . "...";
  208. # recursively iterate through dir and find .c files
  209. my @c_files;
  210. File::Find::find(sub {
  211. # only process files
  212. return if -d $_;
  213. # skip unreadable files
  214. return unless -r $_;
  215. # skip all but files with .c extension
  216. return unless /\.c$/;
  217. push @c_files, $File::Find::name;
  218. }, $dir);
  219. # Look for ISA_ROM or PCI_ROM lines
  220. my $ipxe_nic_list = [];
  221. my $hex_id = qr/0 x [[:xdigit:]]{4} /x;
  222. my $quote = qr/ ['"] /x;
  223. my $non_space = qr/ [^\s] /x;
  224. my $rom_line_counter = 0;
  225. foreach my $c_path ( sort @c_files ) {
  226. my $legacy = 0;
  227. open( my $fh, "<", $c_path );
  228. my $c_file = $c_path;
  229. $c_file =~ s{^\Q$dir\E/?}{} if -d $dir; # Strip directory from reported filename
  230. my $ipxe_driver = basename($c_file, '.c');
  231. while(<$fh>) {
  232. # Most likely EtherBoot legacy API
  233. $legacy = 1 if m/struct \s* nic \s*/x;
  234. # parse ISA|PCI_ROM lines into hashref and append to $ipxe_nic_list
  235. next unless m/^ \s* (?:ISA|PCI)_ROM /x;
  236. $rom_line_counter++;
  237. chomp;
  238. #say; # for debugging regexp
  239. if ( m/^ \s* ISA_ROM \s* \( \s* $quote ( .*? ) $quote \s* , \s* $quote ( .*? ) $quote \s* \) /x ) {
  240. my $image = $1;
  241. my $name = $2;
  242. push @$ipxe_nic_list, {
  243. file => $c_file,
  244. bus => 'isa',
  245. ipxe_driver => $ipxe_driver,
  246. ipxe_name => $image,
  247. ipxe_description => $name,
  248. legacy_api => ( $legacy ? 'yes' : 'no' ),
  249. };
  250. next;
  251. }
  252. if ( m/^ \s* PCI_ROM \s* \( \s* ($hex_id) \s* , \s* ($hex_id) \s* , \s* $quote (.*?) $quote \s* , \s* $quote (.*?) $quote /x ) {
  253. my $vendor_id = lc $1;
  254. my $device_id = lc $2;
  255. my $name = $3;
  256. my $desc = $4;
  257. push @$ipxe_nic_list, {
  258. file => $c_file,
  259. bus => 'pci',
  260. vendor_id => substr($vendor_id, 2), # strip 0x
  261. device_id => substr($device_id, 2), # strip 0x
  262. ipxe_driver => $ipxe_driver,
  263. ipxe_name => $name,
  264. ipxe_description => $desc,
  265. legacy_api => ( $legacy ? 'yes' : 'no' ),
  266. };
  267. next;
  268. }
  269. }
  270. close($fh);
  271. }
  272. # Verify all ROM lines where parsed properly
  273. my @isa_roms = grep { $_->{'bus'} eq 'isa' } @$ipxe_nic_list;
  274. my @pci_roms = grep { $_->{'bus'} eq 'pci' } @$ipxe_nic_list;
  275. if ( $rom_line_counter != ( @isa_roms + @pci_roms ) ) {
  276. say STDERR "Found ROM lines: $rom_line_counter";
  277. say STDERR "Extracted ISA_ROM lines: " . scalar @isa_roms;
  278. say STDERR "Extracted PCI_ROM lines: " . scalar @pci_roms;
  279. die("Mismatch between number of ISA_ROM/PCI_ROM lines and extracted entries. Verify regular expressions.\n");
  280. }
  281. return $ipxe_nic_list;
  282. }
  283. # merge vendor/product name from $pci_id_map into $ipxe_nic_list
  284. sub update_ipxe_nic_names {
  285. my ($ipxe_nic_list, $pci_id_map) = @_;
  286. say STDERR "Merging 'official' vendor/device names...";
  287. foreach my $nic ( @$ipxe_nic_list ) {
  288. next unless $nic->{'bus'} eq 'pci';
  289. $nic->{'vendor_name'} = $pci_id_map->{'devices'}->{ $nic->{'vendor_id'} }->{'name'} || "";
  290. $nic->{'device_name'} = $pci_id_map->{'devices'}->{ $nic->{'vendor_id'} }->{'devices'}->{ $nic->{'device_id'} }->{'name'} || "";
  291. }
  292. return $ipxe_nic_list; # Redundant, as we're mutating the input list, useful for chaining calls
  293. }
  294. # Sort entries in NIC list according to sort criteria
  295. sub sort_ipxe_nic_list {
  296. my ($ipxe_nic_list, $sort_column_names) = @_;
  297. my @sort_column_names = @{ parse_columns_param($sort_column_names) };
  298. say STDERR "Sorting NIC list by: " . join(", ", @sort_column_names );
  299. # Start at the end of the list and resort until list is exhausted
  300. my @sorted_list = @{ $ipxe_nic_list };
  301. while(@sort_column_names) {
  302. my $column_name = pop @sort_column_names;
  303. @sorted_list = sort { ( $a->{$column_name} || "" ) cmp ( $b->{$column_name} || "" ) }
  304. @sorted_list;
  305. }
  306. return \@sorted_list;
  307. }
  308. # Parse comma-separated values into array
  309. sub parse_columns_param {
  310. my ($columns) = @_;
  311. return [
  312. grep { is_valid_column($_) } # only include valid entries
  313. map { s/\s//g; $_; } # filter whitespace
  314. split( /,/, $columns ) # split on comma
  315. ];
  316. }
  317. # Return true if the input column name is valid
  318. sub is_valid_column {
  319. my ($name) = @_;
  320. my $valid_column_map = {
  321. map { $_ => 1 }
  322. qw(
  323. bus file legacy_api
  324. ipxe_driver ipxe_name ipxe_description
  325. vendor_id device_id vendor_name device_name
  326. )
  327. };
  328. return unless $name;
  329. return unless $valid_column_map->{$name};
  330. return 1;
  331. }
  332. # Output NIC list in plain text
  333. sub format_nic_list_text {
  334. my ($nic_list, $column_names) = @_;
  335. return join("\n",
  336. map { format_nic_text($_, $column_names) }
  337. @$nic_list
  338. );
  339. }
  340. # Format one ipxe_nic_list entry for display
  341. # Column order not supported by text format
  342. sub format_nic_text {
  343. my ($nic, $column_names) = @_;
  344. my $labels = {
  345. bus => 'Bus: ',
  346. ipxe_driver => 'iPXE driver: ',
  347. ipxe_name => 'iPXE name: ',
  348. ipxe_description => 'iPXE description:',
  349. file => 'Source file: ',
  350. legacy_api => 'Using legacy API:',
  351. vendor_id => 'PCI vendor ID: ',
  352. device_id => 'PCI device ID: ',
  353. vendor_name => 'Vendor name: ',
  354. device_name => 'Device name: ',
  355. };
  356. my $pci_only = {
  357. vendor_id => 1,
  358. device_id => 1,
  359. vendor_name => 1,
  360. device_name => 1,
  361. };
  362. my $output = "";
  363. foreach my $column ( @$column_names ) {
  364. next if $nic->{'bus'} eq 'isa' and $pci_only->{$column};
  365. $output .= $labels->{$column}
  366. . " "
  367. . ( $nic->{$column} || "" )
  368. . "\n";
  369. }
  370. return $output;
  371. }
  372. # Output NIC list in JSON
  373. sub format_nic_list_json {
  374. my ($nic_list, $column_names) = @_;
  375. # Filter columns not mentioned
  376. my @nics;
  377. foreach my $nic ( @$nic_list ) {
  378. my $filtered_nic = {};
  379. foreach my $key ( @$column_names ) {
  380. $filtered_nic->{$key} = $nic->{$key};
  381. }
  382. push @nics, $filtered_nic;
  383. }
  384. return JSON->new->pretty->utf8->encode(\@nics);
  385. }
  386. # Output NIC list in CSV
  387. sub format_nic_list_csv {
  388. my ($nic_list, $column_names) = @_;
  389. my @output;
  390. # Output CSV header
  391. my $csv = Text::CSV->new();
  392. if ( $csv->combine( @$column_names ) ) {
  393. push @output, $csv->string();
  394. }
  395. # Output CSV lines
  396. foreach my $nic ( @$nic_list ) {
  397. my @columns = @{ $nic }{ @$column_names };
  398. if ( $csv->combine( @columns ) ) {
  399. push @output, $csv->string();
  400. }
  401. }
  402. return join("\n", @output) . "\n";
  403. }
  404. # Output NIC list in HTML
  405. sub format_nic_list_html {
  406. my ($nic_list, $column_names) = @_;
  407. my @output;
  408. push @output, <<'EOM';
  409. <!DOCTYPE html>
  410. <html>
  411. <head>
  412. <meta charset="utf-8">
  413. <title>Network cards supported by iPXE</title>
  414. <style>
  415. table.tablesorter {
  416. border: thin solid black;
  417. }
  418. table.tablesorter thead {
  419. background-color: #EEE;
  420. }
  421. table.tablesorter thead th {
  422. font-weight: bold;
  423. }
  424. table.tablesorter tbody td {
  425. vertical-align: top;
  426. padding-left: 0.25em;
  427. padding-right: 0.25em;
  428. padding-bottom: 0.125em;
  429. white-space: nowrap;
  430. }
  431. table.tablesorter tbody tr.even {
  432. background-color: #eee;
  433. }
  434. table.tablesorter tbody tr.odd {
  435. background-color: #fff;
  436. }
  437. </style>
  438. </head>
  439. <body>
  440. <h1>Network cards supported by iPXE</h1>
  441. <table class="tablesorter">
  442. <thead>
  443. EOM
  444. # Output HTML header
  445. push @output, "<tr>"
  446. . join("",
  447. map { "<th>" . HTML::Entities::encode($_) . "</th>" }
  448. @$column_names
  449. )
  450. . "</tr>";
  451. push @output, <<"EOM";
  452. </thead>
  453. <tbody>
  454. EOM
  455. # Output HTML lines
  456. my $counter = 0;
  457. foreach my $nic ( @$nic_list ) {
  458. my @columns = @{ $nic }{ @$column_names }; # array slice from hashref, see perldoc perldata if confusing
  459. push @output, q!<tr class="! . ( $counter % 2 ? 'even' : 'odd' ) . q!">!
  460. . join("",
  461. map { "<td>" . HTML::Entities::encode( $_ || "" ) . "</td>" }
  462. @columns
  463. )
  464. . "</tr>";
  465. $counter++;
  466. }
  467. push @output, <<'EOM';
  468. </tbody>
  469. </table>
  470. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  471. <script>
  472. /*
  473. *
  474. * TableSorter 2.0 - Client-side table sorting with ease!
  475. * Version 2.0.5b
  476. * @requires jQuery v1.2.3
  477. * From http://tablesorter.com/
  478. *
  479. * Copyright (c) 2007 Christian Bach
  480. * Examples and docs at: http://tablesorter.com
  481. * Dual licensed under the MIT and GPL licenses:
  482. * http://www.opensource.org/licenses/mit-license.php
  483. * http://www.gnu.org/licenses/gpl.html
  484. *
  485. */
  486. (function($){$.extend({tablesorter:new
  487. function(){var parsers=[],widgets=[];this.defaults={cssHeader:"header",cssAsc:"headerSortUp",cssDesc:"headerSortDown",cssChildRow:"expand-child",sortInitialOrder:"asc",sortMultiSortKey:"shiftKey",sortForce:null,sortAppend:null,sortLocaleCompare:true,textExtraction:"simple",parsers:{},widgets:[],widgetZebra:{css:["even","odd"]},headers:{},widthFixed:false,cancelSelection:true,sortList:[],headerList:[],dateFormat:"us",decimal:'/\.|\,/g',onRenderHeader:null,selectorHeaders:'thead th',debug:false};function benchmark(s,d){log(s+","+(new Date().getTime()-d.getTime())+"ms");}this.benchmark=benchmark;function log(s){if(typeof console!="undefined"&&typeof console.debug!="undefined"){console.log(s);}else{alert(s);}}function buildParserCache(table,$headers){if(table.config.debug){var parsersDebug="";}if(table.tBodies.length==0)return;var rows=table.tBodies[0].rows;if(rows[0]){var list=[],cells=rows[0].cells,l=cells.length;for(var i=0;i<l;i++){var p=false;if($.metadata&&($($headers[i]).metadata()&&$($headers[i]).metadata().sorter)){p=getParserById($($headers[i]).metadata().sorter);}else if((table.config.headers[i]&&table.config.headers[i].sorter)){p=getParserById(table.config.headers[i].sorter);}if(!p){p=detectParserForColumn(table,rows,-1,i);}if(table.config.debug){parsersDebug+="column:"+i+" parser:"+p.id+"\n";}list.push(p);}}if(table.config.debug){log(parsersDebug);}return list;};function detectParserForColumn(table,rows,rowIndex,cellIndex){var l=parsers.length,node=false,nodeValue=false,keepLooking=true;while(nodeValue==''&&keepLooking){rowIndex++;if(rows[rowIndex]){node=getNodeFromRowAndCellIndex(rows,rowIndex,cellIndex);nodeValue=trimAndGetNodeText(table.config,node);if(table.config.debug){log('Checking if value was empty on row:'+rowIndex);}}else{keepLooking=false;}}for(var i=1;i<l;i++){if(parsers[i].is(nodeValue,table,node)){return parsers[i];}}return parsers[0];}function getNodeFromRowAndCellIndex(rows,rowIndex,cellIndex){return rows[rowIndex].cells[cellIndex];}function trimAndGetNodeText(config,node){return $.trim(getElementText(config,node));}function getParserById(name){var l=parsers.length;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==name.toLowerCase()){return parsers[i];}}return false;}function buildCache(table){if(table.config.debug){var cacheTime=new Date();}var totalRows=(table.tBodies[0]&&table.tBodies[0].rows.length)||0,totalCells=(table.tBodies[0].rows[0]&&table.tBodies[0].rows[0].cells.length)||0,parsers=table.config.parsers,cache={row:[],normalized:[]};for(var i=0;i<totalRows;++i){var c=$(table.tBodies[0].rows[i]),cols=[];if(c.hasClass(table.config.cssChildRow)){cache.row[cache.row.length-1]=cache.row[cache.row.length-1].add(c);continue;}cache.row.push(c);for(var j=0;j<totalCells;++j){cols.push(parsers[j].format(getElementText(table.config,c[0].cells[j]),table,c[0].cells[j]));}cols.push(cache.normalized.length);cache.normalized.push(cols);cols=null;};if(table.config.debug){benchmark("Building cache for "+totalRows+" rows:",cacheTime);}return cache;};function getElementText(config,node){var text="";if(!node)return"";if(!config.supportsTextContent)config.supportsTextContent=node.textContent||false;if(config.textExtraction=="simple"){if(config.supportsTextContent){text=node.textContent;}else{if(node.childNodes[0]&&node.childNodes[0].hasChildNodes()){text=node.childNodes[0].innerHTML;}else{text=node.innerHTML;}}}else{if(typeof(config.textExtraction)=="function"){text=config.textExtraction(node);}else{text=$(node).text();}}return text;}function appendToTable(table,cache){if(table.config.debug){var appendTime=new Date()}var c=cache,r=c.row,n=c.normalized,totalRows=n.length,checkCell=(n[0].length-1),tableBody=$(table.tBodies[0]),rows=[];for(var i=0;i<totalRows;i++){var pos=n[i][checkCell];rows.push(r[pos]);if(!table.config.appender){var l=r[pos].length;for(var j=0;j<l;j++){tableBody[0].appendChild(r[pos][j]);}}}if(table.config.appender){table.config.appender(table,rows);}rows=null;if(table.config.debug){benchmark("Rebuilt table:",appendTime);}applyWidget(table);setTimeout(function(){$(table).trigger("sortEnd");},0);};function buildHeaders(table){if(table.config.debug){var time=new Date();}var meta=($.metadata)?true:false;var header_index=computeTableHeaderCellIndexes(table);$tableHeaders=$(table.config.selectorHeaders,table).each(function(index){this.column=header_index[this.parentNode.rowIndex+"-"+this.cellIndex];this.order=formatSortingOrder(table.config.sortInitialOrder);this.count=this.order;if(checkHeaderMetadata(this)||checkHeaderOptions(table,index))this.sortDisabled=true;if(checkHeaderOptionsSortingLocked(table,index))this.order=this.lockedOrder=checkHeaderOptionsSortingLocked(table,index);if(!this.sortDisabled){var $th=$(this).addClass(table.config.cssHeader);if(table.config.onRenderHeader)table.config.onRenderHeader.apply($th);}table.config.headerList[index]=this;});if(table.config.debug){benchmark("Built headers:",time);log($tableHeaders);}return $tableHeaders;};function computeTableHeaderCellIndexes(t){var matrix=[];var lookup={};var thead=t.getElementsByTagName('THEAD')[0];var trs=thead.getElementsByTagName('TR');for(var i=0;i<trs.length;i++){var cells=trs[i].cells;for(var j=0;j<cells.length;j++){var c=cells[j];var rowIndex=c.parentNode.rowIndex;var cellId=rowIndex+"-"+c.cellIndex;var rowSpan=c.rowSpan||1;var colSpan=c.colSpan||1
  488. var firstAvailCol;if(typeof(matrix[rowIndex])=="undefined"){matrix[rowIndex]=[];}for(var k=0;k<matrix[rowIndex].length+1;k++){if(typeof(matrix[rowIndex][k])=="undefined"){firstAvailCol=k;break;}}lookup[cellId]=firstAvailCol;for(var k=rowIndex;k<rowIndex+rowSpan;k++){if(typeof(matrix[k])=="undefined"){matrix[k]=[];}var matrixrow=matrix[k];for(var l=firstAvailCol;l<firstAvailCol+colSpan;l++){matrixrow[l]="x";}}}}return lookup;}function checkCellColSpan(table,rows,row){var arr=[],r=table.tHead.rows,c=r[row].cells;for(var i=0;i<c.length;i++){var cell=c[i];if(cell.colSpan>1){arr=arr.concat(checkCellColSpan(table,headerArr,row++));}else{if(table.tHead.length==1||(cell.rowSpan>1||!r[row+1])){arr.push(cell);}}}return arr;};function checkHeaderMetadata(cell){if(($.metadata)&&($(cell).metadata().sorter===false)){return true;};return false;}function checkHeaderOptions(table,i){if((table.config.headers[i])&&(table.config.headers[i].sorter===false)){return true;};return false;}function checkHeaderOptionsSortingLocked(table,i){if((table.config.headers[i])&&(table.config.headers[i].lockedOrder))return table.config.headers[i].lockedOrder;return false;}function applyWidget(table){var c=table.config.widgets;var l=c.length;for(var i=0;i<l;i++){getWidgetById(c[i]).format(table);}}function getWidgetById(name){var l=widgets.length;for(var i=0;i<l;i++){if(widgets[i].id.toLowerCase()==name.toLowerCase()){return widgets[i];}}};function formatSortingOrder(v){if(typeof(v)!="Number"){return(v.toLowerCase()=="desc")?1:0;}else{return(v==1)?1:0;}}function isValueInArray(v,a){var l=a.length;for(var i=0;i<l;i++){if(a[i][0]==v){return true;}}return false;}function setHeadersCss(table,$headers,list,css){$headers.removeClass(css[0]).removeClass(css[1]);var h=[];$headers.each(function(offset){if(!this.sortDisabled){h[this.column]=$(this);}});var l=list.length;for(var i=0;i<l;i++){h[list[i][0]].addClass(css[list[i][1]]);}}function fixColumnWidth(table,$headers){var c=table.config;if(c.widthFixed){var colgroup=$('<colgroup>');$("tr:first td",table.tBodies[0]).each(function(){colgroup.append($('<col>').css('width',$(this).width()));});$(table).prepend(colgroup);};}function updateHeaderSortCount(table,sortList){var c=table.config,l=sortList.length;for(var i=0;i<l;i++){var s=sortList[i],o=c.headerList[s[0]];o.count=s[1];o.count++;}}function multisort(table,sortList,cache){if(table.config.debug){var sortTime=new Date();}var dynamicExp="var sortWrapper = function(a,b) {",l=sortList.length;for(var i=0;i<l;i++){var c=sortList[i][0];var order=sortList[i][1];var s=(table.config.parsers[c].type=="text")?((order==0)?makeSortFunction("text","asc",c):makeSortFunction("text","desc",c)):((order==0)?makeSortFunction("numeric","asc",c):makeSortFunction("numeric","desc",c));var e="e"+i;dynamicExp+="var "+e+" = "+s;dynamicExp+="if("+e+") { return "+e+"; } ";dynamicExp+="else { ";}var orgOrderCol=cache.normalized[0].length-1;dynamicExp+="return a["+orgOrderCol+"]-b["+orgOrderCol+"];";for(var i=0;i<l;i++){dynamicExp+="}; ";}dynamicExp+="return 0; ";dynamicExp+="}; ";if(table.config.debug){benchmark("Evaling expression:"+dynamicExp,new Date());}eval(dynamicExp);cache.normalized.sort(sortWrapper);if(table.config.debug){benchmark("Sorting on "+sortList.toString()+" and dir "+order+" time:",sortTime);}return cache;};function makeSortFunction(type,direction,index){var a="a["+index+"]",b="b["+index+"]";if(type=='text'&&direction=='asc'){return"("+a+" == "+b+" ? 0 : ("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : ("+a+" < "+b+") ? -1 : 1 )));";}else if(type=='text'&&direction=='desc'){return"("+a+" == "+b+" ? 0 : ("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : ("+b+" < "+a+") ? -1 : 1 )));";}else if(type=='numeric'&&direction=='asc'){return"("+a+" === null && "+b+" === null) ? 0 :("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : "+a+" - "+b+"));";}else if(type=='numeric'&&direction=='desc'){return"("+a+" === null && "+b+" === null) ? 0 :("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : "+b+" - "+a+"));";}};function makeSortText(i){return"((a["+i+"] < b["+i+"]) ? -1 : ((a["+i+"] > b["+i+"]) ? 1 : 0));";};function makeSortTextDesc(i){return"((b["+i+"] < a["+i+"]) ? -1 : ((b["+i+"] > a["+i+"]) ? 1 : 0));";};function makeSortNumeric(i){return"a["+i+"]-b["+i+"];";};function makeSortNumericDesc(i){return"b["+i+"]-a["+i+"];";};function sortText(a,b){if(table.config.sortLocaleCompare)return a.localeCompare(b);return((a<b)?-1:((a>b)?1:0));};function sortTextDesc(a,b){if(table.config.sortLocaleCompare)return b.localeCompare(a);return((b<a)?-1:((b>a)?1:0));};function sortNumeric(a,b){return a-b;};function sortNumericDesc(a,b){return b-a;};function getCachedSortType(parsers,i){return parsers[i].type;};this.construct=function(settings){return this.each(function(){if(!this.tHead||!this.tBodies)return;var $this,$document,$headers,cache,config,shiftDown=0,sortOrder;this.config={};config=$.extend(this.config,$.tablesorter.defaults,settings);$this=$(this);$.data(this,"tablesorter",config);$headers=buildHeaders(this);this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);var sortCSS=[config.cssDesc,config.cssAsc];fixColumnWidth(this);$headers.click(function(e){var totalRows=($this[0].tBodies[0]&&$this[0].tBodies[0].rows.length)||0;if(!this.sortDisabled&&totalRows>0){$this.trigger("sortStart");var $cell=$(this);var i=this.column;this.order=this.count++%2;if(this.lockedOrder)this.order=this.lockedOrder;if(!e[config.sortMultiSortKey]){config.sortList=[];if(config.sortForce!=null){var a=config.sortForce;for(var j=0;j<a.length;j++){if(a[j][0]!=i){config.sortList.push(a[j]);}}}config.sortList.push([i,this.order]);}else{if(isValueInArray(i,config.sortList)){for(var j=0;j<config.sortList.length;j++){var s=config.sortList[j],o=config.headerList[s[0]];if(s[0]==i){o.count=s[1];o.count++;s[1]=o.count%2;}}}else{config.sortList.push([i,this.order]);}};setTimeout(function(){setHeadersCss($this[0],$headers,config.sortList,sortCSS);appendToTable($this[0],multisort($this[0],config.sortList,cache));},1);return false;}}).mousedown(function(){if(config.cancelSelection){this.onselectstart=function(){return false};return false;}});$this.bind("update",function(){var me=this;setTimeout(function(){me.config.parsers=buildParserCache(me,$headers);cache=buildCache(me);},1);}).bind("updateCell",function(e,cell){var config=this.config;var pos=[(cell.parentNode.rowIndex-1),cell.cellIndex];cache.normalized[pos[0]][pos[1]]=config.parsers[pos[1]].format(getElementText(config,cell),cell);}).bind("sorton",function(e,list){$(this).trigger("sortStart");config.sortList=list;var sortList=config.sortList;updateHeaderSortCount(this,sortList);setHeadersCss(this,$headers,sortList,sortCSS);appendToTable(this,multisort(this,sortList,cache));}).bind("appendCache",function(){appendToTable(this,cache);}).bind("applyWidgetId",function(e,id){getWidgetById(id).format(this);}).bind("applyWidgets",function(){applyWidget(this);});if($.metadata&&($(this).metadata()&&$(this).metadata().sortlist)){config.sortList=$(this).metadata().sortlist;}if(config.sortList.length>0){$this.trigger("sorton",[config.sortList]);}applyWidget(this);});};this.addParser=function(parser){var l=parsers.length,a=true;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==parser.id.toLowerCase()){a=false;}}if(a){parsers.push(parser);};};this.addWidget=function(widget){widgets.push(widget);};this.formatFloat=function(s){var i=parseFloat(s);return(isNaN(i))?0:i;};this.formatInt=function(s){var i=parseInt(s);return(isNaN(i))?0:i;};this.isDigit=function(s,config){return/^[-+]?\d*$/.test($.trim(s.replace(/[,.']/g,'')));};this.clearTableBody=function(table){if($.browser.msie){function empty(){while(this.firstChild)this.removeChild(this.firstChild);}empty.apply(table.tBodies[0]);}else{table.tBodies[0].innerHTML="";}};}});$.fn.extend({tablesorter:$.tablesorter.construct});var ts=$.tablesorter;ts.addParser({id:"text",is:function(s){return true;},format:function(s){return $.trim(s.toLocaleLowerCase());},type:"text"});ts.addParser({id:"digit",is:function(s,table){var c=table.config;return $.tablesorter.isDigit(s,c);},format:function(s){return $.tablesorter.formatFloat(s);},type:"numeric"});ts.addParser({id:"currency",is:function(s){return/^[£$€?.]/.test(s);},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/[£$€]/g),""));},type:"numeric"});ts.addParser({id:"ipAddress",is:function(s){return/^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);},format:function(s){var a=s.split("."),r="",l=a.length;for(var i=0;i<l;i++){var item=a[i];if(item.length==2){r+="0"+item;}else{r+=item;}}return $.tablesorter.formatFloat(r);},type:"numeric"});ts.addParser({id:"url",is:function(s){return/^(https?|ftp|file):\/\/$/.test(s);},format:function(s){return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));},type:"text"});ts.addParser({id:"isoDate",is:function(s){return/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);},format:function(s){return $.tablesorter.formatFloat((s!="")?new Date(s.replace(new RegExp(/-/g),"/")).getTime():"0");},type:"numeric"});ts.addParser({id:"percent",is:function(s){return/\%$/.test($.trim(s));},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));},type:"numeric"});ts.addParser({id:"usLongDate",is:function(s){return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));},format:function(s){return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"shortDate",is:function(s){return/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);},format:function(s,table){var c=table.config;s=s.replace(/\-/g,"/");if(c.dateFormat=="us"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$1/$2");}else if(c.dateFormat=="uk"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$2/$1");}else if(c.dateFormat=="dd/mm/yy"||c.dateFormat=="dd-mm-yy"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/,"$1/$2/$3");}return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"time",is:function(s){return/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);},format:function(s){return $.tablesorter.formatFloat(new Date("2000/01/01 "+s).getTime());},type:"numeric"});ts.addParser({id:"metadata",is:function(s){return false;},format:function(s,table,cell){var c=table.config,p=(!c.parserMetadataName)?'sortValue':c.parserMetadataName;return $(cell).metadata()[p];},type:"numeric"});ts.addWidget({id:"zebra",format:function(table){if(table.config.debug){var time=new Date();}var $tr,row=-1,odd;$("tr:visible",table.tBodies[0]).each(function(i){$tr=$(this);if(!$tr.hasClass(table.config.cssChildRow))row++;odd=(row%2==0);$tr.removeClass(table.config.widgetZebra.css[odd?0:1]).addClass(table.config.widgetZebra.css[odd?1:0])});if(table.config.debug){$.tablesorter.benchmark("Applying Zebra widget",time);}}});})(jQuery);
  489. </script>
  490. <script type="text/javascript">
  491. $(document).ready(function() {
  492. $("table.tablesorter").tablesorter();
  493. });
  494. </script>
  495. </body>
  496. </html>
  497. EOM
  498. return join("\n", @output);
  499. }
  500. # Output NIC list in DokuWiki format (for http://ipxe.org)
  501. sub format_nic_list_dokuwiki {
  502. my ($nic_list, $column_names) = @_;
  503. my @output;
  504. push @output, <<'EOM';
  505. EOM
  506. # Output DokuWiki table header
  507. push @output, "^"
  508. . join("^",
  509. map { $_ || "" }
  510. @$column_names
  511. )
  512. . "^";
  513. # Output DokuWiki table entries
  514. foreach my $nic ( @$nic_list ) {
  515. my @columns = @{ $nic }{ @$column_names }; # array slice from hashref, see perldoc perldata if confusing
  516. push @output, '|'
  517. . join('|',
  518. map { $_ || "" }
  519. @columns
  520. )
  521. . '|';
  522. }
  523. return join("\n", @output);
  524. }