package interactive; # $Id$ use diagnostics; use strict; #-###################################################################################### #- misc imports #-###################################################################################### use MDK::Common::Func; use common; #- minimal example using interactive: # #- > use lib qw(/usr/lib/libDrakX); #- > use interactive; #- > my $in = interactive->vnew; #- > $in->ask_okcancel('title', 'question'); #- > $in->exit; #- ask_from_ takes global options ($common): #- title => window title #- messages => message displayed in the upper part of the window #- advanced_messages => message displayed when "Advanced" is pressed #- ok => force the name of the "Ok"/"Next" button #- cancel => force the name of the "Cancel"/"Previous" button #- advanced_label => force the name of the "Advanced" button #- advanced_label_close => force the name of the "Basic" button #- advanced_state => if set to 1, force the "Advanced" part of the dialog to be opened initially #- focus_cancel => force focus on the "Cancel" button #- focus_first => force focus on the first entry #- callbacks => functions called when something happen: complete canceled advanced changed focus_out ok_disabled #- ask_from_ takes a list of entries with fields: #- val => reference to the value #- label => description #- icon => icon to put before the description #- help => tooltip #- advanced => wether it is shown in by default or only in advanced mode #- disabled => function returning wether it should be disabled (grayed) #- gtk => gtk preferences #- type => #- button => (with clicked or clicked_may_quit) #- (type defaults to button if clicked or clicked_may_quit is there) #- (val need not be a reference) (if clicked_may_quit return true, it's as if "Ok" was pressed) #- label => (val need not be a reference) (type defaults to label if val is not a reference) #- bool (with "text" or "image" (which overrides text) giving an image filename) #- range (with min, max) #- combo (with list, not_edit, format) #- list (with list, icon2f (aka icon), separator (aka tree), format (aka pre_format function), #- help can be a hash or a function, #- tree_expanded boolean telling wether the tree should be wide open by default #- quit_if_double_click boolean #- allow_empty_list disables the special cases for 0 and 1 element lists #- image2f is a subroutine which takes a value of the list as parameter, and returns an array (text, image_file_name)) #- entry (the default) (with hidden) # #- heritate from this class and you'll get all made interactivity for same steps. #- for this you need to provide #- - ask_from_listW(o, title, messages, arrayref, default) returns one string of arrayref #- #- where #- - o is the object #- - title is a string #- - messages is an refarray of strings #- - default is an optional string (default is in arrayref) #- - arrayref is an arrayref of strings #- - arrayref2 contains booleans telling the default state, #- #- ask_from_list and ask_from_list_ are wrappers around ask_from_biglist and ask_from_smalllist #- #- ask_from_list_ just translate arrayref before calling ask_from_list and untranslate the result #- #- ask_from_listW should handle differently small lists and big ones. #- #-###################################################################################### #- OO Stuff #-###################################################################################### sub new($) { my ($type) = @_; bless {}, ref($type) || $type; } sub vnew { my ($_type, $su, $icon) = @_; $su = $su eq "su"; if ($ENV{INTERACTIVE_HTTP}) { require interactive::http; return interactive::http->new; } require c; if ($su) { $ENV{PATH} = "/sbin:/usr/sbin:$ENV{PATH}"; $su = '' if $::testing || $ENV{TESTING}; } require_root_capability() if $su; if (check_for_xserver()) { eval { require interactive::gtk }; if (!$@) { my $o = interactive::gtk->new; if ($icon && $icon ne 'default' && !$::isWizard) { $o->{icon} = $icon } else { undef $o->{icon} } return $o; } } require 'log.pm'; #- "require log" causes some pb, perl thinking that "log" is the log() function undef *log::l; *log::l = sub {}; # otherwise, it will bother us :( require interactive::newt; interactive::newt->new; } sub enter_console {} sub leave_console {} sub suspend {} sub resume {} sub end {} sub exit { exit($_[0]) } #-###################################################################################### #- Interactive functions #-###################################################################################### sub ask_warn { my ($o, $title, $message) = @_; ask_warn_($o, { title => $title, messages => $message }); } sub ask_yesorno { my ($o, $title, $message, $def) = @_; ask_yesorno_($o, { title => $title, messages => $message }, $def); } sub ask_okcancel { my ($o, $title, $message, $def) = @_; ask_okcancel_($o, { title => $title, messages => $message }, $def); } sub ask_warn_ { my ($o, $common) = @_; ask_from_listf_raw_no_check($o, $common, undef, [ N("Ok") ]); } sub ask_yesorno_ { my ($o, $common, $def) = @_; $common->{cancel} = ''; ask_from_listf_raw($o, $common, sub { translate($_[0]) }, [ N_("Yes"), N_("No") ], $def ? "Yes" : "No") eq "Yes"; } sub ask_okcancel_ { my ($o, $common, $def) = @_; if ($::isWizard) { $::no_separator = 1; $common->{focus_cancel} = !$def; ask_from_no_check($o, $common, []); } else { ask_from_listf_raw($o, $common, sub { translate($_[0]) }, [ N_("Ok"), N_("Cancel") ], $def ? "Ok" : "Cancel") eq "Ok"; } } sub ask_file { my ($o, $title, $dir) = @_; $o->ask_fileW($title, $dir); } sub ask_fileW { my ($o, $title, $_dir) = @_; $o->ask_from_entry($title, N("Choose a file")); } sub ask_from_list { my ($o, $title, $message, $l, $def) = @_; ask_from_listf($o, $title, $message, undef, $l, $def); } sub ask_from_list_ { my ($o, $title, $message, $l, $def) = @_; ask_from_listf($o, $title, $message, sub { translate($_[0]) }, $l, $def); } sub ask_from_listf_ { my ($o, $title, $message, $f, $l, $def) = @_; ask_from_listf($o, $title, $message, sub { translate($f->(@_)) }, $l, $def); } sub ask_from_listf { my ($o, $title, $message, $f, $l, $def) = @_; ask_from_listf_raw($o, { title => $title, messages => $message }, $f, $l, $def); } sub ask_from_listf_raw { my ($_o, $_common, $_f, $l, $_def) = @_; @$l == 0 and die "ask_from_list: empty list\n" . backtrace(); @$l == 1 and return $l->[0]; goto &ask_from_listf_raw_no_check; } sub ask_from_listf_raw_no_check { my ($o, $common, $f, $l, $def) = @_; if (@$l <= ($::isWizard ? 1 : 2)) { my ($ok, $cancel) = map { $_ && may_apply($f, $_) } @$l; if (length "$ok$cancel" < 70) { my $ret = eval { put_in_hash($common, { ok => $ok, if_($cancel, cancel => $cancel, focus_cancel => $def eq $l->[1]) }); ask_from_no_check($o, $common, []) ? $l->[0] : $l->[1]; }; die if $@ && $@ !~ /^wizcancel/; return $@ ? undef : $ret; } } ask_from_no_check($o, $common, [ { val => \$def, type => 'list', list => $l, format => $f } ]) && $def; } sub ask_from_treelist { my ($o, $title, $message, $separator, $l, $def) = @_; ask_from_treelistf($o, $title, $message, $separator, undef, $l, $def); } sub ask_from_treelist_ { my ($o, $title, $message, $separator, $l, $def) = @_; my $transl = sub { join '|', map { translate($_) } split(quotemeta($separator), $_[0]) }; ask_from_treelistf($o, $title, $message, $separator, $transl, $l, $def); } sub ask_from_treelistf { my ($o, $title, $message, $separator, $f, $l, $def) = @_; ask_from($o, $title, $message, [ { val => \$def, separator => $separator, list => $l, format => $f, sort => 1 } ]) or return; $def; } sub ask_many_from_list { my ($o, $title, $message, @l) = @_; @l = grep { @{$_->{list}} } @l or return ''; foreach my $h (@l) { $h->{e}{$_} = { text => may_apply($h->{label}, $_), val => $h->{val} ? $h->{val}->($_) : do { my $i = $h->{value} ? $h->{value}->($_) : $h->{values} ? member($_, @{$h->{values}}) : 0; \$i; }, type => 'bool', help => may_apply($h->{help}, $_, ''), icon => may_apply($h->{icon2f}, $_, ''), } foreach @{$h->{list}}; if ($h->{sort}) { $h->{list} = [ sort { $h->{e}{$a}{text} cmp $h->{e}{$b}{text} } @{$h->{list}} ]; } } $o->ask_from($title, $message, [ map { my $h = $_; map { $h->{e}{$_} } @{$h->{list}} } @l ]) or return; @l = map { my $h = $_; [ grep { ${$h->{e}{$_}{val}} } @{$h->{list}} ]; } @l; wantarray() ? @l : $l[0]; } sub ask_from_entry { my ($o, $title, $message, %callback) = @_; first(ask_from_entries($o, $title, $message, [''], %callback)); } sub ask_from_entries { my ($o, $title, $message, $l, %callback) = @_; my @l = map { my $i = ''; { label => $_, val => \$i } } @$l; $o->ask_from($title, $message, \@l, %callback) ? map { ${$_->{val}} } @l : undef; } sub ask_from__add_modify_remove { my ($o, $title, $message, $l, %callback) = @_; die "ask_from__add_modify_remove only handles one item" if @$l != 1; $callback{$_} or internal_error("missing callback $_") foreach qw(Add Modify Remove); if ($o->can('ask_from__add_modify_removeW')) { $o->ask_from__add_modify_removeW($title, $message, $l, %callback); } else { my $e = $l->[0]; my $chosen_element; put_in_hash($e, { allow_empty_list => 1, val => \$chosen_element, type => 'list' }); while (1) { my $continue; my @l = (@$l, map { my $s = $_; { val => translate($_), clicked_may_quit => sub { my $r = $callback{$s}->($chosen_element); defined $r or return; $continue = 1; } } } N_("Add"), if_(@{$e->{list}} > 0, N_("Modify"), N_("Remove"))); $o->ask_from_({ title => $title, messages => $message, callbacks => \%callback }, \@l) or return; return if !$continue; } } } #- can get a hash of callback: focus_out changed and complete #- moreove if you pass a hash with a field list -> combo #- if you pass a hash with a field hidden -> emulate stty -echo sub ask_from { my ($o, $title, $message, $l, %callback) = @_; ask_from_($o, { title => $title, messages => $message, callbacks => \%callback }, $l); } sub ask_from_normalize { my ($o, $common, $l) = @_; ref($l) eq 'ARRAY' or internal_error('ask_from_normalize'); foreach my $e (@$l) { if (my $li = $e->{list}) { ref($e->{val}) =~ /SCALAR|REF/ or internal_error($e->{val} ? "field {val} must be a reference (it is $e->{val})" : "field {val} is mandatory"); #-# if ($e->{sort} || @$li > 10 && !exists $e->{sort}) { my @l2 = map { may_apply($e->{format}, $_) } @$li; my @places = sort { $l2[$a] cmp $l2[$b] } 0 .. $#l2; $e->{list} = $li = [ map { $li->[$_] } @places ]; } $e->{type} = 'iconlist' if $e->{icon2f}; $e->{type} = 'treelist' if $e->{separator}; add2hash_($e, { not_edit => 1 }); $e->{type} ||= 'combo'; if (!$e->{not_edit}) { die q(when using "not_edit" you must use strings, not a data structure) if ref(${$e->{val}}) || any { ref $_ } @$li; } if ($e->{type} ne 'combo' || $e->{not_edit}) { ${$e->{val}} = $li->[0] if !member(may_apply($e->{format}, ${$e->{val}}), map { may_apply($e->{format}, $_) } @$li); } } elsif ($e->{type} eq 'range') { $e->{min} <= $e->{max} or die "bad range min $e->{min} > max $e->{max} (called from " . join(':', caller()) . ")"; ${$e->{val}} = max($e->{min}, min(${$e->{val}}, $e->{max})); } elsif ($e->{type} eq 'button' || $e->{clicked} || $e->{clicked_may_quit}) { $e->{type} = 'button'; $e->{clicked_may_quit} ||= $e->{clicked} ? sub { $e->{clicked}(); 0 } : sub {}; $e->{val} = \ (my $_v = $e->{val}) if !ref($e->{val}); } elsif ($e->{type} eq 'label' || !ref($e->{val})) { $e->{type} = 'label'; $e->{val} = \ (my $_v = $e->{val}) if !ref($e->{val}); } else { $e->{type} ||= 'entry'; } $e->{disabled} ||= sub { 0 }; } #- don't display empty lists and one element lists @$l = grep { if ($_->{list} && $_->{not_edit} && !$_->{allow_empty_list}) { if (!@{$_->{list}}) { eval { require 'log.pm'; #- "require log" causes some pb, perl thinking that "log" is the log() function log::l("ask_from_normalize: empty list for $_->{label}\n" . backtrace()); }; } @{$_->{list}} > 1; } else { 1; } } @$l; if (!$common->{title} && $::isStandalone) { ($common->{title} = $0) =~ s|.*/||; } $common->{interactive_help} ||= $o->{interactive_help}; $common->{interactive_help} ||= $common->{interactive_help_id} && $o->interactive_help_sub_get_id($common->{interactive_help_id}); $common->{advanced_label} ||= N("Advanced"); $common->{advanced_label_close} ||= N("Basic"); $common->{$_} = $common->{$_} ? [ deref($common->{$_}) ] : [] foreach qw(messages advanced_messages); add2hash_($common->{callbacks} ||= {}, { changed => sub {}, focus_out => sub {}, complete => sub { 0 }, canceled => sub { 0 }, advanced => sub {} }); } sub ask_from_ { my ($o, $common, $l) = @_; ask_from_normalize($o, $common, $l); @$l or return 1; $common->{cancel} = '' if !defined wantarray(); ask_from_real($o, $common, $l); } sub ask_from_no_check { my ($o, $common, $l) = @_; ask_from_normalize($o, $common, $l); $common->{cancel} = '' if !defined wantarray(); $o->ask_fromW($common, partition { !$_->{advanced} } @$l); } sub ask_from_real { my ($o, $common, $l) = @_; my $v = $o->ask_fromW($common, partition { !$_->{advanced} } @$l); %$common = (); $v; } sub ask_browse_tree_info { my ($o, $title, $message, $common) = @_; $common->{interactive_help} ||= $common->{interactive_help_id} && $o->interactive_help_sub_get_id($common->{interactive_help_id}); add2hash_($common, { ok => $::isWizard ? ($::Wizard_finished ? N("Finish") : N("Next ->")) : N("Ok"), cancel => $::isWizard ? N("<- Previous") : N("Cancel") }); add2hash_($common, { title => $title, message => $message }); add2hash_($common, { grep_allowed_to_toggle => sub { @_ }, grep_unselected => sub { grep { $common->{node_state}($_) eq 'unselected' } @_ }, check_interactive_to_toggle => sub { 1 }, toggle_nodes => sub { my ($set_state, @nodes) = @_; my $new_state = !$common->{grep_unselected}($nodes[0]) ? 'selected' : 'unselected'; $set_state->($_, $new_state) foreach @nodes; }, }); $o->ask_browse_tree_info_refW($common); } sub ask_browse_tree_info_refW { #- default definition, do not use with too many items (memory consuming) my ($o, $common) = @_; my ($l, $v, $h) = ([], [], {}); $common->{build_tree}(sub { my ($node) = $common->{grep_allowed_to_toggle}(@_); if (my $state = $node && $common->{node_state}($node)) { push @$l, $node; $state eq 'selected' and push @$v, $node; $h->{$node} = $state eq 'selected'; } }, 'flat'); add2hash_($common, { list => $l, #- TODO interactivity of toggle is missing values => $v, help => sub { $common->{get_info}($_[0]) }, }); my ($new_v) = $o->ask_many_from_list($common->{title}, $common->{message}, $common) or return; $common->{toggle_nodes}(sub {}, grep { ! delete $h->{$_} } @$new_v); $common->{toggle_nodes}(sub {}, grep { $h->{$_} } keys %$h); 1; } sub wait_message { my ($o, $title, $message, $temp) = @_; my $w = $o->wait_messageW($title, [ N("Please wait"), deref($message) ]); push @tempory::objects, $w if $temp; my $b = before_leaving { $o->wait_message_endW($w) }; #- enable access through set MDK::Common::Func::add_f4before_leaving(sub { $o->wait_message_nextW([ deref($_[1]) ], $w) }, $b, 'set'); $b; } sub kill {} sub helper_separator_tree_to_tree { my ($separator, $list, $formatted_list) = @_; my $sep = quotemeta $separator; my $tree = {}; each_index { my @l = split $sep; my $leaf = pop @l; my $node = $tree; foreach (@l) { $node = $node->{$_} ||= do { my $r = {}; push @{$node->{_order_}}, $_; $r; }; } push @{$node->{_leaves_}}, [ $leaf, $list->[$::i] ]; (); } @$formatted_list; $tree; } sub interactive_help_has_id { my ($_o, $id) = @_; exists $help::steps{$id}; } sub interactive_help_get_id { my ($_o, @l) = @_; @l = map { join("\n\n", map { s/\n/ /mg; $_ } split("\n\n", translate($help::steps{$_}))) } grep { exists $help::steps{$_} } @l; join("\n\n\n", @l); } sub interactive_help_sub_get_id { my ($o, $id) = @_; $o->interactive_help_has_id($id) && sub { $o->interactive_help_get_id($id) }; } sub interactive_help_sub_display_id { my ($o, $id) = @_; $o->interactive_help_has_id($id) && sub { $o->ask_warn(N("Help"), $o->interactive_help_get_id($id)) }; } 1; d='n335' href='#n335'>335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
package commands; # $Id$
#-########################################################################
#- This file implement many common shell commands:
#- true, false, cat, which, dirname, basename, rmdir, lsmod, grep, tr,
#- mount, umount, mkdir, mknod, ln, rm, chmod, chown, mkswap, swapon,
#- swapoff, ls, cp, ps, dd, head, tail, strings, hexdump, more, insmod,
#- modprobe, route, df, kill, lspci, lssbus, dmesg, sort, du,
#-########################################################################
use diagnostics;
use strict;
use vars qw($printable_chars *ROUTE *DF *PS);
#-######################################################################################
#- misc imports
#-######################################################################################
use MDK::Common::System;
use common;
#-#####################################################################################
#- Globals
#-#####################################################################################
my $BUFFER_SIZE = 1024;
#-######################################################################################
#- Functions
#-######################################################################################
sub getopts {
my $o = shift;
my @r = map { '' } (@_ = split //, $_[0]);
while (1) {
local $_ = $o->[0];
$_ && /^-/ or return @r;
for (my $i = 0; $i < @_; $i++) { /$_[$i]/ and $r[$i] = $_[$i] }
shift @$o;
}
@r;
}
sub true { exit 0 }
sub false { exit 1 }
sub cat { @ARGV = @_; print while <> }
sub dirname_ { print dirname(@_), "\n" }
sub basename_ { print basename(@_), "\n" }
sub rmdir_ { foreach (@_) { rmdir $_ or die "rmdir: can't remove $_\n" } }
sub lsmod { print "Module Size Used by\n"; cat("/proc/modules") }
sub which {
ARG: foreach (@_) { foreach my $c (split /:/, $ENV{PATH}) { -x "$c/$_" and print("$c/$_\n"), next ARG } }
}
sub grep_ {
my ($h, $v, $i) = getopts(\@_, qw(hvi));
@_ == 0 || $h and die "usage: grep <regexp> [files...]\n";
my $r = shift;
$r = qr/$r/i if $i;
@ARGV = @_; (/$r/ xor $v) and print while <>;
}
sub tr_ {
my ($s, $c, $d) = getopts(\@_, qw(s c d));
@_ >= 1 + (!$d || $s) or die "usage: tr [-c] [-s [-d]] <set1> <set2> [files...]\n or tr [-c] -d <set1> [files...]\n";
my $set1 = shift;
my $set2; !$d || $s and $set2 = shift;
@ARGV = @_;
eval "(tr/$set1/$set2/$s$d$c, print) while <>";
}
sub mount {
@_ or return cat("/proc/mounts");
my ($t, $r) = getopts(\@_, qw(tr));
my $fs = $t && shift;
@_ == 2 or die "usage: mount [-r] [-t <fs>] <device> <dir>\n",
" (use -r for readonly)\n",
" (if /dev/ is left off the device name, a temporary node will be created)\n";
my ($dev, $where) = @_;
$fs ||= $where =~ /:/ ? "nfs" :
$dev =~ /fd/ ? "vfat" : "ext2";
require fs;
require modules;
modules::load_dependencies("/modules/modules.dep");
fs::mount($dev, $where, $fs, $r);
}
sub umount {
@_ == 1 or die "umount expects a single argument\n";
require fs;
fs::umount($_[0]);
}
sub mkdir_ {
my ($_rec) = getopts(\@_, qw(p));
mkdir_p($_) foreach @_;
}
sub mknod {
if (@_ == 1) {
require devices;
eval { devices::make($_[0]) }; $@ and die "mknod: failed to create $_[0]\n";
} elsif (@_ == 4) {
require c;
my $mode = ${{ "b" => c::S_IFBLK(), "c" => c::S_IFCHR() }}{$_[1]} or die "unknown node type $_[1]\n";
syscall_('mknod', my $_a = $_[0], $mode | 0600, makedev($_[2], $_[3])) or die "mknod failed: $!\n";
} else { die "usage: mknod <path> [b|c] <major> <minor> or mknod <path>\n" }
}
sub ln {
my ($force, $soft) = getopts(\@_, qw(fs));
@_ >= 1 or die "usage: ln [-s] [-f] <source> [<dest>]\n";
my ($source, $dest) = @_;
$dest ||= basename($source);
$force and unlink $dest;
($soft ? symlink($source, $dest) : link($source, $dest)) or die "ln failed: $!\n";
}
sub rm {
my ($rec, undef) = getopts(\@_, qw(rf));
my $rm; $rm = sub {
foreach (@_) {
if (!-l $_ && -d $_) {
$rec or die "$_ is a directory\n";
&$rm(glob_($_));
rmdir $_ or die "can't remove directory $_: $!\n";
} else { unlink $_ or die "rm of $_ failed: $!\n" }
}
};
&$rm(@_);
}
sub chmod_ {
@_ >= 2 or die "usage: chmod <mode> <files>\n";
my $mode = shift;
$mode =~ /^[0-7]+$/ or die "illegal mode $mode\n";
foreach (@_) { chmod oct($mode), $_ or die "chmod failed $_: $!\n" }
}
sub chown_ {
my ($rec, undef) = getopts(\@_, qw(r));
local $_ = shift or die "usage: chown [-r] name[.group] <files>\n";
my ($name, $group) = (split('\.'), $_);
my ($uid, $gid) = (getpwnam($name) || $name, getgrnam($group) || $group);
my $chown; $chown = sub {
foreach (@_) {
chown $uid, $gid, $_ or die "chown of file $_ failed: $!\n";
-d $_ && $rec and &$chown(glob_($_));
}
};
&$chown(@_);
}
sub mkswap {
@_ == 1 or die "mkswap <device>\n";
require swap;
swap::enable($_[0], 0);
}
sub swapon {
@_ == 1 or die "swapon <file>\n";
require swap;
swap::swapon($_[0]);
}
sub swapoff {
@_ == 1 or die "swapoff <file>\n";
require swap;
swap::swapoff($_[0]);
}
sub uncpio {
@_ and die "uncpio reads from stdin\n";
# cpioInstallArchive(gzdopen(0, "r"), NULL, 0, NULL, NULL, &fail);
}
sub rights {
my $r = '-' x 9;
my @rights = (qw(x w r x w r x w r), ['t', 0], ['s', 3], ['s', 6]);
for (my $i = 0; $i < @rights; $i++) {
if (vec(pack("S", $_[0]), $i, 1)) {
my ($val, $place) = $i >= 9 ? @{$rights[$i]} : ($rights[$i], $i);
my $old = \substr($r, 8 - $place, 1);
$$old = $$old eq '-' && $i >= 9 ? uc $val : $val;
}
}
my @types = split //, "_pc_d_b_-_l_s";
$types[($_[0] >> 12) & 0xf] . $r;
}
sub displaySize {
my $m = $_[0] >> 12;
$m == 4 || $m == 8 || $m == 10;
}
sub ls {
my ($l, $h) = getopts(\@_, qw(lh));
$h and die "usage: ls [-l] <files...>\n";
@_ or @_ = '.';
@_ == 1 && -d $_[0] and @_ = glob_($_[0]);
foreach (sort @_) {
if ($l) {
my @s = lstat or warn("can't stat file $_\n"), next;
formline(
"@<<<<<<<<< @<<<<<<< @<<<<<<< @>>>>>>>> @>>>>>>>>>>>>>>> @*\n",
rights($s[2]), getpwuid $s[4] || $s[4], getgrgid $s[5] || $s[5],
displaySize($s[2]) ? $s[7] : join(", ", unmakedev($s[6])),
scalar localtime $s[9], -l $_ ? "$_ -> " . readlink $_ : $_);
print $^A; $^A = '';
} else { print "$_\n" }
}
}
sub cp {
@_ >= 2 or die "usage: cp <sources> <dest>\n(this cp does -Rfl by default)\n";
cp_af(@_);
}
sub ps {
@_ and die "usage: ps\n";
my ($pid, $rss, $cpu, $cmd);
my ($uptime) = split ' ', first(cat_("/proc/uptime"));
my $hertz = 100;
require c;
my $page = c::getpagesize() / 1024;
open PS, ">&STDOUT"; #- PS must be not be localised otherwise the "format PS" fails
format PS_TOP =
PID RSS %CPU CMD
.
format PS =
@>>>> @>>>> @>>> @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$pid, $rss, $cpu, $cmd
.
foreach (sort { $a <=> $b } grep { /\d+/ } all('/proc')) {
$pid = $_;
my @l = split(' ', cat_("/proc/$pid/stat"));
$cpu = sprintf "%2.1f", max(0, min(99, ($l[13] + $l[14]) * 100 / $hertz / ($uptime - $l[21] / $hertz)));
$rss = (split ' ', cat_("/proc/$pid/stat"))[23] * $page;
(($cmd) = cat_("/proc/$pid/cmdline")) =~ s/\0/ /g;
$cmd ||= (split ' ', (cat_("/proc/$pid/stat"))[0])[1];
write PS;
}
}
sub dd {
my $u = "usage: dd [-h] [-p] [if=<file>] [of=<file>] [bs=<number>] [count=<number>]\n";
my ($help, $percent) = getopts(\@_, qw(hp));
die $u if $help;
my %h = (if => *STDIN, of => *STDOUT, bs => 512, count => undef);
foreach (@_) {
/(.*?)=(.*)/ && exists $h{$1} or die $u;
$h{$1} = $2;
}
local (*IF, *OF); my ($tmp, $nb, $read);
ref($h{if}) eq 'GLOB' ? (*IF = $h{if}) : sysopen(IF, $h{if}, 0) || die "error: can't open file $h{if}\n";
ref($h{of}) eq 'GLOB' ? (*OF = $h{of}) : sysopen(OF, $h{of}, 0x41) || die "error: can't open file $h{of}\n";
$h{bs} = removeXiBSuffix($h{bs});
for ($nb = 0; !$h{count} || $nb < $h{count}; $nb++) {
printf "\r%02.1d%%", 100 * $nb / $h{count} if $h{count} && $percent;
$read = sysread(IF, $tmp, $h{bs}) or ($h{count} ? die "error: can't read block $nb\n" : last);
syswrite(OF, $tmp) or die "error: can't write block $nb\n";
$read < $h{bs} and $read = 1, last;
}
print STDERR "\r$nb+$read records in\n";
print STDERR "$nb+$read records out\n";
}
sub head_tail {
my ($h, $n) = getopts(\@_, qw(hn));
$h || @_ < to_bool($n) and die "usage: $0 [-h] [-n lines] [<file>]\n";
$n = $n ? shift : 10;
my $fh; @_ ? open($fh, $_[0]) || die "error: can't open file $_[0]\n" : ($fh = *STDIN);
if ($0 eq 'head') {
local $_;
while (<$fh>) { $n-- or return; print }
} else {
@_ = ();
local $_;
while (<$fh>) { push @_, $_; @_ > $n and shift }
print @_;
}
}
sub head { $0 = 'head'; &head_tail }
sub tail { $0 = 'tail'; &head_tail }
sub strings {
my ($h, $o, $n) = getopts(\@_, qw(hon));
$h and die "usage: strings [-o] [-n min-length] [<files>]\n";
$n = $n ? shift : 4;
$/ = "\0"; @ARGV = @_; my $l = 0;
local $_;
while (<>) {
while (/[$printable_chars]{$n,}/og) {
printf "%07d ", ($l + length $') if $o;
print "$&\n";
}
$l += length;
} continue { $l = 0 if eof }
}
sub hexdump {
my $i = 0; $/ = \16; @ARGV = @_;
local $_;
while (<>) {
printf "%08lX ", $i; $i += 16;
print join(" ", (map { sprintf "%02X", $_ } unpack("C*", $_)),
(s/[^$printable_chars]/./og, $_)[1]), "\n";
}
}
sub more {
@ARGV = @_;
require devices;
my $tty = devices::make('tty');
my $n = 0;
open(my $IN, $tty) or die "can't open $tty\n";
local $_;
while (<>) {
if (++$n == 25) {
my $v = <$IN>;
$v =~ /^q/ and exit 0;
$n = 0;
}
print
}
}
sub insmod {
my ($h) = getopts(\@_, qw(h));
$h || @_ == 0 and die "usage: insmod <module> [options]\n";
my $f = local $_ = shift;
require run_program;
#- try to install the module if it exist else extract it from archive.
#- needed for cardmgr.
unless (-r $f) {
$_ = $1 if m!.*/([^/]*)\.o!;
unless (-r ($f = "/lib/modules/$_.o")) {
$f = "/tmp/$_.o";
my $cz = "/lib/modules" . (arch() eq 'sparc64' && "64") . ".cz";
-e $cz or $cz .= '-'.c::kernel_version();
if (-e $cz) {
eval {
require packdrake;
my $packer = new packdrake($cz, quiet => 1);
$packer->extract_archive("/tmp", "$_.o");
};
} elsif (-e "/lib/modules.cpio.bz2") {
run_program::run("cd /tmp ; $ENV{LD_LOADER} bzip2 -cd /lib/modules.cpio.bz2 | $ENV{LD_LOADER} cpio -i $_.o");
} else {
die "unable to find an archive for modules";
}
}
}
-r $f or die "can't find module $_";
run_program::run(["/usr/bin/insmod_", "insmod"], "-f", $f, @_) or die("insmod $_ failed");
unlink $f;
}
sub modprobe {
my ($h) = getopts(\@_, qw(h));
$h || @_ == 0 and die "usage: modprobe <module> [options]\n";
my $name = shift;
require modules;
modules::load_dependencies("/modules/modules.dep");
modules::load([ $name, @_ ]);
}
sub route {
@_ == 0 or die "usage: route\nsorry, no modification handled\n";
my ($titles, @l) = cat_("/proc/net/route");
my @titles = split ' ', $titles;
my %l;
open ROUTE, ">&STDOUT"; #- ROUTE must be not be localised otherwise the "format ROUTE" fails
format ROUTE_TOP =
Destination Gateway Mask Iface
.
format ROUTE =
@<<<<<<<<<<<< @<<<<<<<<<<<< @<<<<<<<<<<<< @<<<<<<<
$l{Destination}, $l{Gateway}, $l{Mask}, $l{Iface}
.
foreach (@l) {
/^\s*$/ and next;
@l{@titles} = split;
$_ = join ".", reverse map { hex $_ } unpack "a2a2a2a2", $_ foreach @l{qw(Destination Gateway Mask)};
$l{Destination} = 'default' if $l{Destination} eq "0.0.0.0";
$l{Gateway} = '*' if $l{Gateway} eq "0.0.0.0";
write ROUTE;
}
}
sub df {
my ($h) = getopts(\@_, qw(h));
my ($dev, $size, $free, $used, $use, $mntpoint);
open DF, ">&STDOUT"; #- DF must be not be localised otherwise the "format DF" fails
format DF_TOP =
Filesystem Size Used Avail Use Mounted on
.
format DF =
@<<<<<<<<<<<<<<<< @>>>>>>> @>>>>>>> @>>>>>>> @>>>>>% @<<<<<<<<<<<<<<<<<<<<<<<<<
$dev, $size, $used, $free, $use, $mntpoint
.
my %h;
foreach (cat_("/proc/mounts"), cat_("/etc/mtab")) {
($dev, $mntpoint) = split;
$h{$dev} = $mntpoint;
}
foreach (sort keys %h) {
$dev = $_;
($size, $free) = MDK::Common::System::df($mntpoint = $h{$dev});
$size or next;
$use = int(100 * ($size - $free) / $size);
$used = $size - $free;
if ($h) {
$used = int($used / 1024 . "M");
$size = int($size / 1024 . "M");
$free = int($free / 1024 . "M");
}
write DF if $size;
}
}
sub kill {
my $signal = 15;
@_ or die "usage: kill [-<signal>] pids\n";
$signal = (shift, $1)[1] if $_[0] =~ /^-(.*)/;
kill $signal, @_ or die "kill failed: $!\n";
}
sub lspci {
require detect_devices;
print join "\n", detect_devices::stringlist(1), '';
}
*lssbus = \&lspci;
sub dmesg { print cat_("/tmp/syslog") }
sub sort {
my ($n, $h) = getopts(\@_, qw(nh));
$h and die "usage: sort [-n] [<file>]\n";
my $fh; @_ ? open($fh, $_[0]) || die "error: can't open file $_[0]\n" : ($fh = *STDIN);
if ($n) {
print(sort { $a <=> $b } <$fh>);
} else {
print(sort <$fh>);
}
}
sub du {
my ($s, $h) = getopts(\@_, qw(sh));
$h || !$s and die "usage: du -s [<directories>]\n";
my $f; $f = sub {
my ($e) = @_;
my $s = (lstat($e))[12];
$s += sum(map { &$f($_) } glob_("$e/*")) if !-l $e && -d $e;
$s;
};
print &$f($_) >> 1, "\t$_\n" foreach @_ ? @_ : glob_("*");
}
sub install_cpio($$;@) {
my ($dir, $name, @more) = @_;
return "$dir/$name" if -e "$dir/$name";
my $cpio = "$dir.cpio.bz2";
-e $cpio or return;
eval { rm("-r", $dir) };
mkdir $dir, 0755;
require run_program;
my $more = join " ", map { $_ && "$_ $_/*" } @more;
run_program::run("cd $dir ; $ENV{LD_LOADER} bzip2 -cd $cpio | $ENV{LD_LOADER} cpio -id $name $name/* $more");
"$dir/$name";
}
sub bug {
my ($h) = getopts(\@_, "h");
$h and die "usage: bug\nput file report.bug on fat formatted floppy\n";
require detect_devices;
mount devices::make(detect_devices::floppy()), "/fd0";
require install_any;
output("/fd0/report.bug", install_any::report_bug("/mnt")); #- no other way :-(
umount "/fd0";
common::sync();
}
sub loadkeys {
my ($h) = getopts(\@_, "h");
$h || @_ != 1 and die "usage: loadkeys <keyboard>\n";
require keyboard;
keyboard::setup({ KEYBOARD => $_[0] });
}
sub sync { common::sync() }
1;