w32.c 292 KB
Newer Older
1
/* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
2

Paul Eggert's avatar
Paul Eggert committed
3
Copyright (C) 1994-1995, 2000-2020 Free Software Foundation, Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
4

5 6
This file is part of GNU Emacs.

7
GNU Emacs is free software: you can redistribute it and/or modify
8
it under the terms of the GNU General Public License as published by
9 10
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
11 12 13 14 15 16 17

GNU Emacs 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 General Public License for more details.

You should have received a copy of the GNU General Public License
Paul Eggert's avatar
Paul Eggert committed
18
along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */
Richard M. Stallman's avatar
Richard M. Stallman committed
19

20
/*
Richard M. Stallman's avatar
Richard M. Stallman committed
21 22
   Geoff Voelker (voelker@cs.washington.edu)                         7-29-94
*/
23

Paul Eggert's avatar
Paul Eggert committed
24 25
#define DEFER_MS_W32_H
#include <config.h>
26

27
#include <mingw_time.h>
Geoff Voelker's avatar
Geoff Voelker committed
28
#include <stddef.h> /* for offsetof */
Richard M. Stallman's avatar
Richard M. Stallman committed
29 30
#include <stdlib.h>
#include <stdio.h>
31
#include <float.h>	/* for DBL_EPSILON */
Richard M. Stallman's avatar
Richard M. Stallman committed
32
#include <io.h>
33
#include <errno.h>
Richard M. Stallman's avatar
Richard M. Stallman committed
34 35
#include <fcntl.h>
#include <ctype.h>
36
#include <signal.h>
Karl Heuer's avatar
Karl Heuer committed
37
#include <sys/file.h>
Eli Zaretskii's avatar
Eli Zaretskii committed
38
#include <time.h>	/* must be before nt/inc/sys/time.h, for MinGW64 */
39
#include <sys/time.h>
40
#include <sys/utime.h>
41
#include <math.h>
42

43
/* Include (most) CRT headers *before* ms-w32.h.  */
Paul Eggert's avatar
Paul Eggert committed
44
#include <ms-w32.h>
Pavel Janík's avatar
Pavel Janík committed
45

46
#include <string.h>	/* for strerror, needed by sys_strerror */
47
#include <mbstring.h>	/* for _mbspbrk, _mbslwr, _mbsrchr, ... */
Pavel Janík's avatar
Pavel Janík committed
48

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
#undef access
#undef chdir
#undef chmod
#undef creat
#undef ctime
#undef fopen
#undef link
#undef mkdir
#undef open
#undef rename
#undef rmdir
#undef unlink

#undef close
#undef dup
#undef dup2
#undef pipe
#undef read
#undef write
Richard M. Stallman's avatar
Richard M. Stallman committed
68

Andrew Innes's avatar
Andrew Innes committed
69 70
#undef strerror

71 72
#undef localtime

73 74 75 76 77 78 79 80 81 82 83 84
char *sys_ctime (const time_t *);
int sys_chdir (const char *);
int sys_creat (const char *, int);
FILE *sys_fopen (const char *, const char *);
int sys_open (const char *, int, int);
int sys_rename (char const *, char const *);
int sys_rmdir (const char *);
int sys_close (int);
int sys_dup2 (int, int);
int sys_read (int, char *, unsigned int);
int sys_write (int, const void *, unsigned int);
struct tm *sys_localtime (const time_t *);
85 86 87 88
/* MinGW64 system headers include string.h too early, causing the
   compiler to emit a warning about sys_strerror having no
   prototype.  */
char *sys_strerror (int);
89 90 91 92 93

#ifdef HAVE_MODULES
extern void dynlib_reset_last_error (void);
#endif

Richard M. Stallman's avatar
Richard M. Stallman committed
94
#include "lisp.h"
95
#include "epaths.h"	/* for PATH_EXEC */
Richard M. Stallman's avatar
Richard M. Stallman committed
96 97

#include <pwd.h>
Lars Hansen's avatar
Lars Hansen committed
98
#include <grp.h>
Richard M. Stallman's avatar
Richard M. Stallman committed
99

100
#include <windows.h>
101 102 103
/* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
   use a different name to avoid compilation problems.  */
typedef struct _MEMORY_STATUS_EX {
104 105 106 107 108 109 110 111 112
  DWORD dwLength;
  DWORD dwMemoryLoad;
  DWORDLONG ullTotalPhys;
  DWORDLONG ullAvailPhys;
  DWORDLONG ullTotalPageFile;
  DWORDLONG ullAvailPageFile;
  DWORDLONG ullTotalVirtual;
  DWORDLONG ullAvailVirtual;
  DWORDLONG ullAvailExtendedVirtual;
113
} MEMORY_STATUS_EX,*LPMEMORY_STATUS_EX;
114

115
/* These are here so that GDB would know about these data types.  This
116
   allows attaching GDB to Emacs when a fatal exception is triggered
117 118 119 120 121 122 123 124 125 126 127 128 129
   and Windows pops up the "application needs to be closed" dialog.
   At that point, _gnu_exception_handler, the top-level exception
   handler installed by the MinGW startup code, is somewhere on the
   call-stack of the main thread, so going to that call frame and
   looking at the argument to _gnu_exception_handler, which is a
   PEXCEPTION_POINTERS pointer, can reveal the exception code
   (excptr->ExceptionRecord->ExceptionCode) and the address where the
   exception happened (excptr->ExceptionRecord->ExceptionAddress), as
   well as some additional information specific to the exception.  */
PEXCEPTION_POINTERS excptr;
PEXCEPTION_RECORD excprec;
PCONTEXT ctxrec;

130
#include <lmcons.h>
131
#include <shlobj.h>
132

133 134
#include <tlhelp32.h>
#include <psapi.h>
135
#ifndef _MSC_VER
Eli Zaretskii's avatar
Eli Zaretskii committed
136
#include <w32api.h>
137
#endif
138
#if _WIN32_WINNT < 0x0500
Juanma Barranquero's avatar
Juanma Barranquero committed
139
#if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
140
/* This either is not in psapi.h or guarded by higher value of
141
   _WIN32_WINNT than what we use.  w32api supplied with MinGW 3.15
Eli Zaretskii's avatar
Eli Zaretskii committed
142
   defines it in psapi.h  */
143
typedef struct _PROCESS_MEMORY_COUNTERS_EX {
144 145 146 147 148 149 150 151 152 153 154
  DWORD  cb;
  DWORD  PageFaultCount;
  SIZE_T PeakWorkingSetSize;
  SIZE_T WorkingSetSize;
  SIZE_T QuotaPeakPagedPoolUsage;
  SIZE_T QuotaPagedPoolUsage;
  SIZE_T QuotaPeakNonPagedPoolUsage;
  SIZE_T QuotaNonPagedPoolUsage;
  SIZE_T PagefileUsage;
  SIZE_T PeakPagefileUsage;
  SIZE_T PrivateUsage;
155
} PROCESS_MEMORY_COUNTERS_EX,*PPROCESS_MEMORY_COUNTERS_EX;
Eli Zaretskii's avatar
Eli Zaretskii committed
156
#endif
157
#endif
158

159 160
#include <winioctl.h>
#include <aclapi.h>
161 162 163
#include <sddl.h>

#include <sys/acl.h>
164
#include <acl.h>
165 166 167 168 169 170

/* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
   define them by hand if not already defined.  */
#ifndef SDDL_REVISION_1
#define SDDL_REVISION_1	1
#endif	/* SDDL_REVISION_1 */
171

172
#if defined(_MSC_VER) || defined(MINGW_W64)
173 174 175 176
/* MSVC and MinGW64 don't provide the definition of
   REPARSE_DATA_BUFFER and the associated macros, except on ntifs.h,
   which cannot be included because it triggers conflicts with other
   Windows API headers.  So we define it here by hand.  */
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203

typedef struct _REPARSE_DATA_BUFFER {
    ULONG  ReparseTag;
    USHORT ReparseDataLength;
    USHORT Reserved;
    union {
        struct {
            USHORT SubstituteNameOffset;
            USHORT SubstituteNameLength;
            USHORT PrintNameOffset;
            USHORT PrintNameLength;
            ULONG Flags;
            WCHAR PathBuffer[1];
        } SymbolicLinkReparseBuffer;
        struct {
            USHORT SubstituteNameOffset;
            USHORT SubstituteNameLength;
            USHORT PrintNameOffset;
            USHORT PrintNameLength;
            WCHAR PathBuffer[1];
        } MountPointReparseBuffer;
        struct {
            UCHAR  DataBuffer[1];
        } GenericReparseBuffer;
    } DUMMYUNIONNAME;
} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;

204
#ifndef FILE_DEVICE_FILE_SYSTEM
205
#define FILE_DEVICE_FILE_SYSTEM	9
206 207
#endif
#ifndef METHOD_BUFFERED
208
#define METHOD_BUFFERED	        0
209 210
#endif
#ifndef FILE_ANY_ACCESS
211
#define FILE_ANY_ACCESS	        0x00000000
212 213
#endif
#ifndef CTL_CODE
214
#define CTL_CODE(t,f,m,a)       (((t)<<16)|((a)<<14)|((f)<<2)|(m))
215
#endif
216 217
/* MinGW64 defines FSCTL_GET_REPARSE_POINT on winioctl.h.  */
#ifndef FSCTL_GET_REPARSE_POINT
218 219
#define FSCTL_GET_REPARSE_POINT \
  CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
220
#endif
221
#endif
222

223
/* TCP connection support.  */
224 225 226 227 228 229
#include <sys/socket.h>
#undef socket
#undef bind
#undef connect
#undef htons
#undef ntohs
230 231
#undef htonl
#undef ntohl
232 233 234 235
#undef inet_addr
#undef gethostname
#undef gethostbyname
#undef getservbyname
236
#undef getpeername
Geoff Voelker's avatar
Geoff Voelker committed
237
#undef shutdown
238 239 240 241 242 243
#undef setsockopt
#undef listen
#undef getsockname
#undef accept
#undef recvfrom
#undef sendto
244

245 246 247 248 249 250 251 252
/* We need at least XP level for GetAdaptersAddresses stuff.  */
#if _WIN32_WINNT < 0x0501
# undef ORIG_WIN32_WINNT
# define ORIG_WIN32_WINNT _WIN32_WINNT
# undef _WIN32_WINNT
# define _WIN32_WINNT 0x0501
#endif

253 254
#include <iphlpapi.h>	/* should be after winsock2.h */

255 256 257 258 259 260
#ifdef ORIG_WIN32_WINNT
# undef _WIN32_WINNT
# define _WIN32_WINNT ORIG_WIN32_WINNT
# undef ORIG_WIN32_WINNT
#endif

261 262
#include <wincrypt.h>

263
#include <c-strcase.h>
264
#include <utimens.h>	/* for fdutimens */
265

Geoff Voelker's avatar
Geoff Voelker committed
266
#include "w32.h"
267
#include <dirent.h>
Daniel Colascione's avatar
Daniel Colascione committed
268
#include "w32common.h"
269
#include "w32select.h"
270
#include "systime.h"		/* for current_timespec, struct timespec */
Eli Zaretskii's avatar
Eli Zaretskii committed
271
#include "dispextern.h"		/* for xstrcasecmp */
272
#include "coding.h"		/* for Vlocale_coding_system */
273

274 275 276
#include "careadlinkat.h"
#include "allocator.h"

277
/* For Lisp_Process, serial_configure and serial_open.  */
278
#include "process.h"
279
#include "systty.h"
280

281 282 283
typedef HRESULT (WINAPI * ShGetFolderPath_fn)
  (IN HWND, IN int, IN HANDLE, IN DWORD, OUT char *);

284
static DWORD get_rid (PSID);
285 286 287 288 289
static int is_symlink (const char *);
static char * chase_symlinks (const char *);
static int enable_privilege (LPCTSTR, BOOL, TOKEN_PRIVILEGES *);
static int restore_privilege (TOKEN_PRIVILEGES *);
static BOOL WINAPI revert_to_self (void);
290

291
static int sys_access (const char *, int);
292 293
extern void *e_malloc (size_t);
extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
294
		       const struct timespec *, const sigset_t *);
295 296
extern int sys_dup (int);

297

298 299 300 301 302 303 304 305 306
/* Initialization states.

   WARNING: If you add any more such variables for additional APIs,
            you MUST add initialization for them to globals_of_w32
            below.  This is because these variables might get set
            to non-NULL values during dumping, but the dumped Emacs
            cannot reuse those values, because it could be run on a
            different version of the OS, where API addresses are
            different.  */
307 308 309 310
static BOOL g_b_init_is_windows_9x;
static BOOL g_b_init_open_process_token;
static BOOL g_b_init_get_token_information;
static BOOL g_b_init_lookup_account_sid;
311 312
static BOOL g_b_init_get_sid_sub_authority;
static BOOL g_b_init_get_sid_sub_authority_count;
313
static BOOL g_b_init_get_security_info;
314 315
static BOOL g_b_init_get_file_security_w;
static BOOL g_b_init_get_file_security_a;
316 317 318
static BOOL g_b_init_get_security_descriptor_owner;
static BOOL g_b_init_get_security_descriptor_group;
static BOOL g_b_init_is_valid_sid;
319 320 321 322 323 324 325 326 327 328
static BOOL g_b_init_create_toolhelp32_snapshot;
static BOOL g_b_init_process32_first;
static BOOL g_b_init_process32_next;
static BOOL g_b_init_open_thread_token;
static BOOL g_b_init_impersonate_self;
static BOOL g_b_init_revert_to_self;
static BOOL g_b_init_get_process_memory_info;
static BOOL g_b_init_get_process_working_set_size;
static BOOL g_b_init_global_memory_status;
static BOOL g_b_init_global_memory_status_ex;
329 330 331
static BOOL g_b_init_get_length_sid;
static BOOL g_b_init_equal_sid;
static BOOL g_b_init_copy_sid;
332 333
static BOOL g_b_init_get_native_system_info;
static BOOL g_b_init_get_system_times;
334 335
static BOOL g_b_init_create_symbolic_link_w;
static BOOL g_b_init_create_symbolic_link_a;
336 337 338 339
static BOOL g_b_init_get_security_descriptor_dacl;
static BOOL g_b_init_convert_sd_to_sddl;
static BOOL g_b_init_convert_sddl_to_sd;
static BOOL g_b_init_is_valid_security_descriptor;
340 341
static BOOL g_b_init_set_file_security_w;
static BOOL g_b_init_set_file_security_a;
342 343
static BOOL g_b_init_set_named_security_info_w;
static BOOL g_b_init_set_named_security_info_a;
344
static BOOL g_b_init_get_adapters_info;
345
static BOOL g_b_init_get_adapters_addresses;
346 347 348
static BOOL g_b_init_reg_open_key_ex_w;
static BOOL g_b_init_reg_query_value_ex_w;
static BOOL g_b_init_expand_environment_strings_w;
349

350
BOOL g_b_init_compare_string_w;
351
BOOL g_b_init_debug_break_process;
352

353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
/*
  BEGIN: Wrapper functions around OpenProcessToken
  and other functions in advapi32.dll that are only
  supported in Windows NT / 2k / XP
*/
  /* ** Function pointer typedefs ** */
typedef BOOL (WINAPI * OpenProcessToken_Proc) (
    HANDLE ProcessHandle,
    DWORD DesiredAccess,
    PHANDLE TokenHandle);
typedef BOOL (WINAPI * GetTokenInformation_Proc) (
    HANDLE TokenHandle,
    TOKEN_INFORMATION_CLASS TokenInformationClass,
    LPVOID TokenInformation,
    DWORD TokenInformationLength,
    PDWORD ReturnLength);
369 370 371 372 373 374 375 376 377
typedef BOOL (WINAPI * GetProcessTimes_Proc) (
    HANDLE process_handle,
    LPFILETIME creation_time,
    LPFILETIME exit_time,
    LPFILETIME kernel_time,
    LPFILETIME user_time);

GetProcessTimes_Proc get_process_times_fn = NULL;

378 379 380 381 382 383 384 385 386 387 388 389 390
#ifdef _UNICODE
const char * const LookupAccountSid_Name = "LookupAccountSidW";
#else
const char * const LookupAccountSid_Name = "LookupAccountSidA";
#endif
typedef BOOL (WINAPI * LookupAccountSid_Proc) (
    LPCTSTR lpSystemName,
    PSID Sid,
    LPTSTR Name,
    LPDWORD cbName,
    LPTSTR DomainName,
    LPDWORD cbDomainName,
    PSID_NAME_USE peUse);
391 392 393 394 395
typedef PDWORD (WINAPI * GetSidSubAuthority_Proc) (
    PSID pSid,
    DWORD n);
typedef PUCHAR (WINAPI * GetSidSubAuthorityCount_Proc) (
    PSID pSid);
396 397 398 399 400 401 402 403 404
typedef DWORD (WINAPI * GetSecurityInfo_Proc) (
    HANDLE handle,
    SE_OBJECT_TYPE ObjectType,
    SECURITY_INFORMATION SecurityInfo,
    PSID *ppsidOwner,
    PSID *ppsidGroup,
    PACL *ppDacl,
    PACL *ppSacl,
    PSECURITY_DESCRIPTOR *ppSecurityDescriptor);
405 406 407 408 409 410 411 412
typedef BOOL (WINAPI * GetFileSecurityW_Proc) (
    LPCWSTR lpFileName,
    SECURITY_INFORMATION RequestedInformation,
    PSECURITY_DESCRIPTOR pSecurityDescriptor,
    DWORD nLength,
    LPDWORD lpnLengthNeeded);
typedef BOOL (WINAPI * GetFileSecurityA_Proc) (
    LPCSTR lpFileName,
413 414 415 416
    SECURITY_INFORMATION RequestedInformation,
    PSECURITY_DESCRIPTOR pSecurityDescriptor,
    DWORD nLength,
    LPDWORD lpnLengthNeeded);
417 418 419 420 421 422
typedef BOOL (WINAPI *SetFileSecurityW_Proc) (
    LPCWSTR lpFileName,
    SECURITY_INFORMATION SecurityInformation,
    PSECURITY_DESCRIPTOR pSecurityDescriptor);
typedef BOOL (WINAPI *SetFileSecurityA_Proc) (
    LPCSTR lpFileName,
423 424
    SECURITY_INFORMATION SecurityInformation,
    PSECURITY_DESCRIPTOR pSecurityDescriptor);
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
typedef DWORD (WINAPI *SetNamedSecurityInfoW_Proc) (
    LPCWSTR lpObjectName,
    SE_OBJECT_TYPE ObjectType,
    SECURITY_INFORMATION SecurityInformation,
    PSID psidOwner,
    PSID psidGroup,
    PACL pDacl,
    PACL pSacl);
typedef DWORD (WINAPI *SetNamedSecurityInfoA_Proc) (
    LPCSTR lpObjectName,
    SE_OBJECT_TYPE ObjectType,
    SECURITY_INFORMATION SecurityInformation,
    PSID psidOwner,
    PSID psidGroup,
    PACL pDacl,
    PACL pSacl);
441 442 443 444 445 446 447 448
typedef BOOL (WINAPI * GetSecurityDescriptorOwner_Proc) (
    PSECURITY_DESCRIPTOR pSecurityDescriptor,
    PSID *pOwner,
    LPBOOL lpbOwnerDefaulted);
typedef BOOL (WINAPI * GetSecurityDescriptorGroup_Proc) (
    PSECURITY_DESCRIPTOR pSecurityDescriptor,
    PSID *pGroup,
    LPBOOL lpbGroupDefaulted);
449 450 451 452 453
typedef BOOL (WINAPI *GetSecurityDescriptorDacl_Proc) (
    PSECURITY_DESCRIPTOR pSecurityDescriptor,
    LPBOOL lpbDaclPresent,
    PACL *pDacl,
    LPBOOL lpbDaclDefaulted);
454 455
typedef BOOL (WINAPI * IsValidSid_Proc) (
    PSID sid);
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
typedef HANDLE (WINAPI * CreateToolhelp32Snapshot_Proc) (
    DWORD dwFlags,
    DWORD th32ProcessID);
typedef BOOL (WINAPI * Process32First_Proc) (
    HANDLE hSnapshot,
    LPPROCESSENTRY32 lppe);
typedef BOOL (WINAPI * Process32Next_Proc) (
    HANDLE hSnapshot,
    LPPROCESSENTRY32 lppe);
typedef BOOL (WINAPI * OpenThreadToken_Proc) (
    HANDLE ThreadHandle,
    DWORD DesiredAccess,
    BOOL OpenAsSelf,
    PHANDLE TokenHandle);
typedef BOOL (WINAPI * ImpersonateSelf_Proc) (
    SECURITY_IMPERSONATION_LEVEL ImpersonationLevel);
typedef BOOL (WINAPI * RevertToSelf_Proc) (void);
typedef BOOL (WINAPI * GetProcessMemoryInfo_Proc) (
    HANDLE Process,
    PPROCESS_MEMORY_COUNTERS ppsmemCounters,
    DWORD cb);
typedef BOOL (WINAPI * GetProcessWorkingSetSize_Proc) (
    HANDLE hProcess,
479 480
    PSIZE_T lpMinimumWorkingSetSize,
    PSIZE_T lpMaximumWorkingSetSize);
481 482 483
typedef BOOL (WINAPI * GlobalMemoryStatus_Proc) (
    LPMEMORYSTATUS lpBuffer);
typedef BOOL (WINAPI * GlobalMemoryStatusEx_Proc) (
484
    LPMEMORY_STATUS_EX lpBuffer);
485 486 487 488 489 490 491 492 493
typedef BOOL (WINAPI * CopySid_Proc) (
    DWORD nDestinationSidLength,
    PSID pDestinationSid,
    PSID pSourceSid);
typedef BOOL (WINAPI * EqualSid_Proc) (
    PSID pSid1,
    PSID pSid2);
typedef DWORD (WINAPI * GetLengthSid_Proc) (
    PSID pSid);
494 495 496 497 498 499
typedef void (WINAPI * GetNativeSystemInfo_Proc) (
    LPSYSTEM_INFO lpSystemInfo);
typedef BOOL (WINAPI * GetSystemTimes_Proc) (
    LPFILETIME lpIdleTime,
    LPFILETIME lpKernelTime,
    LPFILETIME lpUserTime);
500 501 502 503 504 505 506
typedef BOOLEAN (WINAPI *CreateSymbolicLinkW_Proc) (
    LPCWSTR lpSymlinkFileName,
    LPCWSTR lpTargetFileName,
    DWORD  dwFlags);
typedef BOOLEAN (WINAPI *CreateSymbolicLinkA_Proc) (
    LPCSTR lpSymlinkFileName,
    LPCSTR lpTargetFileName,
507
    DWORD  dwFlags);
508 509 510 511 512 513 514 515 516 517 518 519
typedef BOOL (WINAPI *ConvertStringSecurityDescriptorToSecurityDescriptor_Proc) (
    LPCTSTR StringSecurityDescriptor,
    DWORD StringSDRevision,
    PSECURITY_DESCRIPTOR  *SecurityDescriptor,
    PULONG  SecurityDescriptorSize);
typedef BOOL (WINAPI *ConvertSecurityDescriptorToStringSecurityDescriptor_Proc) (
    PSECURITY_DESCRIPTOR  SecurityDescriptor,
    DWORD RequestedStringSDRevision,
    SECURITY_INFORMATION SecurityInformation,
    LPTSTR  *StringSecurityDescriptor,
    PULONG StringSecurityDescriptorLen);
typedef BOOL (WINAPI *IsValidSecurityDescriptor_Proc) (PSECURITY_DESCRIPTOR);
520 521 522
typedef DWORD (WINAPI *GetAdaptersInfo_Proc) (
    PIP_ADAPTER_INFO pAdapterInfo,
    PULONG pOutBufLen);
523 524 525 526 527 528
typedef DWORD (WINAPI *GetAdaptersAddresses_Proc) (
    ULONG,
    ULONG,
    PVOID,
    PIP_ADAPTER_ADDRESSES,
    PULONG);
529

530 531
int (WINAPI *pMultiByteToWideChar)(UINT,DWORD,LPCSTR,int,LPWSTR,int);
int (WINAPI *pWideCharToMultiByte)(UINT,DWORD,LPCWSTR,int,LPSTR,int,LPCSTR,LPBOOL);
532
DWORD multiByteToWideCharFlags;
533 534 535
typedef LONG (WINAPI *RegOpenKeyExW_Proc) (HKEY,LPCWSTR,DWORD,REGSAM,PHKEY);
typedef LONG (WINAPI *RegQueryValueExW_Proc) (HKEY,LPCWSTR,LPDWORD,LPDWORD,LPBYTE,LPDWORD);
typedef DWORD (WINAPI *ExpandEnvironmentStringsW_Proc) (LPCWSTR,LPWSTR,DWORD);
536

537
  /* ** A utility function ** */
Kim F. Storm's avatar
Kim F. Storm committed
538
static BOOL
539
is_windows_9x (void)
540
{
541
  static BOOL s_b_ret = 0;
542
  OSVERSIONINFO os_ver;
543
  if (g_b_init_is_windows_9x == 0)
544
    {
545
      g_b_init_is_windows_9x = 1;
546 547
      ZeroMemory (&os_ver, sizeof (OSVERSIONINFO));
      os_ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
548 549 550 551
      if (GetVersionEx (&os_ver))
        {
          s_b_ret = (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
        }
552
    }
553
  return s_b_ret;
554 555
}

556 557
static Lisp_Object ltime (ULONGLONG);

558
/* Get total user and system times for get-internal-run-time.
559
   Returns a list of integers if the times are provided by the OS
560 561
   (NT derivatives), otherwise it returns the result of current-time. */
Lisp_Object
562
w32_get_internal_run_time (void)
563 564 565 566
{
  if (get_process_times_fn)
    {
      FILETIME create, exit, kernel, user;
567
      HANDLE proc = GetCurrentProcess ();
568 569 570 571 572 573 574 575
      if ((*get_process_times_fn) (proc, &create, &exit, &kernel, &user))
        {
          LARGE_INTEGER user_int, kernel_int, total;
          user_int.LowPart = user.dwLowDateTime;
          user_int.HighPart = user.dwHighDateTime;
          kernel_int.LowPart = kernel.dwLowDateTime;
          kernel_int.HighPart = kernel.dwHighDateTime;
          total.QuadPart = user_int.QuadPart + kernel_int.QuadPart;
576
	  return ltime (total.QuadPart);
577 578 579 580 581 582
        }
    }

  return Fcurrent_time ();
}

583 584
  /* ** The wrapper functions ** */

585 586 587 588
static BOOL WINAPI
open_process_token (HANDLE ProcessHandle,
		    DWORD DesiredAccess,
		    PHANDLE TokenHandle)
589
{
590
  static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
591 592 593 594 595
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
596 597 598 599
  if (g_b_init_open_process_token == 0)
    {
      g_b_init_open_process_token = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
600 601
      s_pfn_Open_Process_Token = (OpenProcessToken_Proc)
        get_proc_addr (hm_advapi32, "OpenProcessToken");
602 603
    }
  if (s_pfn_Open_Process_Token == NULL)
604 605 606 607
    {
      return FALSE;
    }
  return (
608
      s_pfn_Open_Process_Token (
609 610 611 612 613 614
          ProcessHandle,
          DesiredAccess,
          TokenHandle)
      );
}

615 616 617 618 619 620
static BOOL WINAPI
get_token_information (HANDLE TokenHandle,
		       TOKEN_INFORMATION_CLASS TokenInformationClass,
		       LPVOID TokenInformation,
		       DWORD TokenInformationLength,
		       PDWORD ReturnLength)
621
{
622
  static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
623 624 625 626 627
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
628 629 630 631
  if (g_b_init_get_token_information == 0)
    {
      g_b_init_get_token_information = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
632 633
      s_pfn_Get_Token_Information = (GetTokenInformation_Proc)
        get_proc_addr (hm_advapi32, "GetTokenInformation");
634 635
    }
  if (s_pfn_Get_Token_Information == NULL)
636 637 638 639
    {
      return FALSE;
    }
  return (
640
      s_pfn_Get_Token_Information (
641 642 643 644 645 646 647 648
          TokenHandle,
          TokenInformationClass,
          TokenInformation,
          TokenInformationLength,
          ReturnLength)
      );
}

649 650 651 652 653 654 655 656
static BOOL WINAPI
lookup_account_sid (LPCTSTR lpSystemName,
		    PSID Sid,
		    LPTSTR Name,
		    LPDWORD cbName,
		    LPTSTR DomainName,
		    LPDWORD cbDomainName,
		    PSID_NAME_USE peUse)
657
{
658
  static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
659 660 661 662 663
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
664 665 666 667
  if (g_b_init_lookup_account_sid == 0)
    {
      g_b_init_lookup_account_sid = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
668 669
      s_pfn_Lookup_Account_Sid = (LookupAccountSid_Proc)
        get_proc_addr (hm_advapi32, LookupAccountSid_Name);
670 671
    }
  if (s_pfn_Lookup_Account_Sid == NULL)
672 673 674 675
    {
      return FALSE;
    }
  return (
676
      s_pfn_Lookup_Account_Sid (
677 678 679 680 681 682 683 684 685 686
          lpSystemName,
          Sid,
          Name,
          cbName,
          DomainName,
          cbDomainName,
          peUse)
      );
}

687 688
static PDWORD WINAPI
get_sid_sub_authority (PSID pSid, DWORD n)
689 690
{
  static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority = NULL;
691
  static DWORD zero = 0U;
692 693 694
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
695
      return &zero;
696 697 698 699 700
    }
  if (g_b_init_get_sid_sub_authority == 0)
    {
      g_b_init_get_sid_sub_authority = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
701 702
      s_pfn_Get_Sid_Sub_Authority = (GetSidSubAuthority_Proc)
        get_proc_addr (hm_advapi32, "GetSidSubAuthority");
703 704 705
    }
  if (s_pfn_Get_Sid_Sub_Authority == NULL)
    {
706
      return &zero;
707 708 709 710
    }
  return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
}

711 712
static PUCHAR WINAPI
get_sid_sub_authority_count (PSID pSid)
713 714
{
  static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count = NULL;
715
  static UCHAR zero = 0U;
716 717 718
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
719
      return &zero;
720 721 722 723 724
    }
  if (g_b_init_get_sid_sub_authority_count == 0)
    {
      g_b_init_get_sid_sub_authority_count = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
725 726
      s_pfn_Get_Sid_Sub_Authority_Count = (GetSidSubAuthorityCount_Proc)
        get_proc_addr (hm_advapi32, "GetSidSubAuthorityCount");
727 728 729
    }
  if (s_pfn_Get_Sid_Sub_Authority_Count == NULL)
    {
730
      return &zero;
731 732 733 734
    }
  return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
}

735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
static DWORD WINAPI
get_security_info (HANDLE handle,
		   SE_OBJECT_TYPE ObjectType,
		   SECURITY_INFORMATION SecurityInfo,
		   PSID *ppsidOwner,
		   PSID *ppsidGroup,
		   PACL *ppDacl,
		   PACL *ppSacl,
		   PSECURITY_DESCRIPTOR *ppSecurityDescriptor)
{
  static GetSecurityInfo_Proc s_pfn_Get_Security_Info = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
  if (g_b_init_get_security_info == 0)
    {
      g_b_init_get_security_info = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
755 756
      s_pfn_Get_Security_Info = (GetSecurityInfo_Proc)
        get_proc_addr (hm_advapi32, "GetSecurityInfo");
757 758 759 760 761 762 763 764 765 766
    }
  if (s_pfn_Get_Security_Info == NULL)
    {
      return FALSE;
    }
  return (s_pfn_Get_Security_Info (handle, ObjectType, SecurityInfo,
				   ppsidOwner, ppsidGroup, ppDacl, ppSacl,
				   ppSecurityDescriptor));
}

767
static BOOL WINAPI
768
get_file_security (const char *lpFileName,
769 770 771 772
		   SECURITY_INFORMATION RequestedInformation,
		   PSECURITY_DESCRIPTOR pSecurityDescriptor,
		   DWORD nLength,
		   LPDWORD lpnLengthNeeded)
773
{
774 775
  static GetFileSecurityA_Proc s_pfn_Get_File_SecurityA = NULL;
  static GetFileSecurityW_Proc s_pfn_Get_File_SecurityW = NULL;
776 777 778
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
779
      errno = ENOTSUP;
780 781
      return FALSE;
    }
782
  if (w32_unicode_filenames)
783
    {
784 785 786 787 788 789
      wchar_t filename_w[MAX_PATH];

      if (g_b_init_get_file_security_w == 0)
	{
	  g_b_init_get_file_security_w = 1;
	  hm_advapi32 = LoadLibrary ("Advapi32.dll");
790 791
	  s_pfn_Get_File_SecurityW = (GetFileSecurityW_Proc)
            get_proc_addr (hm_advapi32, "GetFileSecurityW");
792 793 794 795 796 797 798 799 800 801
	}
      if (s_pfn_Get_File_SecurityW == NULL)
	{
	  errno = ENOTSUP;
	  return FALSE;
	}
      filename_to_utf16 (lpFileName, filename_w);
      return (s_pfn_Get_File_SecurityW (filename_w, RequestedInformation,
					pSecurityDescriptor, nLength,
					lpnLengthNeeded));
802
    }
803
  else
804
    {
805 806 807 808 809 810
      char filename_a[MAX_PATH];

      if (g_b_init_get_file_security_a == 0)
	{
	  g_b_init_get_file_security_a = 1;
	  hm_advapi32 = LoadLibrary ("Advapi32.dll");
811 812
	  s_pfn_Get_File_SecurityA = (GetFileSecurityA_Proc)
            get_proc_addr (hm_advapi32, "GetFileSecurityA");
813 814 815 816 817 818 819 820 821 822
	}
      if (s_pfn_Get_File_SecurityA == NULL)
	{
	  errno = ENOTSUP;
	  return FALSE;
	}
      filename_to_ansi (lpFileName, filename_a);
      return (s_pfn_Get_File_SecurityA (filename_a, RequestedInformation,
					pSecurityDescriptor, nLength,
					lpnLengthNeeded));
823 824 825
    }
}

826
static BOOL WINAPI
827
set_file_security (const char *lpFileName,
828 829 830
		   SECURITY_INFORMATION SecurityInformation,
		   PSECURITY_DESCRIPTOR pSecurityDescriptor)
{
831 832
  static SetFileSecurityW_Proc s_pfn_Set_File_SecurityW = NULL;
  static SetFileSecurityA_Proc s_pfn_Set_File_SecurityA = NULL;
833 834 835 836 837 838
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      errno = ENOTSUP;
      return FALSE;
    }
839
  if (w32_unicode_filenames)
840
    {
841 842 843 844 845 846
      wchar_t filename_w[MAX_PATH];

      if (g_b_init_set_file_security_w == 0)
	{
	  g_b_init_set_file_security_w = 1;
	  hm_advapi32 = LoadLibrary ("Advapi32.dll");
847 848
	  s_pfn_Set_File_SecurityW = (SetFileSecurityW_Proc)
            get_proc_addr (hm_advapi32, "SetFileSecurityW");
849 850 851 852 853 854 855 856 857
	}
      if (s_pfn_Set_File_SecurityW == NULL)
	{
	  errno = ENOTSUP;
	  return FALSE;
	}
      filename_to_utf16 (lpFileName, filename_w);
      return (s_pfn_Set_File_SecurityW (filename_w, SecurityInformation,
					pSecurityDescriptor));
858
    }
859
  else
860
    {
861 862 863 864 865 866
      char filename_a[MAX_PATH];

      if (g_b_init_set_file_security_a == 0)
	{
	  g_b_init_set_file_security_a = 1;
	  hm_advapi32 = LoadLibrary ("Advapi32.dll");
867 868
	  s_pfn_Set_File_SecurityA = (SetFileSecurityA_Proc)
            get_proc_addr (hm_advapi32, "SetFileSecurityA");
869 870 871 872 873 874 875 876 877
	}
      if (s_pfn_Set_File_SecurityA == NULL)
	{
	  errno = ENOTSUP;
	  return FALSE;
	}
      filename_to_ansi (lpFileName, filename_a);
      return (s_pfn_Set_File_SecurityA (filename_a, SecurityInformation,
					pSecurityDescriptor));
878 879 880
    }
}

881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
static DWORD WINAPI
set_named_security_info (LPCTSTR lpObjectName,
			 SE_OBJECT_TYPE ObjectType,
			 SECURITY_INFORMATION SecurityInformation,
			 PSID psidOwner,
			 PSID psidGroup,
			 PACL pDacl,
			 PACL pSacl)
{
  static SetNamedSecurityInfoW_Proc s_pfn_Set_Named_Security_InfoW = NULL;
  static SetNamedSecurityInfoA_Proc s_pfn_Set_Named_Security_InfoA = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      errno = ENOTSUP;
      return ENOTSUP;
    }
  if (w32_unicode_filenames)
    {
      wchar_t filename_w[MAX_PATH];

      if (g_b_init_set_named_security_info_w == 0)
	{
	  g_b_init_set_named_security_info_w = 1;
	  hm_advapi32 = LoadLibrary ("Advapi32.dll");
906 907
	  s_pfn_Set_Named_Security_InfoW = (SetNamedSecurityInfoW_Proc)
            get_proc_addr (hm_advapi32, "SetNamedSecurityInfoW");
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
	}
      if (s_pfn_Set_Named_Security_InfoW == NULL)
	{
	  errno = ENOTSUP;
	  return ENOTSUP;
	}
      filename_to_utf16 (lpObjectName, filename_w);
      return (s_pfn_Set_Named_Security_InfoW (filename_w, ObjectType,
					      SecurityInformation, psidOwner,
					      psidGroup, pDacl, pSacl));
    }
  else
    {
      char filename_a[MAX_PATH];

      if (g_b_init_set_named_security_info_a == 0)
	{
	  g_b_init_set_named_security_info_a = 1;
	  hm_advapi32 = LoadLibrary ("Advapi32.dll");
927 928
	  s_pfn_Set_Named_Security_InfoA = (SetNamedSecurityInfoA_Proc)
            get_proc_addr (hm_advapi32, "SetNamedSecurityInfoA");
929 930 931 932 933 934 935 936 937 938 939 940 941
	}
      if (s_pfn_Set_Named_Security_InfoA == NULL)
	{
	  errno = ENOTSUP;
	  return ENOTSUP;
	}
      filename_to_ansi (lpObjectName, filename_a);
      return (s_pfn_Set_Named_Security_InfoA (filename_a, ObjectType,
					      SecurityInformation, psidOwner,
					      psidGroup, pDacl, pSacl));
    }
}

942 943 944 945
static BOOL WINAPI
get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
			       PSID *pOwner,
			       LPBOOL lpbOwnerDefaulted)
946 947 948 949 950
{
  static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
951
      errno = ENOTSUP;
952 953 954 955 956 957
      return FALSE;
    }
  if (g_b_init_get_security_descriptor_owner == 0)
    {
      g_b_init_get_security_descriptor_owner = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
958 959
      s_pfn_Get_Security_Descriptor_Owner = (GetSecurityDescriptorOwner_Proc)
        get_proc_addr (hm_advapi32, "GetSecurityDescriptorOwner");
960 961 962
    }
  if (s_pfn_Get_Security_Descriptor_Owner == NULL)
    {
963
      errno = ENOTSUP;
964 965 966 967 968 969
      return FALSE;
    }
  return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
					       lpbOwnerDefaulted));
}

970 971 972 973
static BOOL WINAPI
get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
			       PSID *pGroup,
			       LPBOOL lpbGroupDefaulted)
974 975 976 977 978
{
  static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
979
      errno = ENOTSUP;
980 981 982 983 984 985
      return FALSE;
    }
  if (g_b_init_get_security_descriptor_group == 0)
    {
      g_b_init_get_security_descriptor_group = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
986 987
      s_pfn_Get_Security_Descriptor_Group = (GetSecurityDescriptorGroup_Proc)
        get_proc_addr (hm_advapi32, "GetSecurityDescriptorGroup");
988 989 990
    }
  if (s_pfn_Get_Security_Descriptor_Group == NULL)
    {
991
      errno = ENOTSUP;
992 993 994 995 996 997
      return FALSE;
    }
  return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
					       lpbGroupDefaulted));
}

998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
static BOOL WINAPI
get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor,
			      LPBOOL lpbDaclPresent,
			      PACL *pDacl,
			      LPBOOL lpbDaclDefaulted)
{
  static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      errno = ENOTSUP;
      return FALSE;
    }
  if (g_b_init_get_security_descriptor_dacl == 0)
    {
      g_b_init_get_security_descriptor_dacl = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
1015 1016
      s_pfn_Get_Security_Descriptor_Dacl = (GetSecurityDescriptorDacl_Proc)
        get_proc_addr (hm_advapi32, "GetSecurityDescriptorDacl");
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
    }
  if (s_pfn_Get_Security_Descriptor_Dacl == NULL)
    {
      errno = ENOTSUP;
      return FALSE;
    }
  return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor,
					      lpbDaclPresent, pDacl,
					      lpbDaclDefaulted));
}

1028 1029
static BOOL WINAPI
is_valid_sid (PSID sid)
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
{
  static IsValidSid_Proc s_pfn_Is_Valid_Sid = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
  if (g_b_init_is_valid_sid == 0)
    {
      g_b_init_is_valid_sid = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
1041 1042
      s_pfn_Is_Valid_Sid = (IsValidSid_Proc)
        get_proc_addr (hm_advapi32, "IsValidSid");
1043 1044 1045 1046 1047 1048 1049 1050
    }
  if (s_pfn_Is_Valid_Sid == NULL)
    {
      return FALSE;
    }
  return (s_pfn_Is_Valid_Sid (sid));
}

1051 1052
static BOOL WINAPI
equal_sid (PSID sid1, PSID sid2)
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
{
  static EqualSid_Proc s_pfn_Equal_Sid = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
  if (g_b_init_equal_sid == 0)
    {
      g_b_init_equal_sid = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
1064 1065
      s_pfn_Equal_Sid = (EqualSid_Proc)
        get_proc_addr (hm_advapi32, "EqualSid");
1066 1067 1068 1069 1070 1071 1072 1073
    }
  if (s_pfn_Equal_Sid == NULL)
    {
      return FALSE;
    }
  return (s_pfn_Equal_Sid (sid1, sid2));
}

1074 1075
static DWORD WINAPI
get_length_sid (PSID sid)
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
{
  static GetLengthSid_Proc s_pfn_Get_Length_Sid = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return 0;
    }
  if (g_b_init_get_length_sid == 0)
    {
      g_b_init_get_length_sid = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
1087 1088
      s_pfn_Get_Length_Sid = (GetLengthSid_Proc)
        get_proc_addr (hm_advapi32, "GetLengthSid");
1089 1090 1091 1092 1093 1094 1095 1096
    }
  if (s_pfn_Get_Length_Sid == NULL)
    {
      return 0;
    }
  return (s_pfn_Get_Length_Sid (sid));
}

1097 1098
static BOOL WINAPI
copy_sid (DWORD destlen, PSID dest, PSID src)
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
{
  static CopySid_Proc s_pfn_Copy_Sid = NULL;
  HMODULE hm_advapi32 = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
  if (g_b_init_copy_sid == 0)
    {
      g_b_init_copy_sid = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
1110 1111
      s_pfn_Copy_Sid = (CopySid_Proc)
        get_proc_addr (hm_advapi32, "CopySid");
1112 1113 1114 1115 1116 1117 1118 1119
    }
  if (s_pfn_Copy_Sid == NULL)
    {
      return FALSE;
    }
  return (s_pfn_Copy_Sid (destlen, dest, src));
}

1120 1121 1122 1123 1124 1125
/*
  END: Wrapper functions around OpenProcessToken
  and other functions in advapi32.dll that are only
  supported in Windows NT / 2k / XP
*/

1126 1127
static void WINAPI
get_native_system_info (LPSYSTEM_INFO lpSystemInfo)
1128 1129 1130 1131 1132 1133 1134
{
  static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info = NULL;
  if (is_windows_9x () != TRUE)
    {
      if (g_b_init_get_native_system_info == 0)
	{
	  g_b_init_get_native_system_info = 1;
1135 1136 1137
	  s_pfn_Get_Native_System_Info = (GetNativeSystemInfo_Proc)
            get_proc_addr (GetModuleHandle ("kernel32.dll"),
                                  "GetNativeSystemInfo");
1138 1139 1140 1141 1142 1143 1144 1145
	}
      if (s_pfn_Get_Native_System_Info != NULL)
	s_pfn_Get_Native_System_Info (lpSystemInfo);
    }
  else
    lpSystemInfo->dwNumberOfProcessors = -1;
}

1146 1147 1148 1149
static BOOL WINAPI
get_system_times (LPFILETIME lpIdleTime,
		  LPFILETIME lpKernelTime,
		  LPFILETIME lpUserTime)
1150 1151 1152 1153 1154 1155 1156 1157 1158
{
  static GetSystemTimes_Proc s_pfn_Get_System_times = NULL;
  if (is_windows_9x () == TRUE)
    {
      return FALSE;
    }
  if (g_b_init_get_system_times == 0)
    {
      g_b_init_get_system_times = 1;
1159 1160 1161
      s_pfn_Get_System_times = (GetSystemTimes_Proc)
        get_proc_addr (GetModuleHandle ("kernel32.dll"),
                              "GetSystemTimes");
1162 1163 1164 1165 1166
    }
  if (s_pfn_Get_System_times == NULL)
    return FALSE;
  return (s_pfn_Get_System_times (lpIdleTime, lpKernelTime, lpUserTime));
}
1167 1168

static BOOLEAN WINAPI
1169 1170
create_symbolic_link (LPCSTR lpSymlinkFilename,
		      LPCSTR lpTargetFileName,
1171 1172
		      DWORD dwFlags)
{
1173 1174
  static CreateSymbolicLinkW_Proc s_pfn_Create_Symbolic_LinkW = NULL;
  static CreateSymbolicLinkA_Proc s_pfn_Create_Symbolic_LinkA = NULL;
1175 1176 1177 1178 1179 1180 1181
  BOOLEAN retval;

  if (is_windows_9x () == TRUE)
    {
      errno = ENOSYS;
      return 0;
    }
1182
  if (w32_unicode_filenames)
1183
    {
1184 1185 1186 1187 1188
      wchar_t symfn_w[MAX_PATH], tgtfn_w[MAX_PATH];

      if (g_b_init_create_symbolic_link_w == 0)
	{
	  g_b_init_create_symbolic_link_w = 1;
1189 1190 1191
	  s_pfn_Create_Symbolic_LinkW = (CreateSymbolicLinkW_Proc)
            get_proc_addr (GetModuleHandle ("kernel32.dll"),
                                  "CreateSymbolicLinkW");
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
	}
      if (s_pfn_Create_Symbolic_LinkW == NULL)
	{
	  errno = ENOSYS;
	  return 0;
	}

      filename_to_utf16 (lpSymlinkFilename, symfn_w);
      filename_to_utf16 (lpTargetFileName, tgtfn_w);
      retval = s_pfn_Create_Symbolic_LinkW (symfn_w, tgtfn_w, dwFlags);
      /* If we were denied creation of the symlink, try again after
	 enabling the SeCreateSymbolicLinkPrivilege for our process.  */
      if (!retval)
	{
	  TOKEN_PRIVILEGES priv_current;

	  if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE,
				&priv_current))
	    {
	      retval = s_pfn_Create_Symbolic_LinkW (symfn_w, tgtfn_w, dwFlags);
	      restore_privilege (&priv_current);
	      revert_to_self ();
	    }
	}
1216
    }
1217
  else
1218
    {
1219
      char symfn_a[MAX_PATH], tgtfn_a[MAX_PATH];
1220

1221 1222 1223
      if (g_b_init_create_symbolic_link_a == 0)
	{
	  g_b_init_create_symbolic_link_a = 1;
1224 1225 1226
	  s_pfn_Create_Symbolic_LinkA = (CreateSymbolicLinkA_Proc)
            get_proc_addr (GetModuleHandle ("kernel32.dll"),
                                  "CreateSymbolicLinkA");
1227 1228 1229 1230 1231 1232
	}
      if (s_pfn_Create_Symbolic_LinkA == NULL)
	{
	  errno = ENOSYS;
	  return 0;
	}
1233

1234 1235 1236 1237 1238 1239
      filename_to_ansi (lpSymlinkFilename, symfn_a);
      filename_to_ansi (lpTargetFileName, tgtfn_a);
      retval = s_pfn_Create_Symbolic_LinkA (symfn_a, tgtfn_a, dwFlags);
      /* If we were denied creation of the symlink, try again after
	 enabling the SeCreateSymbolicLinkPrivilege for our process.  */
      if (!retval)
1240
	{
1241 1242 1243 1244 1245 1246 1247 1248 1249
	  TOKEN_PRIVILEGES priv_current;

	  if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE,
				&priv_current))
	    {
	      retval = s_pfn_Create_Symbolic_LinkA (symfn_a, tgtfn_a, dwFlags);
	      restore_privilege (&priv_current);
	      revert_to_self ();
	    }
1250 1251 1252 1253
	}
    }
  return retval;
}
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268

static BOOL WINAPI
is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor)
{
  static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc = NULL;

  if (is_windows_9x () == TRUE)
    {
      errno = ENOTSUP;
      return FALSE;
    }

  if (g_b_init_is_valid_security_descriptor == 0)
    {
      g_b_init_is_valid_security_descriptor = 1;
1269 1270 1271
      s_pfn_Is_Valid_Security_Descriptor_Proc = (IsValidSecurityDescriptor_Proc)
        get_proc_addr (GetModuleHandle ("Advapi32.dll"),
                              "IsValidSecurityDescriptor");
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
    }
  if (s_pfn_Is_Valid_Security_Descriptor_Proc == NULL)
    {
      errno = ENOTSUP;
      return FALSE;
    }

  return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor);
}

static BOOL WINAPI
convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor,
		    DWORD RequestedStringSDRevision,
		    SECURITY_INFORMATION SecurityInformation,
		    LPTSTR  *StringSecurityDescriptor,
		    PULONG StringSecurityDescriptorLen)
{
  static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL = NULL;
  BOOL retval;

  if (is_windows_9x () == TRUE)
    {
      errno = ENOTSUP;
      return FALSE;
    }

  if (g_b_init_convert_sd_to_sddl == 0)
    {
      g_b_init_convert_sd_to_sddl = 1;
#ifdef _UNICODE
      s_pfn_Convert_SD_To_SDDL =
1303 1304 1305
	(ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)
        get_proc_addr (GetModuleHandle ("Advapi32.dll"),
                              "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1306 1307
#else
      s_pfn_Convert_SD_To_SDDL =
1308 1309 1310
	(ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)
        get_proc_addr (GetModuleHandle ("Advapi32.dll"),
                              "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
#endif
    }
  if (s_pfn_Convert_SD_To_SDDL == NULL)
    {
      errno = ENOTSUP;
      return FALSE;
    }

  retval = s_pfn_Convert_SD_To_SDDL (SecurityDescriptor,
				     RequestedStringSDRevision,
				     SecurityInformation,
				     StringSecurityDescriptor,
				     StringSecurityDescriptorLen);

  return retval;
}

static BOOL WINAPI
convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor,
		    DWORD StringSDRevision,
		    PSECURITY_DESCRIPTOR  *SecurityDescriptor,
		    PULONG  SecurityDescriptorSize)
{
  static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD = NULL;
  BOOL retval;

  if (is_windows_9x () == TRUE)
    {
      errno = ENOTSUP;
      return FALSE;
    }

  if (g_b_init_convert_sddl_to_sd == 0)
    {
      g_b_init_convert_sddl_to_sd = 1;
#ifdef _UNICODE
      s_pfn_Convert_SDDL_To_SD =
1348 1349 1350
	(ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)
        get_proc_addr (GetModuleHandle ("Advapi32.dll"),
                              "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1351 1352
#else
      s_pfn_Convert_SDDL_To_SD =
1353 1354 1355
	(ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)
        get_proc_addr (GetModuleHandle ("Advapi32.dll"),
                              "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
#endif
    }
  if (s_pfn_Convert_SDDL_To_SD == NULL)
    {
      errno = ENOTSUP;
      return FALSE;
    }

  retval = s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor,
				     StringSDRevision,
				     SecurityDescriptor,
				     SecurityDescriptorSize);

  return retval;
}

1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
static DWORD WINAPI
get_adapters_info (PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen)
{
  static GetAdaptersInfo_Proc s_pfn_Get_Adapters_Info = NULL;
  HMODULE hm_iphlpapi = NULL;

  if (is_windows_9x () == TRUE)
    return ERROR_NOT_SUPPORTED;

  if (g_b_init_get_adapters_info == 0)
    {
      g_b_init_get_adapters_info = 1;
      hm_iphlpapi = LoadLibrary ("Iphlpapi.dll");
      if (hm_iphlpapi)
	s_pfn_Get_Adapters_Info = (GetAdaptersInfo_Proc)
1387
	  get_proc_addr (hm_iphlpapi, "GetAdaptersInfo");
1388 1389 1390 1391 1392 1393
    }
  if (s_pfn_Get_Adapters_Info == NULL)
    return ERROR_NOT_SUPPORTED;
  return s_pfn_Get_Adapters_Info (pAdapterInfo, pOutBufLen);
}

1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
static DWORD WINAPI
get_adapters_addresses (ULONG family, PIP_ADAPTER_ADDRESSES pAdapterAddresses, PULONG pOutBufLen)
{
  static GetAdaptersAddresses_Proc s_pfn_Get_Adapters_Addresses = NULL;
  HMODULE hm_iphlpapi = NULL;

  if (is_windows_9x () == TRUE)
    return ERROR_NOT_SUPPORTED;

  if (g_b_init_get_adapters_addresses == 0)
    {
      g_b_init_get_adapters_addresses = 1;
      hm_iphlpapi = LoadLibrary ("Iphlpapi.dll");
      if (hm_iphlpapi)
	s_pfn_Get_Adapters_Addresses = (GetAdaptersAddresses_Proc)
	  get_proc_addr (hm_iphlpapi, "GetAdaptersAddresses");
    }
  if (s_pfn_Get_Adapters_Addresses == NULL)
    return ERROR_NOT_SUPPORTED;
  ULONG flags = GAA_FLAG_SKIP_ANYCAST
    | GAA_FLAG_SKIP_MULTICAST
    | GAA_FLAG_SKIP_DNS_SERVER;
  return s_pfn_Get_Adapters_Addresses (family, flags, NULL, pAdapterAddresses, pOutBufLen);
}

1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
static LONG WINAPI
reg_open_key_ex_w (HKEY hkey, LPCWSTR lpSubKey, DWORD ulOptions,
		   REGSAM samDesired, PHKEY phkResult)
{
  static RegOpenKeyExW_Proc s_pfn_Reg_Open_Key_Ex_w = NULL;
  HMODULE hm_advapi32 = NULL;

  if (is_windows_9x () == TRUE)
    return ERROR_NOT_SUPPORTED;

  if (g_b_init_reg_open_key_ex_w == 0)
    {
      g_b_init_reg_open_key_ex_w = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
      if (hm_advapi32)
	s_pfn_Reg_Open_Key_Ex_w = (RegOpenKeyExW_Proc)
1435
	  get_proc_addr (hm_advapi32, "RegOpenKeyExW");
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
    }
  if (s_pfn_Reg_Open_Key_Ex_w == NULL)
    return ERROR_NOT_SUPPORTED;
  return s_pfn_Reg_Open_Key_Ex_w (hkey, lpSubKey, ulOptions,
				  samDesired, phkResult);
}

static LONG WINAPI
reg_query_value_ex_w (HKEY hkey, LPCWSTR lpValueName, LPDWORD lpReserved,
		      LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData)
{
  static RegQueryValueExW_Proc s_pfn_Reg_Query_Value_Ex_w = NULL;
  HMODULE hm_advapi32 = NULL;

  if (is_windows_9x () == TRUE)
    return ERROR_NOT_SUPPORTED;

  if (g_b_init_reg_query_value_ex_w == 0)
    {
      g_b_init_reg_query_value_ex_w = 1;
      hm_advapi32 = LoadLibrary ("Advapi32.dll");
      if (hm_advapi32)
	s_pfn_Reg_Query_Value_Ex_w = (RegQueryValueExW_Proc)
1459
	  get_proc_addr (hm_advapi32, "RegQueryValueExW");
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
    }
  if (s_pfn_Reg_Query_Value_Ex_w == NULL)
    return ERROR_NOT_SUPPORTED;
  return s_pfn_Reg_Query_Value_Ex_w (hkey, lpValueName, lpReserved,
				     lpType, lpData, lpcbData);
}

static DWORD WINAPI
expand_environment_strings_w (LPCWSTR lpSrc, LPWSTR lpDst, DWORD nSize)
{
  static ExpandEnvironmentStringsW_Proc s_pfn_Expand_Environment_Strings_w = NULL;
  HMODULE hm_kernel32 = NULL;

  if (is_windows_9x () == TRUE)
    return ERROR_NOT_SUPPORTED;

  if (g_b_init_expand_environment_strings_w == 0)
    {
      g_b_init_expand_environment_strings_w = 1;
      hm_kernel32 = LoadLibrary ("Kernel32.dll");
      if (hm_kernel32)
	s_pfn_Expand_Environment_Strings_w = (ExpandEnvironmentStringsW_Proc)
1482
	  get_proc_addr (hm_kernel32, "ExpandEnvironmentStringsW");
1483 1484 1485 1486 1487 1488 1489 1490 1491
    }
  if (s_pfn_Expand_Environment_Strings_w == NULL)
    {
      errno = ENOSYS;
      return FALSE;
    }
  return s_pfn_Expand_Environment_Strings_w (lpSrc, lpDst, nSize);
}

Andrew Innes's avatar
Andrew Innes committed
1492 1493


1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513