/* See: Code Fragment 3.1 of Goodrich Tamassia 
   A simple C program that uses seteuid() to change its permissions.
   The fprintf action is done using the permissions of the owner of
   this program, not the user running this program.
*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

static uid_t euid, uid;

int main(int argc, char * argvp[]) {
  FILE *file;
  /* Store real and effective user IDs */
  uid = getuid();
  euid = geteuid();
  /* Drop privileges  */
  seteuid(uid);
  /* Do something useful */
  /* ... */
  /* Raise privileges, in order to access the file */
  seteuid(euid);
  /* Open the file; NB: this is owned and readable only by a different user */
  file = fopen("/tmp/logfile", "a");
  /* Drop privileges again */
  seteuid(uid);
  /* Write to the file */
  if (file) {
    fprintf(file, "Someone used this program: UID=%d, EUID=%d\n",
	    getuid(), geteuid());
  } else {
    fprintf(stderr, "Could not open file /tmp/logfile; aborting ...\n");
    return 1;
  }
  /* Close the file and return */
  fclose(file);
  return 0;
}
