Imported Upstream version 0.66.1
[hcoop/debian/courier-authlib.git] / libs / numlib / changeuidgid.c
CommitLineData
d9898ee8 1/*
2** Copyright 1998 - 2002 Double Precision, Inc. See COPYING for
3** distribution information.
4*/
5
6#if HAVE_CONFIG_H
7#include "config.h"
8#endif
9#include <sys/types.h>
10#if HAVE_UNISTD_H
11#include <unistd.h>
12#endif
13#include <stdio.h>
14#include <stdlib.h>
15#include <string.h>
16#include <grp.h>
17#include <pwd.h>
18#include <errno.h>
19
20#include "numlib.h"
21
d9898ee8 22
23void libmail_changegroup(gid_t gid)
24{
25 if ( setgid(gid))
26 {
27 perror("setgid");
28 exit(1);
29 }
30
31#if HAVE_SETGROUPS
32 if ( getuid() == 0 && setgroups(1, &gid) )
33 {
34 perror("setgroups");
35 exit(1);
36 }
37#endif
38}
39
40void libmail_changeuidgid(uid_t uid, gid_t gid)
41{
42 libmail_changegroup(gid);
43 if ( setuid(uid))
44 {
45 perror("setuid");
46 exit(1);
47 }
48}
49
50void libmail_changeusername(const char *uname, const gid_t *forcegrp)
51{
52struct passwd *pw;
53uid_t changeuid;
54gid_t changegid;
55
56/* uname might be a pointer returned from a previous called to getpw(),
57** and libc has a problem getting it back.
58*/
59char *p=malloc(strlen(uname)+1);
60
61 if (!p)
62 {
63 perror("malloc");
64 exit(1);
65 }
66 strcpy(p, uname);
67
68 errno=ENOENT;
69 if ((pw=getpwnam(p)) == 0)
70 {
71 free(p);
72 perror("getpwnam");
73 exit(1);
74 }
75 free(p);
76
77 changeuid=pw->pw_uid;
78
79 if ( !forcegrp ) forcegrp= &pw->pw_gid;
80
81 changegid= *forcegrp;
82
83 if ( setgid( changegid ))
84 {
85 perror("setgid");
86 exit(1);
87 }
88
89#if HAVE_INITGROUPS
90 if ( getuid() == 0 && initgroups(pw->pw_name, changegid) )
91 {
92 perror("initgroups");
93 exit(1);
94 }
95#else
96#if HAVE_SETGROUPS
97 if ( getuid() == 0 && setgroups(1, &changegid) )
98 {
99 perror("setgroups");
100 exit(1);
101 }
102#endif
103#endif
104
105 if (setuid(changeuid))
106 {
107 perror("setuid");
108 exit(1);
109 }
110}