Skip to content
Advertisement

Retrieve logged on user name or id in the process running under root

I need to run from a privileged (root) application another application with current logged on user.

getenv("USER") and getenv("LOGNAME") return “root” in the privileged application. Effective and current user ids are 0.

cat /proc/self/status | grep [GU]id:
Uid:    0       0       0       0
Gid:    0       0       0       0

I found something close to my needs, user-1000.slice, but I would like to avoid using fscanf on the file /proc/self/cgroup.

cat /proc/self/cgroup | fgrep user
9:devices:/user.slice
8:pids:/user.slice/user-1000.slice
1:name=systemd:/user.slice/user-1000.slice/session-c1.scope

The code bellow outputs 1000 as desired. Is there any more convenient way or API to get a user name of current UI session from a privileged application?

#include <stdio.h>

int main() {
  int luid = 0;
  char line[100];
  FILE* file = fopen("/proc/self/cgroup", "r");

  while (fgets(line, sizeof(line), file)) {
    if (sscanf(line, "%*d:pids:/user.slice/user-%d.slice", &luid) == 1)
      break;
  }
  fclose(file);
  printf("Logged on User Id: ");
  luid ? printf("%dn", luid) : printf("Not foundn");
  return 0;
}

Advertisement

Answer

I noticed it lately that the upstart process is running under a log on user, I thought it is running under root. So, my solution below looks better than one with extracting user id from /proc/self/cgroup.

#include <stdio.h>

int main() {
  int uid = -1;
  char line[100];
  pid_t sid = getsid(0);
  sprintf(line, "/proc/%d/status", sid);
  FILE *file = fopen(line, "r");

  while (fgets(line, sizeof(line), file)) {
    if (sscanf(line, "Uid: %d", &uid) == 1)
      break;
  }
  fclose(file);
  printf("Logged on User Id: ");
  uid != -1 ? printf("%dn", uid) : printf("Not foundn");
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement