SubDomain.pm 214 KB
Newer Older
1
# $Id$
2 3 4
#
# ----------------------------------------------------------------------
#    Copyright (c) 2006 Novell, Inc. All Rights Reserved.
5
#    Copyright (c) 2010 Canonical, Ltd.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#
#    This program is free software; you can redistribute it and/or
#    modify it under the terms of version 2 of the GNU General Public
#    License as published by the Free Software Foundation.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, contact Novell, Inc.
#
#    To contact Novell about this file by physical or electronic mail,
#    you may find current contact information at www.novell.com.
# ----------------------------------------------------------------------

package Immunix::SubDomain;

25
use strict;
26
use warnings;
27 28 29

use Carp;
use Cwd qw(cwd realpath);
30
use File::Basename;
31
use File::Temp qw/ tempfile tempdir /;
32 33
use Data::Dumper;

34 35
use Locale::gettext;
use POSIX;
36 37
use Storable qw(dclone);

38
use Term::ReadKey;
39 40

use Immunix::Severity;
41 42
use Immunix::Repository;
use Immunix::Config;
43
use LibAppArmor;
44 45 46

require Exporter;
our @ISA    = qw(Exporter);
47 48 49 50 51 52 53 54 55
our @EXPORT = qw(
    %sd
    %qualifiers
    %include
    %helpers

    $filename
    $profiledir
    $parser
56
    $logger
57 58 59 60 61 62 63
    $UI_Mode
    $running_under_genprof

    which
    getprofilefilename
    get_full_path
    fatal_error
64
    get_pager
65 66 67 68 69 70 71 72 73 74 75 76

    getprofileflags
    setprofileflags
    complain
    enforce

    autodep
    reload

    UI_GetString
    UI_GetFile
    UI_YesNo
77 78 79
    UI_ShortMessage
    UI_LongMessage

80 81 82
    UI_Important
    UI_Info
    UI_PromptUser
83
    display_changes
84 85 86 87 88 89 90 91
    getkey

    do_logprof_pass

    loadincludes
    readprofile
    readprofiles
    writeprofile
92
    serialize_profile
93 94 95
    attach_profile_data
    parse_repo_profile
    activate_repo_profiles
96 97 98 99 100 101 102 103 104 105

    check_for_subdomain

    setup_yast
    shutdown_yast
    GetDataFromYast
    SendDataToYast

    checkProfileSyntax
    checkIncludeSyntax
106
    check_qualifiers
107 108

    isSkippableFile
109
    isSkippableDir
110
);
111

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
our $confdir = "/etc/apparmor";

our $running_under_genprof = 0;

our $DEBUGGING;

our $unimplemented_warning = 0;

# keep track of if we're running under yast or not - default to text mode
our $UI_Mode = "text";

our $sevdb;

# initialize Term::ReadLine if it's available
our $term;
eval {
128 129 130
    require Term::ReadLine;
    import Term::ReadLine;
    $term = new Term::ReadLine 'AppArmor';
131 132 133
};

# initialize the local poo
134 135
setlocale(LC_MESSAGES, "")
    unless defined(LC_MESSAGES);
136 137 138 139 140
textdomain("apparmor-utils");

# where do we get our log messages from?
our $filename;

141 142 143
our $cfg;
our $repo_cfg;

144 145
our $parser;
our $ldd;
146
our $logger;
147
our $profiledir;
148
our $extraprofiledir;
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164

# we keep track of the included profile fragments with %include
my %include;

my %existing_profiles;

our $seenevents = 0;


# these are globs that the user specifically entered.  we'll keep track of
# them so that if one later matches, we'll suggest it again.
our @userglobs;

### THESE VARIABLES ARE USED WITHIN LOGPROF
our %t;
our %transitions;
165
our %sd;    # we keep track of the original profiles in %sd
166
our %original_sd;
167
our %extras;  # inactive profiles from extras
168

169 170 171
my @log;
my %pid;

172 173 174 175 176
my %seen;
my %profilechanges;
my %prelog;
my %log;
my %changed;
177
my @created;
178
my %skip;
179
our %helpers;    # we want to preserve this one between passes
180

181 182
### THESE VARIABLES ARE USED WITHIN LOGPROF

183
my %filelist;   # file level stuff including variables in config files
184

185 186 187 188 189 190 191 192 193 194 195
my $AA_MAY_EXEC = 1;
my $AA_MAY_WRITE = 2;
my $AA_MAY_READ = 4;
my $AA_MAY_APPEND = 8;
my $AA_MAY_LINK = 16;
my $AA_MAY_LOCK = 32;
my $AA_EXEC_MMAP = 64;
my $AA_EXEC_UNSAFE = 128;
my $AA_EXEC_INHERIT = 256;
my $AA_EXEC_UNCONFINED = 512;
my $AA_EXEC_PROFILE = 1024;
196 197
my $AA_EXEC_CHILD = 2048;
my $AA_EXEC_NT = 4096;
198
my $AA_LINK_SUBSET = 8192;
199

200 201 202
my $AA_OTHER_SHIFT = 14;
my $AA_USER_MASK = 16384 -1;

203
my $AA_EXEC_TYPE = $AA_MAY_EXEC | $AA_EXEC_UNSAFE | $AA_EXEC_INHERIT |
204
		    $AA_EXEC_UNCONFINED | $AA_EXEC_PROFILE | $AA_EXEC_CHILD | $AA_EXEC_NT;
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229

my $ALL_AA_EXEC_TYPE = $AA_EXEC_TYPE;

my %MODE_HASH = (
    x => $AA_MAY_EXEC,
    X => $AA_MAY_EXEC,
    w => $AA_MAY_WRITE,
    W => $AA_MAY_WRITE,
    r => $AA_MAY_READ,
    R => $AA_MAY_READ,
    a => $AA_MAY_APPEND,
    A => $AA_MAY_APPEND,
    l => $AA_MAY_LINK,
    L => $AA_MAY_LINK,
    k => $AA_MAY_LOCK,
    K => $AA_MAY_LOCK,
    m => $AA_EXEC_MMAP,
    M => $AA_EXEC_MMAP,
#   Unsafe => 128,
    i => $AA_EXEC_INHERIT,
    I => $AA_EXEC_INHERIT,
    u => $AA_EXEC_UNCONFINED + $AA_EXEC_UNSAFE,		# U + Unsafe
    U => $AA_EXEC_UNCONFINED,
    p => $AA_EXEC_PROFILE + $AA_EXEC_UNSAFE,		# P + Unsafe
    P => $AA_EXEC_PROFILE,
230 231 232 233
    c => $AA_EXEC_CHILD + $AA_EXEC_UNSAFE,
    C => $AA_EXEC_CHILD,
    n => $AA_EXEC_NT + $AA_EXEC_UNSAFE,
    N => $AA_EXEC_NT,
234
    );
235 236

sub debug ($) {
237
    my $message = shift;
238
    chomp($message);
239

240
    print DEBUG "$message\n" if $DEBUGGING;
241 242
}

243
my %arrows = ( A => "UP", B => "DOWN", C => "RIGHT", D => "LEFT" );
244

245
sub getkey() {
Dominic Reynolds's avatar
Dominic Reynolds committed
246 247 248 249 250 251 252 253 254 255 256 257 258 259
    # change to raw mode
    ReadMode(4);

    my $key = ReadKey(0);

    # decode arrow key control sequences
    if ($key eq "\x1B") {
        $key = ReadKey(0);
        if ($key eq "[") {
            $key = ReadKey(0);
            if ($arrows{$key}) {
                $key = $arrows{$key};
            }
        }
260
    }
261

Dominic Reynolds's avatar
Dominic Reynolds committed
262 263 264
    # return to cooked mode
    ReadMode(0);
    return $key;
265
}
266

267
BEGIN {
268 269 270
    # set things up to log extra info if they want...
    if ($ENV{LOGPROF_DEBUG}) {
        $DEBUGGING = 1;
Steve Beattie's avatar
Steve Beattie committed
271
        open(DEBUG, ">/var/log/apparmor/logprof_debug_$$.log");
272 273 274 275 276 277
        my $oldfd = select(DEBUG);
        $| = 1;
        select($oldfd);
    } else {
        $DEBUGGING = 0;
    }
278 279 280
}

END {
281
    $DEBUGGING && debug "Exiting...";
282

283 284
    # close the debug log if necessary
    close(DEBUG) if $DEBUGGING;
285 286
}

287 288 289
# returns true if the specified program contains references to LD_PRELOAD or
# LD_LIBRARY_PATH to give the PX/UX code better suggestions
sub check_for_LD_XXX ($) {
290
    my $file = shift;
291

292
    return undef unless -f $file;
293

294 295 296
    # limit our checking to programs/scripts under 10k to speed things up a bit
    my $size = -s $file;
    return undef unless ($size && $size < 10000);
297

298 299 300 301 302 303
    my $found = undef;
    if (open(F, $file)) {
        while (<F>) {
            $found = 1 if /LD_(PRELOAD|LIBRARY_PATH)/;
        }
        close(F);
304 305
    }

306
    return $found;
307
}
308 309

sub fatal_error ($) {
310
    my $message = shift;
311

312
    my $details = "$message\n";
313

314
    if ($DEBUGGING) {
315

316 317 318 319 320 321
        # we'll include the stack backtrace if we're debugging...
        $details = Carp::longmess($message);

        # write the error to the log
        print DEBUG $details;
    }
322

323 324 325 326 327
    # we'll just shoot ourselves in the head if it was one of the yast
    # interface functions that ran into an error.  it gets really ugly if
    # the yast frontend goes away and we try to notify the user of that
    # problem by trying to send the yast frontend a pretty dialog box
    my $caller = (caller(1))[3];
328 329

    exit 1 if defined($caller) && $caller =~ /::(Send|Get)Data(To|From)Yast$/;
330

331 332
    # tell the user what the hell happened
    UI_Important($details);
333

334 335
    # make sure the frontend exits cleanly...
    shutdown_yast();
336

337 338
    # die a horrible flaming death
    exit 1;
339 340
}

341
sub setup_yast() {
342

343 344
    # set up the yast connection if we're running under yast...
    if ($ENV{YAST_IS_RUNNING}) {
345

346 347 348 349
        # load the yast module if available.
        eval { require ycp; };
        unless ($@) {
            import ycp;
350

351
            $UI_Mode = "yast";
352

353 354 355 356 357
            # let the frontend know that we're starting
            SendDataToYast({
                type   => "initial_handshake",
                status => "backend_starting"
            });
358

359 360 361 362 363 364 365
            # see if the frontend is just starting up also...
            my ($ypath, $yarg) = GetDataFromYast();
            unless ($yarg
                && (ref($yarg)      eq "HASH")
                && ($yarg->{type}   eq "initial_handshake")
                && ($yarg->{status} eq "frontend_starting"))
            {
366

367 368 369
                # something's broken, die a horrible, painful death
                fatal_error "Yast frontend is out of sync from backend agent.";
            }
Dominic Reynolds's avatar
Dominic Reynolds committed
370
            $DEBUGGING && debug "Initial handshake ok";
371

372 373 374
            # the yast connection seems to be working okay
            return 1;
        }
375

376 377 378 379
    }

    # couldn't init yast
    return 0;
380 381
}

382
sub shutdown_yast() {
383 384 385 386
    if ($UI_Mode eq "yast") {
        SendDataToYast({ type => "final_shutdown" });
        my ($ypath, $yarg) = GetDataFromYast();
    }
387 388 389 390
}

sub check_for_subdomain () {

391 392 393 394 395 396 397 398 399
    my ($support_subdomainfs, $support_securityfs);
    if (open(MOUNTS, "/proc/filesystems")) {
        while (<MOUNTS>) {
            $support_subdomainfs = 1 if m/subdomainfs/;
            $support_securityfs  = 1 if m/securityfs/;
        }
        close(MOUNTS);
    }

400
    my $sd_mountpoint = "";
401 402 403 404 405 406 407 408 409 410 411 412 413
    if (open(MOUNTS, "/proc/mounts")) {
        while (<MOUNTS>) {
            if ($support_subdomainfs) {
                $sd_mountpoint = $1 if m/^\S+\s+(\S+)\s+subdomainfs\s/;
            } elsif ($support_securityfs) {
                if (m/^\S+\s+(\S+)\s+securityfs\s/) {
                    if (-e "$1/apparmor") {
                        $sd_mountpoint = "$1/apparmor";
                    } elsif (-e "$1/subdomain") {
                        $sd_mountpoint = "$1/subdomain";
                    }
                }
            }
414
        }
415
        close(MOUNTS);
416 417
    }

418 419
    # make sure that subdomain is actually mounted there
    $sd_mountpoint = undef unless -f "$sd_mountpoint/profiles";
420

421
    return $sd_mountpoint;
422 423 424
}

sub which ($) {
425
    my $file = shift;
426

427 428 429
    foreach my $dir (split(/:/, $ENV{PATH})) {
        return "$dir/$file" if -x "$dir/$file";
    }
430

431
    return undef;
432 433 434 435
}

# we need to convert subdomain regexps to perl regexps
sub convert_regexp ($) {
436
    my $regexp = shift;
437

438
    # escape regexp-special characters we don't support
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
    $regexp =~ s/(?<!\\)(\.|\+|\$)/\\$1/g;

    # * and ** globs can't collapse to match an empty string when they're
    # the only part of the glob at a specific directory level, which
    # complicates things a little.

    # ** globs match multiple directory levels
    $regexp =~ s{(?<!\\)\*\*+}{
      my ($pre, $post) = ($`, $');
      if (($pre =~ /\/$/) && (!$post || $post =~ /^\//)) {
        'SD_INTERNAL_MULTI_REQUIRED';
      } else {
        'SD_INTERNAL_MULTI_OPTIONAL';
      }
    }gex;

    # convert * globs to match anything at the current path level
    $regexp =~ s{(?<!\\)\*}{
      my ($pre, $post) = ($`, $');
      if (($pre =~ /\/$/) && (!$post || $post =~ /^\//)) {
        'SD_INTERNAL_SINGLE_REQUIRED';
      } else {
        'SD_INTERNAL_SINGLE_OPTIONAL';
      }
    }gex;
464

465 466
    # convert ? globs to match a single character at current path level
    $regexp =~ s/(?<!\\)\?/[^\/]/g;
467

468 469
    # convert {foo,baz} to (foo|baz)
    $regexp =~ y/\{\}\,/\(\)\|/ if $regexp =~ /\{.*\,.*\}/;
470

471 472 473 474 475
    # convert internal markers to their appropriate regexp equivalents
    $regexp =~ s/SD_INTERNAL_SINGLE_OPTIONAL/[^\/]*/g;
    $regexp =~ s/SD_INTERNAL_SINGLE_REQUIRED/[^\/]+/g;
    $regexp =~ s/SD_INTERNAL_MULTI_OPTIONAL/.*/g;
    $regexp =~ s/SD_INTERNAL_MULTI_REQUIRED/[^\/].*/g;
476

477
    return $regexp;
478 479 480
}

sub get_full_path ($) {
481
    my $originalpath = shift;
482

483
    my $path = $originalpath;
484

485 486
    # keep track so we can break out of loops
    my $linkcount = 0;
487

488 489
    # if we don't have any directory foo, look in the current dir
    $path = cwd() . "/$path" if $path !~ m/\//;
490

491 492
    # beat symlinks into submission
    while (-l $path) {
493

494 495 496
        if ($linkcount++ > 64) {
            fatal_error "Followed too many symlinks resolving $originalpath";
        }
497

498 499 500
        # split out the directory/file components
        if ($path =~ m/^(.*)\/(.+)$/) {
            my ($dir, $file) = ($1, $2);
501

502 503 504 505 506 507 508 509 510 511
            # figure out where the link is pointing...
            my $link = readlink($path);
            if ($link =~ /^\//) {
                # if it's an absolute link, just replace it
                $path = $link;
            } else {
                # if it's relative, let abs_path handle it
                $path = $dir . "/$link";
            }
        }
512 513
    }

514 515 516 517 518 519
    if (-f $path) {
        my ($dir, $file) = $path =~ m/^(.*)\/(.+)$/;
        $path = realpath($dir) . "/$file";
    } else {
        $path = realpath($path);
    }
520

521
    return $path;
522 523 524
}

sub findexecutable ($) {
525 526 527 528 529 530 531 532 533 534 535 536 537 538
    my $bin = shift;

    my $fqdbin;
    if (-e $bin) {
        $fqdbin = get_full_path($bin);
        chomp($fqdbin);
    } else {
        if ($bin !~ /\//) {
            my $which = which($bin);
            if ($which) {
                $fqdbin = get_full_path($which);
            }
        }
    }
539

540 541 542 543 544
    unless ($fqdbin && -e $fqdbin) {
        return undef;
    }

    return $fqdbin;
545 546
}

547
sub name_to_prof_filename($) {
548
    my $bin    = shift;
549
    my $filename;
550

551
    unless ($bin =~ /^($profiledir)/) {
552 553 554 555 556 557
	my $fqdbin = findexecutable($bin);
	if ($fqdbin) {
	    $filename = getprofilefilename($fqdbin);
	    return ($filename, $fqdbin) if -f $filename;
	}
    }
558

559 560
    if ($bin =~ /^$profiledir(.*)/) {
	my $profile = $1;
561
	return ($bin, $profile);
562 563
    } elsif ($bin =~ /^\//) {
	$filename = getprofilefilename($bin);
564
	return ($filename, $bin);
565 566 567 568
    } else {
	# not an absolute path try it as a profile_
	$bin = $1 if ($bin !~ /^profile_(.*)/);
	$filename = getprofilefilename($bin);
569
	return ($filename, "profile_${bin}");
570 571 572 573 574 575 576 577 578 579 580 581 582
    }
    return undef;
}

sub complain ($) {
    my $bin = shift;

    return if (!$bin);

    my ($filename, $name) = name_to_prof_filename($bin)
	or fatal_error(sprintf(gettext('Can\'t find %s.'), $bin));

    UI_Info(sprintf(gettext('Setting %s to complain mode.'), $name));
583

584
    setprofileflags($filename, "complain");
585 586 587
}

sub enforce ($) {
588
    my $bin = shift;
589

590
    return if (!$bin);
591

592 593
    my ($filename, $name) = name_to_prof_filename($bin)
	or fatal_error(sprintf(gettext('Can\'t find %s.'), $bin));
594

595
    UI_Info(sprintf(gettext('Setting %s to enforce mode.'), $name));
596

597
    setprofileflags($filename, "");
598 599 600
}

sub head ($) {
601
    my $file = shift;
602

603 604 605 606 607
    my $first = "";
    if (open(FILE, $file)) {
        $first = <FILE>;
        close(FILE);
    }
608

609
    return $first;
610 611
}

612
sub get_output ($@) {
613
    my ($program, @args) = @_;
614

615
    my $ret = -1;
616

617 618
    my $pid;
    my @output;
619

620 621 622 623 624
    if (-x $program) {
        $pid = open(KID_TO_READ, "-|");
        unless (defined $pid) {
            fatal_error "can't fork: $!";
        }
625

626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
        if ($pid) {
            while (<KID_TO_READ>) {
                chomp;
                push @output, $_;
            }
            close(KID_TO_READ);
            $ret = $?;
        } else {
            ($>, $)) = ($<, $();
            open(STDERR, ">&STDOUT")
              || fatal_error "can't dup stdout to stderr";
            exec($program, @args) || fatal_error "can't exec program: $!";

            # NOTREACHED
        }
641 642
    }

643
    return ($ret, @output);
644 645 646
}

sub get_reqs ($) {
647
    my $file = shift;
648

649 650
    my @reqs;
    my ($ret, @ldd) = get_output($ldd, $file);
651

652 653 654 655 656
    if ($ret == 0) {
        for my $line (@ldd) {
            last if $line =~ /not a dynamic executable/;
            last if $line =~ /cannot read header/;
            last if $line =~ /statically linked/;
657

658 659
            # avoid new kernel 2.6 poo
            next if $line =~ /linux-(gate|vdso(32|64)).so/;
660

661 662 663 664 665 666
            if ($line =~ /^\s*\S+ => (\/\S+)/) {
                push @reqs, $1;
            } elsif ($line =~ /^\s*(\/\S+)/) {
                push @reqs, $1;
            }
        }
667 668
    }

669
    return @reqs;
670 671 672
}

sub handle_binfmt ($$) {
673
    my ($profile, $fqdbin) = @_;
674

675 676
    my %reqs;
    my @reqs = get_reqs($fqdbin);
677

678
    while (my $library = shift @reqs) {
679

680
        $library = get_full_path($library);
681

682
        push @reqs, get_reqs($library) unless $reqs{$library}++;
683

684
        # does path match anything pulled in by includes in original profile?
685
        my $combinedmode = match_prof_incs_to_path($profile, 'allow', $library);
686

687 688
        # if we found any matching entries, do the modes match?
        next if $combinedmode;
689

690 691 692
        $library = globcommon($library);
        chomp $library;
        next unless $library;
693

694 695
        $profile->{allow}{path}->{$library}{mode} |= str_to_mode("mr");
        $profile->{allow}{path}->{$library}{audit} |= 0;
696
    }
697 698
}

699
sub get_inactive_profile($) {
700 701 702 703 704
    my $fqdbin = shift;
    if ( $extras{$fqdbin} ) {
        return {$fqdbin => $extras{$fqdbin}};
    }
}
705

706

707

708
sub create_new_profile($) {
709 710
    my $fqdbin = shift;

711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
    my $profile;
    if ($fqdbin =~ /^\// ) {
	$profile = {
	    $fqdbin => {
		flags   => "complain",
		include => { "abstractions/base" => 1    },
		path    => { $fqdbin => { mode => str_to_mode("mr") } },
	    }
	};
    } else {
	$profile = {
	    $fqdbin => {
		flags   => "complain",
		include => { "abstractions/base" => 1    },
	    }
	};
    }
728 729 730 731

    # if the executable exists on this system, pull in extra dependencies
    if (-f $fqdbin) {
        my $hashbang = head($fqdbin);
John Johansen's avatar
John Johansen committed
732
        if ($hashbang && $hashbang =~ /^#!\s*(\S+)/) {
733
            my $interpreter = get_full_path($1);
734 735
            $profile->{$fqdbin}{allow}{path}->{$interpreter}{mode} |= str_to_mode("ix");
            $profile->{$fqdbin}{allow}{path}->{$interpreter}{audit} |= 0;
736 737 738 739 740 741 742 743 744 745 746 747
            if ($interpreter =~ /perl/) {
                $profile->{$fqdbin}{include}->{"abstractions/perl"} = 1;
            } elsif ($interpreter =~ m/\/bin\/(bash|sh)/) {
                $profile->{$fqdbin}{include}->{"abstractions/bash"} = 1;
            }
            handle_binfmt($profile->{$fqdbin}, $interpreter);
        } else {
          handle_binfmt($profile->{$fqdbin}, $fqdbin);
        }
    }

    # create required infrastructure hats if it's a known change_hat app
748
    for my $hatglob (keys %{$cfg->{required_hats}}) {
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
        if ($fqdbin =~ /$hatglob/) {
            for my $hat (sort split(/\s+/, $cfg->{required_hats}{$hatglob})) {
                $profile->{$hat} = { flags => "complain" };
            }
        }
    }
    push @created, $fqdbin;
    return { $fqdbin => $profile };
}

sub delete_profile ($) {
    my $profile = shift;
    my $profilefile = getprofilefilename( $profile );
    if ( -e $profilefile ) {
      unlink( $profilefile );
    }
    if ( defined $sd{$profile} ) {
        delete $sd{$profile};
    }
}

770
sub get_profile($) {
771 772 773
    my $fqdbin = shift;
    my $profile_data;

Dominic Reynolds's avatar
Dominic Reynolds committed
774
    my $distro     = $cfg->{repository}{distro};
775
    my $repo_url   = $cfg->{repository}{url};
776
    my @profiles;
777
    my %profile_hash;
778

779 780 781
    if (repo_is_enabled()) {
       my $results;
       UI_BusyStart( gettext("Connecting to repository.....") );
782

783 784 785 786 787 788 789 790 791 792 793
       my ($status_ok,$ret) =
           fetch_profiles_by_name($repo_url, $distro, $fqdbin );
       UI_BusyStop();
       if ( $status_ok ) {
           %profile_hash = %$ret;
       } else {
           my $errmsg =
             sprintf(gettext("WARNING: Error fetching profiles from the repository:\n%s\n"),
                     $ret?$ret:gettext("UNKNOWN ERROR"));
           UI_Important( $errmsg );
       }
794
    }
795

796 797
    my $inactive_profile = get_inactive_profile($fqdbin);
    if ( defined $inactive_profile && $inactive_profile ne "" ) {
798
        # set the profile to complain mode
799
        my $uname = gettext( "Inactive local profile for ") . $fqdbin;
800
        $inactive_profile->{$fqdbin}{$fqdbin}{flags} = "complain";
John Johansen's avatar
John Johansen committed
801 802
	# inactive profiles store where they came from
	delete $inactive_profile->{$fqdbin}{$fqdbin}{filename};
803
        $profile_hash{$uname} =
804
            {
805
              "username"     => $uname,
806
              "profile_type" => "INACTIVE_LOCAL",
John Johansen's avatar
John Johansen committed
807
              "profile"      => serialize_profile($inactive_profile->{$fqdbin},
808 809 810 811 812
                                  $fqdbin
                                ),
              "profile_data" => $inactive_profile,
            };
    }
813

814
    return undef if ( keys %profile_hash == 0 ); # No repo profiles, no inactive
815
                                            # profile
Dominic Reynolds's avatar
Dominic Reynolds committed
816 817 818 819 820
    my @options;
    my @tmp_list;
    my $preferred_present = 0;
    my $preferred_user  = $cfg->{repository}{preferred_user} || "NOVELL";

821 822
    foreach my $p ( keys %profile_hash ) {
        if ( $profile_hash{$p}->{username} eq $preferred_user ) {
Dominic Reynolds's avatar
Dominic Reynolds committed
823 824
             $preferred_present = 1;
        } else {
825
            push @tmp_list, $profile_hash{$p}->{username};
Dominic Reynolds's avatar
Dominic Reynolds committed
826 827 828 829 830 831 832
        }
    }

    if ( $preferred_present ) {
        push  @options, $preferred_user;
    }
    push  @options, @tmp_list;
833

834 835 836
    my $q = {};
    $q->{headers} = [];
    push @{ $q->{headers} }, gettext("Profile"), $fqdbin;
837

838 839
    $q->{functions} = [ "CMD_VIEW_PROFILE", "CMD_USE_PROFILE",
                        "CMD_CREATE_PROFILE", "CMD_ABORT", "CMD_FINISHED" ];
840

841
    $q->{default} = "CMD_VIEW_PROFILE";
842

843 844
    $q->{options}  = [@options];
    $q->{selected} = 0;
845

846 847 848
    my ($p, $ans, $arg);
    do {
        ($ans, $arg) = UI_PromptUser($q);
849
        $p = $profile_hash{$options[$arg]};
Dominic Reynolds's avatar
Dominic Reynolds committed
850 851
        for (my $i = 0; $i < scalar(@options); $i++) {
            if ($options[$i] eq $options[$arg]) {
852
                $q->{selected} = $i;
853
            }
854
        }
855

856
        if ($ans eq "CMD_VIEW_PROFILE") {
857
            if ($UI_Mode eq "yast") {
858 859 860 861 862 863 864 865 866
                SendDataToYast(
                    {
                        type         => "dialog-view-profile",
                        user         => $options[$arg],
                        profile      => $p->{profile},
                        profile_type => $p->{profile_type}
                    }
                );
                my ($ypath, $yarg) = GetDataFromYast();
867
            } else {
Dominic Reynolds's avatar
Dominic Reynolds committed
868 869
                my $pager = get_pager();
                open(PAGER, "| $pager");
870
                print PAGER gettext("Profile submitted by") .
871
                                    " $options[$arg]:\n\n" . $p->{profile} . "\n\n";
872
                close(PAGER);
873
            }
874 875 876 877 878 879 880 881
        } elsif ($ans eq "CMD_USE_PROFILE") {
            if ( $p->{profile_type} eq "INACTIVE_LOCAL" ) {
                $profile_data = $p->{profile_data};
                push @created, $fqdbin; # This really is ugly here
                                        # need to find a better place to mark
                                        # this as newly created
            } else {
                $profile_data =
882
                    parse_repo_profile($fqdbin, $repo_url, $p);
883 884 885
            }
        }
    } until ($ans =~ /^CMD_(USE_PROFILE|CREATE_PROFILE)$/);
886

887
    return $profile_data;
888 889
}

890 891
sub activate_repo_profiles ($$$) {
    my ($url,$profiles,$complain) = @_;
892

893 894 895 896 897 898 899 900 901 902 903 904
    readprofiles();
    eval {
        for my $p ( @$profiles ) {
            my $pname = $p->[0];
            my $profile_data = parse_repo_profile( $pname, $url, $p->[1] );
            attach_profile_data(\%sd, $profile_data);
            writeprofile($pname);
            if ( $complain ) {
                my $filename = getprofilefilename($pname);
                setprofileflags($filename, "complain");
                UI_Info(sprintf(gettext('Setting %s to complain mode.'),
                                        $pname));
905 906
            }
        }
907 908 909 910 911
    };
    # if there were errors....
    if ($@) {
        $@ =~ s/\n$//;
        print STDERR sprintf(gettext("Error activating profiles: %s\n"), $@);
912
    }
913 914
}

915 916
sub autodep_base($$) {
    my ($bin, $pname) = @_;
917
    %extras = ();
918

919 920
    $bin = $pname if (! $bin) && ($pname =~ /^\//);

921
    unless ($repo_cfg || not defined $cfg->{repository}{url}) {
922
        $repo_cfg = read_config("repository.conf");
923 924
        if ( (not defined $repo_cfg->{repository}) ||
             ($repo_cfg->{repository}{enabled} eq "later") ) {
925
                UI_ask_to_enable_repo();
926
        }
927 928
    }

929 930 931 932 933
    my $fqdbin;
    if ($bin) {
	# findexecutable() might fail if we're running on a different system
	# than the logs were collected on.  ugly.  we'll just hope for the best.
	$fqdbin = findexecutable($bin) || $bin;
934

935 936
	# try to make sure we have a full path in case findexecutable failed
	return unless $fqdbin =~ /^\//;
937

938 939 940 941 942
	# ignore directories
	return if -d $fqdbin;
    }

    $pname = $fqdbin if $fqdbin;
943

944
    my $profile_data;
945

946 947
    readinactiveprofiles(); # need to read the profiles to see if an
                            # inactive local profile is present
948
    $profile_data = eval { get_profile($pname) };
949 950
    # propagate any errors we hit inside the get_profile call
    if ($@) { die $@; }
951 952

    unless ($profile_data) {
953
        $profile_data = create_new_profile($pname);
954
    }
955

956 957
    my $file = getprofilefilename($pname);

958 959
    # stick the profile into our data structure.
    attach_profile_data(\%sd, $profile_data);
960 961 962
    # and store a "clean" version also so we can display the changes we've
    # made during this run
    attach_profile_data(\%original_sd, $profile_data);
963

964
    if (-f "$profiledir/tunables/global") {
965 966
        unless (exists $filelist{$file}) {
            $filelist{$file} = { };
967
        }
968
        $filelist{$file}{include}{'tunables/global'} = 1; # sorry
969
    }
970

971
    # write out the profile...
972 973 974 975 976 977
    writeprofile_ui_feedback($pname);
}

sub autodep ($) {
    my $bin = shift;
    return autodep_base($bin, "");
978 979 980
}

sub getprofilefilename ($) {
981
    my $profile = shift;
982

983
    my $filename = $profile;
984 985 986 987 988
    if ($filename =~ /^\//) {
	$filename =~ s/^\///;                              # strip leading /
    } else {
	$filename = "profile_$filename";
    }
989
    $filename =~ s/\//./g;                            # convert /'s to .'s
990

991
    return "$profiledir/$filename";
992 993 994
}

sub setprofileflags ($$) {
995 996 997 998 999 1000
    my $filename = shift;
    my $newflags = shift;

    if (open(PROFILE, "$filename")) {
        if (open(NEWPROFILE, ">$filename.new")) {
            while (<PROFILE>) {
1001 1002
                if (m/^\s*(("??\/.+?"??)|(profile\s+("??.+?"??)))\s+(flags=\(.+\)\s+)*\{\s*$/) {
                    my ($binary, $flags) = ($1, $5);
1003

1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
                    if ($newflags) {
                        $_ = "$binary flags=($newflags) {\n";
                    } else {
                        $_ = "$binary {\n";
                    }
                } elsif (m/^(\s*\^\S+)\s+(flags=\(.+\)\s+)*\{\s*$/) {
                    my ($hat, $flags) = ($1, $2);

                    if ($newflags) {
                        $_ = "$hat flags=($newflags) {\n";
                    } else {
                        $_ = "$hat {\n";
                    }
                }
                print NEWPROFILE;
            }
            close(NEWPROFILE);
            rename("$filename.new", "$filename");
        }
        close(PROFILE);
    }
}

sub profile_exists($) {
    my $program = shift || return 0;

    # if it's already in the cache, return true
    return 1 if $existing_profiles{$program};

    # if the profile exists, mark it in the cache and return true
    my $profile = getprofilefilename($program);
    if (-e $profile) {
        $existing_profiles{$program} = 1;
        return 1;
    }

    # couldn't find a profile, so we'll return false
    return 0;
}

1044
sub sync_profiles() {
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134

    my ($user, $pass) = get_repo_user_pass();
    return unless ( $user && $pass );

    my @repo_profiles;
    my @changed_profiles;
    my @new_profiles;
    my $serialize_opts = { };
    my ($status_ok,$ret) =
        fetch_profiles_by_user($cfg->{repository}{url},
                               $cfg->{repository}{distro},
                               $user
                              );
    if ( !$status_ok ) {
        my $errmsg =
          sprintf(gettext("WARNING: Error syncronizing profiles with the repository:\n%s\n"),
                  $ret?$ret:gettext("UNKNOWN ERROR"));
        UI_Important($errmsg);
        return;
    } else {
        my $users_repo_profiles = $ret;
        $serialize_opts->{NO_FLAGS} = 1;
        #
        # Find changes made to non-repo profiles
        #
        for my $profile (sort keys %sd) {
            if (is_repo_profile($sd{$profile}{$profile})) {
                push @repo_profiles, $profile;
            }
            if ( grep(/^$profile$/, @created) )  {
                my $p_local = serialize_profile($sd{$profile},
                                                $profile,
                                                $serialize_opts);
                if ( not defined $users_repo_profiles->{$profile} ) {
                    push @new_profiles,  [ $profile, $p_local, "" ];
                } else {
                    my $p_repo = $users_repo_profiles->{$profile}->{profile};
                    if ( $p_local ne $p_repo ) {
                        push @changed_profiles, [ $profile, $p_local, $p_repo ];
                    }
                }
            }
        }

        #
        # Find changes made to local profiles with repo metadata
        #
        if (@repo_profiles) {
            for my $profile (@repo_profiles) {
                my $p_local = serialize_profile($sd{$profile},
                                                $profile,
                                                $serialize_opts);
                if ( not exists $users_repo_profiles->{$profile} ) {
                    push @new_profiles,  [ $profile, $p_local, "" ];
                } else {
                    my $p_repo = "";
                    if ( $sd{$profile}{$profile}{repo}{user} eq $user ) {
                       $p_repo = $users_repo_profiles->{$profile}->{profile};
                    }  else {
                        my ($status_ok,$ret) =
                            fetch_profile_by_id($cfg->{repository}{url},
                                                $sd{$profile}{$profile}{repo}{id}
                                               );
                        if ( $status_ok ) {
                           $p_repo = $ret->{profile};
                        } else {
                            my $errmsg =
                              sprintf(
                                gettext("WARNING: Error syncronizing profiles with the repository:\n%s\n"),
                                $ret?$ret:gettext("UNKNOWN ERROR"));
                            UI_Important($errmsg);
                            next;
                        }
                    }
                    if ( $p_repo ne $p_local ) {
                        push @changed_profiles, [ $profile, $p_local, $p_repo ];
                    }
                }
            }
        }

        if ( @changed_profiles ) {
           submit_changed_profiles( \@changed_profiles );
        }
        if ( @new_profiles ) {
           submit_created_profiles( \@new_profiles );
        }
    }
}

1135
sub submit_created_profiles($) {
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
    my $new_profiles = shift;
    my $url = $cfg->{repository}{url};

    if ($UI_Mode eq "yast") {
        my $title       = gettext("New profiles");
        my $explanation =
          gettext("Please choose the newly created profiles that you would".
          " like\nto store in the repository");
        yast_select_and_upload_profiles($title,
                                        $explanation,
                                        $new_profiles);
    } else {
        my $title       =
          gettext("Submit newly created profiles to the repository");
        my $explanation =
          gettext("Would you like to upload the newly created profiles?");
        console_select_and_upload_profiles($title,
                                           $explanation,
                                           $new_profiles);
    }
}

1158
sub submit_changed_profiles($) {
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
    my $changed_profiles = shift;
    my $url = $cfg->{repository}{url};
    if (@$changed_profiles) {
        if ($UI_Mode eq "yast") {
            my $explanation =
              gettext("Select which of the changed profiles you would".
              " like to upload\nto the repository");
            my $title       = gettext("Changed profiles");
            yast_select_and_upload_profiles($title,
                                            $explanation,
                                            $changed_profiles);
        } else {
            my $title       =
              gettext("Submit changed profiles to the repository");
            my $explanation =
              gettext("The following profiles from the repository were".
              " changed.\nWould you like to upload your changes?");
            console_select_and_upload_profiles($title,
                                               $explanation,
                                               $changed_profiles);
        }
    }
}

1183
sub yast_select_and_upload_profiles($$$) {
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261

    my ($title, $explanation, $profiles_ref) = @_;
    my $url = $cfg->{repository}{url};
    my %profile_changes;
    my @profiles = @$profiles_ref;

    foreach my $prof (@profiles) {
        $profile_changes{ $prof->[0] } =
          get_profile_diff($prof->[2], $prof->[1]);
    }

    my (@selected_profiles, $changelog, $changelogs, $single_changelog);
    SendDataToYast(
        {
            type               => "dialog-select-profiles",
            title              => $title,
            explanation        => $explanation,
            default_select     => "false",
            disable_ask_upload => "true",
            profiles           => \%profile_changes
        }
    );
    my ($ypath, $yarg) = GetDataFromYast();
    if ($yarg->{STATUS} eq "cancel") {
        return;
    } else {
        my $selected_profiles_ref = $yarg->{PROFILES};
        @selected_profiles = @$selected_profiles_ref;
        $changelogs        = $yarg->{CHANGELOG};
        if (defined $changelogs->{SINGLE_CHANGELOG}) {
            $changelog        = $changelogs->{SINGLE_CHANGELOG};
            $single_changelog = 1;
        }
    }

    for my $profile (@selected_profiles) {
        my ($user, $pass) = get_repo_user_pass();
        my $profile_string = serialize_profile($sd{$profile}, $profile);
        if (!$single_changelog) {
            $changelog = $changelogs->{$profile};
        }
        my ($status_ok, $ret) = upload_profile( $url,
                                                $user,
                                                $pass,
                                                $cfg->{repository}{distro},
                                                $profile,
                                                $profile_string,
                                                $changelog
                                              );
        if ($status_ok) {
            my $newprofile = $ret;
            my $newid      = $newprofile->{id};
            set_repo_info($sd{$profile}{$profile}, $url, $user, $newid);
            writeprofile_ui_feedback($profile);
        } else {
            my $errmsg =
              sprintf(
                gettext("WARNING: An error occured while uploading the profile %s\n%s\n"),
                $profile, $ret?$ret:gettext("UNKNOWN ERROR"));
            UI_Important( $errmsg );
        }
    }
    UI_Info(gettext("Uploaded changes to repository."));

    # Check to see if unselected profiles should be marked as local only
    # this is outside of the main repo code as we want users to be able to mark
    # profiles as local only even if they aren't able to connect to the repo.
    if (defined $yarg->{NEVER_ASK_AGAIN}) {
        my @unselected_profiles;
        foreach my $prof (@profiles) {
            if ( grep(/^$prof->[0]$/, @selected_profiles) == 0 ) {
                push @unselected_profiles, $prof->[0];
            }
        }
        set_profiles_local_only( @unselected_profiles );
    }
}

1262
sub console_select_and_upload_profiles($$$) {
1263 1264 1265 1266 1267
    my ($title, $explanation, $profiles_ref) = @_;
    my $url = $cfg->{repository}{url};
    my @profiles = @$profiles_ref;
    my $q = {};
    $q->{title} = $title;
1268
    $q->{headers} = [ gettext("Repository"), $url, ];
1269 1270 1271 1272 1273

    $q->{explanation} = $explanation;

    $q->{functions} = [ "CMD_UPLOAD_CHANGES",
                        "CMD_VIEW_CHANGES",
1274
                        "CMD_ASK_LATER",
1275 1276 1277 1278 1279 1280 1281
                        "CMD_ASK_NEVER",
                        "CMD_ABORT", ];

    $q->{default} = "CMD_VIEW_CHANGES";

    $q->{options} = [ map { $_->[0] } @profiles ];
    $q->{selected} = 0;
1282

1283 1284 1285 1286 1287 1288 1289
    my ($ans, $arg);
    do {
        ($ans, $arg) = UI_PromptUser($q);

        if ($ans eq "CMD_VIEW_CHANGES") {
            display_changes($profiles[$arg]->[2], $profiles[$arg]->[1]);
        }
1290
    } until $ans =~ /^CMD_(UPLOAD_CHANGES|ASK_NEVER|ASK_LATER)/;
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323

    if ($ans eq "CMD_ASK_NEVER") {
        set_profiles_local_only(  map { $_->[0] } @profiles  );
    } elsif ($ans eq "CMD_UPLOAD_CHANGES") {
        my $changelog = UI_GetString(gettext("Changelog Entry: "), "");
        my ($user, $pass) = get_repo_user_pass();
        if ($user && $pass) {
            for my $p_data (@profiles) {
                my $profile          = $p_data->[0];
                my $profile_string   = $p_data->[1];
                my ($status_ok,$ret) =
                    upload_profile( $url,
                                    $user,
                                    $pass,
                                    $cfg->{repository}{distro},
                                    $profile,
                                    $profile_string,
                                    $changelog
                                  );
                if ($status_ok) {
                    my $newprofile = $ret;
                    my $newid      = $newprofile->{id};
                    set_repo_info($sd{$profile}{$profile}, $url, $user, $newid);
                    writeprofile_ui_feedback($profile);
                    UI_Info(
                      sprintf(gettext("Uploaded %s to repository."), $profile)
                    );
                } else {
                    my $errmsg =
                      sprintf(
                        gettext("WARNING: An error occured while uploading the profile %s\n%s\n"),
                        $profile, $ret?$ret:gettext("UNKNOWN ERROR"));
                    UI_Important( $errmsg );
1324 1325
                }
            }
1326 1327 1328 1329 1330
        } else {
            UI_Important(gettext("Repository Error\n" .
                      "Registration or Signin was unsuccessful. User login\n" .
                      "information is required to upload profiles to the\n" .
                      "repository. These changes have not been sent.\n"));
1331 1332 1333 1334
        }
    }
}

1335 1336 1337 1338
#
# Mark the profiles passed in @profiles as local only
# and don't prompt to upload changes to the repository
#
1339
sub set_profiles_local_only(@) {
1340 1341 1342 1343
    my @profiles = @_;
    for my $profile (@profiles) {
         $sd{$profile}{$profile}{repo}{neversubmit} = 1;
         writeprofile_ui_feedback($profile);
1344
    }
1345 1346 1347 1348 1349 1350
}

##########################################################################
# Here are the console/yast interface functions

sub UI_Info ($) {
1351
    my $text = shift;
1352

1353
    $DEBUGGING && debug "UI_Info: $UI_Mode: $text";
1354

1355 1356 1357 1358 1359
    if ($UI_Mode eq "text") {
        print "$text\n";
    } else {
        ycp::y2milestone($text);
    }
1360 1361 1362
}

sub UI_Important ($) {
1363
    my $text = shift;
1364

1365
    $DEBUGGING && debug "UI_Important: $UI_Mode: $text";
1366

1367 1368 1369 1370 1371 1372
    if ($UI_Mode eq "text") {
        print "\n$text\n";
    } else {
        SendDataToYast({ type => "dialog-error", message => $text });
        my ($path, $yarg) = GetDataFromYast();
    }
1373 1374 1375
}

sub UI_YesNo ($$) {
1376 1377
    my $text    = shift;
    my $default = shift;
1378

1379
    $DEBUGGING && debug "UI_YesNo: $UI_Mode: $text $default";
1380

1381 1382
    my $ans;
    if ($UI_Mode eq "text") {
1383

1384 1385
        my $yes = gettext("(Y)es");
        my $no  = gettext("(N)o");
1386

1387 1388 1389 1390 1391 1392
        # figure out our localized hotkeys
        my $usrmsg = "PromptUser: " . gettext("Invalid hotkey for");
        $yes =~ /\((\S)\)/ or fatal_error "$usrmsg '$yes'";
        my $yeskey = lc($1);
        $no =~ /\((\S)\)/ or fatal_error "$usrmsg '$no'";
        my $nokey = lc($1);
1393

1394 1395 1396 1397 1398 1399 1400
        print "\n$text\n";
        if ($default eq "y") {
            print "\n[$yes] / $no\n";
        } else {
            print "\n$yes / [$no]\n";
        }
        $ans = getkey() || (($default eq "y") ? $yeskey : $nokey);
1401

1402 1403 1404
        # convert back from a localized answer to english y or n
        $ans = (lc($ans) eq $yeskey) ? "y" : "n";
    } else {
1405

1406 1407 1408
        SendDataToYast({ type => "dialog-yesno", question => $text });
        my ($ypath, $yarg) = GetDataFromYast();
        $ans = $yarg->{answer} || $default;
1409

1410
    }
1411

1412
    return $ans;
1413 1414
}

1415
sub UI_YesNoCancel ($$) {
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
    my $text    = shift;
    my $default = shift;

    $DEBUGGING && debug "UI_YesNoCancel: $UI_Mode: $text $default";

    my $ans;
    if ($UI_Mode eq "text") {

        my $yes    = gettext("(Y)es");
        my $no     = gettext("(N)o");
        my $cancel = gettext("(C)ancel");

        # figure out our localized hotkeys
        my $usrmsg = "PromptUser: " . gettext("Invalid hotkey for");
        $yes =~ /\((\S)\)/ or fatal_error "$usrmsg '$yes'";
        my $yeskey = lc($1);
        $no =~ /\((\S)\)/ or fatal_error "$usrmsg '$no'";
        my $nokey = lc($1);
        $cancel =~ /\((\S)\)/ or fatal_error "$usrmsg '$cancel'";
        my $cancelkey = lc($1);

        $ans = "XXXINVALIDXXX";
        while (