summaryrefslogtreecommitdiffstats
path: root/lib/isatty.c
blob: ba40d91f938f47a9e487eac4d586a1bd12fe0f22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
/* isatty() replacement.
   Copyright (C) 2012-2022 Free Software Foundation, Inc.

   This file is free software: you can redistribute it and/or modify
   it under the terms of the GNU Lesser General Public License as
   published by the Free Software Foundation; either version 2.1 of the
   License, or (at your option) any later version.

   This file is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public License
   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */

#include <config.h>

/* Specification.  */
#include <unistd.h>

/* This replacement is enabled on native Windows.  */

#include <errno.h>
#include <string.h>

/* Get declarations of the Win32 API functions.  */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#if HAVE_MSVC_INVALID_PARAMETER_HANDLER
# include "msvc-inval.h"
#endif

/* Get _get_osfhandle().  */
#if GNULIB_MSVC_NOTHROW
# include "msvc-nothrow.h"
#else
# include <io.h>
#endif

/* Don't assume that UNICODE is not defined.  */
#undef LoadLibrary
#define LoadLibrary LoadLibraryA
#undef QueryFullProcessImageName
#define QueryFullProcessImageName QueryFullProcessImageNameA

#if !(_WIN32_WINNT >= _WIN32_WINNT_VISTA)

/* Avoid warnings from gcc -Wcast-function-type.  */
# define GetProcAddress \
   (void *) GetProcAddress

/* GetNamedPipeClientProcessId was introduced only in Windows Vista.  */
typedef BOOL (WINAPI * GetNamedPipeClientProcessIdFuncType) (HANDLE hPipe,
                                                             PULONG pClientProcessId);
static GetNamedPipeClientProcessIdFuncType GetNamedPipeClientProcessIdFunc = NULL;
/* QueryFullProcessImageName was introduced only in Windows Vista.  */
typedef BOOL (WINAPI * QueryFullProcessImageNameFuncType) (HANDLE hProcess,
                                                           DWORD dwFlags,
                                                           LPSTR lpExeName,
                                                           PDWORD pdwSize);
static QueryFullProcessImageNameFuncType QueryFullProcessImageNameFunc = NULL;
static BOOL initialized = FALSE;

static void
initialize (void)
{
  HMODULE kernel32 = LoadLibrary ("kernel32.dll");
  if (kernel32 != NULL)
    {
      GetNamedPipeClientProcessIdFunc =
        (GetNamedPipeClientProcessIdFuncType) GetProcAddress (kernel32, "GetNamedPipeClientProcessId");
      QueryFullProcessImageNameFunc =
        (QueryFullProcessImageNameFuncType) GetProcAddress (kernel32, "QueryFullProcessImageNameA");
    }
  initialized = TRUE;
}

#else

# define GetNamedPipeClientProcessIdFunc GetNamedPipeClientProcessId
# define QueryFullProcessImageNameFunc QueryFullProcessImageName

#endif

static BOOL IsConsoleHandle (HANDLE h)
{
  DWORD mode;
  /* GetConsoleMode
     <https://docs.microsoft.com/en-us/windows/console/getconsolemode> */
  return GetConsoleMode (h, &mode) != 0;
}

static BOOL IsCygwinConsoleHandle (HANDLE h)
{
  /* A handle to a Cygwin console is in fact a named pipe whose client process
     and server process is <CYGWIN_INSTALL_DIR>\bin\mintty.exe.  */
  BOOL result = FALSE;
  ULONG processId;

#if !(_WIN32_WINNT >= _WIN32_WINNT_VISTA)
  if (!initialized)
    initialize ();
#endif

  /* GetNamedPipeClientProcessId
     <https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-getnamedpipeclientprocessid>
     It requires -D_WIN32_WINNT=_WIN32_WINNT_VISTA or higher.  */
  if (GetNamedPipeClientProcessIdFunc && QueryFullProcessImageNameFunc
      && GetNamedPipeClientProcessIdFunc (h, &processId))
    {
      /* OpenProcess
         <https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-openprocess> */
      HANDLE processHandle =
        OpenProcess (PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processId);
      if (processHandle != NULL)
        {
          char buf[1024];
          DWORD bufsize = sizeof (buf);
          /* The file name can be determined through
             GetProcessImageFileName
             <https://docs.microsoft.com/en-us/windows/desktop/api/psapi/nf-psapi-getprocessimagefilenamea>
             or
             QueryFullProcessImageName
             <https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-queryfullprocessimagenamea>
             The former returns a file name in non-standard notation (it starts
             with '\Device\') and may require linking with psapi.dll.
             The latter is better, but requires -D_WIN32_WINNT=_WIN32_WINNT_VISTA
             or higher.  */
          if (QueryFullProcessImageNameFunc (processHandle, 0, buf, &bufsize))
            {
              if (strlen (buf) >= 11
                  && strcmp (buf + strlen (buf) - 11, "\\mintty.exe") == 0)
                result = TRUE;
            }
          CloseHandle (processHandle);
        }
    }
  return result;
}

#if HAVE_MSVC_INVALID_PARAMETER_HANDLER
static int
_isatty_nothrow (int fd)
{
  int result;

  TRY_MSVC_INVAL
    {
      result = _isatty (fd);
    }
  CATCH_MSVC_INVAL
    {
      result = 0;
    }
  DONE_MSVC_INVAL;

  return result;
}
#else
# define _isatty_nothrow _isatty
#endif

/* Determine whether FD refers to a console device.  Return 1 if yes.
   Return 0 and set errno if no. (ptsname_r relies on the errno value.)  */
int
isatty (int fd)
{
  HANDLE h = (HANDLE) _get_osfhandle (fd);
  if (h == INVALID_HANDLE_VALUE)
    {
      errno = EBADF;
      return 0;
    }
  /* _isatty (fd) tests whether GetFileType of the handle is FILE_TYPE_CHAR.
     But it does not set errno when it returns 0.  */
  if (_isatty_nothrow (fd))
    {
      if (IsConsoleHandle (h))
        return 1;
    }
  if (IsCygwinConsoleHandle (h))
    return 1;
  errno = ENOTTY;
  return 0;
}