1 /* 2 * Copyright 2008, Ingo Weinhold, ingo_weinhold@gmx.de. All rights reserved. 3 * Copyright 2002-2006, Axel Dörfler, axeld@pinc-software.de. All rights reserved. 4 * Distributed under the terms of the MIT License. 5 */ 6 7 8 #include <syscalls.h> 9 10 #include <ctype.h> 11 #include <errno.h> 12 #include <fcntl.h> 13 #include <limits.h> 14 #include <stdio.h> 15 #include <stdlib.h> 16 #include <string.h> 17 #include <unistd.h> 18 #include <pwd.h> 19 20 21 template<typename T> 22 static inline T 23 set_errno_if_necessary(const T& result) 24 { 25 if (result < 0) { 26 errno = result; 27 return -1; 28 } 29 30 return result; 31 } 32 33 34 // #pragma mark - 35 36 37 gid_t 38 getegid(void) 39 { 40 return _kern_getgid(true); 41 } 42 43 44 uid_t 45 geteuid(void) 46 { 47 return _kern_getuid(true); 48 } 49 50 51 gid_t 52 getgid(void) 53 { 54 return _kern_getgid(false); 55 } 56 57 58 uid_t 59 getuid(void) 60 { 61 return _kern_getuid(false); 62 } 63 64 65 int 66 setgid(gid_t gid) 67 { 68 return set_errno_if_necessary(_kern_setregid(gid, (gid_t)-1, true)); 69 } 70 71 72 int 73 setuid(uid_t uid) 74 { 75 return set_errno_if_necessary(_kern_setreuid(uid, (uid_t)-1, true)); 76 } 77 78 79 int 80 setegid(gid_t gid) 81 { 82 return set_errno_if_necessary(_kern_setregid((gid_t)-1, gid, false)); 83 } 84 85 86 int 87 seteuid(uid_t uid) 88 { 89 return set_errno_if_necessary(_kern_setreuid((uid_t)-1, uid, false)); 90 } 91 92 93 int 94 setregid(gid_t rgid, gid_t egid) 95 { 96 return set_errno_if_necessary(_kern_setregid(rgid, egid, false)); 97 } 98 99 100 int 101 setreuid(uid_t ruid, uid_t euid) 102 { 103 return set_errno_if_necessary(_kern_setreuid(ruid, euid, false)); 104 } 105 106 107 int 108 getgroups(int groupCount, gid_t groupList[]) 109 { 110 return set_errno_if_necessary(_kern_getgroups(groupCount, groupList)); 111 } 112 113 114 int 115 setgroups(int groupCount, const gid_t* groupList) 116 { 117 return set_errno_if_necessary(_kern_setgroups(groupCount, groupList)); 118 } 119 120 // NOTE: getgrouplist() and initgroups() are implemented in grp.cpp. 121