1 /* Test of getting user name.
2    Copyright (C) 2010-2018 Free Software Foundation, Inc.
3 
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8 
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13 
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
16 
17 /* Written by Bruno Haible and Paul Eggert.  */
18 
19 #include <errno.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <unistd.h>
24 #if !(defined _WIN32 && !defined __CYGWIN__)
25 # include <pwd.h>
26 #endif
27 
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 
31 #include "macros.h"
32 
33 static void
test_getlogin_result(const char * buf,int err)34 test_getlogin_result (const char *buf, int err)
35 {
36   if (err != 0)
37     {
38       if (err == ENOENT)
39         {
40           /* This can happen on GNU/Linux.  */
41           fprintf (stderr, "Skipping test: no entry in utmp file.\n");
42           exit (77);
43         }
44 
45       /* It fails when stdin is not connected to a tty.  */
46       ASSERT (err == ENOTTY
47               || err == EINVAL /* seen on Linux/SPARC */
48               || err == ENXIO
49              );
50 #if !defined __hpux /* On HP-UX 11.11 it fails anyway.  */
51       ASSERT (! isatty (0));
52 #endif
53       fprintf (stderr, "Skipping test: stdin is not a tty.\n");
54       exit (77);
55     }
56 
57   /* Compare against the value from the environment.  */
58 #if !(defined _WIN32 && !defined __CYGWIN__)
59   /* Unix platform */
60   {
61     struct stat stat_buf;
62     struct passwd *pwd;
63 
64     if (!isatty (STDIN_FILENO))
65       {
66          fprintf (stderr, "Skipping test: stdin is not a tty.\n");
67          exit (77);
68       }
69 
70     ASSERT (fstat (STDIN_FILENO, &stat_buf) == 0);
71 
72     pwd = getpwnam (buf);
73     if (! pwd)
74       {
75         fprintf (stderr, "Skipping test: %s: no such user\n", buf);
76         exit (77);
77       }
78 
79     ASSERT (pwd->pw_uid == stat_buf.st_uid);
80   }
81 #endif
82 #if defined _WIN32 && !defined __CYGWIN__
83   /* Native Windows platform.
84      Note: This test would fail on Cygwin in an ssh session, because sshd
85      sets USERNAME=SYSTEM.  */
86   {
87     const char *name = getenv ("USERNAME");
88     if (name != NULL && name[0] != '\0')
89       ASSERT (strcmp (buf, name) == 0);
90   }
91 #endif
92 }
93