autoupdate ylwrap
[gnulib.git] / lib / getlogin_r.c
1 /* Provide a working getlogin_r for systems which lack it.
2
3    Copyright (C) 2005-2007, 2010-2011 Free Software Foundation, Inc.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software Foundation,
17    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
18
19 /* Written by Paul Eggert, Derek Price, and Bruno Haible.  */
20
21 #include <config.h>
22
23 /* Specification.  */
24 #include <unistd.h>
25
26 #include <errno.h>
27 #include <string.h>
28
29 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
30 # define WIN32_LEAN_AND_MEAN
31 # include <windows.h>
32 #else
33 # if !HAVE_DECL_GETLOGIN
34 extern char *getlogin (void);
35 # endif
36 #endif
37
38 /* See unistd.in.h for documentation.  */
39 int
40 getlogin_r (char *name, size_t size)
41 {
42 #undef getlogin_r
43 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
44   /* Native Windows platform.  */
45   DWORD sz;
46
47   /* When size > 0x7fff, the doc says that GetUserName will fail.
48      Actually, on Windows XP SP3, it succeeds.  But let's be safe,
49      for the sake of older Windows versions.  */
50   if (size > 0x7fff)
51     size = 0x7fff;
52   sz = size;
53   if (!GetUserName (name, &sz))
54     {
55       if (GetLastError () == ERROR_INSUFFICIENT_BUFFER)
56         /* In this case, the doc says that sz contains the required size, but
57            actually, on Windows XP SP3, it contains 2 * the required size.  */
58         return ERANGE;
59       else
60         return ENOENT;
61     }
62   return 0;
63 #elif HAVE_GETLOGIN_R
64   /* Platform with a getlogin_r() function.  */
65   int ret = getlogin_r (name, size);
66
67   if (ret == 0 && memchr (name, '\0', size) == NULL)
68     /* name contains a truncated result.  */
69     return ERANGE;
70   return ret;
71 #else
72   /* Platform with a getlogin() function.  */
73   char *n;
74   size_t nlen;
75
76   errno = 0;
77   n = getlogin ();
78   if (!n)
79     /* ENOENT is a reasonable errno value if getlogin returns NULL.  */
80     return (errno != 0 ? errno : ENOENT);
81
82   nlen = strlen (n);
83   if (size <= nlen)
84     return ERANGE;
85   memcpy (name, n, nlen + 1);
86   return 0;
87 #endif
88 }