2

I created a simple script like the following called "/usr/bin/mytool1" and make it executable.

#!/usr/bin/rlwrap /usr/bin/perl

while (1) {
    chomp($cmd = <STDIN>);
    print "cmd=$cmd\n";
}

The problem is, if I run it as a regular user, it works fine.

Then I did a "sudo bash" and as root, I run mytool1, it works fine too.

Now I am back as a regular user, running command "mytool1" will give error like:

rlwrap: cannot read and write /home/user1/.perl_history: Permission denied

I did some investigation, here is what I found:

$ ls -l /home/user1/.perl_history
-rw------- 1 root root 138 Dec  6 18:13 /home/user1/.perl_history

The problem here is, rlwrap will change the owner of /home/user1/.perl_history to root when it runs as root.

I think this is a bug on rlwrap because in the case Ubuntu, $HOME didn't change after I run sudo bash, rlwrap should have used $USER to construct the history file.

What do you think?

Hans Lub
  • 5,513
  • 1
  • 23
  • 43
packetie
  • 4,839
  • 8
  • 37
  • 72

3 Answers3

1

sudo might be configured with security policy not to change environment variables, including HOME. You can try to override this behaviour with -H option. See man sudo for more details.

Andrey
  • 2,503
  • 3
  • 30
  • 39
  • Thanks @Andrey for the suggestion. I have other tools that may be broken if I do that. Would rather do something to rlwrap. Thanks. – packetie Dec 07 '15 at 02:48
1

Found a solution that works for me: Download the rlwrap source and make change to src file "main.c" and after line 604, add

history_filename = malloc(100);
sprintf(history_filename, "/home/%s/.%s_history",getenv("USER"),  command_name);

now rlwrap will use different history file for different users.

packetie
  • 4,839
  • 8
  • 37
  • 72
1

There is no need to modify and recompile rlwrap, just specify the history file on the command line:

rlwrap --history-filename=$HOME/.${USER}_command_history command

I am surprised that Ubuntu's sudo preserves $HOME by default, I cannot see why this would ever be useful (there are occasional murmurings against this policy on the Ubuntu lists, but certainly no storms of protest)

In the meantime, I will keep rlwraps behaviour as it is, but try to find out whether and how other programs avoid problems like this (not all of them do)

Edit (aug 2019): From sudo - 1.8.27-1ubuntu2 onwards Ubuntu (finally!) restores sudo handling of $HOME to what everyone else does : it will not preserve $HOME by default. This means that rlwrap will be able to read and write its own history when running under sudo, even without the extra --history-filename argument.

Hans (rlwrap maintainer)

Hans Lub
  • 5,513
  • 1
  • 23
  • 43
  • Thanks @hans-lub, your solution is the best! By the way I guess you meant to say `rlwrap --history-filename=$HOME/.${USER}_command_history command`. – packetie Dec 08 '15 at 22:05