1 /*	$NetBSD: open_as.c,v 1.1.1.1 2009/06/23 10:09:00 tron Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	open_as 3
6 /* SUMMARY
7 /*	open file as user
8 /* SYNOPSIS
9 /*	#include <fcntl.h>
10 /*	#include <open_as.h>
11 /*
12 /*	int	open_as(path, flags, mode, euid, egid)
13 /*	const char *path;
14 /*	int	mode;
15 /*	uid_t	euid;
16 /*	gid_t	egid;
17 /* DESCRIPTION
18 /*	open_as() opens the named \fIpath\fR with the named \fIflags\fR
19 /*	and \fImode\fR, and with the effective rights specified by \fIeuid\fR
20 /*	and \fIegid\fR.  A -1 result means the open failed.
21 /* DIAGNOSTICS
22 /*	Fatal error: no permission to change privilege level.
23 /* SEE ALSO
24 /*	set_eugid(3) switch effective rights
25 /* LICENSE
26 /* .ad
27 /* .fi
28 /*	The Secure Mailer license must be distributed with this software.
29 /* AUTHOR(S)
30 /*	Wietse Venema
31 /*	IBM T.J. Watson Research
32 /*	P.O. Box 704
33 /*	Yorktown Heights, NY 10598, USA
34 /*--*/
35 
36 /* System library. */
37 
38 #include <sys_defs.h>
39 #include <fcntl.h>
40 #include <unistd.h>
41 
42 /* Utility library. */
43 
44 #include "msg.h"
45 #include "set_eugid.h"
46 #include "open_as.h"
47 
48 /* open_as - open file as user */
49 
50 int     open_as(const char *path, int flags, int mode, uid_t euid, gid_t egid)
51 {
52     uid_t   saved_euid = geteuid();
53     gid_t   saved_egid = getegid();
54     int     fd;
55 
56     /*
57      * Switch to the target user privileges.
58      */
59     set_eugid(euid, egid);
60 
61     /*
62      * Open that file.
63      */
64     fd = open(path, flags, mode);
65 
66     /*
67      * Restore saved privileges.
68      */
69     set_eugid(saved_euid, saved_egid);
70 
71     return (fd);
72 }
73