Browse Source

Implement __uid and __user internal variables

Serj Kalichev 3 years ago
parent
commit
1577dcce53
1 changed files with 28 additions and 0 deletions
  1. 28 0
      clish/shell/shell_var.c

+ 28 - 0
clish/shell/shell_var.c

@@ -8,6 +8,7 @@
 #include <ctype.h>
 #include <sys/types.h>
 #include <unistd.h>
+#include <pwd.h>
 
 #include "lub/string.h"
 #include "lub/conv.h"
@@ -111,6 +112,33 @@ static char *find_context_var(const char *name, clish_context_t *this)
 		int depth = clish_shell__get_depth(shell);
 		result = clish_shell__get_pwd_full(shell, depth);
 
+	} else if (!lub_string_nocasecmp(name, "_uid")) {
+		char tmp[10];
+		snprintf(tmp, sizeof(tmp), "%u", getuid());
+		tmp[sizeof(tmp) - 1] = '\0';
+		result = strdup(tmp);
+
+	} else if (!lub_string_nocasecmp(name, "_user")) {
+		char *uname = NULL;
+		/* Try to get username from environment variables
+		 * USER and LOGNAME and then from /etc/passwd. Else use UID.
+		 */
+		if (!(uname = getenv("USER"))) {
+			if (!(uname = getenv("LOGNAME"))) {
+				struct passwd *user = NULL;
+				user = clish_shell__get_user(shell);
+				if (user) {
+					uname = user->pw_name;
+				} else {
+					char tmp[10] = {};
+					snprintf(tmp, sizeof(tmp), "%u", getuid());
+					tmp[sizeof(tmp) - 1] = '\0';
+					uname = tmp;
+				}
+			}
+		}
+		result = strdup(uname);
+
 	/* The vars dependent on command. Code supposes this->cmd is valid.
 	 * Don't put command-independent variables after that line.
 	 */