[PATCH 06/16] scp: Introduce `get_user_name()'

Michael Witten mfwitten at gmail.com
Tue Dec 8 06:56:06 AWST 2015


Date: Wed, 4 Nov 2015 05:41:53 -0000
There's no reason to assume that there is a user name; userspace might be so
primitive that there is no such thing, and `scp' should continue to run as
long as the user explicitly specifies a user name on the command line.

So, this commit introduces a new function for retrieving the user name. This
function is called only when a user name is not specified by the user, in which
case there MUST be a user name that can be retrieved from the current context
of the program; if there is no such user name, then the user is notified of
the error, and informed that a user name must be specified.
---
 scp.c | 27 ++++++++++++++++++++-------
 1 file changed, 20 insertions(+), 7 deletions(-)

diff --git a/scp.c b/scp.c
index 9df8fa5..dd49b68 100644
--- a/scp.c
+++ b/scp.c
@@ -288,8 +288,6 @@ static int okname(const char *);
 void run_err(const char *,...);
 void verifydir(char *);
 
-struct passwd *pwd;
-uid_t userid;
 int errs, remin, remout;
 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
 
@@ -303,6 +301,7 @@ void source(int, char *[]);
 void tolocal(int, char *[]);
 void toremote(char *, int, char *[]);
 void usage(void);
+static const char *get_user_name();
 
 #if defined(DBMULTI_scp) || !defined(DROPBEAR_MULTI)
 #if defined(DBMULTI_scp) && defined(DROPBEAR_MULTI)
@@ -397,9 +396,6 @@ main(int argc, char **argv)
 	argc -= optind;
 	argv += optind;
 
-	if ((pwd = getpwuid(userid = getuid())) == NULL)
-		fatal("unknown user %u", (u_int) userid);
-
 	if (!isatty(STDERR_FILENO))
 		showprogress = 0;
 
@@ -518,7 +514,7 @@ toremote(char *targ, int argc, char **argv)
 				host = cleanhostname(host);
 				suser = argv[i];
 				if (*suser == '\0')
-					suser = pwd->pw_name;
+					suser = get_user_name();
 				else if (!okname(suser))
 					continue;
 				addargs(&alist, "-l");
@@ -587,7 +583,7 @@ tolocal(int argc, char **argv)
 			*host++ = 0;
 			suser = argv[i];
 			if (*suser == '\0')
-				suser = pwd->pw_name;
+				suser = get_user_name();
 		}
 		host = cleanhostname(host);
 		len = strlen(src) + CMDNEEDS + 20;
@@ -1159,6 +1155,23 @@ usage(void)
 	exit(1);
 }
 
+static const char*
+get_user_name()
+{
+	static const char *user_name = NULL;
+
+	if (user_name == NULL) {
+		uid_t userid;
+		struct passwd *pwd;
+		if (pwd = getpwuid(userid = getuid()))
+			user_name = xstrdup(pwd->pw_name);
+		else
+			fatal("unknown user ID '%u'; specify a user name", (u_int) userid);
+	}
+
+	return user_name;
+}
+
 void
 run_err(const char *fmt,...)
 {
-- 
2.4.3



More information about the Dropbear mailing list