79f2ba34bddc26b5bb9fead6bf748651437a689d
[mono.git] / mono / io-layer / security.c
1 /*
2  * security.c:  Security
3  *
4  * Author:
5  *      Sebastien Pouliot  <sebastien@ximian.com>
6  *
7  * (C) 2004 Novell (http://www.novell.com)
8  */
9
10 #include <config.h>
11 #include <mono/io-layer/io-layer.h>
12
13 #include <pwd.h>
14 #include <string.h>
15 #include <sys/types.h>
16 #include <unistd.h>
17
18
19 gboolean
20 GetUserName (gchar *buffer, gint32 *size) 
21 {
22 #ifdef HAVE_GETPWUID_R
23         struct passwd *pbuf;
24         size_t fbufsize;
25         gchar *fbuf;
26 #endif
27         struct passwd *p;
28         uid_t uid;
29
30         if (!size) {
31                 SetLastError (ERROR_INVALID_PARAMETER);
32                 return FALSE;
33         }
34
35         uid = getuid ();
36 #ifdef HAVE_GETPWUID_R
37         fbufsize = (size_t) sysconf (_SC_GETPW_R_SIZE_MAX);
38         fbuf = g_malloc0 (fbufsize);
39         pbuf = g_new0 (struct passwd, 1);
40         getpwuid_r (uid, pbuf, fbuf, fbufsize, &p);
41 #else
42         p = getpwuid (uid);
43 #endif
44         if (p) {
45                 gint32 sz = strlen (p->pw_name);
46                 if (buffer) {
47                         if (sz > *size)
48                                 sz = *size;
49                         strncpy (buffer, p->pw_name, sz);
50                 }
51                 *size = sz;
52                 return TRUE;
53         }
54
55 #ifdef HAVE_GETPWUID_R
56         g_free (pbuf);
57         g_free (fbuf);
58 #endif
59         *size = 0;
60         SetLastError (ERROR_INVALID_HANDLE);
61         return FALSE;
62 }
63