/* Este arquivo mostra as credenciais reais e efetivas de usuario
   e de grupo do processo corrente (UID, EUID, GID, EGID).
   
   Carlos Maziero, DAINF/UTFPR, Jan 2014
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>

#define NAMESIZE 256

int main ()
{
  int uid, euid, gid, egid ;
  struct passwd *pw ;
  struct group *gr ;

  char login[NAMESIZE] ;
  char elogin[NAMESIZE] ;
  char group[NAMESIZE] ;
  char egroup[NAMESIZE] ;

  // get credentials
  uid  = getuid () ;
  euid = geteuid () ;
  gid  = getgid () ;
  egid = getegid () ;

  // get login name for UID
  pw = getpwuid (uid) ;
  if (pw)
    strncpy (login, pw->pw_name, NAMESIZE) ;
  else
    printf ("Login for UID %d not found\n", uid) ;

  // get login name for EUID
  pw = getpwuid (euid) ;
  if (pw)
    strncpy (elogin, pw->pw_name, NAMESIZE) ;
  else
    printf ("Login for EUID %d not found\n", uid) ;

  // get group name for GID
  gr = getgrgid (gid) ;
  if (gr)
    strncpy (group, gr->gr_name, NAMESIZE) ;
  else
    printf ("Group for GID %d not found\n", gid) ;

  // get group name for EGID
  gr = getgrgid (egid) ;
  if (gr)
    strncpy (egroup, gr->gr_name, NAMESIZE) ;
  else
    printf ("Group for EGID %d not found\n", egid) ;

  // print results
  printf ("My UID is %d (%s), my EUID is %d (%s)\n", uid, login, euid, elogin) ;
  printf ("My GID is %d (%s), my EGID is %d (%s)\n", gid, group, egid, egroup) ;

  exit (0);
}

