Converted sys_unlink and sys_rmdir, got rid of pending deletion in w32proc.c.
[bpt/emacs.git] / src / w32.c
CommitLineData
b46a6a83 1/* Utility and Unix shadow routines for GNU Emacs on the Microsoft Windows API.
ab422c4d 2 Copyright (C) 1994-1995, 2000-2013 Free Software Foundation, Inc.
95ed0025 3
3b7ad313
EN
4This file is part of GNU Emacs.
5
9ec0b715 6GNU Emacs is free software: you can redistribute it and/or modify
3b7ad313 7it under the terms of the GNU General Public License as published by
9ec0b715
GM
8the Free Software Foundation, either version 3 of the License, or
9(at your option) any later version.
3b7ad313
EN
10
11GNU Emacs is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
9ec0b715 17along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
95ed0025 18
9ec0b715 19/*
95ed0025
RS
20 Geoff Voelker (voelker@cs.washington.edu) 7-29-94
21*/
279066b2
EZ
22
23#include <mingw_time.h>
76b3903d 24#include <stddef.h> /* for offsetof */
95ed0025
RS
25#include <stdlib.h>
26#include <stdio.h>
ad9e2d54 27#include <float.h> /* for DBL_EPSILON */
95ed0025 28#include <io.h>
480b0c5b 29#include <errno.h>
95ed0025
RS
30#include <fcntl.h>
31#include <ctype.h>
480b0c5b 32#include <signal.h>
b3308d2e 33#include <sys/file.h>
8f5e14c8 34#include <time.h> /* must be before nt/inc/sys/time.h, for MinGW64 */
480b0c5b 35#include <sys/time.h>
16bb7578 36#include <sys/utime.h>
7c80d5ec 37#include <math.h>
480b0c5b
GV
38
39/* must include CRT headers *before* config.h */
4838e624 40
4838e624 41#include <config.h>
6ee4509a 42#include <mbstring.h> /* for _mbspbrk, _mbslwr, _mbsrchr, ... */
4838e624 43
480b0c5b
GV
44#undef access
45#undef chdir
46#undef chmod
47#undef creat
48#undef ctime
49#undef fopen
50#undef link
51#undef mkdir
480b0c5b
GV
52#undef open
53#undef rename
54#undef rmdir
55#undef unlink
56
57#undef close
58#undef dup
59#undef dup2
60#undef pipe
61#undef read
62#undef write
95ed0025 63
d8fcc1b9
AI
64#undef strerror
65
97a93095
EZ
66#undef localtime
67
95ed0025 68#include "lisp.h"
7d9fb4de 69#include "epaths.h" /* for SHELL */
95ed0025
RS
70
71#include <pwd.h>
3d19b645 72#include <grp.h>
95ed0025 73
a18d7de6
EZ
74/* MinGW64 (_W64) defines these in its _mingw.h. */
75#if defined(__GNUC__) && !defined(_W64)
971bce75
AI
76#define _ANONYMOUS_UNION
77#define _ANONYMOUS_STRUCT
78#endif
480b0c5b 79#include <windows.h>
b8526f6e
EZ
80/* Some versions of compiler define MEMORYSTATUSEX, some don't, so we
81 use a different name to avoid compilation problems. */
82typedef struct _MEMORY_STATUS_EX {
bedf4aab
JB
83 DWORD dwLength;
84 DWORD dwMemoryLoad;
85 DWORDLONG ullTotalPhys;
86 DWORDLONG ullAvailPhys;
87 DWORDLONG ullTotalPageFile;
88 DWORDLONG ullAvailPageFile;
89 DWORDLONG ullTotalVirtual;
90 DWORDLONG ullAvailVirtual;
91 DWORDLONG ullAvailExtendedVirtual;
b8526f6e 92} MEMORY_STATUS_EX,*LPMEMORY_STATUS_EX;
7c80d5ec 93
55902276
EZ
94/* These are here so that GDB would know about these data types. This
95 allows to attach GDB to Emacs when a fatal exception is triggered
96 and Windows pops up the "application needs to be closed" dialog.
97 At that point, _gnu_exception_handler, the top-level exception
98 handler installed by the MinGW startup code, is somewhere on the
99 call-stack of the main thread, so going to that call frame and
100 looking at the argument to _gnu_exception_handler, which is a
101 PEXCEPTION_POINTERS pointer, can reveal the exception code
102 (excptr->ExceptionRecord->ExceptionCode) and the address where the
103 exception happened (excptr->ExceptionRecord->ExceptionAddress), as
104 well as some additional information specific to the exception. */
105PEXCEPTION_POINTERS excptr;
106PEXCEPTION_RECORD excprec;
107PCONTEXT ctxrec;
108
634d3003 109#include <lmcons.h>
2d5324c5 110#include <shlobj.h>
00b3b7b3 111
7c80d5ec
EZ
112#include <tlhelp32.h>
113#include <psapi.h>
a6fc3b5c 114#ifndef _MSC_VER
69e847be 115#include <w32api.h>
a6fc3b5c 116#endif
a18d7de6 117#if _WIN32_WINNT < 0x0500
5e617bc2 118#if !defined (__MINGW32__) || __W32API_MAJOR_VERSION < 3 || (__W32API_MAJOR_VERSION == 3 && __W32API_MINOR_VERSION < 15)
7c80d5ec 119/* This either is not in psapi.h or guarded by higher value of
a6d3e72e 120 _WIN32_WINNT than what we use. w32api supplied with MinGW 3.15
69e847be 121 defines it in psapi.h */
7c80d5ec 122typedef struct _PROCESS_MEMORY_COUNTERS_EX {
cb576b5c
FP
123 DWORD cb;
124 DWORD PageFaultCount;
125 SIZE_T PeakWorkingSetSize;
126 SIZE_T WorkingSetSize;
127 SIZE_T QuotaPeakPagedPoolUsage;
128 SIZE_T QuotaPagedPoolUsage;
129 SIZE_T QuotaPeakNonPagedPoolUsage;
130 SIZE_T QuotaNonPagedPoolUsage;
131 SIZE_T PagefileUsage;
132 SIZE_T PeakPagefileUsage;
133 SIZE_T PrivateUsage;
7c80d5ec 134} PROCESS_MEMORY_COUNTERS_EX,*PPROCESS_MEMORY_COUNTERS_EX;
69e847be 135#endif
a18d7de6 136#endif
7c80d5ec 137
6dad7178
EZ
138#include <winioctl.h>
139#include <aclapi.h>
66447e07
EZ
140#include <sddl.h>
141
142#include <sys/acl.h>
143
144/* This is not in MinGW's sddl.h (but they are in MSVC headers), so we
145 define them by hand if not already defined. */
146#ifndef SDDL_REVISION_1
147#define SDDL_REVISION_1 1
148#endif /* SDDL_REVISION_1 */
6dad7178 149
c6e72e17
EZ
150#if defined(_MSC_VER) || defined(_W64)
151/* MSVC and MinGW64 don't provide the definition of
152 REPARSE_DATA_BUFFER and the associated macros, except on ntifs.h,
153 which cannot be included because it triggers conflicts with other
154 Windows API headers. So we define it here by hand. */
6dad7178
EZ
155
156typedef struct _REPARSE_DATA_BUFFER {
157 ULONG ReparseTag;
158 USHORT ReparseDataLength;
159 USHORT Reserved;
160 union {
161 struct {
162 USHORT SubstituteNameOffset;
163 USHORT SubstituteNameLength;
164 USHORT PrintNameOffset;
165 USHORT PrintNameLength;
166 ULONG Flags;
167 WCHAR PathBuffer[1];
168 } SymbolicLinkReparseBuffer;
169 struct {
170 USHORT SubstituteNameOffset;
171 USHORT SubstituteNameLength;
172 USHORT PrintNameOffset;
173 USHORT PrintNameLength;
174 WCHAR PathBuffer[1];
175 } MountPointReparseBuffer;
176 struct {
177 UCHAR DataBuffer[1];
178 } GenericReparseBuffer;
179 } DUMMYUNIONNAME;
180} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
181
c7b36b95 182#ifndef FILE_DEVICE_FILE_SYSTEM
88c4a13c 183#define FILE_DEVICE_FILE_SYSTEM 9
c7b36b95
FP
184#endif
185#ifndef METHOD_BUFFERED
88c4a13c 186#define METHOD_BUFFERED 0
c7b36b95
FP
187#endif
188#ifndef FILE_ANY_ACCESS
88c4a13c 189#define FILE_ANY_ACCESS 0x00000000
c7b36b95
FP
190#endif
191#ifndef CTL_CODE
88c4a13c 192#define CTL_CODE(t,f,m,a) (((t)<<16)|((a)<<14)|((f)<<2)|(m))
c7b36b95 193#endif
c86f791f
EZ
194/* MinGW64 defines FSCTL_GET_REPARSE_POINT on winioctl.h. */
195#ifndef FSCTL_GET_REPARSE_POINT
88c4a13c
EZ
196#define FSCTL_GET_REPARSE_POINT \
197 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
6dad7178 198#endif
c86f791f 199#endif
6dad7178 200
7d701334 201/* TCP connection support. */
480b0c5b
GV
202#include <sys/socket.h>
203#undef socket
204#undef bind
205#undef connect
206#undef htons
207#undef ntohs
208#undef inet_addr
209#undef gethostname
210#undef gethostbyname
211#undef getservbyname
ecd270eb 212#undef getpeername
380961a6 213#undef shutdown
962955c5
JR
214#undef setsockopt
215#undef listen
216#undef getsockname
217#undef accept
218#undef recvfrom
219#undef sendto
00b3b7b3 220
3dffe395
EZ
221#include <iphlpapi.h> /* should be after winsock2.h */
222
489f9371 223#include "w32.h"
95ef7787 224#include <dirent.h>
501199a3 225#include "w32common.h"
489f9371 226#include "w32heap.h"
a68089e4 227#include "w32select.h"
253574a6 228#include "systime.h"
f481eb31 229#include "dispextern.h" /* for xstrcasecmp */
7c80d5ec 230#include "coding.h" /* for Vlocale_coding_system */
253574a6 231
973f782d
EZ
232#include "careadlinkat.h"
233#include "allocator.h"
234
1eb8fd91 235/* For serial_configure and serial_open. */
d888760c 236#include "process.h"
d888760c 237
2d5324c5
JR
238typedef HRESULT (WINAPI * ShGetFolderPath_fn)
239 (IN HWND, IN int, IN HANDLE, IN DWORD, OUT char *);
240
0898ca10
JB
241Lisp_Object QCloaded_from;
242
b56ceb92 243void globals_of_w32 (void);
8aaaec6b 244static DWORD get_rid (PSID);
6dad7178
EZ
245static int is_symlink (const char *);
246static char * chase_symlinks (const char *);
247static int enable_privilege (LPCTSTR, BOOL, TOKEN_PRIVILEGES *);
248static int restore_privilege (TOKEN_PRIVILEGES *);
249static BOOL WINAPI revert_to_self (void);
9785d95b 250
b1846422 251static int sys_access (const char *, int);
a68089e4
EZ
252extern void *e_malloc (size_t);
253extern int sys_select (int, SELECT_TYPE *, SELECT_TYPE *, SELECT_TYPE *,
43aac990 254 struct timespec *, void *);
1d442672
EZ
255extern int sys_dup (int);
256
a68089e4
EZ
257
258
18e070ac 259\f
9d95a291
EZ
260/* Initialization states.
261
262 WARNING: If you add any more such variables for additional APIs,
263 you MUST add initialization for them to globals_of_w32
264 below. This is because these variables might get set
265 to non-NULL values during dumping, but the dumped Emacs
266 cannot reuse those values, because it could be run on a
267 different version of the OS, where API addresses are
268 different. */
9785d95b
BK
269static BOOL g_b_init_is_windows_9x;
270static BOOL g_b_init_open_process_token;
271static BOOL g_b_init_get_token_information;
272static BOOL g_b_init_lookup_account_sid;
c617afce
EZ
273static BOOL g_b_init_get_sid_sub_authority;
274static BOOL g_b_init_get_sid_sub_authority_count;
6dad7178 275static BOOL g_b_init_get_security_info;
8aaaec6b
EZ
276static BOOL g_b_init_get_file_security;
277static BOOL g_b_init_get_security_descriptor_owner;
278static BOOL g_b_init_get_security_descriptor_group;
279static BOOL g_b_init_is_valid_sid;
7c80d5ec
EZ
280static BOOL g_b_init_create_toolhelp32_snapshot;
281static BOOL g_b_init_process32_first;
282static BOOL g_b_init_process32_next;
283static BOOL g_b_init_open_thread_token;
284static BOOL g_b_init_impersonate_self;
285static BOOL g_b_init_revert_to_self;
286static BOOL g_b_init_get_process_memory_info;
287static BOOL g_b_init_get_process_working_set_size;
288static BOOL g_b_init_global_memory_status;
289static BOOL g_b_init_global_memory_status_ex;
f8b35b24
EZ
290static BOOL g_b_init_get_length_sid;
291static BOOL g_b_init_equal_sid;
292static BOOL g_b_init_copy_sid;
ad9e2d54
EZ
293static BOOL g_b_init_get_native_system_info;
294static BOOL g_b_init_get_system_times;
6dad7178 295static BOOL g_b_init_create_symbolic_link;
66447e07
EZ
296static BOOL g_b_init_get_security_descriptor_dacl;
297static BOOL g_b_init_convert_sd_to_sddl;
298static BOOL g_b_init_convert_sddl_to_sd;
299static BOOL g_b_init_is_valid_security_descriptor;
300static BOOL g_b_init_set_file_security;
3dffe395 301static BOOL g_b_init_get_adapters_info;
9785d95b 302
f60ae425
BK
303/*
304 BEGIN: Wrapper functions around OpenProcessToken
305 and other functions in advapi32.dll that are only
306 supported in Windows NT / 2k / XP
307*/
308 /* ** Function pointer typedefs ** */
309typedef BOOL (WINAPI * OpenProcessToken_Proc) (
310 HANDLE ProcessHandle,
311 DWORD DesiredAccess,
312 PHANDLE TokenHandle);
313typedef BOOL (WINAPI * GetTokenInformation_Proc) (
314 HANDLE TokenHandle,
315 TOKEN_INFORMATION_CLASS TokenInformationClass,
316 LPVOID TokenInformation,
317 DWORD TokenInformationLength,
318 PDWORD ReturnLength);
74258518
JR
319typedef BOOL (WINAPI * GetProcessTimes_Proc) (
320 HANDLE process_handle,
321 LPFILETIME creation_time,
322 LPFILETIME exit_time,
323 LPFILETIME kernel_time,
324 LPFILETIME user_time);
325
326GetProcessTimes_Proc get_process_times_fn = NULL;
327
f60ae425
BK
328#ifdef _UNICODE
329const char * const LookupAccountSid_Name = "LookupAccountSidW";
8aaaec6b 330const char * const GetFileSecurity_Name = "GetFileSecurityW";
66447e07 331const char * const SetFileSecurity_Name = "SetFileSecurityW";
f60ae425
BK
332#else
333const char * const LookupAccountSid_Name = "LookupAccountSidA";
8aaaec6b 334const char * const GetFileSecurity_Name = "GetFileSecurityA";
66447e07 335const char * const SetFileSecurity_Name = "SetFileSecurityA";
f60ae425
BK
336#endif
337typedef BOOL (WINAPI * LookupAccountSid_Proc) (
338 LPCTSTR lpSystemName,
339 PSID Sid,
340 LPTSTR Name,
341 LPDWORD cbName,
342 LPTSTR DomainName,
343 LPDWORD cbDomainName,
344 PSID_NAME_USE peUse);
c617afce
EZ
345typedef PDWORD (WINAPI * GetSidSubAuthority_Proc) (
346 PSID pSid,
347 DWORD n);
348typedef PUCHAR (WINAPI * GetSidSubAuthorityCount_Proc) (
349 PSID pSid);
6dad7178
EZ
350typedef DWORD (WINAPI * GetSecurityInfo_Proc) (
351 HANDLE handle,
352 SE_OBJECT_TYPE ObjectType,
353 SECURITY_INFORMATION SecurityInfo,
354 PSID *ppsidOwner,
355 PSID *ppsidGroup,
356 PACL *ppDacl,
357 PACL *ppSacl,
358 PSECURITY_DESCRIPTOR *ppSecurityDescriptor);
8aaaec6b
EZ
359typedef BOOL (WINAPI * GetFileSecurity_Proc) (
360 LPCTSTR lpFileName,
361 SECURITY_INFORMATION RequestedInformation,
362 PSECURITY_DESCRIPTOR pSecurityDescriptor,
363 DWORD nLength,
364 LPDWORD lpnLengthNeeded);
66447e07
EZ
365typedef BOOL (WINAPI *SetFileSecurity_Proc) (
366 LPCTSTR lpFileName,
367 SECURITY_INFORMATION SecurityInformation,
368 PSECURITY_DESCRIPTOR pSecurityDescriptor);
8aaaec6b
EZ
369typedef BOOL (WINAPI * GetSecurityDescriptorOwner_Proc) (
370 PSECURITY_DESCRIPTOR pSecurityDescriptor,
371 PSID *pOwner,
372 LPBOOL lpbOwnerDefaulted);
373typedef BOOL (WINAPI * GetSecurityDescriptorGroup_Proc) (
374 PSECURITY_DESCRIPTOR pSecurityDescriptor,
375 PSID *pGroup,
376 LPBOOL lpbGroupDefaulted);
66447e07
EZ
377typedef BOOL (WINAPI *GetSecurityDescriptorDacl_Proc) (
378 PSECURITY_DESCRIPTOR pSecurityDescriptor,
379 LPBOOL lpbDaclPresent,
380 PACL *pDacl,
381 LPBOOL lpbDaclDefaulted);
8aaaec6b
EZ
382typedef BOOL (WINAPI * IsValidSid_Proc) (
383 PSID sid);
7c80d5ec
EZ
384typedef HANDLE (WINAPI * CreateToolhelp32Snapshot_Proc) (
385 DWORD dwFlags,
386 DWORD th32ProcessID);
387typedef BOOL (WINAPI * Process32First_Proc) (
388 HANDLE hSnapshot,
389 LPPROCESSENTRY32 lppe);
390typedef BOOL (WINAPI * Process32Next_Proc) (
391 HANDLE hSnapshot,
392 LPPROCESSENTRY32 lppe);
393typedef BOOL (WINAPI * OpenThreadToken_Proc) (
394 HANDLE ThreadHandle,
395 DWORD DesiredAccess,
396 BOOL OpenAsSelf,
397 PHANDLE TokenHandle);
398typedef BOOL (WINAPI * ImpersonateSelf_Proc) (
399 SECURITY_IMPERSONATION_LEVEL ImpersonationLevel);
400typedef BOOL (WINAPI * RevertToSelf_Proc) (void);
401typedef BOOL (WINAPI * GetProcessMemoryInfo_Proc) (
402 HANDLE Process,
403 PPROCESS_MEMORY_COUNTERS ppsmemCounters,
404 DWORD cb);
405typedef BOOL (WINAPI * GetProcessWorkingSetSize_Proc) (
406 HANDLE hProcess,
cb576b5c
FP
407 PSIZE_T lpMinimumWorkingSetSize,
408 PSIZE_T lpMaximumWorkingSetSize);
7c80d5ec
EZ
409typedef BOOL (WINAPI * GlobalMemoryStatus_Proc) (
410 LPMEMORYSTATUS lpBuffer);
411typedef BOOL (WINAPI * GlobalMemoryStatusEx_Proc) (
b8526f6e 412 LPMEMORY_STATUS_EX lpBuffer);
f8b35b24
EZ
413typedef BOOL (WINAPI * CopySid_Proc) (
414 DWORD nDestinationSidLength,
415 PSID pDestinationSid,
416 PSID pSourceSid);
417typedef BOOL (WINAPI * EqualSid_Proc) (
418 PSID pSid1,
419 PSID pSid2);
420typedef DWORD (WINAPI * GetLengthSid_Proc) (
421 PSID pSid);
ad9e2d54
EZ
422typedef void (WINAPI * GetNativeSystemInfo_Proc) (
423 LPSYSTEM_INFO lpSystemInfo);
424typedef BOOL (WINAPI * GetSystemTimes_Proc) (
425 LPFILETIME lpIdleTime,
426 LPFILETIME lpKernelTime,
427 LPFILETIME lpUserTime);
6dad7178
EZ
428typedef BOOLEAN (WINAPI *CreateSymbolicLink_Proc) (
429 LPTSTR lpSymlinkFileName,
430 LPTSTR lpTargetFileName,
431 DWORD dwFlags);
66447e07
EZ
432typedef BOOL (WINAPI *ConvertStringSecurityDescriptorToSecurityDescriptor_Proc) (
433 LPCTSTR StringSecurityDescriptor,
434 DWORD StringSDRevision,
435 PSECURITY_DESCRIPTOR *SecurityDescriptor,
436 PULONG SecurityDescriptorSize);
437typedef BOOL (WINAPI *ConvertSecurityDescriptorToStringSecurityDescriptor_Proc) (
438 PSECURITY_DESCRIPTOR SecurityDescriptor,
439 DWORD RequestedStringSDRevision,
440 SECURITY_INFORMATION SecurityInformation,
441 LPTSTR *StringSecurityDescriptor,
442 PULONG StringSecurityDescriptorLen);
443typedef BOOL (WINAPI *IsValidSecurityDescriptor_Proc) (PSECURITY_DESCRIPTOR);
3dffe395
EZ
444typedef DWORD (WINAPI *GetAdaptersInfo_Proc) (
445 PIP_ADAPTER_INFO pAdapterInfo,
446 PULONG pOutBufLen);
f8b35b24 447
f60ae425 448 /* ** A utility function ** */
9bfb11f9 449static BOOL
b56ceb92 450is_windows_9x (void)
f60ae425 451{
bedf4aab 452 static BOOL s_b_ret = 0;
f60ae425 453 OSVERSIONINFO os_ver;
9785d95b 454 if (g_b_init_is_windows_9x == 0)
f60ae425 455 {
9785d95b 456 g_b_init_is_windows_9x = 1;
ed3751c8
JB
457 ZeroMemory (&os_ver, sizeof (OSVERSIONINFO));
458 os_ver.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
9785d95b
BK
459 if (GetVersionEx (&os_ver))
460 {
461 s_b_ret = (os_ver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
462 }
f60ae425 463 }
9785d95b 464 return s_b_ret;
f60ae425
BK
465}
466
d35af63c
PE
467static Lisp_Object ltime (ULONGLONG);
468
74258518 469/* Get total user and system times for get-internal-run-time.
d35af63c 470 Returns a list of integers if the times are provided by the OS
74258518
JR
471 (NT derivatives), otherwise it returns the result of current-time. */
472Lisp_Object
b56ceb92 473w32_get_internal_run_time (void)
74258518
JR
474{
475 if (get_process_times_fn)
476 {
477 FILETIME create, exit, kernel, user;
ed3751c8 478 HANDLE proc = GetCurrentProcess ();
74258518
JR
479 if ((*get_process_times_fn) (proc, &create, &exit, &kernel, &user))
480 {
481 LARGE_INTEGER user_int, kernel_int, total;
74258518
JR
482 user_int.LowPart = user.dwLowDateTime;
483 user_int.HighPart = user.dwHighDateTime;
484 kernel_int.LowPart = kernel.dwLowDateTime;
485 kernel_int.HighPart = kernel.dwHighDateTime;
486 total.QuadPart = user_int.QuadPart + kernel_int.QuadPart;
d35af63c 487 return ltime (total.QuadPart);
74258518
JR
488 }
489 }
490
491 return Fcurrent_time ();
492}
493
f60ae425
BK
494 /* ** The wrapper functions ** */
495
bedf4aab
JB
496static BOOL WINAPI
497open_process_token (HANDLE ProcessHandle,
498 DWORD DesiredAccess,
499 PHANDLE TokenHandle)
f60ae425 500{
9785d95b 501 static OpenProcessToken_Proc s_pfn_Open_Process_Token = NULL;
f60ae425
BK
502 HMODULE hm_advapi32 = NULL;
503 if (is_windows_9x () == TRUE)
504 {
505 return FALSE;
506 }
9785d95b
BK
507 if (g_b_init_open_process_token == 0)
508 {
509 g_b_init_open_process_token = 1;
510 hm_advapi32 = LoadLibrary ("Advapi32.dll");
511 s_pfn_Open_Process_Token =
512 (OpenProcessToken_Proc) GetProcAddress (hm_advapi32, "OpenProcessToken");
513 }
514 if (s_pfn_Open_Process_Token == NULL)
f60ae425
BK
515 {
516 return FALSE;
517 }
518 return (
9785d95b 519 s_pfn_Open_Process_Token (
f60ae425
BK
520 ProcessHandle,
521 DesiredAccess,
522 TokenHandle)
523 );
524}
525
bedf4aab
JB
526static BOOL WINAPI
527get_token_information (HANDLE TokenHandle,
528 TOKEN_INFORMATION_CLASS TokenInformationClass,
529 LPVOID TokenInformation,
530 DWORD TokenInformationLength,
531 PDWORD ReturnLength)
f60ae425 532{
9785d95b 533 static GetTokenInformation_Proc s_pfn_Get_Token_Information = NULL;
f60ae425
BK
534 HMODULE hm_advapi32 = NULL;
535 if (is_windows_9x () == TRUE)
536 {
537 return FALSE;
538 }
9785d95b
BK
539 if (g_b_init_get_token_information == 0)
540 {
541 g_b_init_get_token_information = 1;
542 hm_advapi32 = LoadLibrary ("Advapi32.dll");
543 s_pfn_Get_Token_Information =
544 (GetTokenInformation_Proc) GetProcAddress (hm_advapi32, "GetTokenInformation");
545 }
546 if (s_pfn_Get_Token_Information == NULL)
f60ae425
BK
547 {
548 return FALSE;
549 }
550 return (
9785d95b 551 s_pfn_Get_Token_Information (
f60ae425
BK
552 TokenHandle,
553 TokenInformationClass,
554 TokenInformation,
555 TokenInformationLength,
556 ReturnLength)
557 );
558}
559
bedf4aab
JB
560static BOOL WINAPI
561lookup_account_sid (LPCTSTR lpSystemName,
562 PSID Sid,
563 LPTSTR Name,
564 LPDWORD cbName,
565 LPTSTR DomainName,
566 LPDWORD cbDomainName,
567 PSID_NAME_USE peUse)
f60ae425 568{
9785d95b 569 static LookupAccountSid_Proc s_pfn_Lookup_Account_Sid = NULL;
f60ae425
BK
570 HMODULE hm_advapi32 = NULL;
571 if (is_windows_9x () == TRUE)
572 {
573 return FALSE;
574 }
9785d95b
BK
575 if (g_b_init_lookup_account_sid == 0)
576 {
577 g_b_init_lookup_account_sid = 1;
578 hm_advapi32 = LoadLibrary ("Advapi32.dll");
579 s_pfn_Lookup_Account_Sid =
580 (LookupAccountSid_Proc) GetProcAddress (hm_advapi32, LookupAccountSid_Name);
581 }
582 if (s_pfn_Lookup_Account_Sid == NULL)
f60ae425
BK
583 {
584 return FALSE;
585 }
586 return (
9785d95b 587 s_pfn_Lookup_Account_Sid (
f60ae425
BK
588 lpSystemName,
589 Sid,
590 Name,
591 cbName,
592 DomainName,
593 cbDomainName,
594 peUse)
595 );
596}
597
bedf4aab
JB
598static PDWORD WINAPI
599get_sid_sub_authority (PSID pSid, DWORD n)
c617afce
EZ
600{
601 static GetSidSubAuthority_Proc s_pfn_Get_Sid_Sub_Authority = NULL;
6811b9f4 602 static DWORD zero = 0U;
c617afce
EZ
603 HMODULE hm_advapi32 = NULL;
604 if (is_windows_9x () == TRUE)
605 {
6811b9f4 606 return &zero;
c617afce
EZ
607 }
608 if (g_b_init_get_sid_sub_authority == 0)
609 {
610 g_b_init_get_sid_sub_authority = 1;
611 hm_advapi32 = LoadLibrary ("Advapi32.dll");
612 s_pfn_Get_Sid_Sub_Authority =
613 (GetSidSubAuthority_Proc) GetProcAddress (
614 hm_advapi32, "GetSidSubAuthority");
615 }
616 if (s_pfn_Get_Sid_Sub_Authority == NULL)
617 {
6811b9f4 618 return &zero;
c617afce
EZ
619 }
620 return (s_pfn_Get_Sid_Sub_Authority (pSid, n));
621}
622
bedf4aab
JB
623static PUCHAR WINAPI
624get_sid_sub_authority_count (PSID pSid)
c617afce
EZ
625{
626 static GetSidSubAuthorityCount_Proc s_pfn_Get_Sid_Sub_Authority_Count = NULL;
6811b9f4 627 static UCHAR zero = 0U;
c617afce
EZ
628 HMODULE hm_advapi32 = NULL;
629 if (is_windows_9x () == TRUE)
630 {
6811b9f4 631 return &zero;
c617afce
EZ
632 }
633 if (g_b_init_get_sid_sub_authority_count == 0)
634 {
635 g_b_init_get_sid_sub_authority_count = 1;
636 hm_advapi32 = LoadLibrary ("Advapi32.dll");
637 s_pfn_Get_Sid_Sub_Authority_Count =
638 (GetSidSubAuthorityCount_Proc) GetProcAddress (
639 hm_advapi32, "GetSidSubAuthorityCount");
640 }
641 if (s_pfn_Get_Sid_Sub_Authority_Count == NULL)
642 {
6811b9f4 643 return &zero;
c617afce
EZ
644 }
645 return (s_pfn_Get_Sid_Sub_Authority_Count (pSid));
646}
647
6dad7178
EZ
648static DWORD WINAPI
649get_security_info (HANDLE handle,
650 SE_OBJECT_TYPE ObjectType,
651 SECURITY_INFORMATION SecurityInfo,
652 PSID *ppsidOwner,
653 PSID *ppsidGroup,
654 PACL *ppDacl,
655 PACL *ppSacl,
656 PSECURITY_DESCRIPTOR *ppSecurityDescriptor)
657{
658 static GetSecurityInfo_Proc s_pfn_Get_Security_Info = NULL;
659 HMODULE hm_advapi32 = NULL;
660 if (is_windows_9x () == TRUE)
661 {
662 return FALSE;
663 }
664 if (g_b_init_get_security_info == 0)
665 {
666 g_b_init_get_security_info = 1;
667 hm_advapi32 = LoadLibrary ("Advapi32.dll");
668 s_pfn_Get_Security_Info =
669 (GetSecurityInfo_Proc) GetProcAddress (
670 hm_advapi32, "GetSecurityInfo");
671 }
672 if (s_pfn_Get_Security_Info == NULL)
673 {
674 return FALSE;
675 }
676 return (s_pfn_Get_Security_Info (handle, ObjectType, SecurityInfo,
677 ppsidOwner, ppsidGroup, ppDacl, ppSacl,
678 ppSecurityDescriptor));
679}
680
bedf4aab
JB
681static BOOL WINAPI
682get_file_security (LPCTSTR lpFileName,
683 SECURITY_INFORMATION RequestedInformation,
684 PSECURITY_DESCRIPTOR pSecurityDescriptor,
685 DWORD nLength,
686 LPDWORD lpnLengthNeeded)
8aaaec6b
EZ
687{
688 static GetFileSecurity_Proc s_pfn_Get_File_Security = NULL;
689 HMODULE hm_advapi32 = NULL;
690 if (is_windows_9x () == TRUE)
691 {
66447e07 692 errno = ENOTSUP;
8aaaec6b
EZ
693 return FALSE;
694 }
695 if (g_b_init_get_file_security == 0)
696 {
697 g_b_init_get_file_security = 1;
698 hm_advapi32 = LoadLibrary ("Advapi32.dll");
699 s_pfn_Get_File_Security =
700 (GetFileSecurity_Proc) GetProcAddress (
701 hm_advapi32, GetFileSecurity_Name);
702 }
703 if (s_pfn_Get_File_Security == NULL)
704 {
66447e07 705 errno = ENOTSUP;
8aaaec6b
EZ
706 return FALSE;
707 }
708 return (s_pfn_Get_File_Security (lpFileName, RequestedInformation,
709 pSecurityDescriptor, nLength,
710 lpnLengthNeeded));
711}
712
66447e07
EZ
713static BOOL WINAPI
714set_file_security (LPCTSTR lpFileName,
715 SECURITY_INFORMATION SecurityInformation,
716 PSECURITY_DESCRIPTOR pSecurityDescriptor)
717{
718 static SetFileSecurity_Proc s_pfn_Set_File_Security = NULL;
719 HMODULE hm_advapi32 = NULL;
720 if (is_windows_9x () == TRUE)
721 {
722 errno = ENOTSUP;
723 return FALSE;
724 }
725 if (g_b_init_set_file_security == 0)
726 {
727 g_b_init_set_file_security = 1;
728 hm_advapi32 = LoadLibrary ("Advapi32.dll");
729 s_pfn_Set_File_Security =
730 (SetFileSecurity_Proc) GetProcAddress (
731 hm_advapi32, SetFileSecurity_Name);
732 }
733 if (s_pfn_Set_File_Security == NULL)
734 {
735 errno = ENOTSUP;
736 return FALSE;
737 }
738 return (s_pfn_Set_File_Security (lpFileName, SecurityInformation,
739 pSecurityDescriptor));
740}
741
bedf4aab
JB
742static BOOL WINAPI
743get_security_descriptor_owner (PSECURITY_DESCRIPTOR pSecurityDescriptor,
744 PSID *pOwner,
745 LPBOOL lpbOwnerDefaulted)
8aaaec6b
EZ
746{
747 static GetSecurityDescriptorOwner_Proc s_pfn_Get_Security_Descriptor_Owner = NULL;
748 HMODULE hm_advapi32 = NULL;
749 if (is_windows_9x () == TRUE)
750 {
66447e07 751 errno = ENOTSUP;
8aaaec6b
EZ
752 return FALSE;
753 }
754 if (g_b_init_get_security_descriptor_owner == 0)
755 {
756 g_b_init_get_security_descriptor_owner = 1;
757 hm_advapi32 = LoadLibrary ("Advapi32.dll");
758 s_pfn_Get_Security_Descriptor_Owner =
759 (GetSecurityDescriptorOwner_Proc) GetProcAddress (
760 hm_advapi32, "GetSecurityDescriptorOwner");
761 }
762 if (s_pfn_Get_Security_Descriptor_Owner == NULL)
763 {
66447e07 764 errno = ENOTSUP;
8aaaec6b
EZ
765 return FALSE;
766 }
767 return (s_pfn_Get_Security_Descriptor_Owner (pSecurityDescriptor, pOwner,
768 lpbOwnerDefaulted));
769}
770
bedf4aab
JB
771static BOOL WINAPI
772get_security_descriptor_group (PSECURITY_DESCRIPTOR pSecurityDescriptor,
773 PSID *pGroup,
774 LPBOOL lpbGroupDefaulted)
8aaaec6b
EZ
775{
776 static GetSecurityDescriptorGroup_Proc s_pfn_Get_Security_Descriptor_Group = NULL;
777 HMODULE hm_advapi32 = NULL;
778 if (is_windows_9x () == TRUE)
779 {
66447e07 780 errno = ENOTSUP;
8aaaec6b
EZ
781 return FALSE;
782 }
783 if (g_b_init_get_security_descriptor_group == 0)
784 {
785 g_b_init_get_security_descriptor_group = 1;
786 hm_advapi32 = LoadLibrary ("Advapi32.dll");
787 s_pfn_Get_Security_Descriptor_Group =
788 (GetSecurityDescriptorGroup_Proc) GetProcAddress (
789 hm_advapi32, "GetSecurityDescriptorGroup");
790 }
791 if (s_pfn_Get_Security_Descriptor_Group == NULL)
792 {
66447e07 793 errno = ENOTSUP;
8aaaec6b
EZ
794 return FALSE;
795 }
796 return (s_pfn_Get_Security_Descriptor_Group (pSecurityDescriptor, pGroup,
797 lpbGroupDefaulted));
798}
799
66447e07
EZ
800static BOOL WINAPI
801get_security_descriptor_dacl (PSECURITY_DESCRIPTOR pSecurityDescriptor,
802 LPBOOL lpbDaclPresent,
803 PACL *pDacl,
804 LPBOOL lpbDaclDefaulted)
805{
806 static GetSecurityDescriptorDacl_Proc s_pfn_Get_Security_Descriptor_Dacl = NULL;
807 HMODULE hm_advapi32 = NULL;
808 if (is_windows_9x () == TRUE)
809 {
810 errno = ENOTSUP;
811 return FALSE;
812 }
813 if (g_b_init_get_security_descriptor_dacl == 0)
814 {
815 g_b_init_get_security_descriptor_dacl = 1;
816 hm_advapi32 = LoadLibrary ("Advapi32.dll");
817 s_pfn_Get_Security_Descriptor_Dacl =
818 (GetSecurityDescriptorDacl_Proc) GetProcAddress (
819 hm_advapi32, "GetSecurityDescriptorDacl");
820 }
821 if (s_pfn_Get_Security_Descriptor_Dacl == NULL)
822 {
823 errno = ENOTSUP;
824 return FALSE;
825 }
826 return (s_pfn_Get_Security_Descriptor_Dacl (pSecurityDescriptor,
827 lpbDaclPresent, pDacl,
828 lpbDaclDefaulted));
829}
830
bedf4aab
JB
831static BOOL WINAPI
832is_valid_sid (PSID sid)
8aaaec6b
EZ
833{
834 static IsValidSid_Proc s_pfn_Is_Valid_Sid = NULL;
835 HMODULE hm_advapi32 = NULL;
836 if (is_windows_9x () == TRUE)
837 {
838 return FALSE;
839 }
840 if (g_b_init_is_valid_sid == 0)
841 {
842 g_b_init_is_valid_sid = 1;
843 hm_advapi32 = LoadLibrary ("Advapi32.dll");
844 s_pfn_Is_Valid_Sid =
845 (IsValidSid_Proc) GetProcAddress (
846 hm_advapi32, "IsValidSid");
847 }
848 if (s_pfn_Is_Valid_Sid == NULL)
849 {
850 return FALSE;
851 }
852 return (s_pfn_Is_Valid_Sid (sid));
853}
854
bedf4aab
JB
855static BOOL WINAPI
856equal_sid (PSID sid1, PSID sid2)
f8b35b24
EZ
857{
858 static EqualSid_Proc s_pfn_Equal_Sid = NULL;
859 HMODULE hm_advapi32 = NULL;
860 if (is_windows_9x () == TRUE)
861 {
862 return FALSE;
863 }
864 if (g_b_init_equal_sid == 0)
865 {
866 g_b_init_equal_sid = 1;
867 hm_advapi32 = LoadLibrary ("Advapi32.dll");
868 s_pfn_Equal_Sid =
869 (EqualSid_Proc) GetProcAddress (
870 hm_advapi32, "EqualSid");
871 }
872 if (s_pfn_Equal_Sid == NULL)
873 {
874 return FALSE;
875 }
876 return (s_pfn_Equal_Sid (sid1, sid2));
877}
878
bedf4aab
JB
879static DWORD WINAPI
880get_length_sid (PSID sid)
f8b35b24
EZ
881{
882 static GetLengthSid_Proc s_pfn_Get_Length_Sid = NULL;
883 HMODULE hm_advapi32 = NULL;
884 if (is_windows_9x () == TRUE)
885 {
886 return 0;
887 }
888 if (g_b_init_get_length_sid == 0)
889 {
890 g_b_init_get_length_sid = 1;
891 hm_advapi32 = LoadLibrary ("Advapi32.dll");
892 s_pfn_Get_Length_Sid =
893 (GetLengthSid_Proc) GetProcAddress (
894 hm_advapi32, "GetLengthSid");
895 }
896 if (s_pfn_Get_Length_Sid == NULL)
897 {
898 return 0;
899 }
900 return (s_pfn_Get_Length_Sid (sid));
901}
902
bedf4aab
JB
903static BOOL WINAPI
904copy_sid (DWORD destlen, PSID dest, PSID src)
f8b35b24
EZ
905{
906 static CopySid_Proc s_pfn_Copy_Sid = NULL;
907 HMODULE hm_advapi32 = NULL;
908 if (is_windows_9x () == TRUE)
909 {
910 return FALSE;
911 }
912 if (g_b_init_copy_sid == 0)
913 {
914 g_b_init_copy_sid = 1;
915 hm_advapi32 = LoadLibrary ("Advapi32.dll");
916 s_pfn_Copy_Sid =
917 (CopySid_Proc) GetProcAddress (
918 hm_advapi32, "CopySid");
919 }
920 if (s_pfn_Copy_Sid == NULL)
921 {
922 return FALSE;
923 }
924 return (s_pfn_Copy_Sid (destlen, dest, src));
925}
926
f60ae425
BK
927/*
928 END: Wrapper functions around OpenProcessToken
929 and other functions in advapi32.dll that are only
930 supported in Windows NT / 2k / XP
931*/
932
bedf4aab
JB
933static void WINAPI
934get_native_system_info (LPSYSTEM_INFO lpSystemInfo)
ad9e2d54
EZ
935{
936 static GetNativeSystemInfo_Proc s_pfn_Get_Native_System_Info = NULL;
937 if (is_windows_9x () != TRUE)
938 {
939 if (g_b_init_get_native_system_info == 0)
940 {
941 g_b_init_get_native_system_info = 1;
942 s_pfn_Get_Native_System_Info =
943 (GetNativeSystemInfo_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
944 "GetNativeSystemInfo");
945 }
946 if (s_pfn_Get_Native_System_Info != NULL)
947 s_pfn_Get_Native_System_Info (lpSystemInfo);
948 }
949 else
950 lpSystemInfo->dwNumberOfProcessors = -1;
951}
952
bedf4aab
JB
953static BOOL WINAPI
954get_system_times (LPFILETIME lpIdleTime,
955 LPFILETIME lpKernelTime,
956 LPFILETIME lpUserTime)
ad9e2d54
EZ
957{
958 static GetSystemTimes_Proc s_pfn_Get_System_times = NULL;
959 if (is_windows_9x () == TRUE)
960 {
961 return FALSE;
962 }
963 if (g_b_init_get_system_times == 0)
964 {
965 g_b_init_get_system_times = 1;
966 s_pfn_Get_System_times =
967 (GetSystemTimes_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
968 "GetSystemTimes");
969 }
970 if (s_pfn_Get_System_times == NULL)
971 return FALSE;
972 return (s_pfn_Get_System_times (lpIdleTime, lpKernelTime, lpUserTime));
973}
6dad7178
EZ
974
975static BOOLEAN WINAPI
976create_symbolic_link (LPTSTR lpSymlinkFilename,
977 LPTSTR lpTargetFileName,
978 DWORD dwFlags)
979{
980 static CreateSymbolicLink_Proc s_pfn_Create_Symbolic_Link = NULL;
981 BOOLEAN retval;
982
983 if (is_windows_9x () == TRUE)
984 {
985 errno = ENOSYS;
986 return 0;
987 }
988 if (g_b_init_create_symbolic_link == 0)
989 {
990 g_b_init_create_symbolic_link = 1;
991#ifdef _UNICODE
992 s_pfn_Create_Symbolic_Link =
993 (CreateSymbolicLink_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
994 "CreateSymbolicLinkW");
995#else
996 s_pfn_Create_Symbolic_Link =
997 (CreateSymbolicLink_Proc)GetProcAddress (GetModuleHandle ("kernel32.dll"),
998 "CreateSymbolicLinkA");
999#endif
1000 }
1001 if (s_pfn_Create_Symbolic_Link == NULL)
1002 {
1003 errno = ENOSYS;
1004 return 0;
1005 }
1006
1007 retval = s_pfn_Create_Symbolic_Link (lpSymlinkFilename, lpTargetFileName,
1008 dwFlags);
1009 /* If we were denied creation of the symlink, try again after
1010 enabling the SeCreateSymbolicLinkPrivilege for our process. */
1011 if (!retval)
1012 {
1013 TOKEN_PRIVILEGES priv_current;
1014
1015 if (enable_privilege (SE_CREATE_SYMBOLIC_LINK_NAME, TRUE, &priv_current))
1016 {
1017 retval = s_pfn_Create_Symbolic_Link (lpSymlinkFilename, lpTargetFileName,
1018 dwFlags);
1019 restore_privilege (&priv_current);
1020 revert_to_self ();
1021 }
1022 }
1023 return retval;
1024}
66447e07
EZ
1025
1026static BOOL WINAPI
1027is_valid_security_descriptor (PSECURITY_DESCRIPTOR pSecurityDescriptor)
1028{
1029 static IsValidSecurityDescriptor_Proc s_pfn_Is_Valid_Security_Descriptor_Proc = NULL;
1030
1031 if (is_windows_9x () == TRUE)
1032 {
1033 errno = ENOTSUP;
1034 return FALSE;
1035 }
1036
1037 if (g_b_init_is_valid_security_descriptor == 0)
1038 {
1039 g_b_init_is_valid_security_descriptor = 1;
1040 s_pfn_Is_Valid_Security_Descriptor_Proc =
1041 (IsValidSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1042 "IsValidSecurityDescriptor");
1043 }
1044 if (s_pfn_Is_Valid_Security_Descriptor_Proc == NULL)
1045 {
1046 errno = ENOTSUP;
1047 return FALSE;
1048 }
1049
1050 return s_pfn_Is_Valid_Security_Descriptor_Proc (pSecurityDescriptor);
1051}
1052
1053static BOOL WINAPI
1054convert_sd_to_sddl (PSECURITY_DESCRIPTOR SecurityDescriptor,
1055 DWORD RequestedStringSDRevision,
1056 SECURITY_INFORMATION SecurityInformation,
1057 LPTSTR *StringSecurityDescriptor,
1058 PULONG StringSecurityDescriptorLen)
1059{
1060 static ConvertSecurityDescriptorToStringSecurityDescriptor_Proc s_pfn_Convert_SD_To_SDDL = NULL;
1061 BOOL retval;
1062
1063 if (is_windows_9x () == TRUE)
1064 {
1065 errno = ENOTSUP;
1066 return FALSE;
1067 }
1068
1069 if (g_b_init_convert_sd_to_sddl == 0)
1070 {
1071 g_b_init_convert_sd_to_sddl = 1;
1072#ifdef _UNICODE
1073 s_pfn_Convert_SD_To_SDDL =
1074 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1075 "ConvertSecurityDescriptorToStringSecurityDescriptorW");
1076#else
1077 s_pfn_Convert_SD_To_SDDL =
1078 (ConvertSecurityDescriptorToStringSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1079 "ConvertSecurityDescriptorToStringSecurityDescriptorA");
1080#endif
1081 }
1082 if (s_pfn_Convert_SD_To_SDDL == NULL)
1083 {
1084 errno = ENOTSUP;
1085 return FALSE;
1086 }
1087
1088 retval = s_pfn_Convert_SD_To_SDDL (SecurityDescriptor,
1089 RequestedStringSDRevision,
1090 SecurityInformation,
1091 StringSecurityDescriptor,
1092 StringSecurityDescriptorLen);
1093
1094 return retval;
1095}
1096
1097static BOOL WINAPI
1098convert_sddl_to_sd (LPCTSTR StringSecurityDescriptor,
1099 DWORD StringSDRevision,
1100 PSECURITY_DESCRIPTOR *SecurityDescriptor,
1101 PULONG SecurityDescriptorSize)
1102{
1103 static ConvertStringSecurityDescriptorToSecurityDescriptor_Proc s_pfn_Convert_SDDL_To_SD = NULL;
1104 BOOL retval;
1105
1106 if (is_windows_9x () == TRUE)
1107 {
1108 errno = ENOTSUP;
1109 return FALSE;
1110 }
1111
1112 if (g_b_init_convert_sddl_to_sd == 0)
1113 {
1114 g_b_init_convert_sddl_to_sd = 1;
1115#ifdef _UNICODE
1116 s_pfn_Convert_SDDL_To_SD =
1117 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1118 "ConvertStringSecurityDescriptorToSecurityDescriptorW");
1119#else
1120 s_pfn_Convert_SDDL_To_SD =
1121 (ConvertStringSecurityDescriptorToSecurityDescriptor_Proc)GetProcAddress (GetModuleHandle ("Advapi32.dll"),
1122 "ConvertStringSecurityDescriptorToSecurityDescriptorA");
1123#endif
1124 }
1125 if (s_pfn_Convert_SDDL_To_SD == NULL)
1126 {
1127 errno = ENOTSUP;
1128 return FALSE;
1129 }
1130
1131 retval = s_pfn_Convert_SDDL_To_SD (StringSecurityDescriptor,
1132 StringSDRevision,
1133 SecurityDescriptor,
1134 SecurityDescriptorSize);
1135
1136 return retval;
1137}
1138
3dffe395
EZ
1139static DWORD WINAPI
1140get_adapters_info (PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen)
1141{
1142 static GetAdaptersInfo_Proc s_pfn_Get_Adapters_Info = NULL;
1143 HMODULE hm_iphlpapi = NULL;
1144
1145 if (is_windows_9x () == TRUE)
1146 return ERROR_NOT_SUPPORTED;
1147
1148 if (g_b_init_get_adapters_info == 0)
1149 {
1150 g_b_init_get_adapters_info = 1;
1151 hm_iphlpapi = LoadLibrary ("Iphlpapi.dll");
1152 if (hm_iphlpapi)
1153 s_pfn_Get_Adapters_Info = (GetAdaptersInfo_Proc)
1154 GetProcAddress (hm_iphlpapi, "GetAdaptersInfo");
1155 }
1156 if (s_pfn_Get_Adapters_Info == NULL)
1157 return ERROR_NOT_SUPPORTED;
1158 return s_pfn_Get_Adapters_Info (pAdapterInfo, pOutBufLen);
1159}
1160
f60ae425 1161\f
18e070ac 1162
ed91b2ad
EZ
1163/* Return 1 if P is a valid pointer to an object of size SIZE. Return
1164 0 if P is NOT a valid pointer. Return -1 if we cannot validate P.
1165
1166 This is called from alloc.c:valid_pointer_p. */
1167int
1168w32_valid_pointer_p (void *p, int size)
1169{
1170 SIZE_T done;
1171 HANDLE h = OpenProcess (PROCESS_VM_READ, FALSE, GetCurrentProcessId ());
1172
1173 if (h)
1174 {
1175 unsigned char *buf = alloca (size);
1176 int retval = ReadProcessMemory (h, p, buf, size, &done);
1177
1178 CloseHandle (h);
1179 return retval;
1180 }
1181 else
1182 return -1;
1183}
1184
03d58cca
EZ
1185\f
1186
c3e9160b
EZ
1187/* Converting file names from UTF-8 to either UTF-16 or the ANSI
1188 codepage defined by file-name-coding-system. */
1189
1190/* Current codepage for encoding file names. */
1191static int file_name_codepage;
1192
1193/* Produce a Windows ANSI codepage suitable for encoding file names.
1194 Return the information about that codepage in CP_INFO. */
1195static int
1196codepage_for_filenames (CPINFO *cp_info)
1197{
1198 /* A simple cache to avoid calling GetCPInfo every time we need to
1199 encode/decode a file name. The file-name encoding is not
1200 supposed to be changed too frequently, if ever. */
1201 static Lisp_Object last_file_name_encoding;
1202 static CPINFO cp;
1203 Lisp_Object current_encoding;
1204
1205 current_encoding = Vfile_name_coding_system;
1206 if (NILP (current_encoding))
1207 current_encoding = Vdefault_file_name_coding_system;
1208
1209 if (!EQ (last_file_name_encoding, current_encoding))
1210 {
1211 /* Default to the current ANSI codepage. */
1212 file_name_codepage = w32_ansi_code_page;
1213
1214 if (NILP (current_encoding))
1215 {
1216 char *cpname = SDATA (SYMBOL_NAME (current_encoding));
1217 char *cp = NULL, *end;
1218 int cpnum;
1219
1220 if (strncmp (cpname, "cp", 2) == 0)
1221 cp = cpname + 2;
1222 else if (strncmp (cpname, "windows-", 8) == 0)
1223 cp = cpname + 8;
1224
1225 if (cp)
1226 {
1227 end = cp;
1228 cpnum = strtol (cp, &end, 10);
1229 if (cpnum && *end == '\0' && end - cp >= 2)
1230 file_name_codepage = cpnum;
1231 }
1232 }
1233
1234 if (!file_name_codepage)
1235 file_name_codepage = CP_ACP; /* CP_ACP = 0, but let's not assume that */
1236
1237 if (!GetCPInfo (file_name_codepage, &cp))
1238 {
1239 file_name_codepage = CP_ACP;
1240 if (!GetCPInfo (file_name_codepage, &cp))
1241 emacs_abort ();
1242 }
1243 }
1244 if (cp_info)
1245 *cp_info = cp;
1246
1247 return file_name_codepage;
1248}
1249
03d58cca
EZ
1250static int
1251filename_to_utf16 (const char *fn_in, wchar_t *fn_out)
1252{
c3e9160b
EZ
1253 int result = MultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS, fn_in, -1,
1254 fn_out, MAX_PATH);
03d58cca
EZ
1255
1256 if (!result)
1257 {
1258 DWORD err = GetLastError ();
1259
1260 switch (err)
1261 {
1262 case ERROR_INVALID_FLAGS:
1263 case ERROR_INVALID_PARAMETER:
1264 errno = EINVAL;
1265 break;
1266 case ERROR_INSUFFICIENT_BUFFER:
1267 case ERROR_NO_UNICODE_TRANSLATION:
1268 default:
1269 errno = ENOENT;
1270 break;
1271 }
1272 return -1;
1273 }
1274 return 0;
1275}
1276
1277static int
1278filename_from_utf16 (const wchar_t *fn_in, char *fn_out)
1279{
c3e9160b
EZ
1280 int result = WideCharToMultiByte (CP_UTF8, 0, fn_in, -1,
1281 fn_out, MAX_UTF8_PATH, NULL, NULL);
1282
1283 if (!result)
1284 {
1285 DWORD err = GetLastError ();
1286
1287 switch (err)
1288 {
1289 case ERROR_INVALID_FLAGS:
1290 case ERROR_INVALID_PARAMETER:
1291 errno = EINVAL;
1292 break;
1293 case ERROR_INSUFFICIENT_BUFFER:
1294 case ERROR_NO_UNICODE_TRANSLATION:
1295 default:
1296 errno = ENOENT;
1297 break;
1298 }
1299 return -1;
1300 }
1301 return 0;
03d58cca
EZ
1302}
1303
1304static int
1305filename_to_ansi (const char *fn_in, char *fn_out)
1306{
80fcb9d2 1307 wchar_t fn_utf16[MAX_PATH];
03d58cca
EZ
1308
1309 if (filename_to_utf16 (fn_in, fn_utf16) == 0)
1310 {
c3e9160b
EZ
1311 int result;
1312 int codepage = codepage_for_filenames (NULL);
03d58cca 1313
c3e9160b 1314 result = WideCharToMultiByte (codepage, 0, fn_utf16, -1,
80fcb9d2 1315 fn_out, MAX_PATH, NULL, NULL);
03d58cca
EZ
1316 if (!result)
1317 {
1318 DWORD err = GetLastError ();
1319
1320 switch (err)
1321 {
1322 case ERROR_INVALID_FLAGS:
1323 case ERROR_INVALID_PARAMETER:
1324 errno = EINVAL;
1325 break;
1326 case ERROR_INSUFFICIENT_BUFFER:
1327 case ERROR_NO_UNICODE_TRANSLATION:
1328 default:
1329 errno = ENOENT;
1330 break;
1331 }
1332 return -1;
1333 }
1334 return 0;
1335 }
c3e9160b 1336 return -1;
03d58cca
EZ
1337}
1338
1fd201bb 1339int
03d58cca
EZ
1340filename_from_ansi (const char *fn_in, char *fn_out)
1341{
80fcb9d2 1342 wchar_t fn_utf16[MAX_PATH];
c3e9160b
EZ
1343 int codepage = codepage_for_filenames (NULL);
1344 int result = MultiByteToWideChar (codepage, MB_ERR_INVALID_CHARS, fn_in, -1,
1345 fn_utf16, MAX_PATH);
1346
1347 if (!result)
1348 {
1349 DWORD err = GetLastError ();
1350
1351 switch (err)
1352 {
1353 case ERROR_INVALID_FLAGS:
1354 case ERROR_INVALID_PARAMETER:
1355 errno = EINVAL;
1356 break;
1357 case ERROR_INSUFFICIENT_BUFFER:
1358 case ERROR_NO_UNICODE_TRANSLATION:
1359 default:
1360 errno = ENOENT;
1361 break;
1362 }
1363 return -1;
1364 }
1365 return filename_from_utf16 (fn_utf16, fn_out);
03d58cca
EZ
1366}
1367
1368\f
1369
5c4a19a9 1370/* The directory where we started, in UTF-8. */
03d58cca 1371static char startup_dir[MAX_UTF8_PATH];
00b3b7b3 1372
95ed0025 1373/* Get the current working directory. */
480b0c5b 1374char *
ec84768f 1375getcwd (char *dir, int dirsize)
95ed0025 1376{
9239d970
PE
1377 if (!dirsize)
1378 {
1379 errno = EINVAL;
1380 return NULL;
1381 }
1382 if (dirsize <= strlen (startup_dir))
1383 {
1384 errno = ERANGE;
1385 return NULL;
1386 }
76b3903d 1387#if 0
480b0c5b
GV
1388 if (GetCurrentDirectory (MAXPATHLEN, dir) > 0)
1389 return dir;
1390 return NULL;
76b3903d 1391#else
8d38f461
EZ
1392 /* Emacs doesn't actually change directory itself, it stays in the
1393 same directory where it was started. */
76b3903d
GV
1394 strcpy (dir, startup_dir);
1395 return dir;
1396#endif
95ed0025
RS
1397}
1398
95ed0025 1399/* Emulate getloadavg. */
ad9e2d54
EZ
1400
1401struct load_sample {
1402 time_t sample_time;
1403 ULONGLONG idle;
1404 ULONGLONG kernel;
1405 ULONGLONG user;
1406};
1407
1408/* Number of processors on this machine. */
1409static unsigned num_of_processors;
1410
1411/* We maintain 1-sec samples for the last 16 minutes in a circular buffer. */
1412static struct load_sample samples[16*60];
1413static int first_idx = -1, last_idx = -1;
1414static int max_idx = sizeof (samples) / sizeof (samples[0]);
1415
1416static int
1417buf_next (int from)
1418{
1419 int next_idx = from + 1;
1420
1421 if (next_idx >= max_idx)
1422 next_idx = 0;
1423
1424 return next_idx;
1425}
1426
1427static int
1428buf_prev (int from)
1429{
1430 int prev_idx = from - 1;
1431
1432 if (prev_idx < 0)
1433 prev_idx = max_idx - 1;
1434
1435 return prev_idx;
1436}
1437
1438static void
1439sample_system_load (ULONGLONG *idle, ULONGLONG *kernel, ULONGLONG *user)
1440{
1441 SYSTEM_INFO sysinfo;
1442 FILETIME ft_idle, ft_user, ft_kernel;
1443
1444 /* Initialize the number of processors on this machine. */
1445 if (num_of_processors <= 0)
1446 {
1447 get_native_system_info (&sysinfo);
1448 num_of_processors = sysinfo.dwNumberOfProcessors;
1449 if (num_of_processors <= 0)
1450 {
1451 GetSystemInfo (&sysinfo);
1452 num_of_processors = sysinfo.dwNumberOfProcessors;
1453 }
1454 if (num_of_processors <= 0)
1455 num_of_processors = 1;
1456 }
1457
1458 /* TODO: Take into account threads that are ready to run, by
1459 sampling the "\System\Processor Queue Length" performance
1460 counter. The code below accounts only for threads that are
1461 actually running. */
1462
1463 if (get_system_times (&ft_idle, &ft_kernel, &ft_user))
1464 {
1465 ULARGE_INTEGER uidle, ukernel, uuser;
1466
1467 memcpy (&uidle, &ft_idle, sizeof (ft_idle));
1468 memcpy (&ukernel, &ft_kernel, sizeof (ft_kernel));
1469 memcpy (&uuser, &ft_user, sizeof (ft_user));
1470 *idle = uidle.QuadPart;
1471 *kernel = ukernel.QuadPart;
1472 *user = uuser.QuadPart;
1473 }
1474 else
1475 {
1476 *idle = 0;
1477 *kernel = 0;
1478 *user = 0;
1479 }
1480}
1481
1482/* Produce the load average for a given time interval, using the
1483 samples in the samples[] array. WHICH can be 0, 1, or 2, meaning
1484 1-minute, 5-minute, or 15-minute average, respectively. */
1485static double
1486getavg (int which)
1487{
1488 double retval = -1.0;
1489 double tdiff;
1490 int idx;
1491 double span = (which == 0 ? 1.0 : (which == 1 ? 5.0 : 15.0)) * 60;
1492 time_t now = samples[last_idx].sample_time;
1493
1494 if (first_idx != last_idx)
1495 {
1496 for (idx = buf_prev (last_idx); ; idx = buf_prev (idx))
1497 {
1498 tdiff = difftime (now, samples[idx].sample_time);
1499 if (tdiff >= span - 2*DBL_EPSILON*now)
1500 {
1501 long double sys =
1502 samples[last_idx].kernel + samples[last_idx].user
1503 - (samples[idx].kernel + samples[idx].user);
1504 long double idl = samples[last_idx].idle - samples[idx].idle;
1505
1506 retval = (1.0 - idl / sys) * num_of_processors;
1507 break;
1508 }
1509 if (idx == first_idx)
1510 break;
1511 }
1512 }
1513
1514 return retval;
1515}
1516
95ed0025
RS
1517int
1518getloadavg (double loadavg[], int nelem)
1519{
ad9e2d54
EZ
1520 int elem;
1521 ULONGLONG idle, kernel, user;
1522 time_t now = time (NULL);
1523
1524 /* Store another sample. We ignore samples that are less than 1 sec
1525 apart. */
1526 if (difftime (now, samples[last_idx].sample_time) >= 1.0 - 2*DBL_EPSILON*now)
1527 {
1528 sample_system_load (&idle, &kernel, &user);
1529 last_idx = buf_next (last_idx);
1530 samples[last_idx].sample_time = now;
1531 samples[last_idx].idle = idle;
1532 samples[last_idx].kernel = kernel;
1533 samples[last_idx].user = user;
1534 /* If the buffer has more that 15 min worth of samples, discard
1535 the old ones. */
1536 if (first_idx == -1)
1537 first_idx = last_idx;
1538 while (first_idx != last_idx
1539 && (difftime (now, samples[first_idx].sample_time)
1540 >= 15.0*60 + 2*DBL_EPSILON*now))
1541 first_idx = buf_next (first_idx);
1542 }
95ed0025 1543
ad9e2d54 1544 for (elem = 0; elem < nelem; elem++)
95ed0025 1545 {
ad9e2d54
EZ
1546 double avg = getavg (elem);
1547
1548 if (avg < 0)
1549 break;
1550 loadavg[elem] = avg;
95ed0025 1551 }
ad9e2d54
EZ
1552
1553 return elem;
95ed0025
RS
1554}
1555
480b0c5b 1556/* Emulate getpwuid, getpwnam and others. */
95ed0025 1557
051fe60d
GV
1558#define PASSWD_FIELD_SIZE 256
1559
07f7980a
EZ
1560static char dflt_passwd_name[PASSWD_FIELD_SIZE];
1561static char dflt_passwd_passwd[PASSWD_FIELD_SIZE];
1562static char dflt_passwd_gecos[PASSWD_FIELD_SIZE];
5c4a19a9
EZ
1563static char dflt_passwd_dir[MAX_UTF8_PATH];
1564static char dflt_passwd_shell[MAX_UTF8_PATH];
95ed0025 1565
07f7980a 1566static struct passwd dflt_passwd =
95ed0025 1567{
07f7980a
EZ
1568 dflt_passwd_name,
1569 dflt_passwd_passwd,
95ed0025
RS
1570 0,
1571 0,
1572 0,
07f7980a
EZ
1573 dflt_passwd_gecos,
1574 dflt_passwd_dir,
1575 dflt_passwd_shell,
95ed0025
RS
1576};
1577
07f7980a
EZ
1578static char dflt_group_name[GNLEN+1];
1579
1580static struct group dflt_group =
3d19b645 1581{
07f7980a
EZ
1582 /* When group information is not available, we return this as the
1583 group for all files. */
1584 dflt_group_name,
1585 0,
3d19b645
LH
1586};
1587
22749e9a 1588unsigned
b56ceb92 1589getuid (void)
177c0ea7 1590{
07f7980a 1591 return dflt_passwd.pw_uid;
480b0c5b
GV
1592}
1593
22749e9a 1594unsigned
b56ceb92 1595geteuid (void)
177c0ea7 1596{
480b0c5b
GV
1597 /* I could imagine arguing for checking to see whether the user is
1598 in the Administrators group and returning a UID of 0 for that
1599 case, but I don't know how wise that would be in the long run. */
177c0ea7 1600 return getuid ();
480b0c5b
GV
1601}
1602
22749e9a 1603unsigned
b56ceb92 1604getgid (void)
177c0ea7 1605{
07f7980a 1606 return dflt_passwd.pw_gid;
480b0c5b
GV
1607}
1608
22749e9a 1609unsigned
b56ceb92 1610getegid (void)
177c0ea7 1611{
480b0c5b
GV
1612 return getgid ();
1613}
1614
95ed0025 1615struct passwd *
22749e9a 1616getpwuid (unsigned uid)
95ed0025 1617{
07f7980a
EZ
1618 if (uid == dflt_passwd.pw_uid)
1619 return &dflt_passwd;
480b0c5b 1620 return NULL;
95ed0025
RS
1621}
1622
3d19b645
LH
1623struct group *
1624getgrgid (gid_t gid)
1625{
07f7980a 1626 return &dflt_group;
3d19b645
LH
1627}
1628
95ed0025
RS
1629struct passwd *
1630getpwnam (char *name)
1631{
1632 struct passwd *pw;
177c0ea7 1633
95ed0025
RS
1634 pw = getpwuid (getuid ());
1635 if (!pw)
1636 return pw;
1637
05131107 1638 if (xstrcasecmp (name, pw->pw_name))
95ed0025
RS
1639 return NULL;
1640
1641 return pw;
1642}
1643
bedf4aab 1644static void
b56ceb92 1645init_user_info (void)
95ed0025 1646{
480b0c5b
GV
1647 /* Find the user's real name by opening the process token and
1648 looking up the name associated with the user-sid in that token.
1649
1650 Use the relative portion of the identifier authority value from
1651 the user-sid as the user id value (same for group id using the
1652 primary group sid from the process token). */
1653
07f7980a 1654 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
32cef06e 1655 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
07f7980a 1656 DWORD glength = sizeof (gname);
10aabbf9
JB
1657 HANDLE token = NULL;
1658 SID_NAME_USE user_type;
32cef06e
EZ
1659 unsigned char *buf = NULL;
1660 DWORD blen = 0;
634d3003
EZ
1661 TOKEN_USER user_token;
1662 TOKEN_PRIMARY_GROUP group_token;
32cef06e 1663 BOOL result;
10aabbf9 1664
32cef06e
EZ
1665 result = open_process_token (GetCurrentProcess (), TOKEN_QUERY, &token);
1666 if (result)
1667 {
1668 result = get_token_information (token, TokenUser, NULL, 0, &blen);
1669 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1670 {
1671 buf = xmalloc (blen);
1672 result = get_token_information (token, TokenUser,
1673 (LPVOID)buf, blen, &needed);
1674 if (result)
1675 {
1676 memcpy (&user_token, buf, sizeof (user_token));
1677 result = lookup_account_sid (NULL, user_token.User.Sid,
1678 uname, &ulength,
1679 domain, &dlength, &user_type);
1680 }
1681 }
1682 else
1683 result = FALSE;
1684 }
1685 if (result)
d1c1c3d2 1686 {
07f7980a 1687 strcpy (dflt_passwd.pw_name, uname);
c617afce 1688 /* Determine a reasonable uid value. */
05131107 1689 if (xstrcasecmp ("administrator", uname) == 0)
480b0c5b 1690 {
07f7980a
EZ
1691 dflt_passwd.pw_uid = 500; /* well-known Administrator uid */
1692 dflt_passwd.pw_gid = 513; /* well-known None gid */
480b0c5b
GV
1693 }
1694 else
1695 {
ce0ee994
EZ
1696 /* Use the last sub-authority value of the RID, the relative
1697 portion of the SID, as user/group ID. */
8aaaec6b 1698 dflt_passwd.pw_uid = get_rid (user_token.User.Sid);
480b0c5b 1699
8aaaec6b 1700 /* Get group id and name. */
32cef06e
EZ
1701 result = get_token_information (token, TokenPrimaryGroup,
1702 (LPVOID)buf, blen, &needed);
1703 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
1704 {
1705 buf = xrealloc (buf, blen = needed);
1706 result = get_token_information (token, TokenPrimaryGroup,
1707 (LPVOID)buf, blen, &needed);
1708 }
1709 if (result)
480b0c5b 1710 {
634d3003 1711 memcpy (&group_token, buf, sizeof (group_token));
8aaaec6b 1712 dflt_passwd.pw_gid = get_rid (group_token.PrimaryGroup);
07f7980a 1713 dlength = sizeof (domain);
32cef06e
EZ
1714 /* If we can get at the real Primary Group name, use that.
1715 Otherwise, the default group name was already set to
1716 "None" in globals_of_w32. */
07f7980a
EZ
1717 if (lookup_account_sid (NULL, group_token.PrimaryGroup,
1718 gname, &glength, NULL, &dlength,
1719 &user_type))
1720 strcpy (dflt_group_name, gname);
480b0c5b
GV
1721 }
1722 else
07f7980a 1723 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
480b0c5b
GV
1724 }
1725 }
1726 /* If security calls are not supported (presumably because we
32cef06e 1727 are running under Windows 9X), fallback to this: */
07f7980a 1728 else if (GetUserName (uname, &ulength))
480b0c5b 1729 {
07f7980a 1730 strcpy (dflt_passwd.pw_name, uname);
05131107 1731 if (xstrcasecmp ("administrator", uname) == 0)
07f7980a 1732 dflt_passwd.pw_uid = 0;
480b0c5b 1733 else
07f7980a
EZ
1734 dflt_passwd.pw_uid = 123;
1735 dflt_passwd.pw_gid = dflt_passwd.pw_uid;
480b0c5b
GV
1736 }
1737 else
1738 {
07f7980a
EZ
1739 strcpy (dflt_passwd.pw_name, "unknown");
1740 dflt_passwd.pw_uid = 123;
1741 dflt_passwd.pw_gid = 123;
d1c1c3d2 1742 }
07f7980a 1743 dflt_group.gr_gid = dflt_passwd.pw_gid;
95ed0025 1744
480b0c5b 1745 /* Set dir and shell from environment variables. */
5c4a19a9
EZ
1746 if (w32_unicode_filenames)
1747 {
1748 wchar_t *home = _wgetenv (L"HOME");
1749 wchar_t *shell = _wgetenv (L"SHELL");
1750
1751 /* Ensure HOME and SHELL are defined. */
1752 if (home == NULL)
1753 emacs_abort ();
1754 if (shell == NULL)
1755 emacs_abort ();
1756 filename_from_utf16 (home, dflt_passwd.pw_dir);
1757 filename_from_utf16 (shell, dflt_passwd.pw_shell);
1758 }
1759 else
1760 {
1761 char *home = getenv ("HOME");
1762 char *shell = getenv ("SHELL");
1763
1764 if (home == NULL)
1765 emacs_abort ();
1766 if (shell == NULL)
1767 emacs_abort ();
1768 filename_from_ansi (home, dflt_passwd.pw_dir);
1769 filename_from_ansi (shell, dflt_passwd.pw_shell);
1770 }
bd4a449f 1771
32cef06e 1772 xfree (buf);
480b0c5b
GV
1773 if (token)
1774 CloseHandle (token);
95ed0025
RS
1775}
1776
95ed0025 1777int
b56ceb92 1778random (void)
95ed0025 1779{
480b0c5b
GV
1780 /* rand () on NT gives us 15 random bits...hack together 30 bits. */
1781 return ((rand () << 15) | rand ());
95ed0025
RS
1782}
1783
95ed0025 1784void
480b0c5b 1785srandom (int seed)
95ed0025 1786{
480b0c5b 1787 srand (seed);
95ed0025
RS
1788}
1789
6d2851de
EZ
1790/* Return the maximum length in bytes of a multibyte character
1791 sequence encoded in the current ANSI codepage. This is required to
1792 correctly walk the encoded file names one character at a time. */
1793static int
1794max_filename_mbslen (void)
1795{
c3e9160b 1796 CPINFO cp_info;
6d2851de 1797
c3e9160b
EZ
1798 codepage_for_filenames (&cp_info);
1799 return cp_info.MaxCharSize;
6d2851de 1800}
76b3903d 1801
1fd201bb
EZ
1802/* Normalize filename by converting in-place all of its path
1803 separators to the separator specified by PATH_SEP. */
cbe39279
RS
1804
1805static void
1fd201bb 1806normalize_filename (register char *fp, char path_sep)
cbe39279 1807{
1fd201bb 1808 char *p2;
e7ac588e 1809
5162ffce
MB
1810 /* Always lower-case drive letters a-z, even if the filesystem
1811 preserves case in filenames.
1812 This is so filenames can be compared by string comparison
1813 functions that are case-sensitive. Even case-preserving filesystems
1814 do not distinguish case in drive letters. */
1fd201bb 1815 p2 = fp + 1;
6d2851de
EZ
1816
1817 if (*p2 == ':' && *fp >= 'A' && *fp <= 'Z')
5162ffce
MB
1818 {
1819 *fp += 'a' - 'A';
1820 fp += 2;
1821 }
1822
1fd201bb 1823 while (*fp)
cbe39279 1824 {
1fd201bb
EZ
1825 if (*fp == '/' || *fp == '\\')
1826 *fp = path_sep;
1827 fp++;
cbe39279 1828 }
cbe39279
RS
1829}
1830
1fd201bb 1831/* Destructively turn backslashes into slashes. */
95ed0025 1832void
1fd201bb 1833dostounix_filename (register char *p)
95ed0025 1834{
1fd201bb 1835 normalize_filename (p, '/');
95ed0025
RS
1836}
1837
480b0c5b 1838/* Destructively turn slashes into backslashes. */
95ed0025 1839void
b56ceb92 1840unixtodos_filename (register char *p)
95ed0025 1841{
1fd201bb 1842 normalize_filename (p, '\\');
95ed0025
RS
1843}
1844
480b0c5b
GV
1845/* Remove all CR's that are followed by a LF.
1846 (From msdos.c...probably should figure out a way to share it,
1847 although this code isn't going to ever change.) */
bedf4aab 1848static int
b56ceb92 1849crlf_to_lf (register int n, register unsigned char *buf)
35f0d482 1850{
480b0c5b
GV
1851 unsigned char *np = buf;
1852 unsigned char *startp = buf;
1853 unsigned char *endp = buf + n;
35f0d482 1854
480b0c5b
GV
1855 if (n == 0)
1856 return n;
1857 while (buf < endp - 1)
95ed0025 1858 {
480b0c5b
GV
1859 if (*buf == 0x0d)
1860 {
1861 if (*(++buf) != 0x0a)
1862 *np++ = 0x0d;
1863 }
1864 else
1865 *np++ = *buf++;
95ed0025 1866 }
480b0c5b
GV
1867 if (buf < endp)
1868 *np++ = *buf++;
1869 return np - startp;
95ed0025
RS
1870}
1871
76b3903d
GV
1872/* Parse the root part of file name, if present. Return length and
1873 optionally store pointer to char after root. */
1874static int
f5441ba4 1875parse_root (const char * name, const char ** pPath)
76b3903d 1876{
f5441ba4 1877 const char * start = name;
76b3903d
GV
1878
1879 if (name == NULL)
1880 return 0;
1881
1882 /* find the root name of the volume if given */
1883 if (isalpha (name[0]) && name[1] == ':')
1884 {
1885 /* skip past drive specifier */
1886 name += 2;
1887 if (IS_DIRECTORY_SEP (name[0]))
1888 name++;
1889 }
1890 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
1891 {
1892 int slashes = 2;
806fed21 1893
76b3903d
GV
1894 name += 2;
1895 do
1896 {
1897 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
1898 break;
1fd201bb 1899 name++;
76b3903d
GV
1900 }
1901 while ( *name );
1902 if (IS_DIRECTORY_SEP (name[0]))
1903 name++;
1904 }
1905
1906 if (pPath)
1907 *pPath = name;
1908
1909 return name - start;
1910}
1911
1912/* Get long base name for name; name is assumed to be absolute. */
1913static int
1914get_long_basename (char * name, char * buf, int size)
1915{
76b3903d 1916 HANDLE dir_handle;
1fd201bb 1917 char fname_utf8[MAX_UTF8_PATH];
76b3903d 1918 int len = 0;
1fd201bb 1919 int cstatus;
76b3903d 1920
1fd201bb
EZ
1921 /* Must be valid filename, no wild cards or other invalid characters. */
1922 if (strpbrk (name, "*?|<>\""))
bb1584c8
RS
1923 return 0;
1924
1fd201bb 1925 if (w32_unicode_filenames)
76b3903d 1926 {
1fd201bb
EZ
1927 wchar_t fname_utf16[MAX_PATH];
1928 WIN32_FIND_DATAW find_data_wide;
1929
1930 filename_to_utf16 (name, fname_utf16);
1931 dir_handle = FindFirstFileW (fname_utf16, &find_data_wide);
1932 if (dir_handle != INVALID_HANDLE_VALUE)
1933 cstatus = filename_from_utf16 (find_data_wide.cFileName, fname_utf8);
1934 }
1935 else
1936 {
1937 char fname_ansi[MAX_PATH];
1938 WIN32_FIND_DATAA find_data_ansi;
1939
1940 filename_to_ansi (name, fname_ansi);
1941 dir_handle = FindFirstFileA (fname_ansi, &find_data_ansi);
1942 if (dir_handle != INVALID_HANDLE_VALUE)
1943 cstatus = filename_from_ansi (find_data_ansi.cFileName, fname_utf8);
76b3903d 1944 }
1fd201bb
EZ
1945
1946 if (cstatus == 0 && (len = strlen (fname_utf8)) < size)
1947 memcpy (buf, fname_utf8, len + 1);
1948 else
1949 len = 0;
1950
1951 if (dir_handle != INVALID_HANDLE_VALUE)
1952 FindClose (dir_handle);
1953
76b3903d
GV
1954 return len;
1955}
1956
1957/* Get long name for file, if possible (assumed to be absolute). */
1958BOOL
1959w32_get_long_filename (char * name, char * buf, int size)
1960{
1961 char * o = buf;
1962 char * p;
f5441ba4 1963 const char * q;
1fd201bb 1964 char full[ MAX_UTF8_PATH ];
76b3903d
GV
1965 int len;
1966
1967 len = strlen (name);
1fd201bb 1968 if (len >= MAX_UTF8_PATH)
76b3903d
GV
1969 return FALSE;
1970
1971 /* Use local copy for destructive modification. */
1972 memcpy (full, name, len+1);
1973 unixtodos_filename (full);
1974
1975 /* Copy root part verbatim. */
f5441ba4 1976 len = parse_root (full, (const char **)&p);
76b3903d
GV
1977 memcpy (o, full, len);
1978 o += len;
4f8ac0b2 1979 *o = '\0';
76b3903d
GV
1980 size -= len;
1981
4f8ac0b2 1982 while (p != NULL && *p)
76b3903d
GV
1983 {
1984 q = p;
1fd201bb 1985 p = strchr (q, '\\');
76b3903d
GV
1986 if (p) *p = '\0';
1987 len = get_long_basename (full, o, size);
1988 if (len > 0)
1989 {
1990 o += len;
1991 size -= len;
1992 if (p != NULL)
1993 {
1994 *p++ = '\\';
1995 if (size < 2)
1996 return FALSE;
1997 *o++ = '\\';
1998 size--;
1999 *o = '\0';
2000 }
2001 }
2002 else
2003 return FALSE;
2004 }
76b3903d
GV
2005
2006 return TRUE;
2007}
2008
1fd201bb
EZ
2009unsigned int
2010w32_get_short_filename (char * name, char * buf, int size)
2011{
2012 if (w32_unicode_filenames)
2013 {
2014 wchar_t name_utf16[MAX_PATH], short_name[MAX_PATH];
2015 unsigned int retval;
2016
2017 filename_to_utf16 (name, name_utf16);
2018 retval = GetShortPathNameW (name_utf16, short_name, size);
2019 if (retval && retval < size)
2020 filename_from_utf16 (short_name, buf);
2021 return retval;
2022 }
2023 else
2024 {
2025 char name_ansi[MAX_PATH];
2026
2027 filename_to_ansi (name, name_ansi);
2028 return GetShortPathNameA (name_ansi, buf, size);
2029 }
2030}
2031
bedf4aab 2032static int
9d3355d1
GV
2033is_unc_volume (const char *filename)
2034{
2035 const char *ptr = filename;
2036
2037 if (!IS_DIRECTORY_SEP (ptr[0]) || !IS_DIRECTORY_SEP (ptr[1]) || !ptr[2])
2038 return 0;
2039
b1846422 2040 if (strpbrk (ptr + 2, "*?|<>\"\\/"))
9d3355d1
GV
2041 return 0;
2042
2043 return 1;
2044}
76b3903d 2045
75ceee05
EZ
2046/* Emulate the Posix unsetenv. */
2047int
2048unsetenv (const char *name)
2049{
2050 char *var;
2051 size_t name_len;
2052 int retval;
2053
2054 if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
2055 {
2056 errno = EINVAL;
2057 return -1;
2058 }
2059 name_len = strlen (name);
2060 /* MS docs says an environment variable cannot be longer than 32K. */
2061 if (name_len > 32767)
2062 {
2063 errno = ENOMEM;
a16e75cd 2064 return 0;
75ceee05
EZ
2065 }
2066 /* It is safe to use 'alloca' with 32K size, since the stack is at
2067 least 2MB, and we set it to 8MB in the link command line. */
2068 var = alloca (name_len + 2);
a7f11948 2069 strncpy (var, name, name_len);
75ceee05
EZ
2070 var[name_len++] = '=';
2071 var[name_len] = '\0';
2072 return _putenv (var);
2073}
2074
2075/* MS _putenv doesn't support removing a variable when the argument
2076 does not include the '=' character, so we fix that here. */
2077int
2078sys_putenv (char *str)
2079{
2080 const char *const name_end = strchr (str, '=');
2081
2082 if (name_end == NULL)
2083 {
2084 /* Remove the variable from the environment. */
2085 return unsetenv (str);
2086 }
2087
2088 return _putenv (str);
2089}
2090
480b0c5b 2091#define REG_ROOT "SOFTWARE\\GNU\\Emacs"
f332b293 2092
177c0ea7 2093LPBYTE
b56ceb92 2094w32_get_resource (char *key, LPDWORD lpdwtype)
f332b293
GV
2095{
2096 LPBYTE lpvalue;
2097 HKEY hrootkey = NULL;
2098 DWORD cbData;
177c0ea7
JB
2099
2100 /* Check both the current user and the local machine to see if
f332b293 2101 we have any resources. */
177c0ea7 2102
f332b293
GV
2103 if (RegOpenKeyEx (HKEY_CURRENT_USER, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2104 {
2105 lpvalue = NULL;
2106
177c0ea7 2107 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
23f86fce 2108 && (lpvalue = xmalloc (cbData)) != NULL
f332b293
GV
2109 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
2110 {
4da4d9bb 2111 RegCloseKey (hrootkey);
f332b293
GV
2112 return (lpvalue);
2113 }
2114
70fdbb46 2115 xfree (lpvalue);
177c0ea7 2116
f332b293 2117 RegCloseKey (hrootkey);
177c0ea7
JB
2118 }
2119
f332b293
GV
2120 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, REG_ROOT, 0, KEY_READ, &hrootkey) == ERROR_SUCCESS)
2121 {
2122 lpvalue = NULL;
177c0ea7 2123
76b3903d 2124 if (RegQueryValueEx (hrootkey, key, NULL, NULL, NULL, &cbData) == ERROR_SUCCESS
23f86fce 2125 && (lpvalue = xmalloc (cbData)) != NULL
76b3903d 2126 && RegQueryValueEx (hrootkey, key, NULL, lpdwtype, lpvalue, &cbData) == ERROR_SUCCESS)
f332b293 2127 {
4da4d9bb 2128 RegCloseKey (hrootkey);
f332b293
GV
2129 return (lpvalue);
2130 }
177c0ea7 2131
70fdbb46 2132 xfree (lpvalue);
177c0ea7 2133
f332b293 2134 RegCloseKey (hrootkey);
177c0ea7
JB
2135 }
2136
f332b293
GV
2137 return (NULL);
2138}
2139
2140void
aa7b87b0 2141init_environment (char ** argv)
f332b293 2142{
b3308d2e
KH
2143 static const char * const tempdirs[] = {
2144 "$TMPDIR", "$TEMP", "$TMP", "c:/"
2145 };
2d5324c5 2146
b3308d2e 2147 int i;
2d5324c5 2148
b3308d2e
KH
2149 const int imax = sizeof (tempdirs) / sizeof (tempdirs[0]);
2150
b1846422
EZ
2151 /* Implementation note: This function explicitly works with ANSI
2152 file names, not with UTF-8 encoded file names. This is because
2153 this function pushes variables into the Emacs's environment, and
2154 the environment variables are always assumed to be in the
2155 locale-specific encoding. Do NOT call any functions that accept
2156 UTF-8 file names from this function! */
2157
b3308d2e
KH
2158 /* Make sure they have a usable $TMPDIR. Many Emacs functions use
2159 temporary files and assume "/tmp" if $TMPDIR is unset, which
2160 will break on DOS/Windows. Refuse to work if we cannot find
2161 a directory, not even "c:/", usable for that purpose. */
2162 for (i = 0; i < imax ; i++)
2163 {
2164 const char *tmp = tempdirs[i];
2165
2166 if (*tmp == '$')
2167 tmp = getenv (tmp + 1);
2168 /* Note that `access' can lie to us if the directory resides on a
2169 read-only filesystem, like CD-ROM or a write-protected floppy.
2170 The only way to be really sure is to actually create a file and
2171 see if it succeeds. But I think that's too much to ask. */
6dad7178 2172
b1846422
EZ
2173 /* MSVCRT's _access crashes with D_OK, so we use our replacement. */
2174 if (tmp && sys_access (tmp, D_OK) == 0)
b3308d2e
KH
2175 {
2176 char * var = alloca (strlen (tmp) + 8);
2177 sprintf (var, "TMPDIR=%s", tmp);
aca583b2 2178 _putenv (strdup (var));
b3308d2e
KH
2179 break;
2180 }
2181 }
2182 if (i >= imax)
2183 cmd_error_internal
2184 (Fcons (Qerror,
2185 Fcons (build_string ("no usable temporary directories found!!"),
2186 Qnil)),
2187 "While setting TMPDIR: ");
2188
ca149beb
AI
2189 /* Check for environment variables and use registry settings if they
2190 don't exist. Fallback on default values where applicable. */
f332b293 2191 {
480b0c5b
GV
2192 int i;
2193 LPBYTE lpval;
2194 DWORD dwType;
69fb0241 2195 char locale_name[32];
2d5324c5 2196 char default_home[MAX_PATH];
fdc5744d 2197 int appdata = 0;
f332b293 2198
e00b99c8 2199 static const struct env_entry
ca149beb
AI
2200 {
2201 char * name;
2202 char * def_value;
e00b99c8 2203 } dflt_envvars[] =
ca149beb 2204 {
76151e2c
EZ
2205 /* If the default value is NULL, we will use the value from the
2206 outside environment or the Registry, but will not push the
2207 variable into the Emacs environment if it is defined neither
2208 in the Registry nor in the outside environment. */
ca149beb
AI
2209 {"HOME", "C:/"},
2210 {"PRELOAD_WINSOCK", NULL},
2211 {"emacs_dir", "C:/emacs"},
76151e2c 2212 {"EMACSLOADPATH", NULL},
7d9fb4de 2213 {"SHELL", "cmdproxy.exe"}, /* perhaps it is somewhere on PATH */
76151e2c
EZ
2214 {"EMACSDATA", NULL},
2215 {"EMACSPATH", NULL},
2216 {"INFOPATH", NULL},
2217 {"EMACSDOC", NULL},
69fb0241
JR
2218 {"TERM", "cmd"},
2219 {"LANG", NULL},
480b0c5b
GV
2220 };
2221
ed3751c8 2222#define N_ENV_VARS sizeof (dflt_envvars)/sizeof (dflt_envvars[0])
e00b99c8
EZ
2223
2224 /* We need to copy dflt_envvars[] and work on the copy because we
2225 don't want the dumped Emacs to inherit the values of
2226 environment variables we saw during dumping (which could be on
2227 a different system). The defaults above must be left intact. */
2228 struct env_entry env_vars[N_ENV_VARS];
2229
2230 for (i = 0; i < N_ENV_VARS; i++)
2231 env_vars[i] = dflt_envvars[i];
2232
2d5324c5
JR
2233 /* For backwards compatibility, check if a .emacs file exists in C:/
2234 If not, then we can try to default to the appdata directory under the
2235 user's profile, which is more likely to be writable. */
b1846422 2236 if (sys_access ("C:/.emacs", F_OK) != 0)
94eab1c8
JB
2237 {
2238 HRESULT profile_result;
2239 /* Dynamically load ShGetFolderPath, as it won't exist on versions
2240 of Windows 95 and NT4 that have not been updated to include
2241 MSIE 5. */
2242 ShGetFolderPath_fn get_folder_path;
2243 get_folder_path = (ShGetFolderPath_fn)
2244 GetProcAddress (GetModuleHandle ("shell32.dll"), "SHGetFolderPathA");
2245
2246 if (get_folder_path != NULL)
2247 {
2248 profile_result = get_folder_path (NULL, CSIDL_APPDATA, NULL,
2249 0, default_home);
2d5324c5 2250
94eab1c8
JB
2251 /* If we can't get the appdata dir, revert to old behavior. */
2252 if (profile_result == S_OK)
fdc5744d
JB
2253 {
2254 env_vars[0].def_value = default_home;
2255 appdata = 1;
2256 }
94eab1c8
JB
2257 }
2258 }
2d5324c5 2259
69fb0241
JR
2260 /* Get default locale info and use it for LANG. */
2261 if (GetLocaleInfo (LOCALE_USER_DEFAULT,
2262 LOCALE_SABBREVLANGNAME | LOCALE_USE_CP_ACP,
2263 locale_name, sizeof (locale_name)))
2264 {
e00b99c8 2265 for (i = 0; i < N_ENV_VARS; i++)
69fb0241
JR
2266 {
2267 if (strcmp (env_vars[i].name, "LANG") == 0)
2268 {
2269 env_vars[i].def_value = locale_name;
2270 break;
2271 }
2272 }
2273 }
2274
ca149beb
AI
2275#define SET_ENV_BUF_SIZE (4 * MAX_PATH) /* to cover EMACSLOADPATH */
2276
2277 /* Treat emacs_dir specially: set it unconditionally based on our
76151e2c 2278 location. */
ca149beb
AI
2279 {
2280 char *p;
2281 char modname[MAX_PATH];
2282
2283 if (!GetModuleFileName (NULL, modname, MAX_PATH))
1088b922 2284 emacs_abort ();
6ee4509a 2285 if ((p = _mbsrchr (modname, '\\')) == NULL)
1088b922 2286 emacs_abort ();
ca149beb
AI
2287 *p = 0;
2288
7d9fb4de
EZ
2289 if ((p = _mbsrchr (modname, '\\'))
2290 /* From bin means installed Emacs, from src means uninstalled. */
2291 && (xstrcasecmp (p, "\\bin") == 0 || xstrcasecmp (p, "\\src") == 0))
ca149beb
AI
2292 {
2293 char buf[SET_ENV_BUF_SIZE];
7d9fb4de 2294 int within_build_tree = xstrcasecmp (p, "\\src") == 0;
ca149beb
AI
2295
2296 *p = 0;
6ee4509a 2297 for (p = modname; *p; p = CharNext (p))
ca149beb 2298 if (*p == '\\') *p = '/';
177c0ea7 2299
ed3751c8 2300 _snprintf (buf, sizeof (buf)-1, "emacs_dir=%s", modname);
a302c7ae 2301 _putenv (strdup (buf));
7d9fb4de
EZ
2302 /* If we are running from the Posix-like build tree, define
2303 SHELL to point to our own cmdproxy. The loop below will
2304 then disregard PATH_EXEC and the default value. */
2305 if (within_build_tree)
2306 {
2307 _snprintf (buf, sizeof (buf) - 1,
2308 "SHELL=%s/nt/cmdproxy.exe", modname);
2309 _putenv (strdup (buf));
2310 }
ca149beb
AI
2311 }
2312 }
2313
e00b99c8 2314 for (i = 0; i < N_ENV_VARS; i++)
f332b293 2315 {
ca149beb 2316 if (!getenv (env_vars[i].name))
480b0c5b 2317 {
ca149beb 2318 int dont_free = 0;
7d9fb4de 2319 char bufc[SET_ENV_BUF_SIZE];
480b0c5b 2320
aa5ee2a3
JB
2321 if ((lpval = w32_get_resource (env_vars[i].name, &dwType)) == NULL
2322 /* Also ignore empty environment variables. */
2323 || *lpval == 0)
ca149beb 2324 {
70fdbb46 2325 xfree (lpval);
ca149beb 2326 dont_free = 1;
7d9fb4de
EZ
2327 if (strcmp (env_vars[i].name, "SHELL") == 0)
2328 {
2329 /* Look for cmdproxy.exe in every directory in
2330 PATH_EXEC. FIXME: This does not find cmdproxy
2331 in nt/ when we run uninstalled. */
2332 char fname[MAX_PATH];
2333 const char *pstart = PATH_EXEC, *pend;
2334
2335 do {
2336 pend = _mbschr (pstart, ';');
2337 if (!pend)
2338 pend = pstart + strlen (pstart);
2339 /* Be defensive against series of ;;; characters. */
2340 if (pend > pstart)
2341 {
2342 strncpy (fname, pstart, pend - pstart);
2343 fname[pend - pstart] = '/';
2344 strcpy (&fname[pend - pstart + 1], "cmdproxy.exe");
2345 ExpandEnvironmentStrings ((LPSTR) fname, bufc,
2346 sizeof (bufc));
b1846422 2347 if (sys_access (bufc, F_OK) == 0)
7d9fb4de
EZ
2348 {
2349 lpval = bufc;
2350 dwType = REG_SZ;
2351 break;
2352 }
2353 }
2354 if (*pend)
2355 pstart = pend + 1;
2356 else
2357 pstart = pend;
2358 if (!*pstart)
2359 {
2360 /* If not found in any directory, use the
2361 default as the last resort. */
2362 lpval = env_vars[i].def_value;
2363 dwType = REG_EXPAND_SZ;
2364 }
2365 } while (*pstart);
2366 }
2367 else
2368 {
2369 lpval = env_vars[i].def_value;
2370 dwType = REG_EXPAND_SZ;
2371 }
2372 if (strcmp (env_vars[i].name, "HOME") == 0 && !appdata)
3438fe21
EZ
2373 Vdelayed_warnings_list
2374 = Fcons (listn (CONSTYPE_HEAP, 2,
073c88c2 2375 intern ("initialization"),
694b6c97 2376 build_string ("Setting HOME to C:\\ by default is deprecated")),
073c88c2 2377 Vdelayed_warnings_list);
480b0c5b 2378 }
ca149beb
AI
2379
2380 if (lpval)
480b0c5b 2381 {
892eb237 2382 char buf1[SET_ENV_BUF_SIZE], buf2[SET_ENV_BUF_SIZE];
ca149beb 2383
892eb237 2384 if (dwType == REG_EXPAND_SZ)
ed3751c8 2385 ExpandEnvironmentStrings ((LPSTR) lpval, buf1, sizeof (buf1));
ca149beb 2386 else if (dwType == REG_SZ)
892eb237
EZ
2387 strcpy (buf1, lpval);
2388 if (dwType == REG_EXPAND_SZ || dwType == REG_SZ)
ca149beb 2389 {
ed3751c8 2390 _snprintf (buf2, sizeof (buf2)-1, "%s=%s", env_vars[i].name,
892eb237
EZ
2391 buf1);
2392 _putenv (strdup (buf2));
ca149beb 2393 }
f332b293 2394
ca149beb
AI
2395 if (!dont_free)
2396 xfree (lpval);
2397 }
480b0c5b
GV
2398 }
2399 }
2400 }
2401
75b08edb
GV
2402 /* Rebuild system configuration to reflect invoking system. */
2403 Vsystem_configuration = build_string (EMACS_CONFIGURATION);
2404
76b3903d
GV
2405 /* Another special case: on NT, the PATH variable is actually named
2406 "Path" although cmd.exe (perhaps NT itself) arranges for
2407 environment variable lookup and setting to be case insensitive.
2408 However, Emacs assumes a fully case sensitive environment, so we
2409 need to change "Path" to "PATH" to match the expectations of
2410 various elisp packages. We do this by the sneaky method of
2411 modifying the string in the C runtime environ entry.
2412
2413 The same applies to COMSPEC. */
2414 {
2415 char ** envp;
2416
2417 for (envp = environ; *envp; envp++)
2418 if (_strnicmp (*envp, "PATH=", 5) == 0)
2419 memcpy (*envp, "PATH=", 5);
2420 else if (_strnicmp (*envp, "COMSPEC=", 8) == 0)
2421 memcpy (*envp, "COMSPEC=", 8);
2422 }
2423
9239d970 2424 /* Remember the initial working directory for getcwd. */
6dad7178
EZ
2425 /* FIXME: Do we need to resolve possible symlinks in startup_dir?
2426 Does it matter anywhere in Emacs? */
5c4a19a9
EZ
2427 if (w32_unicode_filenames)
2428 {
2429 wchar_t wstartup_dir[MAX_PATH];
2430
2431 if (!GetCurrentDirectoryW (MAX_PATH, wstartup_dir))
2432 emacs_abort ();
2433 filename_from_utf16 (wstartup_dir, startup_dir);
2434 }
2435 else
2436 {
2437 char astartup_dir[MAX_PATH];
2438
2439 if (!GetCurrentDirectoryA (MAX_PATH, astartup_dir))
2440 emacs_abort ();
2441 filename_from_ansi (astartup_dir, startup_dir);
2442 }
76b3903d
GV
2443
2444 {
aa7b87b0 2445 static char modname[MAX_PATH];
76b3903d
GV
2446
2447 if (!GetModuleFileName (NULL, modname, MAX_PATH))
1088b922 2448 emacs_abort ();
aa7b87b0 2449 argv[0] = modname;
76b3903d
GV
2450 }
2451
20af4831
JR
2452 /* Determine if there is a middle mouse button, to allow parse_button
2453 to decide whether right mouse events should be mouse-2 or
2454 mouse-3. */
e0c181dd 2455 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
20af4831 2456
480b0c5b
GV
2457 init_user_info ();
2458}
2459
6dad7178
EZ
2460/* Called from expand-file-name when default-directory is not a string. */
2461
bf794306
EZ
2462char *
2463emacs_root_dir (void)
2464{
b1846422 2465 static char root_dir[MAX_UTF8_PATH];
bf794306
EZ
2466 const char *p;
2467
2468 p = getenv ("emacs_dir");
2469 if (p == NULL)
1088b922 2470 emacs_abort ();
b1846422 2471 filename_from_ansi (p, root_dir);
bf794306 2472 root_dir[parse_root (root_dir, NULL)] = '\0';
1fd201bb 2473 dostounix_filename (root_dir);
bf794306
EZ
2474 return root_dir;
2475}
2476
35f0d482
KH
2477#include <sys/timeb.h>
2478
2479/* Emulate gettimeofday (Ulrich Leodolter, 1/11/95). */
97dababa 2480int
e2d8a6f0 2481gettimeofday (struct timeval *__restrict tv, struct timezone *__restrict tz)
35f0d482 2482{
6e602566 2483 struct _timeb tb;
35f0d482
KH
2484 _ftime (&tb);
2485
2486 tv->tv_sec = tb.time;
2487 tv->tv_usec = tb.millitm * 1000L;
97a93095
EZ
2488 /* Implementation note: _ftime sometimes doesn't update the dstflag
2489 according to the new timezone when the system timezone is
2490 changed. We could fix that by using GetSystemTime and
2491 GetTimeZoneInformation, but that doesn't seem necessary, since
2492 Emacs always calls gettimeofday with the 2nd argument NULL (see
e9a9ae03 2493 current_emacs_time). */
177c0ea7 2494 if (tz)
35f0d482
KH
2495 {
2496 tz->tz_minuteswest = tb.timezone; /* minutes west of Greenwich */
2497 tz->tz_dsttime = tb.dstflag; /* type of dst correction */
2498 }
97dababa 2499 return 0;
35f0d482 2500}
35f0d482 2501
388cdec0
EZ
2502/* Emulate fdutimens. */
2503
2504/* Set the access and modification time stamps of FD (a.k.a. FILE) to be
2505 TIMESPEC[0] and TIMESPEC[1], respectively.
2506 FD must be either negative -- in which case it is ignored --
2507 or a file descriptor that is open on FILE.
2508 If FD is nonnegative, then FILE can be NULL, which means
2509 use just futimes instead of utimes.
2510 If TIMESPEC is null, FAIL.
2511 Return 0 on success, -1 (setting errno) on failure. */
2512
2513int
2514fdutimens (int fd, char const *file, struct timespec const timespec[2])
2515{
388cdec0
EZ
2516 if (!timespec)
2517 {
2518 errno = ENOSYS;
2519 return -1;
2520 }
2521 if (fd < 0 && !file)
2522 {
2523 errno = EBADF;
2524 return -1;
2525 }
b34454d0
EZ
2526 /* _futime's prototype defines 2nd arg as having the type 'struct
2527 _utimbuf', while utime needs to accept 'struct utimbuf' for
2528 compatibility with Posix. So we need to use 2 different (but
2529 equivalent) types to avoid compiler warnings, sigh. */
388cdec0 2530 if (fd >= 0)
b34454d0
EZ
2531 {
2532 struct _utimbuf _ut;
2533
2534 _ut.actime = timespec[0].tv_sec;
2535 _ut.modtime = timespec[1].tv_sec;
2536 return _futime (fd, &_ut);
2537 }
388cdec0 2538 else
b34454d0
EZ
2539 {
2540 struct utimbuf ut;
2541
2542 ut.actime = timespec[0].tv_sec;
2543 ut.modtime = timespec[1].tv_sec;
2544 /* Call 'utime', which is implemented below, not the MS library
2545 function, which fails on directories. */
2546 return utime (file, &ut);
2547 }
388cdec0
EZ
2548}
2549
2550
480b0c5b 2551/* ------------------------------------------------------------------------- */
b46a6a83 2552/* IO support and wrapper functions for the Windows API. */
480b0c5b 2553/* ------------------------------------------------------------------------- */
95ed0025 2554
480b0c5b 2555/* Place a wrapper around the MSVC version of ctime. It returns NULL
177c0ea7 2556 on network directories, so we handle that case here.
480b0c5b
GV
2557 (Ulrich Leodolter, 1/11/95). */
2558char *
2559sys_ctime (const time_t *t)
2560{
2561 char *str = (char *) ctime (t);
2562 return (str ? str : "Sun Jan 01 00:00:00 1970");
2563}
2564
2565/* Emulate sleep...we could have done this with a define, but that
2566 would necessitate including windows.h in the files that used it.
2567 This is much easier. */
2568void
2569sys_sleep (int seconds)
2570{
2571 Sleep (seconds * 1000);
2572}
2573
76b3903d 2574/* Internal MSVC functions for low-level descriptor munging */
480b0c5b
GV
2575extern int __cdecl _set_osfhnd (int fd, long h);
2576extern int __cdecl _free_osfhnd (int fd);
2577
2578/* parallel array of private info on file handles */
2579filedesc fd_info [ MAXDESC ];
2580
76b3903d
GV
2581typedef struct volume_info_data {
2582 struct volume_info_data * next;
2583
2584 /* time when info was obtained */
2585 DWORD timestamp;
2586
2587 /* actual volume info */
2588 char * root_dir;
480b0c5b
GV
2589 DWORD serialnum;
2590 DWORD maxcomp;
2591 DWORD flags;
76b3903d
GV
2592 char * name;
2593 char * type;
2594} volume_info_data;
2595
2596/* Global referenced by various functions. */
2597static volume_info_data volume_info;
2598
2599/* Vector to indicate which drives are local and fixed (for which cached
2600 data never expires). */
2601static BOOL fixed_drives[26];
2602
2603/* Consider cached volume information to be stale if older than 10s,
2604 at least for non-local drives. Info for fixed drives is never stale. */
2605#define DRIVE_INDEX( c ) ( (c) <= 'Z' ? (c) - 'A' : (c) - 'a' )
2606#define VOLINFO_STILL_VALID( root_dir, info ) \
2607 ( ( isalpha (root_dir[0]) && \
2608 fixed_drives[ DRIVE_INDEX (root_dir[0]) ] ) \
2609 || GetTickCount () - info->timestamp < 10000 )
2610
2611/* Cache support functions. */
2612
2613/* Simple linked list with linear search is sufficient. */
2614static volume_info_data *volume_cache = NULL;
2615
2616static volume_info_data *
2617lookup_volume_info (char * root_dir)
2618{
2619 volume_info_data * info;
2620
2621 for (info = volume_cache; info; info = info->next)
05131107 2622 if (xstrcasecmp (info->root_dir, root_dir) == 0)
76b3903d
GV
2623 break;
2624 return info;
2625}
2626
2627static void
2628add_volume_info (char * root_dir, volume_info_data * info)
2629{
a302c7ae 2630 info->root_dir = xstrdup (root_dir);
f5441ba4 2631 unixtodos_filename (info->root_dir);
76b3903d
GV
2632 info->next = volume_cache;
2633 volume_cache = info;
2634}
2635
2636
2637/* Wrapper for GetVolumeInformation, which uses caching to avoid
2638 performance penalty (~2ms on 486 for local drives, 7.5ms for local
2639 cdrom drive, ~5-10ms or more for remote drives on LAN). */
bedf4aab 2640static volume_info_data *
76b3903d
GV
2641GetCachedVolumeInformation (char * root_dir)
2642{
2643 volume_info_data * info;
f5441ba4
EZ
2644 char default_root[ MAX_UTF8_PATH ];
2645 char name[MAX_PATH+1];
2646 char type[MAX_PATH+1];
76b3903d
GV
2647
2648 /* NULL for root_dir means use root from current directory. */
2649 if (root_dir == NULL)
2650 {
f5441ba4
EZ
2651 if (w32_unicode_filenames)
2652 {
2653 wchar_t curdirw[MAX_PATH];
2654
2655 if (GetCurrentDirectoryW (MAX_PATH, curdirw) == 0)
2656 return NULL;
2657 filename_from_utf16 (curdirw, default_root);
2658 }
2659 else
2660 {
2661 char curdira[MAX_PATH];
2662
2663 if (GetCurrentDirectoryA (MAX_PATH, curdira) == 0)
2664 return NULL;
2665 filename_from_ansi (curdira, default_root);
2666 }
2667 parse_root (default_root, (const char **)&root_dir);
76b3903d
GV
2668 *root_dir = 0;
2669 root_dir = default_root;
2670 }
2671
2672 /* Local fixed drives can be cached permanently. Removable drives
2673 cannot be cached permanently, since the volume name and serial
2674 number (if nothing else) can change. Remote drives should be
2675 treated as if they are removable, since there is no sure way to
2676 tell whether they are or not. Also, the UNC association of drive
2677 letters mapped to remote volumes can be changed at any time (even
2678 by other processes) without notice.
177c0ea7 2679
76b3903d
GV
2680 As a compromise, so we can benefit from caching info for remote
2681 volumes, we use a simple expiry mechanism to invalidate cache
2682 entries that are more than ten seconds old. */
2683
2684#if 0
2685 /* No point doing this, because WNetGetConnection is even slower than
2686 GetVolumeInformation, consistently taking ~50ms on a 486 (FWIW,
2687 GetDriveType is about the only call of this type which does not
2688 involve network access, and so is extremely quick). */
2689
2690 /* Map drive letter to UNC if remote. */
ed3751c8 2691 if (isalpha (root_dir[0]) && !fixed[DRIVE_INDEX (root_dir[0])])
76b3903d
GV
2692 {
2693 char remote_name[ 256 ];
2694 char drive[3] = { root_dir[0], ':' };
2695
2696 if (WNetGetConnection (drive, remote_name, sizeof (remote_name))
2697 == NO_ERROR)
2698 /* do something */ ;
2699 }
2700#endif
2701
2702 info = lookup_volume_info (root_dir);
2703
2704 if (info == NULL || ! VOLINFO_STILL_VALID (root_dir, info))
94eab1c8 2705 {
94eab1c8
JB
2706 DWORD serialnum;
2707 DWORD maxcomp;
2708 DWORD flags;
94eab1c8
JB
2709
2710 /* Info is not cached, or is stale. */
f5441ba4
EZ
2711 if (w32_unicode_filenames)
2712 {
2713 wchar_t root_w[MAX_PATH];
2714 wchar_t name_w[MAX_PATH+1];
2715 wchar_t type_w[MAX_PATH+1];
2716
2717 filename_to_utf16 (root_dir, root_w);
2718 if (!GetVolumeInformationW (root_w,
2719 name_w, sizeof (name_w),
2720 &serialnum,
2721 &maxcomp,
2722 &flags,
2723 type_w, sizeof (type_w)))
2724 return NULL;
2725 /* Hmm... not really 100% correct, as these 2 are not file
2726 names... */
2727 filename_from_utf16 (name_w, name);
2728 filename_from_utf16 (type_w, type);
2729 }
2730 else
2731 {
2732 char root_a[MAX_PATH];
2733 char name_a[MAX_PATH+1];
2734 char type_a[MAX_PATH+1];
2735
2736 filename_to_ansi (root_dir, root_a);
2737 if (!GetVolumeInformationA (root_a,
2738 name_a, sizeof (name_a),
2739 &serialnum,
2740 &maxcomp,
2741 &flags,
2742 type_a, sizeof (type_a)))
2743 return NULL;
2744 filename_from_ansi (name_a, name);
2745 filename_from_ansi (type_a, type);
2746 }
76b3903d 2747
94eab1c8
JB
2748 /* Cache the volume information for future use, overwriting existing
2749 entry if present. */
2750 if (info == NULL)
2751 {
23f86fce 2752 info = xmalloc (sizeof (volume_info_data));
94eab1c8
JB
2753 add_volume_info (root_dir, info);
2754 }
2755 else
2756 {
2757 xfree (info->name);
2758 xfree (info->type);
2759 }
2760
2761 info->name = xstrdup (name);
f5441ba4 2762 unixtodos_filename (info->name);
94eab1c8
JB
2763 info->serialnum = serialnum;
2764 info->maxcomp = maxcomp;
2765 info->flags = flags;
2766 info->type = xstrdup (type);
2767 info->timestamp = GetTickCount ();
2768 }
76b3903d
GV
2769
2770 return info;
2771}
480b0c5b 2772
6dad7178
EZ
2773/* Get information on the volume where NAME is held; set path pointer to
2774 start of pathname in NAME (past UNC header\volume header if present),
2775 if pPath is non-NULL.
2776
2777 Note: if NAME includes symlinks, the information is for the volume
2778 of the symlink, not of its target. That's because, even though
2779 GetVolumeInformation returns information about the symlink target
2780 of its argument, we only pass the root directory to
2781 GetVolumeInformation, not the full NAME. */
bedf4aab 2782static int
480b0c5b 2783get_volume_info (const char * name, const char ** pPath)
95ed0025 2784{
f5441ba4 2785 char temp[MAX_UTF8_PATH];
480b0c5b 2786 char *rootname = NULL; /* default to current volume */
76b3903d 2787 volume_info_data * info;
f5441ba4 2788 int root_len = parse_root (name, pPath);
480b0c5b
GV
2789
2790 if (name == NULL)
2791 return FALSE;
2792
f5441ba4
EZ
2793 /* Copy the root name of the volume, if given. */
2794 if (root_len)
95ed0025 2795 {
f5441ba4
EZ
2796 strncpy (temp, name, root_len);
2797 temp[root_len] = '\0';
2798 unixtodos_filename (temp);
480b0c5b 2799 rootname = temp;
95ed0025 2800 }
480b0c5b 2801
76b3903d
GV
2802 info = GetCachedVolumeInformation (rootname);
2803 if (info != NULL)
95ed0025 2804 {
76b3903d
GV
2805 /* Set global referenced by other functions. */
2806 volume_info = *info;
480b0c5b 2807 return TRUE;
95ed0025 2808 }
480b0c5b
GV
2809 return FALSE;
2810}
2811
2812/* Determine if volume is FAT format (ie. only supports short 8.3
6dad7178
EZ
2813 names); also set path pointer to start of pathname in name, if
2814 pPath is non-NULL. */
bedf4aab 2815static int
480b0c5b
GV
2816is_fat_volume (const char * name, const char ** pPath)
2817{
2818 if (get_volume_info (name, pPath))
2819 return (volume_info.maxcomp == 12);
2820 return FALSE;
2821}
2822
f5441ba4
EZ
2823/* Convert all slashes in a filename to backslashes, and map filename
2824 to a valid 8.3 name if necessary. The result is a pointer to a
2825 static buffer, so CAVEAT EMPTOR! */
480b0c5b 2826const char *
fbd6baed 2827map_w32_filename (const char * name, const char ** pPath)
480b0c5b 2828{
f5441ba4 2829 static char shortname[MAX_UTF8_PATH];
480b0c5b
GV
2830 char * str = shortname;
2831 char c;
480b0c5b 2832 char * path;
76b3903d 2833 const char * save_name = name;
480b0c5b 2834
f5441ba4 2835 if (strlen (name) >= sizeof (shortname))
ca149beb
AI
2836 {
2837 /* Return a filename which will cause callers to fail. */
2838 strcpy (shortname, "?");
2839 return shortname;
2840 }
2841
a302c7ae 2842 if (is_fat_volume (name, (const char **)&path)) /* truncate to 8.3 */
95ed0025 2843 {
480b0c5b
GV
2844 register int left = 8; /* maximum number of chars in part */
2845 register int extn = 0; /* extension added? */
2846 register int dots = 2; /* maximum number of dots allowed */
2847
2848 while (name < path)
2849 *str++ = *name++; /* skip past UNC header */
2850
2851 while ((c = *name++))
2852 {
2853 switch ( c )
2854 {
6dad7178 2855 case ':':
480b0c5b
GV
2856 case '\\':
2857 case '/':
6dad7178 2858 *str++ = (c == ':' ? ':' : '\\');
480b0c5b
GV
2859 extn = 0; /* reset extension flags */
2860 dots = 2; /* max 2 dots */
2861 left = 8; /* max length 8 for main part */
2862 break;
2863 case '.':
2864 if ( dots )
2865 {
2866 /* Convert path components of the form .xxx to _xxx,
2867 but leave . and .. as they are. This allows .emacs
2868 to be read as _emacs, for example. */
2869
2870 if (! *name ||
2871 *name == '.' ||
2872 IS_DIRECTORY_SEP (*name))
2873 {
2874 *str++ = '.';
2875 dots--;
2876 }
2877 else
2878 {
2879 *str++ = '_';
2880 left--;
2881 dots = 0;
2882 }
2883 }
2884 else if ( !extn )
2885 {
2886 *str++ = '.';
2887 extn = 1; /* we've got an extension */
2888 left = 3; /* 3 chars in extension */
2889 }
2890 else
2891 {
2892 /* any embedded dots after the first are converted to _ */
2893 *str++ = '_';
2894 }
2895 break;
2896 case '~':
2897 case '#': /* don't lose these, they're important */
2898 if ( ! left )
2899 str[-1] = c; /* replace last character of part */
2900 /* FALLTHRU */
2901 default:
f5441ba4 2902 if ( left && 'A' <= c && c <= 'Z' )
480b0c5b
GV
2903 {
2904 *str++ = tolower (c); /* map to lower case (looks nicer) */
2905 left--;
2906 dots = 0; /* started a path component */
2907 }
2908 break;
2909 }
2910 }
2911 *str = '\0';
fc85cb29
RS
2912 }
2913 else
2914 {
2915 strcpy (shortname, name);
2916 unixtodos_filename (shortname);
95ed0025 2917 }
480b0c5b
GV
2918
2919 if (pPath)
76b3903d 2920 *pPath = shortname + (path - save_name);
480b0c5b 2921
fc85cb29 2922 return shortname;
480b0c5b
GV
2923}
2924
b3308d2e
KH
2925static int
2926is_exec (const char * name)
2927{
2928 char * p = strrchr (name, '.');
2929 return
2930 (p != NULL
05131107
JR
2931 && (xstrcasecmp (p, ".exe") == 0 ||
2932 xstrcasecmp (p, ".com") == 0 ||
2933 xstrcasecmp (p, ".bat") == 0 ||
2934 xstrcasecmp (p, ".cmd") == 0));
b3308d2e
KH
2935}
2936
0b9de7cd
EZ
2937/* Emulate the Unix directory procedures opendir, closedir, and
2938 readdir. We rename them to sys_* names because some versions of
2939 MinGW startup code call opendir and readdir to glob wildcards, and
2940 the code that calls them doesn't grok UTF-8 encoded file names we
2941 produce in dirent->d_name[]. */
76b3903d 2942
95ef7787 2943struct dirent dir_static; /* simulated directory contents */
76b3903d
GV
2944static HANDLE dir_find_handle = INVALID_HANDLE_VALUE;
2945static int dir_is_fat;
0b9de7cd
EZ
2946static char dir_pathname[MAX_UTF8_PATH];
2947static WIN32_FIND_DATAW dir_find_data_w;
2948static WIN32_FIND_DATAA dir_find_data_a;
76b3903d 2949
9d3355d1
GV
2950/* Support shares on a network resource as subdirectories of a read-only
2951 root directory. */
2952static HANDLE wnet_enum_handle = INVALID_HANDLE_VALUE;
bedf4aab 2953static HANDLE open_unc_volume (const char *);
0b9de7cd 2954static void *read_unc_volume (HANDLE, wchar_t *, char *, int);
bedf4aab 2955static void close_unc_volume (HANDLE);
9d3355d1 2956
76b3903d 2957DIR *
0b9de7cd 2958sys_opendir (const char *filename)
76b3903d
GV
2959{
2960 DIR *dirp;
2961
2962 /* Opening is done by FindFirstFile. However, a read is inherent to
2963 this operation, so we defer the open until read time. */
2964
76b3903d
GV
2965 if (dir_find_handle != INVALID_HANDLE_VALUE)
2966 return NULL;
9d3355d1
GV
2967 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
2968 return NULL;
2969
6dad7178
EZ
2970 /* Note: We don't support traversal of UNC volumes via symlinks.
2971 Doing so would mean punishing 99.99% of use cases by resolving
2972 all the possible symlinks in FILENAME, recursively. */
9d3355d1
GV
2973 if (is_unc_volume (filename))
2974 {
2975 wnet_enum_handle = open_unc_volume (filename);
2976 if (wnet_enum_handle == INVALID_HANDLE_VALUE)
2977 return NULL;
2978 }
2979
2980 if (!(dirp = (DIR *) malloc (sizeof (DIR))))
2981 return NULL;
76b3903d
GV
2982
2983 dirp->dd_fd = 0;
2984 dirp->dd_loc = 0;
2985 dirp->dd_size = 0;
2986
0b9de7cd
EZ
2987 strncpy (dir_pathname, map_w32_filename (filename, NULL), MAX_UTF8_PATH - 1);
2988 dir_pathname[MAX_UTF8_PATH - 1] = '\0';
6dad7178
EZ
2989 /* Note: We don't support symlinks to file names on FAT volumes.
2990 Doing so would mean punishing 99.99% of use cases by resolving
2991 all the possible symlinks in FILENAME, recursively. */
76b3903d
GV
2992 dir_is_fat = is_fat_volume (filename, NULL);
2993
2994 return dirp;
2995}
2996
2997void
0b9de7cd 2998sys_closedir (DIR *dirp)
76b3903d
GV
2999{
3000 /* If we have a find-handle open, close it. */
3001 if (dir_find_handle != INVALID_HANDLE_VALUE)
3002 {
3003 FindClose (dir_find_handle);
3004 dir_find_handle = INVALID_HANDLE_VALUE;
3005 }
9d3355d1
GV
3006 else if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3007 {
3008 close_unc_volume (wnet_enum_handle);
3009 wnet_enum_handle = INVALID_HANDLE_VALUE;
3010 }
76b3903d
GV
3011 xfree ((char *) dirp);
3012}
3013
95ef7787 3014struct dirent *
0b9de7cd 3015sys_readdir (DIR *dirp)
76b3903d 3016{
b07103dc
EZ
3017 int downcase = !NILP (Vw32_downcase_file_names);
3018
9d3355d1
GV
3019 if (wnet_enum_handle != INVALID_HANDLE_VALUE)
3020 {
177c0ea7 3021 if (!read_unc_volume (wnet_enum_handle,
0b9de7cd
EZ
3022 dir_find_data_w.cFileName,
3023 dir_find_data_a.cFileName,
59eb0929 3024 MAX_PATH))
9d3355d1
GV
3025 return NULL;
3026 }
76b3903d 3027 /* If we aren't dir_finding, do a find-first, otherwise do a find-next. */
9d3355d1 3028 else if (dir_find_handle == INVALID_HANDLE_VALUE)
76b3903d 3029 {
0b9de7cd 3030 char filename[MAX_UTF8_PATH + 2];
76b3903d
GV
3031 int ln;
3032
3033 strcpy (filename, dir_pathname);
3034 ln = strlen (filename) - 1;
0b9de7cd
EZ
3035 if (!IS_DIRECTORY_SEP (filename[ln]))
3036 strcat (filename, "\\");
3037 strcat (filename, "*");
3038
3039 /* Note: No need to resolve symlinks in FILENAME, because
3040 FindFirst opens the directory that is the target of a
3041 symlink. */
3042 if (w32_unicode_filenames)
806fed21 3043 {
0b9de7cd
EZ
3044 wchar_t fnw[MAX_PATH];
3045
3046 filename_to_utf16 (filename, fnw);
3047 dir_find_handle = FindFirstFileW (fnw, &dir_find_data_w);
806fed21
EZ
3048 }
3049 else
3050 {
0b9de7cd 3051 char fna[MAX_PATH];
806fed21 3052
0b9de7cd
EZ
3053 filename_to_ansi (filename, fna);
3054 dir_find_handle = FindFirstFileA (fna, &dir_find_data_a);
806fed21 3055 }
76b3903d
GV
3056
3057 if (dir_find_handle == INVALID_HANDLE_VALUE)
3058 return NULL;
3059 }
0b9de7cd
EZ
3060 else if (w32_unicode_filenames)
3061 {
3062 if (!FindNextFileW (dir_find_handle, &dir_find_data_w))
3063 return NULL;
3064 }
76b3903d
GV
3065 else
3066 {
0b9de7cd 3067 if (!FindNextFileA (dir_find_handle, &dir_find_data_a))
76b3903d
GV
3068 return NULL;
3069 }
177c0ea7 3070
76b3903d
GV
3071 /* Emacs never uses this value, so don't bother making it match
3072 value returned by stat(). */
3073 dir_static.d_ino = 1;
177c0ea7 3074
0b9de7cd 3075 if (w32_unicode_filenames)
b07103dc 3076 {
0b9de7cd
EZ
3077 if (downcase || dir_is_fat)
3078 {
3079 wchar_t tem[MAX_PATH];
177c0ea7 3080
0b9de7cd
EZ
3081 wcscpy (tem, dir_find_data_w.cFileName);
3082 CharLowerW (tem);
3083 filename_from_utf16 (tem, dir_static.d_name);
3084 }
3085 else
3086 filename_from_utf16 (dir_find_data_w.cFileName, dir_static.d_name);
192788d7
EZ
3087 }
3088 else
76b3903d 3089 {
0b9de7cd
EZ
3090 char tem[MAX_PATH];
3091
3092 /* If the file name in cFileName[] includes `?' characters, it
3093 means the original file name used characters that cannot be
3094 represented by the current ANSI codepage. To avoid total
3095 lossage, retrieve the short 8+3 alias of the long file
3096 name. */
3097 if (_mbspbrk (dir_find_data_a.cFileName, "?"))
6d2851de 3098 {
0b9de7cd
EZ
3099 strcpy (tem, dir_find_data_a.cAlternateFileName);
3100 /* 8+3 aliases are returned in all caps, which could break
3101 various alists that look at filenames' extensions. */
3102 downcase = 1;
3103 }
3104 else if (downcase || dir_is_fat)
3105 strcpy (tem, dir_find_data_a.cFileName);
3106 else
3107 filename_from_ansi (dir_find_data_a.cFileName, dir_static.d_name);
3108 if (downcase || dir_is_fat)
3109 {
3110 _mbslwr (tem);
3111 filename_from_ansi (tem, dir_static.d_name);
6d2851de 3112 }
76b3903d 3113 }
177c0ea7 3114
0b9de7cd
EZ
3115 dir_static.d_namlen = strlen (dir_static.d_name);
3116 dir_static.d_reclen = sizeof (struct dirent) - MAX_UTF8_PATH + 3 +
3117 dir_static.d_namlen - dir_static.d_namlen % 4;
3118
76b3903d
GV
3119 return &dir_static;
3120}
3121
bedf4aab 3122static HANDLE
e0c181dd 3123open_unc_volume (const char *path)
9d3355d1 3124{
0b9de7cd
EZ
3125 const char *fn = map_w32_filename (path, NULL);
3126 DWORD result;
9d3355d1 3127 HANDLE henum;
9d3355d1 3128
0b9de7cd
EZ
3129 if (w32_unicode_filenames)
3130 {
3131 NETRESOURCEW nrw;
3132 wchar_t fnw[MAX_PATH];
3133
3134 nrw.dwScope = RESOURCE_GLOBALNET;
3135 nrw.dwType = RESOURCETYPE_DISK;
3136 nrw.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3137 nrw.dwUsage = RESOURCEUSAGE_CONTAINER;
3138 nrw.lpLocalName = NULL;
3139 filename_to_utf16 (fn, fnw);
3140 nrw.lpRemoteName = fnw;
3141 nrw.lpComment = NULL;
3142 nrw.lpProvider = NULL;
9d3355d1 3143
0b9de7cd
EZ
3144 result = WNetOpenEnumW (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3145 RESOURCEUSAGE_CONNECTABLE, &nrw, &henum);
3146 }
3147 else
3148 {
3149 NETRESOURCEA nra;
3150 char fna[MAX_PATH];
9d3355d1 3151
0b9de7cd
EZ
3152 nra.dwScope = RESOURCE_GLOBALNET;
3153 nra.dwType = RESOURCETYPE_DISK;
3154 nra.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
3155 nra.dwUsage = RESOURCEUSAGE_CONTAINER;
3156 nra.lpLocalName = NULL;
3157 filename_to_ansi (fn, fna);
3158 nra.lpRemoteName = fna;
3159 nra.lpComment = NULL;
3160 nra.lpProvider = NULL;
3161
3162 result = WNetOpenEnumA (RESOURCE_GLOBALNET, RESOURCETYPE_DISK,
3163 RESOURCEUSAGE_CONNECTABLE, &nra, &henum);
3164 }
9d3355d1
GV
3165 if (result == NO_ERROR)
3166 return henum;
3167 else
3168 return INVALID_HANDLE_VALUE;
3169}
3170
0b9de7cd
EZ
3171static void *
3172read_unc_volume (HANDLE henum, wchar_t *fname_w, char *fname_a, int size)
9d3355d1 3173{
a302c7ae 3174 DWORD count;
9d3355d1 3175 int result;
9d3355d1 3176 char *buffer;
0b9de7cd
EZ
3177 DWORD bufsize = 512;
3178 void *retval;
9d3355d1
GV
3179
3180 count = 1;
0b9de7cd
EZ
3181 if (w32_unicode_filenames)
3182 {
3183 wchar_t *ptrw;
9d3355d1 3184
0b9de7cd
EZ
3185 bufsize *= 2;
3186 buffer = alloca (bufsize);
3187 result = WNetEnumResourceW (henum, &count, buffer, &bufsize);
3188 if (result != NO_ERROR)
3189 return NULL;
3190 /* WNetEnumResource returns \\resource\share...skip forward to "share". */
3191 ptrw = ((LPNETRESOURCEW) buffer)->lpRemoteName;
3192 ptrw += 2;
3193 while (*ptrw && *ptrw != L'/' && *ptrw != L'\\') ptrw++;
3194 ptrw++;
3195 wcsncpy (fname_w, ptrw, size);
3196 retval = fname_w;
3197 }
806fed21
EZ
3198 else
3199 {
0b9de7cd
EZ
3200 int dbcs_p = max_filename_mbslen () > 1;
3201 char *ptra;
3202
3203 buffer = alloca (bufsize);
3204 result = WNetEnumResourceA (henum, &count, buffer, &bufsize);
3205 if (result != NO_ERROR)
3206 return NULL;
3207 ptra = ((LPNETRESOURCEA) buffer)->lpRemoteName;
3208 ptra += 2;
3209 if (!dbcs_p)
3210 while (*ptra && !IS_DIRECTORY_SEP (*ptra)) ptra++;
3211 else
3212 {
3213 while (*ptra && !IS_DIRECTORY_SEP (*ptra))
3214 ptra = CharNextExA (file_name_codepage, ptra, 0);
3215 }
3216 ptra++;
3217 strncpy (fname_a, ptra, size);
3218 retval = fname_a;
806fed21 3219 }
9d3355d1 3220
0b9de7cd 3221 return retval;
9d3355d1
GV
3222}
3223
bedf4aab 3224static void
9d3355d1
GV
3225close_unc_volume (HANDLE henum)
3226{
3227 if (henum != INVALID_HANDLE_VALUE)
3228 WNetCloseEnum (henum);
3229}
3230
bedf4aab 3231static DWORD
e0c181dd 3232unc_volume_file_attributes (const char *path)
9d3355d1
GV
3233{
3234 HANDLE henum;
3235 DWORD attrs;
3236
3237 henum = open_unc_volume (path);
3238 if (henum == INVALID_HANDLE_VALUE)
3239 return -1;
3240
3241 attrs = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_DIRECTORY;
3242
3243 close_unc_volume (henum);
3244
3245 return attrs;
3246}
3247
302d7d54
JR
3248/* Ensure a network connection is authenticated. */
3249static void
3250logon_network_drive (const char *path)
3251{
0b9de7cd 3252 char share[MAX_UTF8_PATH];
806fed21 3253 int n_slashes;
40a339c8 3254 char drive[4];
be4c6380 3255 UINT drvtype;
806fed21 3256 char *p;
0b9de7cd 3257 DWORD val;
40a339c8 3258
be4c6380
EZ
3259 if (IS_DIRECTORY_SEP (path[0]) && IS_DIRECTORY_SEP (path[1]))
3260 drvtype = DRIVE_REMOTE;
3261 else if (path[0] == '\0' || path[1] != ':')
3262 drvtype = GetDriveType (NULL);
3263 else
3264 {
3265 drive[0] = path[0];
3266 drive[1] = ':';
3267 drive[2] = '\\';
3268 drive[3] = '\0';
3269 drvtype = GetDriveType (drive);
3270 }
302d7d54
JR
3271
3272 /* Only logon to networked drives. */
be4c6380 3273 if (drvtype != DRIVE_REMOTE)
302d7d54 3274 return;
40a339c8 3275
302d7d54 3276 n_slashes = 2;
0b9de7cd 3277 strncpy (share, path, MAX_UTF8_PATH);
302d7d54 3278 /* Truncate to just server and share name. */
0b9de7cd 3279 for (p = share + 2; *p && p < share + MAX_UTF8_PATH; p++)
302d7d54 3280 {
806fed21 3281 if (IS_DIRECTORY_SEP (*p) && ++n_slashes > 3)
302d7d54 3282 {
806fed21 3283 *p = '\0';
302d7d54
JR
3284 break;
3285 }
3286 }
3287
0b9de7cd
EZ
3288 if (w32_unicode_filenames)
3289 {
3290 NETRESOURCEW resourcew;
3291 wchar_t share_w[MAX_PATH];
3292
3293 resourcew.dwScope = RESOURCE_GLOBALNET;
3294 resourcew.dwType = RESOURCETYPE_DISK;
3295 resourcew.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3296 resourcew.dwUsage = RESOURCEUSAGE_CONTAINER;
3297 resourcew.lpLocalName = NULL;
3298 filename_to_utf16 (share, share_w);
3299 resourcew.lpRemoteName = share_w;
3300 resourcew.lpProvider = NULL;
3301
3302 val = WNetAddConnection2W (&resourcew, NULL, NULL, CONNECT_INTERACTIVE);
3303 }
3304 else
3305 {
3306 NETRESOURCEA resourcea;
3307 char share_a[MAX_PATH];
3308
3309 resourcea.dwScope = RESOURCE_GLOBALNET;
3310 resourcea.dwType = RESOURCETYPE_DISK;
3311 resourcea.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
3312 resourcea.dwUsage = RESOURCEUSAGE_CONTAINER;
3313 resourcea.lpLocalName = NULL;
3314 filename_to_ansi (share, share_a);
3315 resourcea.lpRemoteName = share_a;
3316 resourcea.lpProvider = NULL;
302d7d54 3317
0b9de7cd
EZ
3318 val = WNetAddConnection2A (&resourcea, NULL, NULL, CONNECT_INTERACTIVE);
3319 }
3320
3321 switch (val)
3322 {
3323 case NO_ERROR:
3324 case ERROR_ALREADY_ASSIGNED:
3325 break;
3326 case ERROR_ACCESS_DENIED:
3327 case ERROR_LOGON_FAILURE:
3328 errno = EACCES;
3329 break;
3330 case ERROR_BUSY:
3331 errno = EAGAIN;
3332 break;
3333 case ERROR_BAD_NET_NAME:
3334 case ERROR_NO_NET_OR_BAD_PATH:
3335 case ERROR_NO_NETWORK:
3336 case ERROR_CANCELLED:
3337 default:
3338 errno = ENOENT;
3339 break;
3340 }
302d7d54 3341}
480b0c5b 3342
14f20728 3343/* Emulate faccessat(2). */
480b0c5b 3344int
14f20728 3345faccessat (int dirfd, const char * path, int mode, int flags)
480b0c5b 3346{
b3308d2e
KH
3347 DWORD attributes;
3348
14f20728
EZ
3349 if (dirfd != AT_FDCWD
3350 && !(IS_DIRECTORY_SEP (path[0])
3351 || IS_DEVICE_SEP (path[1])))
73dcdb9f
PE
3352 {
3353 errno = EBADF;
3354 return -1;
3355 }
3356
8d38f461
EZ
3357 /* MSVCRT implementation of 'access' doesn't recognize D_OK, and its
3358 newer versions blow up when passed D_OK. */
b3308d2e 3359 path = map_w32_filename (path, NULL);
6dad7178
EZ
3360 /* If the last element of PATH is a symlink, we need to resolve it
3361 to get the attributes of its target file. Note: any symlinks in
3362 PATH elements other than the last one are transparently resolved
3363 by GetFileAttributes below. */
14f20728
EZ
3364 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0
3365 && (flags & AT_SYMLINK_NOFOLLOW) == 0)
6dad7178
EZ
3366 path = chase_symlinks (path);
3367
e75e4a89
EZ
3368 if (w32_unicode_filenames)
3369 {
3370 wchar_t path_w[MAX_PATH];
3371
3372 filename_to_utf16 (path, path_w);
3373 attributes = GetFileAttributesW (path_w);
3374 }
3375 else
3376 {
3377 char path_a[MAX_PATH];
3378
3379 filename_to_ansi (path, path_a);
3380 attributes = GetFileAttributesA (path_a);
3381 }
3382
3383 if (attributes == -1)
b3308d2e 3384 {
8d38f461
EZ
3385 DWORD w32err = GetLastError ();
3386
3387 switch (w32err)
3388 {
6dad7178
EZ
3389 case ERROR_INVALID_NAME:
3390 case ERROR_BAD_PATHNAME:
3391 if (is_unc_volume (path))
3392 {
3393 attributes = unc_volume_file_attributes (path);
3394 if (attributes == -1)
3395 {
3396 errno = EACCES;
3397 return -1;
3398 }
3399 break;
3400 }
3401 /* FALLTHROUGH */
8d38f461 3402 case ERROR_FILE_NOT_FOUND:
6dad7178 3403 case ERROR_BAD_NETPATH:
8d38f461
EZ
3404 errno = ENOENT;
3405 break;
3406 default:
3407 errno = EACCES;
3408 break;
3409 }
b3308d2e
KH
3410 return -1;
3411 }
6ad30855
EZ
3412 if ((mode & X_OK) != 0
3413 && !(is_exec (path) || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
b3308d2e
KH
3414 {
3415 errno = EACCES;
3416 return -1;
3417 }
3418 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3419 {
3420 errno = EACCES;
3421 return -1;
3422 }
3423 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3424 {
3425 errno = EACCES;
3426 return -1;
3427 }
3428 return 0;
480b0c5b
GV
3429}
3430
b1846422
EZ
3431/* A version of 'access' to be used locally with file names in
3432 locale-specific encoding. Does not resolve symlinks and does not
3433 support file names on FAT12 and FAT16 volumes, but that's OK, since
3434 we only invoke this function for files inside the Emacs source or
3435 installation tree, on directories (so any symlinks should have the
3436 directory bit set), and on short file names such as "C:/.emacs". */
3437static int
3438sys_access (const char *fname, int mode)
3439{
3440 char fname_copy[MAX_PATH], *p;
3441 DWORD attributes;
3442
3443 strcpy (fname_copy, fname);
3444 /* Do the equivalent of unixtodos_filename. */
3445 for (p = fname_copy; *p; p = CharNext (p))
3446 if (*p == '/')
3447 *p = '\\';
3448
3449 if ((attributes = GetFileAttributesA (fname_copy)) == -1)
3450 {
3451 DWORD w32err = GetLastError ();
3452
3453 switch (w32err)
3454 {
3455 case ERROR_INVALID_NAME:
3456 case ERROR_BAD_PATHNAME:
3457 case ERROR_FILE_NOT_FOUND:
3458 case ERROR_BAD_NETPATH:
3459 errno = ENOENT;
3460 break;
3461 default:
3462 errno = EACCES;
3463 break;
3464 }
3465 return -1;
3466 }
3467 if ((mode & X_OK) != 0
3468 && !(is_exec (fname_copy)
3469 || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0))
3470 {
3471 errno = EACCES;
3472 return -1;
3473 }
3474 if ((mode & W_OK) != 0 && (attributes & FILE_ATTRIBUTE_READONLY) != 0)
3475 {
3476 errno = EACCES;
3477 return -1;
3478 }
3479 if ((mode & D_OK) != 0 && (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
3480 {
3481 errno = EACCES;
3482 return -1;
3483 }
3484 return 0;
3485}
3486
14f20728
EZ
3487/* Shadow some MSVC runtime functions to map requests for long filenames
3488 to reasonable short names if necessary. This was originally added to
3489 permit running Emacs on NT 3.1 on a FAT partition, which doesn't support
3490 long file names. */
3491
480b0c5b
GV
3492int
3493sys_chdir (const char * path)
3494{
e75e4a89 3495 path = map_w32_filename (path, NULL);
03d58cca
EZ
3496 if (w32_unicode_filenames)
3497 {
e75e4a89 3498 wchar_t newdir_w[MAX_PATH];
03d58cca 3499
e75e4a89
EZ
3500 if (filename_to_utf16 (path, newdir_w) == 0)
3501 return _wchdir (newdir_w);
03d58cca
EZ
3502 return -1;
3503 }
3504 else
3505 {
e75e4a89 3506 char newdir_a[MAX_PATH];
03d58cca 3507
e75e4a89
EZ
3508 if (filename_to_ansi (path, newdir_a) == 0)
3509 return _chdir (newdir_a);
03d58cca
EZ
3510 return -1;
3511 }
480b0c5b
GV
3512}
3513
3514int
3515sys_chmod (const char * path, int mode)
3516{
6dad7178 3517 path = chase_symlinks (map_w32_filename (path, NULL));
e75e4a89
EZ
3518 if (w32_unicode_filenames)
3519 {
3520 wchar_t path_w[MAX_PATH];
3521
3522 filename_to_utf16 (path, path_w);
3523 return _wchmod (path_w, mode);
3524 }
3525 else
3526 {
3527 char path_a[MAX_PATH];
3528
3529 filename_to_ansi (path, path_a);
3530 return _chmod (path_a, mode);
3531 }
480b0c5b
GV
3532}
3533
3534int
3535sys_creat (const char * path, int mode)
3536{
e75e4a89
EZ
3537 path = map_w32_filename (path, NULL);
3538 if (w32_unicode_filenames)
3539 {
3540 wchar_t path_w[MAX_PATH];
3541
3542 filename_to_utf16 (path, path_w);
3543 return _wcreat (path_w, mode);
3544 }
3545 else
3546 {
3547 char path_a[MAX_PATH];
3548
3549 filename_to_ansi (path, path_a);
3550 return _creat (path_a, mode);
3551 }
480b0c5b
GV
3552}
3553
3554FILE *
b56ceb92 3555sys_fopen (const char * path, const char * mode)
480b0c5b
GV
3556{
3557 int fd;
3558 int oflag;
3559 const char * mode_save = mode;
3560
3561 /* Force all file handles to be non-inheritable. This is necessary to
3562 ensure child processes don't unwittingly inherit handles that might
3563 prevent future file access. */
3564
3565 if (mode[0] == 'r')
3566 oflag = O_RDONLY;
3567 else if (mode[0] == 'w' || mode[0] == 'a')
3568 oflag = O_WRONLY | O_CREAT | O_TRUNC;
95ed0025 3569 else
480b0c5b
GV
3570 return NULL;
3571
3572 /* Only do simplistic option parsing. */
3573 while (*++mode)
3574 if (mode[0] == '+')
3575 {
3576 oflag &= ~(O_RDONLY | O_WRONLY);
3577 oflag |= O_RDWR;
3578 }
3579 else if (mode[0] == 'b')
3580 {
3581 oflag &= ~O_TEXT;
3582 oflag |= O_BINARY;
3583 }
3584 else if (mode[0] == 't')
3585 {
3586 oflag &= ~O_BINARY;
3587 oflag |= O_TEXT;
3588 }
3589 else break;
3590
e75e4a89
EZ
3591 path = map_w32_filename (path, NULL);
3592 if (w32_unicode_filenames)
3593 {
3594 wchar_t path_w[MAX_PATH];
3595
3596 filename_to_utf16 (path, path_w);
3597 fd = _wopen (path_w, oflag | _O_NOINHERIT, 0644);
3598 }
3599 else
3600 {
3601 char path_a[MAX_PATH];
3602
3603 filename_to_ansi (path, path_a);
3604 fd = _open (path_a, oflag | _O_NOINHERIT, 0644);
3605 }
480b0c5b
GV
3606 if (fd < 0)
3607 return NULL;
3608
76b3903d 3609 return _fdopen (fd, mode_save);
95ed0025 3610}
480b0c5b 3611
76b3903d 3612/* This only works on NTFS volumes, but is useful to have. */
480b0c5b 3613int
76b3903d 3614sys_link (const char * old, const char * new)
480b0c5b 3615{
76b3903d
GV
3616 HANDLE fileh;
3617 int result = -1;
6349f70a
EZ
3618 char oldname[MAX_UTF8_PATH], newname[MAX_UTF8_PATH];
3619 wchar_t oldname_w[MAX_PATH];
3620 char oldname_a[MAX_PATH];
76b3903d
GV
3621
3622 if (old == NULL || new == NULL)
3623 {
3624 errno = ENOENT;
3625 return -1;
3626 }
3627
3628 strcpy (oldname, map_w32_filename (old, NULL));
3629 strcpy (newname, map_w32_filename (new, NULL));
3630
6349f70a
EZ
3631 if (w32_unicode_filenames)
3632 {
3633 filename_to_utf16 (oldname, oldname_w);
3634 fileh = CreateFileW (oldname_w, 0, 0, NULL, OPEN_EXISTING,
3635 FILE_FLAG_BACKUP_SEMANTICS, NULL);
3636 }
3637 else
3638 {
3639 filename_to_ansi (oldname, oldname_a);
3640 fileh = CreateFileA (oldname_a, 0, 0, NULL, OPEN_EXISTING,
3641 FILE_FLAG_BACKUP_SEMANTICS, NULL);
3642 }
76b3903d
GV
3643 if (fileh != INVALID_HANDLE_VALUE)
3644 {
3645 int wlen;
3646
3647 /* Confusingly, the "alternate" stream name field does not apply
3648 when restoring a hard link, and instead contains the actual
3649 stream data for the link (ie. the name of the link to create).
3650 The WIN32_STREAM_ID structure before the cStreamName field is
3651 the stream header, which is then immediately followed by the
3652 stream data. */
3653
3654 struct {
3655 WIN32_STREAM_ID wid;
3656 WCHAR wbuffer[MAX_PATH]; /* extra space for link name */
3657 } data;
3658
6349f70a
EZ
3659 /* We used to pass MB_PRECOMPOSED as the 2nd arg here, but MSDN
3660 indicates that flag is unsupported for CP_UTF8, and OTOH says
3661 it is the default anyway. */
3662 wlen = MultiByteToWideChar (CP_UTF8, 0, newname, -1,
76b3903d
GV
3663 data.wid.cStreamName, MAX_PATH);
3664 if (wlen > 0)
3665 {
3666 LPVOID context = NULL;
3667 DWORD wbytes = 0;
3668
3669 data.wid.dwStreamId = BACKUP_LINK;
3670 data.wid.dwStreamAttributes = 0;
ed3751c8 3671 data.wid.Size.LowPart = wlen * sizeof (WCHAR);
76b3903d
GV
3672 data.wid.Size.HighPart = 0;
3673 data.wid.dwStreamNameSize = 0;
3674
3675 if (BackupWrite (fileh, (LPBYTE)&data,
3676 offsetof (WIN32_STREAM_ID, cStreamName)
3677 + data.wid.Size.LowPart,
3678 &wbytes, FALSE, FALSE, &context)
3679 && BackupWrite (fileh, NULL, 0, &wbytes, TRUE, FALSE, &context))
3680 {
3681 /* succeeded */
3682 result = 0;
3683 }
3684 else
3685 {
6349f70a
EZ
3686 DWORD err = GetLastError ();
3687 DWORD attributes;
3688
3689 switch (err)
3690 {
3691 case ERROR_ACCESS_DENIED:
3692 /* This is what happens when OLDNAME is a directory,
3693 since Windows doesn't support hard links to
3694 directories. Posix says to set errno to EPERM in
3695 that case. */
3696 if (w32_unicode_filenames)
3697 attributes = GetFileAttributesW (oldname_w);
3698 else
3699 attributes = GetFileAttributesA (oldname_a);
3700 if (attributes != -1
3701 && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
3702 errno = EPERM;
3703 else if (attributes == -1
3704 && is_unc_volume (oldname)
3705 && unc_volume_file_attributes (oldname) != -1)
3706 errno = EPERM;
3707 else
3708 errno = EACCES;
3709 break;
3710 case ERROR_TOO_MANY_LINKS:
3711 errno = EMLINK;
3712 break;
3713 case ERROR_NOT_SAME_DEVICE:
3714 errno = EXDEV;
3715 break;
3716 default:
3717 errno = EINVAL;
3718 break;
3719 }
76b3903d
GV
3720 }
3721 }
3722
3723 CloseHandle (fileh);
3724 }
3725 else
3726 errno = ENOENT;
3727
3728 return result;
480b0c5b
GV
3729}
3730
3731int
3732sys_mkdir (const char * path)
3733{
44b32251
EZ
3734 path = map_w32_filename (path, NULL);
3735
3736 if (w32_unicode_filenames)
3737 {
3738 wchar_t path_w[MAX_PATH];
3739
3740 filename_to_utf16 (path, path_w);
3741 return _wmkdir (path_w);
3742 }
3743 else
3744 {
3745 char path_a[MAX_PATH];
3746
3747 filename_to_ansi (path, path_a);
3748 return _mkdir (path_a);
3749 }
480b0c5b
GV
3750}
3751
63f5c6c2
EZ
3752int
3753sys_open (const char * path, int oflag, int mode)
3754{
3755 const char* mpath = map_w32_filename (path, NULL);
3756 int res = -1;
3757
44b32251
EZ
3758 if (w32_unicode_filenames)
3759 {
3760 wchar_t mpath_w[MAX_PATH];
3761
3762 filename_to_utf16 (mpath, mpath_w);
3763 /* If possible, try to open file without _O_CREAT, to be able to
3764 write to existing hidden and system files. Force all file
3765 handles to be non-inheritable. */
3766 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
3767 res = _wopen (mpath_w, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
3768 if (res < 0)
3769 res = _wopen (mpath_w, oflag | _O_NOINHERIT, mode);
3770 }
3771 else
3772 {
3773 char mpath_a[MAX_PATH];
3774
3775 filename_to_ansi (mpath, mpath_a);
3776 if ((oflag & (_O_CREAT | _O_EXCL)) != (_O_CREAT | _O_EXCL))
3777 res = _open (mpath_a, (oflag & ~_O_CREAT) | _O_NOINHERIT, mode);
3778 if (res < 0)
3779 res = _open (mpath_a, oflag | _O_NOINHERIT, mode);
3780 }
63f5c6c2
EZ
3781
3782 return res;
3783}
3784
3785/* Implementation of mkostemp for MS-Windows, to avoid race conditions
3786 when using mktemp.
3787
3788 Standard algorithm for generating a temporary file name seems to be
3789 use pid or tid with a letter on the front (in place of the 6 X's)
3790 and cycle through the letters to find a unique name. We extend
3791 that to allow any reasonable character as the first of the 6 X's,
3792 so that the number of simultaneously used temporary files will be
3793 greater. */
3794
3795int
3796mkostemp (char * template, int flags)
480b0c5b 3797{
9d1778b1 3798 char * p;
63f5c6c2 3799 int i, fd = -1;
9d1778b1 3800 unsigned uid = GetCurrentThreadId ();
63f5c6c2 3801 int save_errno = errno;
9d1778b1
RS
3802 static char first_char[] = "abcdefghijklmnopqrstuvwyz0123456789!%-_@#";
3803
63f5c6c2 3804 errno = EINVAL;
9d1778b1 3805 if (template == NULL)
63f5c6c2
EZ
3806 return -1;
3807
9d1778b1
RS
3808 p = template + strlen (template);
3809 i = 5;
3810 /* replace up to the last 5 X's with uid in decimal */
3811 while (--p >= template && p[0] == 'X' && --i >= 0)
3812 {
3813 p[0] = '0' + uid % 10;
3814 uid /= 10;
3815 }
3816
3817 if (i < 0 && p[0] == 'X')
3818 {
3819 i = 0;
3820 do
3821 {
9d1778b1 3822 p[0] = first_char[i];
63f5c6c2
EZ
3823 if ((fd = sys_open (template,
3824 flags | _O_CREAT | _O_EXCL | _O_RDWR,
3825 S_IRUSR | S_IWUSR)) >= 0
3826 || errno != EEXIST)
9d1778b1 3827 {
63f5c6c2
EZ
3828 if (fd >= 0)
3829 errno = save_errno;
3830 return fd;
9d1778b1
RS
3831 }
3832 }
3833 while (++i < sizeof (first_char));
3834 }
3835
63f5c6c2
EZ
3836 /* Template is badly formed or else we can't generate a unique name. */
3837 return -1;
480b0c5b
GV
3838}
3839
3840int
70743157
PE
3841fchmod (int fd, mode_t mode)
3842{
3843 return 0;
3844}
3845
3846int
3847sys_rename_replace (const char *oldname, const char *newname, BOOL force)
480b0c5b 3848{
cfb5e855 3849 BOOL result;
f5c287f4 3850 char temp[MAX_UTF8_PATH], temp_a[MAX_PATH];;
069d2b50
L
3851 int newname_dev;
3852 int oldname_dev;
f5c287f4 3853 bool have_temp_a = false;
480b0c5b 3854
e9e23e23 3855 /* MoveFile on Windows 95 doesn't correctly change the short file name
5162ffce
MB
3856 alias in a number of circumstances (it is not easy to predict when
3857 just by looking at oldname and newname, unfortunately). In these
3858 cases, renaming through a temporary name avoids the problem.
3859
e9e23e23 3860 A second problem on Windows 95 is that renaming through a temp name when
5162ffce
MB
3861 newname is uppercase fails (the final long name ends up in
3862 lowercase, although the short alias might be uppercase) UNLESS the
3863 long temp name is not 8.3.
3864
e9e23e23 3865 So, on Windows 95 we always rename through a temp name, and we make sure
5162ffce 3866 the temp name has a long extension to ensure correct renaming. */
480b0c5b 3867
fbd6baed 3868 strcpy (temp, map_w32_filename (oldname, NULL));
480b0c5b 3869
069d2b50
L
3870 /* volume_info is set indirectly by map_w32_filename. */
3871 oldname_dev = volume_info.serialnum;
3872
417a7a0e 3873 if (os_subtype == OS_9X)
480b0c5b 3874 {
b3308d2e 3875 char * o;
480b0c5b 3876 char * p;
b3308d2e 3877 int i = 0;
f5c287f4 3878 char oldname_a[MAX_PATH];
b3308d2e
KH
3879
3880 oldname = map_w32_filename (oldname, NULL);
f5c287f4
EZ
3881 filename_to_ansi (oldname, oldname_a);
3882 filename_to_ansi (temp, temp_a);
3883 if ((o = strrchr (oldname_a, '\\')))
b3308d2e
KH
3884 o++;
3885 else
f5c287f4 3886 o = (char *) oldname_a;
480b0c5b 3887
f5c287f4 3888 if ((p = strrchr (temp_a, '\\')))
480b0c5b
GV
3889 p++;
3890 else
f5c287f4 3891 p = temp_a;
b3308d2e
KH
3892
3893 do
3894 {
3895 /* Force temp name to require a manufactured 8.3 alias - this
3896 seems to make the second rename work properly. */
f313ee82 3897 sprintf (p, "_.%s.%u", o, i);
b3308d2e 3898 i++;
f5c287f4 3899 result = rename (oldname_a, temp_a);
b3308d2e
KH
3900 }
3901 /* This loop must surely terminate! */
cfb5e855 3902 while (result < 0 && errno == EEXIST);
58f0cb7e 3903 if (result < 0)
480b0c5b 3904 return -1;
f5c287f4 3905 have_temp_a = true;
480b0c5b
GV
3906 }
3907
70743157 3908 /* If FORCE, emulate Unix behavior - newname is deleted if it already exists
5162ffce 3909 (at least if it is a file; don't do this for directories).
76b3903d 3910
b3308d2e
KH
3911 Since we mustn't do this if we are just changing the case of the
3912 file name (we would end up deleting the file we are trying to
3913 rename!), we let rename detect if the destination file already
3914 exists - that way we avoid the possible pitfalls of trying to
3915 determine ourselves whether two names really refer to the same
3916 file, which is not always possible in the general case. (Consider
3917 all the permutations of shared or subst'd drives, etc.) */
3918
3919 newname = map_w32_filename (newname, NULL);
069d2b50
L
3920
3921 /* volume_info is set indirectly by map_w32_filename. */
3922 newname_dev = volume_info.serialnum;
3923
f5c287f4 3924 if (w32_unicode_filenames)
069d2b50 3925 {
f5c287f4 3926 wchar_t temp_w[MAX_PATH], newname_w[MAX_PATH];
069d2b50 3927
f5c287f4
EZ
3928 filename_to_utf16 (temp, temp_w);
3929 filename_to_utf16 (newname, newname_w);
3930 result = _wrename (temp_w, newname_w);
3931 if (result < 0 && force)
069d2b50 3932 {
f5c287f4
EZ
3933 DWORD w32err = GetLastError ();
3934
3935 if (errno == EACCES
3936 && newname_dev != oldname_dev)
3937 {
3938 /* The implementation of `rename' on Windows does not return
3939 errno = EXDEV when you are moving a directory to a
3940 different storage device (ex. logical disk). It returns
3941 EACCES instead. So here we handle such situations and
3942 return EXDEV. */
3943 DWORD attributes;
3944
3945 if ((attributes = GetFileAttributesW (temp_w)) != -1
3946 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
3947 errno = EXDEV;
3948 }
3949 else if (errno == EEXIST)
3950 {
3951 if (_wchmod (newname_w, 0666) != 0)
3952 return result;
3953 if (_wunlink (newname_w) != 0)
3954 return result;
3955 result = _wrename (temp_w, newname_w);
3956 }
3957 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
3958 && is_symlink (temp))
3959 {
3960 /* This is Windows prohibiting the user from creating a
3961 symlink in another place, since that requires
3962 privileges. */
3963 errno = EPERM;
3964 }
069d2b50 3965 }
f5c287f4
EZ
3966 }
3967 else
3968 {
3969 char newname_a[MAX_PATH];
3970
3971 if (!have_temp_a)
3972 filename_to_ansi (temp, temp_a);
3973 filename_to_ansi (newname, newname_a);
3974 result = rename (temp_a, newname_a);
3975 if (result < 0 && force)
6dad7178 3976 {
f5c287f4
EZ
3977 DWORD w32err = GetLastError ();
3978
3979 if (errno == EACCES
3980 && newname_dev != oldname_dev)
3981 {
3982 DWORD attributes;
3983
3984 if ((attributes = GetFileAttributesA (temp_a)) != -1
3985 && (attributes & FILE_ATTRIBUTE_DIRECTORY))
3986 errno = EXDEV;
3987 }
3988 else if (errno == EEXIST)
3989 {
3990 if (_chmod (newname_a, 0666) != 0)
3991 return result;
3992 if (_unlink (newname_a) != 0)
3993 return result;
3994 result = rename (temp_a, newname_a);
3995 }
3996 else if (w32err == ERROR_PRIVILEGE_NOT_HELD
3997 && is_symlink (temp))
3998 errno = EPERM;
6dad7178 3999 }
069d2b50 4000 }
480b0c5b 4001
eb9ea53f 4002 return result;
480b0c5b
GV
4003}
4004
70743157
PE
4005int
4006sys_rename (char const *old, char const *new)
4007{
4008 return sys_rename_replace (old, new, TRUE);
4009}
4010
480b0c5b
GV
4011int
4012sys_rmdir (const char * path)
4013{
8dc689ce
EZ
4014 path = map_w32_filename (path, NULL);
4015
4016 if (w32_unicode_filenames)
4017 {
4018 wchar_t path_w[MAX_PATH];
4019
4020 filename_to_utf16 (path, path_w);
4021 return _wrmdir (path_w);
4022 }
4023 else
4024 {
4025 char path_a[MAX_PATH];
4026
4027 filename_to_ansi (path, path_a);
4028 return _rmdir (path_a);
4029 }
480b0c5b
GV
4030}
4031
4032int
4033sys_unlink (const char * path)
4034{
16bb7578
GV
4035 path = map_w32_filename (path, NULL);
4036
8dc689ce
EZ
4037 if (w32_unicode_filenames)
4038 {
4039 wchar_t path_w[MAX_PATH];
4040
4041 filename_to_utf16 (path, path_w);
4042 /* On Unix, unlink works without write permission. */
4043 _wchmod (path_w, 0666);
4044 return _wunlink (path_w);
4045 }
4046 else
4047 {
4048 char path_a[MAX_PATH];
4049
4050 filename_to_ansi (path, path_a);
4051 _chmod (path_a, 0666);
4052 return _unlink (path_a);
4053 }
480b0c5b
GV
4054}
4055
4056static FILETIME utc_base_ft;
5da9424d 4057static ULONGLONG utc_base; /* In 100ns units */
480b0c5b
GV
4058static int init = 0;
4059
5da9424d
JB
4060#define FILETIME_TO_U64(result, ft) \
4061 do { \
4062 ULARGE_INTEGER uiTemp; \
4063 uiTemp.LowPart = (ft).dwLowDateTime; \
4064 uiTemp.HighPart = (ft).dwHighDateTime; \
4065 result = uiTemp.QuadPart; \
4066 } while (0)
4067
4068static void
b56ceb92 4069initialize_utc_base (void)
7c80d5ec 4070{
5da9424d
JB
4071 /* Determine the delta between 1-Jan-1601 and 1-Jan-1970. */
4072 SYSTEMTIME st;
4073
4074 st.wYear = 1970;
4075 st.wMonth = 1;
4076 st.wDay = 1;
4077 st.wHour = 0;
4078 st.wMinute = 0;
4079 st.wSecond = 0;
4080 st.wMilliseconds = 0;
4081
4082 SystemTimeToFileTime (&st, &utc_base_ft);
4083 FILETIME_TO_U64 (utc_base, utc_base_ft);
7c80d5ec
EZ
4084}
4085
480b0c5b
GV
4086static time_t
4087convert_time (FILETIME ft)
4088{
5da9424d 4089 ULONGLONG tmp;
480b0c5b
GV
4090
4091 if (!init)
4092 {
9d4f32e8 4093 initialize_utc_base ();
480b0c5b
GV
4094 init = 1;
4095 }
4096
4097 if (CompareFileTime (&ft, &utc_base_ft) < 0)
4098 return 0;
4099
5da9424d
JB
4100 FILETIME_TO_U64 (tmp, ft);
4101 return (time_t) ((tmp - utc_base) / 10000000L);
480b0c5b
GV
4102}
4103
bedf4aab 4104static void
480b0c5b
GV
4105convert_from_time_t (time_t time, FILETIME * pft)
4106{
5da9424d 4107 ULARGE_INTEGER tmp;
480b0c5b
GV
4108
4109 if (!init)
4110 {
5da9424d 4111 initialize_utc_base ();
480b0c5b
GV
4112 init = 1;
4113 }
4114
4115 /* time in 100ns units since 1-Jan-1601 */
5da9424d
JB
4116 tmp.QuadPart = (ULONGLONG) time * 10000000L + utc_base;
4117 pft->dwHighDateTime = tmp.HighPart;
4118 pft->dwLowDateTime = tmp.LowPart;
480b0c5b 4119}
480b0c5b 4120
8aaaec6b 4121static PSECURITY_DESCRIPTOR
6dad7178
EZ
4122get_file_security_desc_by_handle (HANDLE h)
4123{
4124 PSECURITY_DESCRIPTOR psd = NULL;
4125 DWORD err;
4126 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4127 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4128
4129 err = get_security_info (h, SE_FILE_OBJECT, si,
4130 NULL, NULL, NULL, NULL, &psd);
4131 if (err != ERROR_SUCCESS)
4132 return NULL;
4133
4134 return psd;
4135}
4136
4137static PSECURITY_DESCRIPTOR
4138get_file_security_desc_by_name (const char *fname)
8aaaec6b
EZ
4139{
4140 PSECURITY_DESCRIPTOR psd = NULL;
4141 DWORD sd_len, err;
4142 SECURITY_INFORMATION si = OWNER_SECURITY_INFORMATION
4143 | GROUP_SECURITY_INFORMATION /* | DACL_SECURITY_INFORMATION */ ;
4144
4145 if (!get_file_security (fname, si, psd, 0, &sd_len))
4146 {
4147 err = GetLastError ();
4148 if (err != ERROR_INSUFFICIENT_BUFFER)
4149 return NULL;
4150 }
4151
4152 psd = xmalloc (sd_len);
4153 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
4154 {
4155 xfree (psd);
4156 return NULL;
4157 }
4158
4159 return psd;
4160}
4161
4162static DWORD
4163get_rid (PSID sid)
4164{
4165 unsigned n_subauthorities;
4166
4167 /* Use the last sub-authority value of the RID, the relative
4168 portion of the SID, as user/group ID. */
4169 n_subauthorities = *get_sid_sub_authority_count (sid);
4170 if (n_subauthorities < 1)
4171 return 0; /* the "World" RID */
4172 return *get_sid_sub_authority (sid, n_subauthorities - 1);
4173}
4174
f8b35b24
EZ
4175/* Caching SID and account values for faster lokup. */
4176
f8b35b24 4177struct w32_id {
22749e9a 4178 unsigned rid;
f8b35b24
EZ
4179 struct w32_id *next;
4180 char name[GNLEN+1];
4181 unsigned char sid[FLEXIBLE_ARRAY_MEMBER];
4182};
4183
4184static struct w32_id *w32_idlist;
4185
4186static int
22749e9a 4187w32_cached_id (PSID sid, unsigned *id, char *name)
f8b35b24
EZ
4188{
4189 struct w32_id *tail, *found;
4190
4191 for (found = NULL, tail = w32_idlist; tail; tail = tail->next)
4192 {
4193 if (equal_sid ((PSID)tail->sid, sid))
4194 {
4195 found = tail;
4196 break;
4197 }
4198 }
4199 if (found)
4200 {
4201 *id = found->rid;
4202 strcpy (name, found->name);
4203 return 1;
4204 }
4205 else
4206 return 0;
4207}
4208
4209static void
22749e9a 4210w32_add_to_cache (PSID sid, unsigned id, char *name)
f8b35b24
EZ
4211{
4212 DWORD sid_len;
4213 struct w32_id *new_entry;
4214
4215 /* We don't want to leave behind stale cache from when Emacs was
4216 dumped. */
4217 if (initialized)
4218 {
4219 sid_len = get_length_sid (sid);
4220 new_entry = xmalloc (offsetof (struct w32_id, sid) + sid_len);
4221 if (new_entry)
4222 {
4223 new_entry->rid = id;
4224 strcpy (new_entry->name, name);
4225 copy_sid (sid_len, (PSID)new_entry->sid, sid);
4226 new_entry->next = w32_idlist;
4227 w32_idlist = new_entry;
4228 }
4229 }
4230}
4231
8aaaec6b
EZ
4232#define UID 1
4233#define GID 2
4234
4235static int
92340ec7 4236get_name_and_id (PSECURITY_DESCRIPTOR psd, unsigned *id, char *nm, int what)
8aaaec6b
EZ
4237{
4238 PSID sid = NULL;
8aaaec6b
EZ
4239 BOOL dflt;
4240 SID_NAME_USE ignore;
4241 char name[UNLEN+1];
4242 DWORD name_len = sizeof (name);
4243 char domain[1024];
ed3751c8 4244 DWORD domain_len = sizeof (domain);
8aaaec6b
EZ
4245 int use_dflt = 0;
4246 int result;
4247
4248 if (what == UID)
4249 result = get_security_descriptor_owner (psd, &sid, &dflt);
4250 else if (what == GID)
4251 result = get_security_descriptor_group (psd, &sid, &dflt);
4252 else
4253 result = 0;
4254
4255 if (!result || !is_valid_sid (sid))
4256 use_dflt = 1;
f8b35b24 4257 else if (!w32_cached_id (sid, id, nm))
8aaaec6b 4258 {
92340ec7 4259 if (!lookup_account_sid (NULL, sid, name, &name_len,
8aaaec6b
EZ
4260 domain, &domain_len, &ignore)
4261 || name_len > UNLEN+1)
4262 use_dflt = 1;
4263 else
4264 {
4265 *id = get_rid (sid);
4266 strcpy (nm, name);
f8b35b24 4267 w32_add_to_cache (sid, *id, name);
8aaaec6b
EZ
4268 }
4269 }
4270 return use_dflt;
4271}
4272
4273static void
92340ec7 4274get_file_owner_and_group (PSECURITY_DESCRIPTOR psd, struct stat *st)
8aaaec6b
EZ
4275{
4276 int dflt_usr = 0, dflt_grp = 0;
4277
4278 if (!psd)
4279 {
4280 dflt_usr = 1;
4281 dflt_grp = 1;
4282 }
4283 else
4284 {
92340ec7 4285 if (get_name_and_id (psd, &st->st_uid, st->st_uname, UID))
8aaaec6b 4286 dflt_usr = 1;
92340ec7 4287 if (get_name_and_id (psd, &st->st_gid, st->st_gname, GID))
8aaaec6b
EZ
4288 dflt_grp = 1;
4289 }
4290 /* Consider files to belong to current user/group, if we cannot get
4291 more accurate information. */
4292 if (dflt_usr)
4293 {
4294 st->st_uid = dflt_passwd.pw_uid;
4295 strcpy (st->st_uname, dflt_passwd.pw_name);
4296 }
4297 if (dflt_grp)
4298 {
4299 st->st_gid = dflt_passwd.pw_gid;
4300 strcpy (st->st_gname, dflt_group.gr_name);
4301 }
4302}
4303
be4c6380
EZ
4304/* Return non-zero if NAME is a potentially slow filesystem. */
4305int
4306is_slow_fs (const char *name)
4307{
4308 char drive_root[4];
4309 UINT devtype;
4310
4311 if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
4312 devtype = DRIVE_REMOTE; /* assume UNC name is remote */
4313 else if (!(strlen (name) >= 2 && IS_DEVICE_SEP (name[1])))
4314 devtype = GetDriveType (NULL); /* use root of current drive */
4315 else
4316 {
4317 /* GetDriveType needs the root directory of the drive. */
4318 strncpy (drive_root, name, 2);
4319 drive_root[2] = '\\';
4320 drive_root[3] = '\0';
4321 devtype = GetDriveType (drive_root);
4322 }
4323 return !(devtype == DRIVE_FIXED || devtype == DRIVE_RAMDISK);
4324}
4325
5c207910
EZ
4326/* If this is non-zero, the caller wants accurate information about
4327 file's owner and group, which could be expensive to get. */
4328int w32_stat_get_owner_group;
4329
480b0c5b
GV
4330/* MSVC stat function can't cope with UNC names and has other bugs, so
4331 replace it with our own. This also allows us to calculate consistent
6dad7178
EZ
4332 inode values and owner/group without hacks in the main Emacs code. */
4333
4334static int
4335stat_worker (const char * path, struct stat * buf, int follow_symlinks)
480b0c5b 4336{
6dad7178 4337 char *name, *save_name, *r;
480b0c5b
GV
4338 WIN32_FIND_DATA wfd;
4339 HANDLE fh;
6dad7178 4340 unsigned __int64 fake_inode = 0;
480b0c5b
GV
4341 int permission;
4342 int len;
4343 int rootdir = FALSE;
8aaaec6b 4344 PSECURITY_DESCRIPTOR psd = NULL;
6dad7178
EZ
4345 int is_a_symlink = 0;
4346 DWORD file_flags = FILE_FLAG_BACKUP_SEMANTICS;
4347 DWORD access_rights = 0;
4348 DWORD fattrs = 0, serialnum = 0, fs_high = 0, fs_low = 0, nlinks = 1;
4349 FILETIME ctime, atime, wtime;
806fed21 4350 int dbcs_p;
480b0c5b
GV
4351
4352 if (path == NULL || buf == NULL)
4353 {
4354 errno = EFAULT;
4355 return -1;
4356 }
4357
6dad7178 4358 save_name = name = (char *) map_w32_filename (path, &path);
22189f79
EZ
4359 /* Must be valid filename, no wild cards or other invalid
4360 characters. We use _mbspbrk to support multibyte strings that
4361 might look to strpbrk as if they included literal *, ?, and other
4362 characters mentioned below that are disallowed by Windows
4363 filesystems. */
4364 if (_mbspbrk (name, "*?|<>\""))
480b0c5b
GV
4365 {
4366 errno = ENOENT;
4367 return -1;
4368 }
4369
4370 /* Remove trailing directory separator, unless name is the root
4371 directory of a drive or UNC volume in which case ensure there
4372 is a trailing separator. */
4373 len = strlen (name);
480b0c5b
GV
4374 name = strcpy (alloca (len + 2), name);
4375
6dad7178
EZ
4376 /* Avoid a somewhat costly call to is_symlink if the filesystem
4377 doesn't support symlinks. */
4378 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
4379 is_a_symlink = is_symlink (name);
4380
4381 /* Plan A: Open the file and get all the necessary information via
4382 the resulting handle. This solves several issues in one blow:
4383
4384 . retrieves attributes for the target of a symlink, if needed
4385 . gets attributes of root directories and symlinks pointing to
4386 root directories, thus avoiding the need for special-casing
4387 these and detecting them by examining the file-name format
4388 . retrieves more accurate attributes (e.g., non-zero size for
4389 some directories, esp. directories that are junction points)
4390 . correctly resolves "c:/..", "/.." and similar file names
4391 . avoids run-time penalties for 99% of use cases
4392
4393 Plan A is always tried first, unless the user asked not to (but
4394 if the file is a symlink and we need to follow links, we try Plan
4395 A even if the user asked not to).
4396
4397 If Plan A fails, we go to Plan B (below), where various
4398 potentially expensive techniques must be used to handle "special"
4399 files such as UNC volumes etc. */
8aaaec6b 4400 if (!(NILP (Vw32_get_true_file_attributes)
19ced600 4401 || (EQ (Vw32_get_true_file_attributes, Qlocal) && is_slow_fs (name)))
6dad7178
EZ
4402 /* Following symlinks requires getting the info by handle. */
4403 || (is_a_symlink && follow_symlinks))
480b0c5b 4404 {
6dad7178
EZ
4405 BY_HANDLE_FILE_INFORMATION info;
4406
4407 if (is_a_symlink && !follow_symlinks)
4408 file_flags |= FILE_FLAG_OPEN_REPARSE_POINT;
4409 /* READ_CONTROL access rights are required to get security info
4410 by handle. But if the OS doesn't support security in the
4411 first place, we don't need to try. */
4412 if (is_windows_9x () != TRUE)
4413 access_rights |= READ_CONTROL;
4414
4415 fh = CreateFile (name, access_rights, 0, NULL, OPEN_EXISTING,
4416 file_flags, NULL);
4417 /* If CreateFile fails with READ_CONTROL, try again with zero as
4418 access rights. */
4419 if (fh == INVALID_HANDLE_VALUE && access_rights)
4420 fh = CreateFile (name, 0, 0, NULL, OPEN_EXISTING,
4421 file_flags, NULL);
4422 if (fh == INVALID_HANDLE_VALUE)
4423 goto no_true_file_attributes;
4424
3ed8598c 4425 /* This is more accurate in terms of getting the correct number
aa5ee2a3 4426 of links, but is quite slow (it is noticeable when Emacs is
480b0c5b 4427 making a list of file name completions). */
480b0c5b
GV
4428 if (GetFileInformationByHandle (fh, &info))
4429 {
6dad7178 4430 nlinks = info.nNumberOfLinks;
76b3903d
GV
4431 /* Might as well use file index to fake inode values, but this
4432 is not guaranteed to be unique unless we keep a handle open
4433 all the time (even then there are situations where it is
4434 not unique). Reputedly, there are at most 48 bits of info
4435 (on NTFS, presumably less on FAT). */
e3b88685
EZ
4436 fake_inode = info.nFileIndexHigh;
4437 fake_inode <<= 32;
4438 fake_inode += info.nFileIndexLow;
6dad7178
EZ
4439 serialnum = info.dwVolumeSerialNumber;
4440 fs_high = info.nFileSizeHigh;
4441 fs_low = info.nFileSizeLow;
4442 ctime = info.ftCreationTime;
4443 atime = info.ftLastAccessTime;
4444 wtime = info.ftLastWriteTime;
4445 fattrs = info.dwFileAttributes;
480b0c5b
GV
4446 }
4447 else
4448 {
6dad7178
EZ
4449 /* We don't go to Plan B here, because it's not clear that
4450 it's a good idea. The only known use case where
4451 CreateFile succeeds, but GetFileInformationByHandle fails
4452 (with ERROR_INVALID_FUNCTION) is for character devices
4453 such as NUL, PRN, etc. For these, switching to Plan B is
4454 a net loss, because we lose the character device
4455 attribute returned by GetFileType below (FindFirstFile
4456 doesn't set that bit in the attributes), and the other
4457 fields don't make sense for character devices anyway.
4458 Emacs doesn't really care for non-file entities in the
4459 context of l?stat, so neither do we. */
4460
4461 /* w32err is assigned so one could put a breakpoint here and
4462 examine its value, when GetFileInformationByHandle
4463 fails. */
4464 DWORD w32err = GetLastError ();
4465
4466 switch (w32err)
4467 {
4468 case ERROR_FILE_NOT_FOUND: /* can this ever happen? */
4469 errno = ENOENT;
4470 return -1;
4471 }
01f31dfb
AI
4472 }
4473
6dad7178
EZ
4474 /* Test for a symlink before testing for a directory, since
4475 symlinks to directories have the directory bit set, but we
4476 don't want them to appear as directories. */
4477 if (is_a_symlink && !follow_symlinks)
4478 buf->st_mode = S_IFLNK;
4479 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
4480 buf->st_mode = S_IFDIR;
93e0f0da
JR
4481 else
4482 {
6dad7178
EZ
4483 DWORD ftype = GetFileType (fh);
4484
4485 switch (ftype)
93e0f0da
JR
4486 {
4487 case FILE_TYPE_DISK:
e3b88685 4488 buf->st_mode = S_IFREG;
93e0f0da
JR
4489 break;
4490 case FILE_TYPE_PIPE:
e3b88685 4491 buf->st_mode = S_IFIFO;
93e0f0da
JR
4492 break;
4493 case FILE_TYPE_CHAR:
4494 case FILE_TYPE_UNKNOWN:
4495 default:
e3b88685 4496 buf->st_mode = S_IFCHR;
93e0f0da 4497 }
480b0c5b 4498 }
6dad7178
EZ
4499 /* We produce the fallback owner and group data, based on the
4500 current user that runs Emacs, in the following cases:
4501
5c207910 4502 . caller didn't request owner and group info
6dad7178
EZ
4503 . this is Windows 9X
4504 . getting security by handle failed, and we need to produce
4505 information for the target of a symlink (this is better
4506 than producing a potentially misleading info about the
4507 symlink itself)
4508
4509 If getting security by handle fails, and we don't need to
4510 resolve symlinks, we try getting security by name. */
5c207910 4511 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
92340ec7 4512 get_file_owner_and_group (NULL, buf);
5c207910 4513 else
6dad7178 4514 {
5c207910
EZ
4515 psd = get_file_security_desc_by_handle (fh);
4516 if (psd)
4517 {
a4b0cca1 4518 get_file_owner_and_group (psd, buf);
5c207910
EZ
4519 LocalFree (psd);
4520 }
4521 else if (!(is_a_symlink && follow_symlinks))
4522 {
4523 psd = get_file_security_desc_by_name (name);
a4b0cca1 4524 get_file_owner_and_group (psd, buf);
5c207910
EZ
4525 xfree (psd);
4526 }
4527 else
a4b0cca1 4528 get_file_owner_and_group (NULL, buf);
6dad7178 4529 }
01f31dfb 4530 CloseHandle (fh);
76b3903d
GV
4531 }
4532 else
4533 {
6dad7178
EZ
4534 no_true_file_attributes:
4535 /* Plan B: Either getting a handle on the file failed, or the
4536 caller explicitly asked us to not bother making this
4537 information more accurate.
4538
4539 Implementation note: In Plan B, we never bother to resolve
4540 symlinks, even if we got here because we tried Plan A and
4541 failed. That's because, even if the caller asked for extra
4542 precision by setting Vw32_get_true_file_attributes to t,
4543 resolving symlinks requires acquiring a file handle to the
4544 symlink, which we already know will fail. And if the user
4545 did not ask for extra precision, resolving symlinks will fly
4546 in the face of that request, since the user then wants the
4547 lightweight version of the code. */
806fed21 4548 dbcs_p = max_filename_mbslen () > 1;
6dad7178
EZ
4549 rootdir = (path >= save_name + len - 1
4550 && (IS_DIRECTORY_SEP (*path) || *path == 0));
4551
4552 /* If name is "c:/.." or "/.." then stat "c:/" or "/". */
4553 r = IS_DEVICE_SEP (name[1]) ? &name[2] : name;
4554 if (IS_DIRECTORY_SEP (r[0])
4555 && r[1] == '.' && r[2] == '.' && r[3] == '\0')
4556 r[1] = r[2] = '\0';
4557
4558 /* Note: If NAME is a symlink to the root of a UNC volume
4559 (i.e. "\\SERVER"), we will not detect that here, and we will
4560 return data about the symlink as result of FindFirst below.
4561 This is unfortunate, but that marginal use case does not
4562 justify a call to chase_symlinks which would impose a penalty
4563 on all the other use cases. (We get here for symlinks to
4564 roots of UNC volumes because CreateFile above fails for them,
4565 unlike with symlinks to root directories X:\ of drives.) */
4566 if (is_unc_volume (name))
4567 {
4568 fattrs = unc_volume_file_attributes (name);
4569 if (fattrs == -1)
4570 return -1;
4571
4572 ctime = atime = wtime = utc_base_ft;
4573 }
4574 else if (rootdir)
4575 {
806fed21
EZ
4576 if (!dbcs_p)
4577 {
4578 if (!IS_DIRECTORY_SEP (name[len-1]))
4579 strcat (name, "\\");
4580 }
4581 else
4582 {
4583 char *end = name + len;
4584 char *n = CharPrevExA (file_name_codepage, name, end, 0);
4585
4586 if (!IS_DIRECTORY_SEP (*n))
4587 strcat (name, "\\");
4588 }
6dad7178
EZ
4589 if (GetDriveType (name) < 2)
4590 {
4591 errno = ENOENT;
4592 return -1;
4593 }
4594
4595 fattrs = FILE_ATTRIBUTE_DIRECTORY;
4596 ctime = atime = wtime = utc_base_ft;
4597 }
4598 else
4599 {
806fed21
EZ
4600 if (!dbcs_p)
4601 {
4602 if (IS_DIRECTORY_SEP (name[len-1]))
4603 name[len - 1] = 0;
4604 }
4605 else
4606 {
4607 char *end = name + len;
4608 char *n = CharPrevExA (file_name_codepage, name, end, 0);
4609
4610 if (IS_DIRECTORY_SEP (*n))
4611 *n = 0;
4612 }
6dad7178
EZ
4613
4614 /* (This is hacky, but helps when doing file completions on
4615 network drives.) Optimize by using information available from
4616 active readdir if possible. */
4617 len = strlen (dir_pathname);
806fed21
EZ
4618 if (!dbcs_p)
4619 {
4620 if (IS_DIRECTORY_SEP (dir_pathname[len-1]))
4621 len--;
4622 }
4623 else
4624 {
4625 char *end = dir_pathname + len;
4626 char *n = CharPrevExA (file_name_codepage, dir_pathname, end, 0);
4627
4628 if (IS_DIRECTORY_SEP (*n))
4629 len--;
4630 }
6dad7178
EZ
4631 if (dir_find_handle != INVALID_HANDLE_VALUE
4632 && !(is_a_symlink && follow_symlinks)
4633 && strnicmp (save_name, dir_pathname, len) == 0
4634 && IS_DIRECTORY_SEP (name[len])
4635 && xstrcasecmp (name + len + 1, dir_static.d_name) == 0)
4636 {
4637 /* This was the last entry returned by readdir. */
0b9de7cd 4638 wfd = dir_find_data_a; /* FIXME!!! */
6dad7178
EZ
4639 }
4640 else
4641 {
4642 logon_network_drive (name);
4643
4644 fh = FindFirstFile (name, &wfd);
4645 if (fh == INVALID_HANDLE_VALUE)
4646 {
4647 errno = ENOENT;
4648 return -1;
4649 }
4650 FindClose (fh);
4651 }
4652 /* Note: if NAME is a symlink, the information we get from
4653 FindFirstFile is for the symlink, not its target. */
4654 fattrs = wfd.dwFileAttributes;
4655 ctime = wfd.ftCreationTime;
4656 atime = wfd.ftLastAccessTime;
4657 wtime = wfd.ftLastWriteTime;
4658 fs_high = wfd.nFileSizeHigh;
4659 fs_low = wfd.nFileSizeLow;
4660 fake_inode = 0;
4661 nlinks = 1;
4662 serialnum = volume_info.serialnum;
4663 }
4664 if (is_a_symlink && !follow_symlinks)
4665 buf->st_mode = S_IFLNK;
4666 else if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
4667 buf->st_mode = S_IFDIR;
4668 else
4669 buf->st_mode = S_IFREG;
8aaaec6b 4670
92340ec7 4671 get_file_owner_and_group (NULL, buf);
76b3903d
GV
4672 }
4673
4674#if 0
4675 /* Not sure if there is any point in this. */
4676 if (!NILP (Vw32_generate_fake_inodes))
4677 fake_inode = generate_inode_val (name);
4678 else if (fake_inode == 0)
4679 {
4680 /* For want of something better, try to make everything unique. */
4681 static DWORD gen_num = 0;
4682 fake_inode = ++gen_num;
480b0c5b 4683 }
76b3903d
GV
4684#endif
4685
6dad7178 4686 buf->st_ino = fake_inode;
480b0c5b 4687
6dad7178
EZ
4688 buf->st_dev = serialnum;
4689 buf->st_rdev = serialnum;
480b0c5b 4690
6dad7178 4691 buf->st_size = fs_high;
8aaaec6b 4692 buf->st_size <<= 32;
6dad7178
EZ
4693 buf->st_size += fs_low;
4694 buf->st_nlink = nlinks;
480b0c5b
GV
4695
4696 /* Convert timestamps to Unix format. */
6dad7178
EZ
4697 buf->st_mtime = convert_time (wtime);
4698 buf->st_atime = convert_time (atime);
480b0c5b 4699 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
6dad7178 4700 buf->st_ctime = convert_time (ctime);
480b0c5b
GV
4701 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
4702
4703 /* determine rwx permissions */
6dad7178
EZ
4704 if (is_a_symlink && !follow_symlinks)
4705 permission = S_IREAD | S_IWRITE | S_IEXEC; /* Posix expectations */
480b0c5b 4706 else
6dad7178
EZ
4707 {
4708 if (fattrs & FILE_ATTRIBUTE_READONLY)
4709 permission = S_IREAD;
4710 else
4711 permission = S_IREAD | S_IWRITE;
177c0ea7 4712
6dad7178
EZ
4713 if (fattrs & FILE_ATTRIBUTE_DIRECTORY)
4714 permission |= S_IEXEC;
4715 else if (is_exec (name))
4716 permission |= S_IEXEC;
4717 }
480b0c5b
GV
4718
4719 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
4720
4721 return 0;
4722}
4723
6dad7178
EZ
4724int
4725stat (const char * path, struct stat * buf)
4726{
4727 return stat_worker (path, buf, 1);
4728}
4729
4730int
4731lstat (const char * path, struct stat * buf)
4732{
4733 return stat_worker (path, buf, 0);
4734}
4735
8654f9d7
PE
4736int
4737fstatat (int fd, char const *name, struct stat *st, int flags)
4738{
4739 /* Rely on a hack: an open directory is modeled as file descriptor 0.
4740 This is good enough for the current usage in Emacs, but is fragile.
4741
d9c287e5 4742 FIXME: Add proper support for fdopendir, fstatat, readlinkat.
8654f9d7
PE
4743 Gnulib does this and can serve as a model. */
4744 char fullname[MAX_PATH];
4745
4746 if (fd != AT_FDCWD)
4747 {
4748 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
4749 < 0)
4750 {
4751 errno = ENAMETOOLONG;
4752 return -1;
4753 }
4754 name = fullname;
4755 }
4756
4757 return stat_worker (name, st, ! (flags & AT_SYMLINK_NOFOLLOW));
4758}
4759
16bb7578
GV
4760/* Provide fstat and utime as well as stat for consistent handling of
4761 file timestamps. */
4762int
4763fstat (int desc, struct stat * buf)
4764{
4765 HANDLE fh = (HANDLE) _get_osfhandle (desc);
4766 BY_HANDLE_FILE_INFORMATION info;
e3b88685 4767 unsigned __int64 fake_inode;
16bb7578
GV
4768 int permission;
4769
4770 switch (GetFileType (fh) & ~FILE_TYPE_REMOTE)
4771 {
4772 case FILE_TYPE_DISK:
e3b88685 4773 buf->st_mode = S_IFREG;
16bb7578
GV
4774 if (!GetFileInformationByHandle (fh, &info))
4775 {
4776 errno = EACCES;
4777 return -1;
4778 }
4779 break;
4780 case FILE_TYPE_PIPE:
e3b88685 4781 buf->st_mode = S_IFIFO;
16bb7578
GV
4782 goto non_disk;
4783 case FILE_TYPE_CHAR:
4784 case FILE_TYPE_UNKNOWN:
4785 default:
e3b88685 4786 buf->st_mode = S_IFCHR;
16bb7578
GV
4787 non_disk:
4788 memset (&info, 0, sizeof (info));
4789 info.dwFileAttributes = 0;
4790 info.ftCreationTime = utc_base_ft;
4791 info.ftLastAccessTime = utc_base_ft;
4792 info.ftLastWriteTime = utc_base_ft;
4793 }
4794
4795 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
e3b88685 4796 buf->st_mode = S_IFDIR;
93e0f0da
JR
4797
4798 buf->st_nlink = info.nNumberOfLinks;
4799 /* Might as well use file index to fake inode values, but this
4800 is not guaranteed to be unique unless we keep a handle open
4801 all the time (even then there are situations where it is
4802 not unique). Reputedly, there are at most 48 bits of info
4803 (on NTFS, presumably less on FAT). */
e3b88685
EZ
4804 fake_inode = info.nFileIndexHigh;
4805 fake_inode <<= 32;
4806 fake_inode += info.nFileIndexLow;
16bb7578
GV
4807
4808 /* MSVC defines _ino_t to be short; other libc's might not. */
4809 if (sizeof (buf->st_ino) == 2)
4810 buf->st_ino = fake_inode ^ (fake_inode >> 16);
4811 else
4812 buf->st_ino = fake_inode;
4813
76e9f7b9
EZ
4814 /* If the caller so requested, get the true file owner and group.
4815 Otherwise, consider the file to belong to the current user. */
4816 if (!w32_stat_get_owner_group || is_windows_9x () == TRUE)
4817 get_file_owner_and_group (NULL, buf);
4818 else
4819 {
4820 PSECURITY_DESCRIPTOR psd = NULL;
4821
4822 psd = get_file_security_desc_by_handle (fh);
4823 if (psd)
4824 {
4825 get_file_owner_and_group (psd, buf);
4826 LocalFree (psd);
4827 }
4828 else
4829 get_file_owner_and_group (NULL, buf);
4830 }
16bb7578
GV
4831
4832 buf->st_dev = info.dwVolumeSerialNumber;
4833 buf->st_rdev = info.dwVolumeSerialNumber;
4834
8aaaec6b
EZ
4835 buf->st_size = info.nFileSizeHigh;
4836 buf->st_size <<= 32;
4837 buf->st_size += info.nFileSizeLow;
16bb7578
GV
4838
4839 /* Convert timestamps to Unix format. */
4840 buf->st_mtime = convert_time (info.ftLastWriteTime);
4841 buf->st_atime = convert_time (info.ftLastAccessTime);
4842 if (buf->st_atime == 0) buf->st_atime = buf->st_mtime;
4843 buf->st_ctime = convert_time (info.ftCreationTime);
4844 if (buf->st_ctime == 0) buf->st_ctime = buf->st_mtime;
4845
4846 /* determine rwx permissions */
4847 if (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
e3b88685 4848 permission = S_IREAD;
16bb7578 4849 else
e3b88685 4850 permission = S_IREAD | S_IWRITE;
177c0ea7 4851
16bb7578 4852 if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
e3b88685 4853 permission |= S_IEXEC;
16bb7578
GV
4854 else
4855 {
4856#if 0 /* no way of knowing the filename */
4857 char * p = strrchr (name, '.');
4858 if (p != NULL &&
05131107
JR
4859 (xstrcasecmp (p, ".exe") == 0 ||
4860 xstrcasecmp (p, ".com") == 0 ||
4861 xstrcasecmp (p, ".bat") == 0 ||
4862 xstrcasecmp (p, ".cmd") == 0))
e3b88685 4863 permission |= S_IEXEC;
16bb7578
GV
4864#endif
4865 }
4866
4867 buf->st_mode |= permission | (permission >> 3) | (permission >> 6);
4868
4869 return 0;
4870}
4871
b34454d0
EZ
4872/* A version of 'utime' which handles directories as well as
4873 files. */
4874
16bb7578 4875int
86e93460 4876utime (const char *name, struct utimbuf *times)
16bb7578 4877{
86e93460 4878 struct utimbuf deftime;
16bb7578
GV
4879 HANDLE fh;
4880 FILETIME mtime;
4881 FILETIME atime;
4882
4883 if (times == NULL)
4884 {
4885 deftime.modtime = deftime.actime = time (NULL);
4886 times = &deftime;
4887 }
4888
80fcb9d2
EZ
4889 if (w32_unicode_filenames)
4890 {
4891 wchar_t name_utf16[MAX_PATH];
4892
4893 if (filename_to_utf16 (name, name_utf16) != 0)
4894 return -1; /* errno set by filename_to_utf16 */
4895
4896 /* Need write access to set times. */
4897 fh = CreateFileW (name_utf16, FILE_WRITE_ATTRIBUTES,
4898 /* If NAME specifies a directory, FILE_SHARE_DELETE
4899 allows other processes to delete files inside it,
4900 while we have the directory open. */
4901 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
4902 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
4903 }
4904 else
4905 {
4906 char name_ansi[MAX_PATH];
4907
4908 if (filename_to_ansi (name, name_ansi) != 0)
4909 return -1; /* errno set by filename_to_ansi */
4910
4911 fh = CreateFileA (name_ansi, FILE_WRITE_ATTRIBUTES,
4912 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
4913 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
4914 }
7604f298 4915 if (fh != INVALID_HANDLE_VALUE)
16bb7578
GV
4916 {
4917 convert_from_time_t (times->actime, &atime);
4918 convert_from_time_t (times->modtime, &mtime);
4919 if (!SetFileTime (fh, NULL, &atime, &mtime))
4920 {
4921 CloseHandle (fh);
4922 errno = EACCES;
4923 return -1;
4924 }
4925 CloseHandle (fh);
4926 }
4927 else
4928 {
80fcb9d2
EZ
4929 DWORD err = GetLastError ();
4930
4931 switch (err)
4932 {
4933 case ERROR_FILE_NOT_FOUND:
4934 case ERROR_PATH_NOT_FOUND:
4935 case ERROR_INVALID_DRIVE:
4936 case ERROR_BAD_NETPATH:
4937 case ERROR_DEV_NOT_EXIST:
4938 /* ERROR_INVALID_NAME is the error CreateFile sets when the
4939 file name includes ?s, i.e. translation to ANSI failed. */
4940 case ERROR_INVALID_NAME:
4941 errno = ENOENT;
4942 break;
4943 case ERROR_TOO_MANY_OPEN_FILES:
4944 errno = ENFILE;
4945 break;
4946 case ERROR_ACCESS_DENIED:
4947 case ERROR_SHARING_VIOLATION:
4948 errno = EACCES;
4949 break;
4950 default:
4951 errno = EINVAL;
4952 break;
4953 }
16bb7578
GV
4954 return -1;
4955 }
4956 return 0;
4957}
4958
7c80d5ec 4959\f
6dad7178
EZ
4960/* Symlink-related functions. */
4961#ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
4962#define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
4963#endif
4964
0f7bb05d 4965int
6dad7178 4966symlink (char const *filename, char const *linkname)
0f7bb05d 4967{
6dad7178
EZ
4968 char linkfn[MAX_PATH], *tgtfn;
4969 DWORD flags = 0;
4970 int dir_access, filename_ends_in_slash;
806fed21 4971 int dbcs_p;
6dad7178
EZ
4972
4973 /* Diagnostics follows Posix as much as possible. */
4974 if (filename == NULL || linkname == NULL)
4975 {
4976 errno = EFAULT;
4977 return -1;
4978 }
4979 if (!*filename)
4980 {
4981 errno = ENOENT;
4982 return -1;
4983 }
4984 if (strlen (filename) > MAX_PATH || strlen (linkname) > MAX_PATH)
4985 {
4986 errno = ENAMETOOLONG;
4987 return -1;
4988 }
4989
4990 strcpy (linkfn, map_w32_filename (linkname, NULL));
4991 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0)
4992 {
4993 errno = EPERM;
4994 return -1;
4995 }
4996
806fed21
EZ
4997 dbcs_p = max_filename_mbslen () > 1;
4998
6dad7178
EZ
4999 /* Note: since empty FILENAME was already rejected, we can safely
5000 refer to FILENAME[1]. */
5001 if (!(IS_DIRECTORY_SEP (filename[0]) || IS_DEVICE_SEP (filename[1])))
5002 {
5003 /* Non-absolute FILENAME is understood as being relative to
5004 LINKNAME's directory. We need to prepend that directory to
14f20728 5005 FILENAME to get correct results from faccessat below, since
6dad7178
EZ
5006 otherwise it will interpret FILENAME relative to the
5007 directory where the Emacs process runs. Note that
5008 make-symbolic-link always makes sure LINKNAME is a fully
5009 expanded file name. */
5010 char tem[MAX_PATH];
5011 char *p = linkfn + strlen (linkfn);
5012
806fed21
EZ
5013 if (!dbcs_p)
5014 {
5015 while (p > linkfn && !IS_ANY_SEP (p[-1]))
5016 p--;
5017 }
5018 else
5019 {
5020 char *p1 = CharPrevExA (file_name_codepage, linkfn, p, 0);
5021
5022 while (p > linkfn && !IS_ANY_SEP (*p1))
5023 {
5024 p = p1;
5025 p1 = CharPrevExA (file_name_codepage, linkfn, p1, 0);
5026 }
5027 }
6dad7178
EZ
5028 if (p > linkfn)
5029 strncpy (tem, linkfn, p - linkfn);
5030 tem[p - linkfn] = '\0';
5031 strcat (tem, filename);
14f20728 5032 dir_access = faccessat (AT_FDCWD, tem, D_OK, AT_EACCESS);
6dad7178
EZ
5033 }
5034 else
14f20728 5035 dir_access = faccessat (AT_FDCWD, filename, D_OK, AT_EACCESS);
6dad7178
EZ
5036
5037 /* Since Windows distinguishes between symlinks to directories and
8b2e00a3 5038 to files, we provide a kludgy feature: if FILENAME doesn't
6dad7178
EZ
5039 exist, but ends in a slash, we create a symlink to directory. If
5040 FILENAME exists and is a directory, we always create a symlink to
5041 directory. */
806fed21
EZ
5042 if (!dbcs_p)
5043 filename_ends_in_slash = IS_DIRECTORY_SEP (filename[strlen (filename) - 1]);
5044 else
5045 {
5046 const char *end = filename + strlen (filename);
5047 const char *n = CharPrevExA (file_name_codepage, filename, end, 0);
5048
5049 filename_ends_in_slash = IS_DIRECTORY_SEP (*n);
5050 }
6dad7178
EZ
5051 if (dir_access == 0 || filename_ends_in_slash)
5052 flags = SYMBOLIC_LINK_FLAG_DIRECTORY;
5053
5054 tgtfn = (char *)map_w32_filename (filename, NULL);
5055 if (filename_ends_in_slash)
5056 tgtfn[strlen (tgtfn) - 1] = '\0';
5057
5058 errno = 0;
5059 if (!create_symbolic_link (linkfn, tgtfn, flags))
5060 {
5061 /* ENOSYS is set by create_symbolic_link, when it detects that
5062 the OS doesn't support the CreateSymbolicLink API. */
5063 if (errno != ENOSYS)
5064 {
5065 DWORD w32err = GetLastError ();
5066
5067 switch (w32err)
5068 {
5069 /* ERROR_SUCCESS is sometimes returned when LINKFN and
5070 TGTFN point to the same file name, go figure. */
5071 case ERROR_SUCCESS:
5072 case ERROR_FILE_EXISTS:
5073 errno = EEXIST;
5074 break;
5075 case ERROR_ACCESS_DENIED:
5076 errno = EACCES;
5077 break;
5078 case ERROR_FILE_NOT_FOUND:
5079 case ERROR_PATH_NOT_FOUND:
5080 case ERROR_BAD_NETPATH:
5081 case ERROR_INVALID_REPARSE_DATA:
5082 errno = ENOENT;
5083 break;
5084 case ERROR_DIRECTORY:
5085 errno = EISDIR;
5086 break;
5087 case ERROR_PRIVILEGE_NOT_HELD:
5088 case ERROR_NOT_ALL_ASSIGNED:
5089 errno = EPERM;
5090 break;
5091 case ERROR_DISK_FULL:
5092 errno = ENOSPC;
5093 break;
5094 default:
5095 errno = EINVAL;
5096 break;
5097 }
5098 }
5099 return -1;
5100 }
5101 return 0;
0f7bb05d
EZ
5102}
5103
6dad7178
EZ
5104/* A quick inexpensive test of whether FILENAME identifies a file that
5105 is a symlink. Returns non-zero if it is, zero otherwise. FILENAME
5106 must already be in the normalized form returned by
5107 map_w32_filename.
5108
5109 Note: for repeated operations on many files, it is best to test
5110 whether the underlying volume actually supports symlinks, by
5111 testing the FILE_SUPPORTS_REPARSE_POINTS bit in volume's flags, and
5112 avoid the call to this function if it doesn't. That's because the
8b2e00a3 5113 call to GetFileAttributes takes a non-negligible time, especially
6dad7178
EZ
5114 on non-local or removable filesystems. See stat_worker for an
5115 example of how to do that. */
5116static int
5117is_symlink (const char *filename)
5118{
5119 DWORD attrs;
5120 WIN32_FIND_DATA wfd;
5121 HANDLE fh;
5122
5123 attrs = GetFileAttributes (filename);
5124 if (attrs == -1)
5125 {
5126 DWORD w32err = GetLastError ();
5127
5128 switch (w32err)
5129 {
5130 case ERROR_BAD_NETPATH: /* network share, can't be a symlink */
5131 break;
5132 case ERROR_ACCESS_DENIED:
5133 errno = EACCES;
5134 break;
5135 case ERROR_FILE_NOT_FOUND:
5136 case ERROR_PATH_NOT_FOUND:
5137 default:
5138 errno = ENOENT;
5139 break;
5140 }
5141 return 0;
5142 }
5143 if ((attrs & FILE_ATTRIBUTE_REPARSE_POINT) == 0)
5144 return 0;
5145 logon_network_drive (filename);
5146 fh = FindFirstFile (filename, &wfd);
5147 if (fh == INVALID_HANDLE_VALUE)
5148 return 0;
5149 FindClose (fh);
5150 return (wfd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
5151 && (wfd.dwReserved0 & IO_REPARSE_TAG_SYMLINK) == IO_REPARSE_TAG_SYMLINK;
5152}
5153
5154/* If NAME identifies a symbolic link, copy into BUF the file name of
5155 the symlink's target. Copy at most BUF_SIZE bytes, and do NOT
5156 null-terminate the target name, even if it fits. Return the number
5157 of bytes copied, or -1 if NAME is not a symlink or any error was
5158 encountered while resolving it. The file name copied into BUF is
5159 encoded in the current ANSI codepage. */
0f7bb05d 5160ssize_t
6dad7178 5161readlink (const char *name, char *buf, size_t buf_size)
0f7bb05d 5162{
6dad7178
EZ
5163 const char *path;
5164 TOKEN_PRIVILEGES privs;
5165 int restore_privs = 0;
5166 HANDLE sh;
5167 ssize_t retval;
5168
5169 if (name == NULL)
5170 {
5171 errno = EFAULT;
5172 return -1;
5173 }
5174 if (!*name)
5175 {
5176 errno = ENOENT;
5177 return -1;
5178 }
5179
5180 path = map_w32_filename (name, NULL);
5181
5182 if (strlen (path) > MAX_PATH)
5183 {
5184 errno = ENAMETOOLONG;
5185 return -1;
5186 }
5187
5188 errno = 0;
5189 if (is_windows_9x () == TRUE
5190 || (volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) == 0
5191 || !is_symlink (path))
5192 {
5193 if (!errno)
5194 errno = EINVAL; /* not a symlink */
5195 return -1;
5196 }
5197
5198 /* Done with simple tests, now we're in for some _real_ work. */
5199 if (enable_privilege (SE_BACKUP_NAME, TRUE, &privs))
5200 restore_privs = 1;
5201 /* Implementation note: From here and onward, don't return early,
5202 since that will fail to restore the original set of privileges of
5203 the calling thread. */
5204
5205 retval = -1; /* not too optimistic, are we? */
5206
5207 /* Note: In the next call to CreateFile, we use zero as the 2nd
5208 argument because, when the symlink is a hidden/system file,
5209 e.g. 'C:\Users\All Users', GENERIC_READ fails with
5210 ERROR_ACCESS_DENIED. Zero seems to work just fine, both for file
5211 and directory symlinks. */
5212 sh = CreateFile (path, 0, 0, NULL, OPEN_EXISTING,
5213 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
5214 NULL);
5215 if (sh != INVALID_HANDLE_VALUE)
5216 {
5217 BYTE reparse_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
5218 REPARSE_DATA_BUFFER *reparse_data = (REPARSE_DATA_BUFFER *)&reparse_buf[0];
5219 DWORD retbytes;
5220
5221 if (!DeviceIoControl (sh, FSCTL_GET_REPARSE_POINT, NULL, 0,
5222 reparse_buf, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
5223 &retbytes, NULL))
5224 errno = EIO;
5225 else if (reparse_data->ReparseTag != IO_REPARSE_TAG_SYMLINK)
5226 errno = EINVAL;
5227 else
5228 {
474d441e 5229 /* Copy the link target name, in wide characters, from
6dad7178
EZ
5230 reparse_data, then convert it to multibyte encoding in
5231 the current locale's codepage. */
5232 WCHAR *lwname;
5233 BYTE lname[MAX_PATH];
5234 USHORT lname_len;
5235 USHORT lwname_len =
5236 reparse_data->SymbolicLinkReparseBuffer.PrintNameLength;
5237 WCHAR *lwname_src =
5238 reparse_data->SymbolicLinkReparseBuffer.PathBuffer
5239 + reparse_data->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
26854e9c
EZ
5240 /* This updates file_name_codepage which we need below. */
5241 int dbcs_p = max_filename_mbslen () > 1;
6dad7178
EZ
5242
5243 /* According to MSDN, PrintNameLength does not include the
5244 terminating null character. */
5245 lwname = alloca ((lwname_len + 1) * sizeof(WCHAR));
5246 memcpy (lwname, lwname_src, lwname_len);
5247 lwname[lwname_len/sizeof(WCHAR)] = 0; /* null-terminate */
5248
26854e9c 5249 lname_len = WideCharToMultiByte (file_name_codepage, 0, lwname, -1,
6dad7178
EZ
5250 lname, MAX_PATH, NULL, NULL);
5251 if (!lname_len)
5252 {
5253 /* WideCharToMultiByte failed. */
5254 DWORD w32err1 = GetLastError ();
5255
5256 switch (w32err1)
5257 {
5258 case ERROR_INSUFFICIENT_BUFFER:
5259 errno = ENAMETOOLONG;
5260 break;
5261 case ERROR_INVALID_PARAMETER:
5262 errno = EFAULT;
5263 break;
5264 case ERROR_NO_UNICODE_TRANSLATION:
5265 errno = ENOENT;
5266 break;
5267 default:
5268 errno = EINVAL;
5269 break;
5270 }
5271 }
5272 else
5273 {
5274 size_t size_to_copy = buf_size;
6ee4509a 5275 BYTE *p = lname, *p2;
6dad7178
EZ
5276 BYTE *pend = p + lname_len;
5277
5278 /* Normalize like dostounix_filename does, but we don't
5279 want to assume that lname is null-terminated. */
6ee4509a 5280 if (dbcs_p)
26854e9c 5281 p2 = CharNextExA (file_name_codepage, p, 0);
6ee4509a
EZ
5282 else
5283 p2 = p + 1;
5284 if (*p && *p2 == ':' && *p >= 'A' && *p <= 'Z')
5285 {
5286 *p += 'a' - 'A';
5287 p += 2;
5288 }
6dad7178
EZ
5289 while (p <= pend)
5290 {
5291 if (*p == '\\')
5292 *p = '/';
6ee4509a
EZ
5293 if (dbcs_p)
5294 {
26854e9c 5295 p = CharNextExA (file_name_codepage, p, 0);
6ee4509a
EZ
5296 /* CharNextExA doesn't advance at null character. */
5297 if (!*p)
5298 break;
5299 }
5300 else
5301 ++p;
6dad7178
EZ
5302 }
5303 /* Testing for null-terminated LNAME is paranoia:
5304 WideCharToMultiByte should always return a
5305 null-terminated string when its 4th argument is -1
5306 and its 3rd argument is null-terminated (which they
5307 are, see above). */
5308 if (lname[lname_len - 1] == '\0')
5309 lname_len--;
5310 if (lname_len <= buf_size)
5311 size_to_copy = lname_len;
5312 strncpy (buf, lname, size_to_copy);
5313 /* Success! */
5314 retval = size_to_copy;
5315 }
5316 }
5317 CloseHandle (sh);
5318 }
5319 else
5320 {
5321 /* CreateFile failed. */
5322 DWORD w32err2 = GetLastError ();
5323
5324 switch (w32err2)
5325 {
5326 case ERROR_FILE_NOT_FOUND:
5327 case ERROR_PATH_NOT_FOUND:
5328 errno = ENOENT;
5329 break;
5330 case ERROR_ACCESS_DENIED:
5331 case ERROR_TOO_MANY_OPEN_FILES:
5332 errno = EACCES;
5333 break;
5334 default:
5335 errno = EPERM;
5336 break;
5337 }
5338 }
5339 if (restore_privs)
5340 {
5341 restore_privilege (&privs);
5342 revert_to_self ();
5343 }
5344
5345 return retval;
0f7bb05d
EZ
5346}
5347
8654f9d7
PE
5348ssize_t
5349readlinkat (int fd, char const *name, char *buffer,
5350 size_t buffer_size)
5351{
5352 /* Rely on a hack: an open directory is modeled as file descriptor 0,
5353 as in fstatat. FIXME: Add proper support for readlinkat. */
5354 char fullname[MAX_PATH];
5355
5356 if (fd != AT_FDCWD)
5357 {
5358 if (_snprintf (fullname, sizeof fullname, "%s/%s", dir_pathname, name)
5359 < 0)
5360 {
5361 errno = ENAMETOOLONG;
5362 return -1;
5363 }
5364 name = fullname;
5365 }
5366
5367 return readlink (name, buffer, buffer_size);
5368}
5369
6dad7178
EZ
5370/* If FILE is a symlink, return its target (stored in a static
5371 buffer); otherwise return FILE.
5372
5373 This function repeatedly resolves symlinks in the last component of
5374 a chain of symlink file names, as in foo -> bar -> baz -> ...,
5375 until it arrives at a file whose last component is not a symlink,
5376 or some error occurs. It returns the target of the last
5377 successfully resolved symlink in the chain. If it succeeds to
5378 resolve even a single symlink, the value returned is an absolute
5379 file name with backslashes (result of GetFullPathName). By
5380 contrast, if the original FILE is returned, it is unaltered.
5381
5382 Note: This function can set errno even if it succeeds.
5383
5384 Implementation note: we only resolve the last portion ("basename")
5385 of the argument FILE and of each following file in the chain,
5386 disregarding any possible symlinks in its leading directories.
5387 This is because Windows system calls and library functions
5388 transparently resolve symlinks in leading directories and return
5389 correct information, as long as the basename is not a symlink. */
5390static char *
5391chase_symlinks (const char *file)
5392{
5393 static char target[MAX_PATH];
5394 char link[MAX_PATH];
5395 ssize_t res, link_len;
5396 int loop_count = 0;
806fed21 5397 int dbcs_p;
6dad7178
EZ
5398
5399 if (is_windows_9x () == TRUE || !is_symlink (file))
5400 return (char *)file;
5401
5402 if ((link_len = GetFullPathName (file, MAX_PATH, link, NULL)) == 0)
5403 return (char *)file;
5404
806fed21 5405 dbcs_p = max_filename_mbslen () > 1;
6dad7178
EZ
5406 target[0] = '\0';
5407 do {
5408
5409 /* Remove trailing slashes, as we want to resolve the last
5410 non-trivial part of the link name. */
806fed21
EZ
5411 if (!dbcs_p)
5412 {
5413 while (link_len > 3 && IS_DIRECTORY_SEP (link[link_len-1]))
5414 link[link_len--] = '\0';
5415 }
5416 else if (link_len > 3)
5417 {
5418 char *n = CharPrevExA (file_name_codepage, link, link + link_len, 0);
5419
5420 while (n >= link + 2 && IS_DIRECTORY_SEP (*n))
5421 {
5422 n[1] = '\0';
5423 n = CharPrevExA (file_name_codepage, link, n, 0);
5424 }
5425 }
6dad7178
EZ
5426
5427 res = readlink (link, target, MAX_PATH);
5428 if (res > 0)
5429 {
5430 target[res] = '\0';
5431 if (!(IS_DEVICE_SEP (target[1])
25a20a3a 5432 || (IS_DIRECTORY_SEP (target[0]) && IS_DIRECTORY_SEP (target[1]))))
6dad7178
EZ
5433 {
5434 /* Target is relative. Append it to the directory part of
5435 the symlink, then copy the result back to target. */
5436 char *p = link + link_len;
5437
806fed21
EZ
5438 if (!dbcs_p)
5439 {
5440 while (p > link && !IS_ANY_SEP (p[-1]))
5441 p--;
5442 }
5443 else
5444 {
5445 char *p1 = CharPrevExA (file_name_codepage, link, p, 0);
5446
5447 while (p > link && !IS_ANY_SEP (*p1))
5448 {
5449 p = p1;
5450 p1 = CharPrevExA (file_name_codepage, link, p1, 0);
5451 }
5452 }
6dad7178
EZ
5453 strcpy (p, target);
5454 strcpy (target, link);
5455 }
5456 /* Resolve any "." and ".." to get a fully-qualified file name
5457 in link[] again. */
5458 link_len = GetFullPathName (target, MAX_PATH, link, NULL);
5459 }
5460 } while (res > 0 && link_len > 0 && ++loop_count <= 100);
5461
5462 if (loop_count > 100)
5463 errno = ELOOP;
5464
5465 if (target[0] == '\0') /* not a single call to readlink succeeded */
5466 return (char *)file;
5467 return target;
5468}
5469
66447e07
EZ
5470\f
5471/* Posix ACL emulation. */
5472
5473int
5474acl_valid (acl_t acl)
5475{
5476 return is_valid_security_descriptor ((PSECURITY_DESCRIPTOR)acl) ? 0 : -1;
5477}
5478
5479char *
5480acl_to_text (acl_t acl, ssize_t *size)
5481{
5482 LPTSTR str_acl;
5483 SECURITY_INFORMATION flags =
5484 OWNER_SECURITY_INFORMATION |
5485 GROUP_SECURITY_INFORMATION |
5486 DACL_SECURITY_INFORMATION;
5487 char *retval = NULL;
b764d018 5488 ULONG local_size;
66447e07
EZ
5489 int e = errno;
5490
5491 errno = 0;
5492
5493 if (convert_sd_to_sddl ((PSECURITY_DESCRIPTOR)acl, SDDL_REVISION_1, flags, &str_acl, &local_size))
5494 {
5495 errno = e;
5496 /* We don't want to mix heaps, so we duplicate the string in our
5497 heap and free the one allocated by the API. */
5498 retval = xstrdup (str_acl);
5499 if (size)
5500 *size = local_size;
5501 LocalFree (str_acl);
5502 }
5503 else if (errno != ENOTSUP)
5504 errno = EINVAL;
5505
5506 return retval;
5507}
5508
5509acl_t
5510acl_from_text (const char *acl_str)
5511{
5512 PSECURITY_DESCRIPTOR psd, retval = NULL;
5513 ULONG sd_size;
5514 int e = errno;
5515
5516 errno = 0;
5517
5518 if (convert_sddl_to_sd (acl_str, SDDL_REVISION_1, &psd, &sd_size))
5519 {
5520 errno = e;
5521 retval = xmalloc (sd_size);
5522 memcpy (retval, psd, sd_size);
5523 LocalFree (psd);
5524 }
5525 else if (errno != ENOTSUP)
5526 errno = EINVAL;
5527
5528 return retval;
5529}
5530
5531int
5532acl_free (void *ptr)
5533{
5534 xfree (ptr);
5535 return 0;
5536}
5537
5538acl_t
5539acl_get_file (const char *fname, acl_type_t type)
5540{
5541 PSECURITY_DESCRIPTOR psd = NULL;
474d441e 5542 const char *filename;
66447e07
EZ
5543
5544 if (type == ACL_TYPE_ACCESS)
5545 {
5546 DWORD sd_len, err;
5547 SECURITY_INFORMATION si =
5548 OWNER_SECURITY_INFORMATION |
5549 GROUP_SECURITY_INFORMATION |
5550 DACL_SECURITY_INFORMATION ;
5551 int e = errno;
5552
474d441e
EZ
5553 filename = map_w32_filename (fname, NULL);
5554 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
5555 fname = chase_symlinks (filename);
5556 else
5557 fname = filename;
5558
66447e07
EZ
5559 errno = 0;
5560 if (!get_file_security (fname, si, psd, 0, &sd_len)
5561 && errno != ENOTSUP)
5562 {
5563 err = GetLastError ();
5564 if (err == ERROR_INSUFFICIENT_BUFFER)
5565 {
5566 psd = xmalloc (sd_len);
5567 if (!get_file_security (fname, si, psd, sd_len, &sd_len))
5568 {
5569 xfree (psd);
5570 errno = EIO;
5571 psd = NULL;
5572 }
5573 }
5574 else if (err == ERROR_FILE_NOT_FOUND
5575 || err == ERROR_PATH_NOT_FOUND)
5576 errno = ENOENT;
5577 else
5578 errno = EIO;
5579 }
5580 else if (!errno)
5581 errno = e;
5582 }
5583 else if (type != ACL_TYPE_DEFAULT)
5584 errno = EINVAL;
5585
5586 return psd;
5587}
5588
5589int
5590acl_set_file (const char *fname, acl_type_t type, acl_t acl)
5591{
5592 TOKEN_PRIVILEGES old1, old2;
5593 DWORD err;
66447e07
EZ
5594 int st = 0, retval = -1;
5595 SECURITY_INFORMATION flags = 0;
5596 PSID psid;
5597 PACL pacl;
5598 BOOL dflt;
5599 BOOL dacl_present;
5600 int e;
474d441e 5601 const char *filename;
66447e07
EZ
5602
5603 if (acl_valid (acl) != 0
5604 || (type != ACL_TYPE_DEFAULT && type != ACL_TYPE_ACCESS))
5605 {
5606 errno = EINVAL;
5607 return -1;
5608 }
5609
5610 if (type == ACL_TYPE_DEFAULT)
5611 {
5612 errno = ENOSYS;
5613 return -1;
5614 }
5615
474d441e
EZ
5616 filename = map_w32_filename (fname, NULL);
5617 if ((volume_info.flags & FILE_SUPPORTS_REPARSE_POINTS) != 0)
5618 fname = chase_symlinks (filename);
5619 else
5620 fname = filename;
5621
66447e07
EZ
5622 if (get_security_descriptor_owner ((PSECURITY_DESCRIPTOR)acl, &psid, &dflt)
5623 && psid)
5624 flags |= OWNER_SECURITY_INFORMATION;
5625 if (get_security_descriptor_group ((PSECURITY_DESCRIPTOR)acl, &psid, &dflt)
5626 && psid)
5627 flags |= GROUP_SECURITY_INFORMATION;
5628 if (get_security_descriptor_dacl ((PSECURITY_DESCRIPTOR)acl, &dacl_present,
5629 &pacl, &dflt)
5630 && dacl_present)
5631 flags |= DACL_SECURITY_INFORMATION;
5632 if (!flags)
5633 return 0;
5634
5635 /* According to KB-245153, setting the owner will succeed if either:
5636 (1) the caller is the user who will be the new owner, and has the
5637 SE_TAKE_OWNERSHIP privilege, or
5638 (2) the caller has the SE_RESTORE privilege, in which case she can
5639 set any valid user or group as the owner
5640
5641 We request below both SE_TAKE_OWNERSHIP and SE_RESTORE
5642 privileges, and disregard any failures in obtaining them. If
5643 these privileges cannot be obtained, and do not already exist in
5644 the calling thread's security token, this function could fail
5645 with EPERM. */
5646 if (enable_privilege (SE_TAKE_OWNERSHIP_NAME, TRUE, &old1))
5647 st++;
5648 if (enable_privilege (SE_RESTORE_NAME, TRUE, &old2))
5649 st++;
5650
5651 e = errno;
5652 errno = 0;
84e5ed96 5653 if (!set_file_security ((char *)fname, flags, (PSECURITY_DESCRIPTOR)acl))
474d441e 5654 {
84e5ed96 5655 err = GetLastError ();
40ff07a5 5656
84e5ed96
EZ
5657 if (errno == ENOTSUP)
5658 ;
5659 else if (err == ERROR_INVALID_OWNER
5660 || err == ERROR_NOT_ALL_ASSIGNED
5661 || err == ERROR_ACCESS_DENIED)
40ff07a5 5662 {
84e5ed96
EZ
5663 /* Maybe the requested ACL and the one the file already has
5664 are identical, in which case we can silently ignore the
5665 failure. (And no, Windows doesn't.) */
5666 acl_t current_acl = acl_get_file (fname, ACL_TYPE_ACCESS);
40ff07a5 5667
84e5ed96
EZ
5668 errno = EPERM;
5669 if (current_acl)
40ff07a5 5670 {
84e5ed96
EZ
5671 char *acl_from = acl_to_text (current_acl, NULL);
5672 char *acl_to = acl_to_text (acl, NULL);
5673
5674 if (acl_from && acl_to && xstrcasecmp (acl_from, acl_to) == 0)
5675 {
5676 retval = 0;
5677 errno = e;
5678 }
5679 if (acl_from)
5680 acl_free (acl_from);
5681 if (acl_to)
5682 acl_free (acl_to);
5683 acl_free (current_acl);
40ff07a5 5684 }
40ff07a5 5685 }
84e5ed96
EZ
5686 else if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND)
5687 errno = ENOENT;
5688 else
5689 errno = EACCES;
5690 }
5691 else
5692 {
5693 retval = 0;
5694 errno = e;
5695 }
5696
5697 if (st)
5698 {
5699 if (st >= 2)
5700 restore_privilege (&old2);
5701 restore_privilege (&old1);
5702 revert_to_self ();
40ff07a5 5703 }
66447e07
EZ
5704
5705 return retval;
5706}
5707
5708\f
6dad7178
EZ
5709/* MS-Windows version of careadlinkat (cf. ../lib/careadlinkat.c). We
5710 have a fixed max size for file names, so we don't need the kind of
5711 alloc/malloc/realloc dance the gnulib version does. We also don't
5712 support FD-relative symlinks. */
973f782d
EZ
5713char *
5714careadlinkat (int fd, char const *filename,
5715 char *buffer, size_t buffer_size,
5716 struct allocator const *alloc,
5717 ssize_t (*preadlinkat) (int, char const *, char *, size_t))
5718{
6dad7178
EZ
5719 char linkname[MAX_PATH];
5720 ssize_t link_size;
5721
6dad7178
EZ
5722 link_size = preadlinkat (fd, filename, linkname, sizeof(linkname));
5723
5724 if (link_size > 0)
5725 {
5726 char *retval = buffer;
5727
5728 linkname[link_size++] = '\0';
5729 if (link_size > buffer_size)
5730 retval = (char *)(alloc ? alloc->allocate : xmalloc) (link_size);
5731 if (retval)
5732 memcpy (retval, linkname, link_size);
5733
5734 return retval;
5735 }
973f782d
EZ
5736 return NULL;
5737}
5738
0f7bb05d 5739\f
7c80d5ec
EZ
5740/* Support for browsing other processes and their attributes. See
5741 process.c for the Lisp bindings. */
5742
5743/* Helper wrapper functions. */
5744
bedf4aab
JB
5745static HANDLE WINAPI
5746create_toolhelp32_snapshot (DWORD Flags, DWORD Ignored)
7c80d5ec
EZ
5747{
5748 static CreateToolhelp32Snapshot_Proc s_pfn_Create_Toolhelp32_Snapshot = NULL;
5749
5750 if (g_b_init_create_toolhelp32_snapshot == 0)
5751 {
5752 g_b_init_create_toolhelp32_snapshot = 1;
5753 s_pfn_Create_Toolhelp32_Snapshot = (CreateToolhelp32Snapshot_Proc)
5754 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5755 "CreateToolhelp32Snapshot");
5756 }
5757 if (s_pfn_Create_Toolhelp32_Snapshot == NULL)
5758 {
5759 return INVALID_HANDLE_VALUE;
5760 }
5761 return (s_pfn_Create_Toolhelp32_Snapshot (Flags, Ignored));
5762}
5763
bedf4aab
JB
5764static BOOL WINAPI
5765process32_first (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
7c80d5ec
EZ
5766{
5767 static Process32First_Proc s_pfn_Process32_First = NULL;
5768
5769 if (g_b_init_process32_first == 0)
5770 {
5771 g_b_init_process32_first = 1;
5772 s_pfn_Process32_First = (Process32First_Proc)
5773 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5774 "Process32First");
5775 }
5776 if (s_pfn_Process32_First == NULL)
5777 {
5778 return FALSE;
5779 }
5780 return (s_pfn_Process32_First (hSnapshot, lppe));
5781}
5782
bedf4aab
JB
5783static BOOL WINAPI
5784process32_next (HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
7c80d5ec
EZ
5785{
5786 static Process32Next_Proc s_pfn_Process32_Next = NULL;
5787
5788 if (g_b_init_process32_next == 0)
5789 {
5790 g_b_init_process32_next = 1;
5791 s_pfn_Process32_Next = (Process32Next_Proc)
5792 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5793 "Process32Next");
5794 }
5795 if (s_pfn_Process32_Next == NULL)
5796 {
5797 return FALSE;
5798 }
5799 return (s_pfn_Process32_Next (hSnapshot, lppe));
5800}
5801
bedf4aab
JB
5802static BOOL WINAPI
5803open_thread_token (HANDLE ThreadHandle,
5804 DWORD DesiredAccess,
5805 BOOL OpenAsSelf,
5806 PHANDLE TokenHandle)
7c80d5ec
EZ
5807{
5808 static OpenThreadToken_Proc s_pfn_Open_Thread_Token = NULL;
5809 HMODULE hm_advapi32 = NULL;
5810 if (is_windows_9x () == TRUE)
5811 {
5812 SetLastError (ERROR_NOT_SUPPORTED);
5813 return FALSE;
5814 }
5815 if (g_b_init_open_thread_token == 0)
5816 {
5817 g_b_init_open_thread_token = 1;
5818 hm_advapi32 = LoadLibrary ("Advapi32.dll");
5819 s_pfn_Open_Thread_Token =
5820 (OpenThreadToken_Proc) GetProcAddress (hm_advapi32, "OpenThreadToken");
5821 }
5822 if (s_pfn_Open_Thread_Token == NULL)
5823 {
5824 SetLastError (ERROR_NOT_SUPPORTED);
5825 return FALSE;
5826 }
5827 return (
5828 s_pfn_Open_Thread_Token (
5829 ThreadHandle,
5830 DesiredAccess,
5831 OpenAsSelf,
5832 TokenHandle)
5833 );
5834}
5835
bedf4aab
JB
5836static BOOL WINAPI
5837impersonate_self (SECURITY_IMPERSONATION_LEVEL ImpersonationLevel)
7c80d5ec
EZ
5838{
5839 static ImpersonateSelf_Proc s_pfn_Impersonate_Self = NULL;
5840 HMODULE hm_advapi32 = NULL;
5841 if (is_windows_9x () == TRUE)
5842 {
5843 return FALSE;
5844 }
5845 if (g_b_init_impersonate_self == 0)
5846 {
5847 g_b_init_impersonate_self = 1;
5848 hm_advapi32 = LoadLibrary ("Advapi32.dll");
5849 s_pfn_Impersonate_Self =
5850 (ImpersonateSelf_Proc) GetProcAddress (hm_advapi32, "ImpersonateSelf");
5851 }
5852 if (s_pfn_Impersonate_Self == NULL)
5853 {
5854 return FALSE;
5855 }
5856 return s_pfn_Impersonate_Self (ImpersonationLevel);
5857}
5858
bedf4aab
JB
5859static BOOL WINAPI
5860revert_to_self (void)
7c80d5ec
EZ
5861{
5862 static RevertToSelf_Proc s_pfn_Revert_To_Self = NULL;
5863 HMODULE hm_advapi32 = NULL;
5864 if (is_windows_9x () == TRUE)
5865 {
5866 return FALSE;
5867 }
5868 if (g_b_init_revert_to_self == 0)
5869 {
5870 g_b_init_revert_to_self = 1;
5871 hm_advapi32 = LoadLibrary ("Advapi32.dll");
5872 s_pfn_Revert_To_Self =
5873 (RevertToSelf_Proc) GetProcAddress (hm_advapi32, "RevertToSelf");
5874 }
5875 if (s_pfn_Revert_To_Self == NULL)
5876 {
5877 return FALSE;
5878 }
5879 return s_pfn_Revert_To_Self ();
5880}
5881
bedf4aab
JB
5882static BOOL WINAPI
5883get_process_memory_info (HANDLE h_proc,
5884 PPROCESS_MEMORY_COUNTERS mem_counters,
5885 DWORD bufsize)
7c80d5ec
EZ
5886{
5887 static GetProcessMemoryInfo_Proc s_pfn_Get_Process_Memory_Info = NULL;
5888 HMODULE hm_psapi = NULL;
5889 if (is_windows_9x () == TRUE)
5890 {
5891 return FALSE;
5892 }
5893 if (g_b_init_get_process_memory_info == 0)
5894 {
5895 g_b_init_get_process_memory_info = 1;
5896 hm_psapi = LoadLibrary ("Psapi.dll");
5897 if (hm_psapi)
5898 s_pfn_Get_Process_Memory_Info = (GetProcessMemoryInfo_Proc)
5899 GetProcAddress (hm_psapi, "GetProcessMemoryInfo");
5900 }
5901 if (s_pfn_Get_Process_Memory_Info == NULL)
5902 {
5903 return FALSE;
5904 }
5905 return s_pfn_Get_Process_Memory_Info (h_proc, mem_counters, bufsize);
5906}
5907
bedf4aab
JB
5908static BOOL WINAPI
5909get_process_working_set_size (HANDLE h_proc,
cb576b5c
FP
5910 PSIZE_T minrss,
5911 PSIZE_T maxrss)
7c80d5ec
EZ
5912{
5913 static GetProcessWorkingSetSize_Proc
5914 s_pfn_Get_Process_Working_Set_Size = NULL;
5915
5916 if (is_windows_9x () == TRUE)
5917 {
5918 return FALSE;
5919 }
5920 if (g_b_init_get_process_working_set_size == 0)
5921 {
5922 g_b_init_get_process_working_set_size = 1;
5923 s_pfn_Get_Process_Working_Set_Size = (GetProcessWorkingSetSize_Proc)
5924 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5925 "GetProcessWorkingSetSize");
5926 }
5927 if (s_pfn_Get_Process_Working_Set_Size == NULL)
5928 {
5929 return FALSE;
5930 }
5931 return s_pfn_Get_Process_Working_Set_Size (h_proc, minrss, maxrss);
5932}
5933
bedf4aab
JB
5934static BOOL WINAPI
5935global_memory_status (MEMORYSTATUS *buf)
7c80d5ec
EZ
5936{
5937 static GlobalMemoryStatus_Proc s_pfn_Global_Memory_Status = NULL;
5938
5939 if (is_windows_9x () == TRUE)
5940 {
5941 return FALSE;
5942 }
5943 if (g_b_init_global_memory_status == 0)
5944 {
5945 g_b_init_global_memory_status = 1;
5946 s_pfn_Global_Memory_Status = (GlobalMemoryStatus_Proc)
5947 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5948 "GlobalMemoryStatus");
5949 }
5950 if (s_pfn_Global_Memory_Status == NULL)
5951 {
5952 return FALSE;
5953 }
5954 return s_pfn_Global_Memory_Status (buf);
5955}
5956
bedf4aab
JB
5957static BOOL WINAPI
5958global_memory_status_ex (MEMORY_STATUS_EX *buf)
7c80d5ec
EZ
5959{
5960 static GlobalMemoryStatusEx_Proc s_pfn_Global_Memory_Status_Ex = NULL;
5961
5962 if (is_windows_9x () == TRUE)
5963 {
5964 return FALSE;
5965 }
5966 if (g_b_init_global_memory_status_ex == 0)
5967 {
5968 g_b_init_global_memory_status_ex = 1;
5969 s_pfn_Global_Memory_Status_Ex = (GlobalMemoryStatusEx_Proc)
5970 GetProcAddress (GetModuleHandle ("kernel32.dll"),
5971 "GlobalMemoryStatusEx");
5972 }
5973 if (s_pfn_Global_Memory_Status_Ex == NULL)
5974 {
5975 return FALSE;
5976 }
5977 return s_pfn_Global_Memory_Status_Ex (buf);
5978}
5979
5980Lisp_Object
b56ceb92 5981list_system_processes (void)
7c80d5ec
EZ
5982{
5983 struct gcpro gcpro1;
5984 Lisp_Object proclist = Qnil;
5985 HANDLE h_snapshot;
5986
5987 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
5988
5989 if (h_snapshot != INVALID_HANDLE_VALUE)
5990 {
5991 PROCESSENTRY32 proc_entry;
5992 DWORD proc_id;
5993 BOOL res;
5994
5995 GCPRO1 (proclist);
5996
5997 proc_entry.dwSize = sizeof (PROCESSENTRY32);
5998 for (res = process32_first (h_snapshot, &proc_entry); res;
5999 res = process32_next (h_snapshot, &proc_entry))
6000 {
6001 proc_id = proc_entry.th32ProcessID;
6002 proclist = Fcons (make_fixnum_or_float (proc_id), proclist);
6003 }
6004
6005 CloseHandle (h_snapshot);
6006 UNGCPRO;
6007 proclist = Fnreverse (proclist);
6008 }
6009
6010 return proclist;
6011}
6012
6013static int
6014enable_privilege (LPCTSTR priv_name, BOOL enable_p, TOKEN_PRIVILEGES *old_priv)
6015{
6016 TOKEN_PRIVILEGES priv;
6017 DWORD priv_size = sizeof (priv);
6018 DWORD opriv_size = sizeof (*old_priv);
6019 HANDLE h_token = NULL;
6020 HANDLE h_thread = GetCurrentThread ();
6021 int ret_val = 0;
6022 BOOL res;
6023
6024 res = open_thread_token (h_thread,
6025 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6026 FALSE, &h_token);
6027 if (!res && GetLastError () == ERROR_NO_TOKEN)
6028 {
6029 if (impersonate_self (SecurityImpersonation))
6030 res = open_thread_token (h_thread,
6031 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6032 FALSE, &h_token);
6033 }
6034 if (res)
6035 {
6036 priv.PrivilegeCount = 1;
6037 priv.Privileges[0].Attributes = enable_p ? SE_PRIVILEGE_ENABLED : 0;
6038 LookupPrivilegeValue (NULL, priv_name, &priv.Privileges[0].Luid);
6039 if (AdjustTokenPrivileges (h_token, FALSE, &priv, priv_size,
6040 old_priv, &opriv_size)
6041 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6042 ret_val = 1;
6043 }
6044 if (h_token)
6045 CloseHandle (h_token);
6046
6047 return ret_val;
6048}
6049
6050static int
6051restore_privilege (TOKEN_PRIVILEGES *priv)
6052{
6053 DWORD priv_size = sizeof (*priv);
6054 HANDLE h_token = NULL;
6055 int ret_val = 0;
6056
6057 if (open_thread_token (GetCurrentThread (),
6058 TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
6059 FALSE, &h_token))
6060 {
6061 if (AdjustTokenPrivileges (h_token, FALSE, priv, priv_size, NULL, NULL)
6062 && GetLastError () != ERROR_NOT_ALL_ASSIGNED)
6063 ret_val = 1;
6064 }
6065 if (h_token)
6066 CloseHandle (h_token);
6067
6068 return ret_val;
6069}
6070
ca300656 6071static Lisp_Object
d35af63c 6072ltime (ULONGLONG time_100ns)
7c80d5ec 6073{
d35af63c
PE
6074 ULONGLONG time_sec = time_100ns / 10000000;
6075 int subsec = time_100ns % 10000000;
3de717bd
DA
6076 return list4i (time_sec >> 16, time_sec & 0xffff,
6077 subsec / 10, subsec % 10 * 100000);
7c80d5ec
EZ
6078}
6079
d35af63c 6080#define U64_TO_LISP_TIME(time) ltime (time)
5da9424d 6081
7c80d5ec 6082static int
b56ceb92
JB
6083process_times (HANDLE h_proc, Lisp_Object *ctime, Lisp_Object *etime,
6084 Lisp_Object *stime, Lisp_Object *utime, Lisp_Object *ttime,
6085 double *pcpu)
7c80d5ec
EZ
6086{
6087 FILETIME ft_creation, ft_exit, ft_kernel, ft_user, ft_current;
5da9424d 6088 ULONGLONG tem1, tem2, tem3, tem;
7c80d5ec
EZ
6089
6090 if (!h_proc
6091 || !get_process_times_fn
ed3751c8
JB
6092 || !(*get_process_times_fn) (h_proc, &ft_creation, &ft_exit,
6093 &ft_kernel, &ft_user))
7c80d5ec
EZ
6094 return 0;
6095
6096 GetSystemTimeAsFileTime (&ft_current);
6097
5da9424d 6098 FILETIME_TO_U64 (tem1, ft_kernel);
5da9424d
JB
6099 *stime = U64_TO_LISP_TIME (tem1);
6100
6101 FILETIME_TO_U64 (tem2, ft_user);
5da9424d
JB
6102 *utime = U64_TO_LISP_TIME (tem2);
6103
6104 tem3 = tem1 + tem2;
6105 *ttime = U64_TO_LISP_TIME (tem3);
6106
6107 FILETIME_TO_U64 (tem, ft_creation);
3af03101
EZ
6108 /* Process no 4 (System) returns zero creation time. */
6109 if (tem)
d35af63c 6110 tem -= utc_base;
5da9424d
JB
6111 *ctime = U64_TO_LISP_TIME (tem);
6112
3af03101 6113 if (tem)
5da9424d
JB
6114 {
6115 FILETIME_TO_U64 (tem3, ft_current);
d35af63c 6116 tem = (tem3 - utc_base) - tem;
5da9424d
JB
6117 }
6118 *etime = U64_TO_LISP_TIME (tem);
7c80d5ec 6119
3af03101
EZ
6120 if (tem)
6121 {
6122 *pcpu = 100.0 * (tem1 + tem2) / tem;
6123 if (*pcpu > 100)
6124 *pcpu = 100.0;
6125 }
6126 else
6127 *pcpu = 0;
6128
6129 return 1;
7c80d5ec
EZ
6130}
6131
6132Lisp_Object
b56ceb92 6133system_process_attributes (Lisp_Object pid)
7c80d5ec
EZ
6134{
6135 struct gcpro gcpro1, gcpro2, gcpro3;
6136 Lisp_Object attrs = Qnil;
6137 Lisp_Object cmd_str, decoded_cmd, tem;
6138 HANDLE h_snapshot, h_proc;
6139 DWORD proc_id;
754a2d13 6140 int found_proc = 0;
7c80d5ec 6141 char uname[UNLEN+1], gname[GNLEN+1], domain[1025];
32cef06e 6142 DWORD ulength = sizeof (uname), dlength = sizeof (domain), needed;
7c80d5ec
EZ
6143 DWORD glength = sizeof (gname);
6144 HANDLE token = NULL;
6145 SID_NAME_USE user_type;
32cef06e
EZ
6146 unsigned char *buf = NULL;
6147 DWORD blen = 0;
7c80d5ec
EZ
6148 TOKEN_USER user_token;
6149 TOKEN_PRIMARY_GROUP group_token;
22749e9a
EZ
6150 unsigned euid;
6151 unsigned egid;
7c80d5ec
EZ
6152 PROCESS_MEMORY_COUNTERS mem;
6153 PROCESS_MEMORY_COUNTERS_EX mem_ex;
cb576b5c 6154 SIZE_T minrss, maxrss;
7c80d5ec 6155 MEMORYSTATUS memst;
b8526f6e 6156 MEMORY_STATUS_EX memstex;
7c80d5ec 6157 double totphys = 0.0;
031da700 6158 Lisp_Object ctime, stime, utime, etime, ttime;
7c80d5ec 6159 double pcpu;
32cef06e 6160 BOOL result = FALSE;
7c80d5ec
EZ
6161
6162 CHECK_NUMBER_OR_FLOAT (pid);
6163 proc_id = FLOATP (pid) ? XFLOAT_DATA (pid) : XINT (pid);
6164
6165 h_snapshot = create_toolhelp32_snapshot (TH32CS_SNAPPROCESS, 0);
6166
6167 GCPRO3 (attrs, decoded_cmd, tem);
6168
6169 if (h_snapshot != INVALID_HANDLE_VALUE)
6170 {
6171 PROCESSENTRY32 pe;
6172 BOOL res;
6173
6174 pe.dwSize = sizeof (PROCESSENTRY32);
6175 for (res = process32_first (h_snapshot, &pe); res;
6176 res = process32_next (h_snapshot, &pe))
6177 {
6178 if (proc_id == pe.th32ProcessID)
6179 {
6180 if (proc_id == 0)
6181 decoded_cmd = build_string ("Idle");
6182 else
6183 {
6184 /* Decode the command name from locale-specific
6185 encoding. */
309f24d1
DA
6186 cmd_str = build_unibyte_string (pe.szExeFile);
6187
7c80d5ec
EZ
6188 decoded_cmd =
6189 code_convert_string_norecord (cmd_str,
6190 Vlocale_coding_system, 0);
6191 }
6192 attrs = Fcons (Fcons (Qcomm, decoded_cmd), attrs);
6193 attrs = Fcons (Fcons (Qppid,
6194 make_fixnum_or_float (pe.th32ParentProcessID)),
6195 attrs);
6196 attrs = Fcons (Fcons (Qpri, make_number (pe.pcPriClassBase)),
6197 attrs);
6198 attrs = Fcons (Fcons (Qthcount,
6199 make_fixnum_or_float (pe.cntThreads)),
6200 attrs);
754a2d13 6201 found_proc = 1;
7c80d5ec
EZ
6202 break;
6203 }
6204 }
6205
6206 CloseHandle (h_snapshot);
6207 }
6208
754a2d13
EZ
6209 if (!found_proc)
6210 {
6211 UNGCPRO;
6212 return Qnil;
6213 }
6214
7c80d5ec
EZ
6215 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6216 FALSE, proc_id);
6217 /* If we were denied a handle to the process, try again after
6218 enabling the SeDebugPrivilege in our process. */
6219 if (!h_proc)
6220 {
6221 TOKEN_PRIVILEGES priv_current;
6222
6223 if (enable_privilege (SE_DEBUG_NAME, TRUE, &priv_current))
6224 {
6225 h_proc = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
6226 FALSE, proc_id);
6227 restore_privilege (&priv_current);
6228 revert_to_self ();
6229 }
6230 }
32cef06e 6231 if (h_proc)
7c80d5ec 6232 {
32cef06e
EZ
6233 result = open_process_token (h_proc, TOKEN_QUERY, &token);
6234 if (result)
f8b35b24 6235 {
32cef06e
EZ
6236 result = get_token_information (token, TokenUser, NULL, 0, &blen);
6237 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
6238 {
6239 buf = xmalloc (blen);
6240 result = get_token_information (token, TokenUser,
6241 (LPVOID)buf, blen, &needed);
6242 if (result)
6243 {
6244 memcpy (&user_token, buf, sizeof (user_token));
6245 if (!w32_cached_id (user_token.User.Sid, &euid, uname))
6246 {
6247 euid = get_rid (user_token.User.Sid);
6248 result = lookup_account_sid (NULL, user_token.User.Sid,
6249 uname, &ulength,
6250 domain, &dlength,
6251 &user_type);
6252 if (result)
6253 w32_add_to_cache (user_token.User.Sid, euid, uname);
6254 else
6255 {
6256 strcpy (uname, "unknown");
6257 result = TRUE;
6258 }
6259 }
6260 ulength = strlen (uname);
6261 }
6262 }
7c80d5ec 6263 }
32cef06e 6264 if (result)
7c80d5ec 6265 {
32cef06e
EZ
6266 /* Determine a reasonable euid and gid values. */
6267 if (xstrcasecmp ("administrator", uname) == 0)
7c80d5ec 6268 {
32cef06e
EZ
6269 euid = 500; /* well-known Administrator uid */
6270 egid = 513; /* well-known None gid */
6271 }
6272 else
6273 {
6274 /* Get group id and name. */
6275 result = get_token_information (token, TokenPrimaryGroup,
6276 (LPVOID)buf, blen, &needed);
6277 if (!result && GetLastError () == ERROR_INSUFFICIENT_BUFFER)
f8b35b24 6278 {
32cef06e
EZ
6279 buf = xrealloc (buf, blen = needed);
6280 result = get_token_information (token, TokenPrimaryGroup,
6281 (LPVOID)buf, blen, &needed);
6282 }
6283 if (result)
6284 {
6285 memcpy (&group_token, buf, sizeof (group_token));
6286 if (!w32_cached_id (group_token.PrimaryGroup, &egid, gname))
6287 {
6288 egid = get_rid (group_token.PrimaryGroup);
6289 dlength = sizeof (domain);
6290 result =
6291 lookup_account_sid (NULL, group_token.PrimaryGroup,
6292 gname, &glength, NULL, &dlength,
6293 &user_type);
6294 if (result)
6295 w32_add_to_cache (group_token.PrimaryGroup,
6296 egid, gname);
6297 else
6298 {
6299 strcpy (gname, "None");
6300 result = TRUE;
6301 }
6302 }
6303 glength = strlen (gname);
f8b35b24 6304 }
7c80d5ec 6305 }
7c80d5ec 6306 }
5f445726 6307 xfree (buf);
7c80d5ec 6308 }
32cef06e 6309 if (!result)
7c80d5ec 6310 {
32cef06e
EZ
6311 if (!is_windows_9x ())
6312 {
6313 /* We couldn't open the process token, presumably because of
6314 insufficient access rights. Assume this process is run
6315 by the system. */
6316 strcpy (uname, "SYSTEM");
6317 strcpy (gname, "None");
6318 euid = 18; /* SYSTEM */
6319 egid = 513; /* None */
6320 glength = strlen (gname);
6321 ulength = strlen (uname);
6322 }
6323 /* If we are running under Windows 9X, where security calls are
6324 not supported, we assume all processes are run by the current
6325 user. */
6326 else if (GetUserName (uname, &ulength))
6327 {
6328 if (xstrcasecmp ("administrator", uname) == 0)
6329 euid = 0;
6330 else
6331 euid = 123;
6332 egid = euid;
6333 strcpy (gname, "None");
6334 glength = strlen (gname);
6335 ulength = strlen (uname);
6336 }
7c80d5ec 6337 else
32cef06e
EZ
6338 {
6339 euid = 123;
6340 egid = 123;
6341 strcpy (uname, "administrator");
6342 ulength = strlen (uname);
6343 strcpy (gname, "None");
6344 glength = strlen (gname);
6345 }
6346 if (token)
6347 CloseHandle (token);
7c80d5ec 6348 }
7c80d5ec
EZ
6349
6350 attrs = Fcons (Fcons (Qeuid, make_fixnum_or_float (euid)), attrs);
6351 tem = make_unibyte_string (uname, ulength);
6352 attrs = Fcons (Fcons (Quser,
6353 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
6354 attrs);
6355 attrs = Fcons (Fcons (Qegid, make_fixnum_or_float (egid)), attrs);
6356 tem = make_unibyte_string (gname, glength);
6357 attrs = Fcons (Fcons (Qgroup,
6358 code_convert_string_norecord (tem, Vlocale_coding_system, 0)),
6359 attrs);
6360
6361 if (global_memory_status_ex (&memstex))
235661f6 6362#if __GNUC__ || (defined (_MSC_VER) && _MSC_VER >= 1300)
7c80d5ec 6363 totphys = memstex.ullTotalPhys / 1024.0;
235661f6
EZ
6364#else
6365 /* Visual Studio 6 cannot convert an unsigned __int64 type to
6366 double, so we need to do this for it... */
6367 {
6368 DWORD tot_hi = memstex.ullTotalPhys >> 32;
6369 DWORD tot_md = (memstex.ullTotalPhys & 0x00000000ffffffff) >> 10;
6370 DWORD tot_lo = memstex.ullTotalPhys % 1024;
6371
6372 totphys = tot_hi * 4194304.0 + tot_md + tot_lo / 1024.0;
6373 }
6374#endif /* __GNUC__ || _MSC_VER >= 1300 */
7c80d5ec
EZ
6375 else if (global_memory_status (&memst))
6376 totphys = memst.dwTotalPhys / 1024.0;
6377
6378 if (h_proc
6379 && get_process_memory_info (h_proc, (PROCESS_MEMORY_COUNTERS *)&mem_ex,
6380 sizeof (mem_ex)))
6381 {
cb576b5c 6382 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
7c80d5ec
EZ
6383
6384 attrs = Fcons (Fcons (Qmajflt,
6385 make_fixnum_or_float (mem_ex.PageFaultCount)),
6386 attrs);
6387 attrs = Fcons (Fcons (Qvsize,
6388 make_fixnum_or_float (mem_ex.PrivateUsage / 1024)),
6389 attrs);
6390 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
6391 if (totphys)
6392 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6393 }
6394 else if (h_proc
6395 && get_process_memory_info (h_proc, &mem, sizeof (mem)))
6396 {
cb576b5c 6397 SIZE_T rss = mem_ex.WorkingSetSize / 1024;
7c80d5ec
EZ
6398
6399 attrs = Fcons (Fcons (Qmajflt,
6400 make_fixnum_or_float (mem.PageFaultCount)),
6401 attrs);
6402 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (rss)), attrs);
6403 if (totphys)
6404 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6405 }
6406 else if (h_proc
6407 && get_process_working_set_size (h_proc, &minrss, &maxrss))
6408 {
6409 DWORD rss = maxrss / 1024;
6410
6411 attrs = Fcons (Fcons (Qrss, make_fixnum_or_float (maxrss / 1024)), attrs);
6412 if (totphys)
6413 attrs = Fcons (Fcons (Qpmem, make_float (100. * rss / totphys)), attrs);
6414 }
6415
031da700 6416 if (process_times (h_proc, &ctime, &etime, &stime, &utime, &ttime, &pcpu))
7c80d5ec
EZ
6417 {
6418 attrs = Fcons (Fcons (Qutime, utime), attrs);
6419 attrs = Fcons (Fcons (Qstime, stime), attrs);
031da700 6420 attrs = Fcons (Fcons (Qtime, ttime), attrs);
7c80d5ec
EZ
6421 attrs = Fcons (Fcons (Qstart, ctime), attrs);
6422 attrs = Fcons (Fcons (Qetime, etime), attrs);
6423 attrs = Fcons (Fcons (Qpcpu, make_float (pcpu)), attrs);
6424 }
6425
6426 /* FIXME: Retrieve command line by walking the PEB of the process. */
6427
6428 if (h_proc)
6429 CloseHandle (h_proc);
6430 UNGCPRO;
6431 return attrs;
6432}
6433
6434\f
480b0c5b
GV
6435/* Wrappers for winsock functions to map between our file descriptors
6436 and winsock's handles; also set h_errno for convenience.
6437
6438 To allow Emacs to run on systems which don't have winsock support
6439 installed, we dynamically link to winsock on startup if present, and
6440 otherwise provide the minimum necessary functionality
6441 (eg. gethostname). */
6442
6443/* function pointers for relevant socket functions */
6444int (PASCAL *pfn_WSAStartup) (WORD wVersionRequired, LPWSADATA lpWSAData);
6445void (PASCAL *pfn_WSASetLastError) (int iError);
6446int (PASCAL *pfn_WSAGetLastError) (void);
26fb7bc4 6447int (PASCAL *pfn_WSAEventSelect) (SOCKET s, HANDLE hEventObject, long lNetworkEvents);
64570b36
KS
6448HANDLE (PASCAL *pfn_WSACreateEvent) (void);
6449int (PASCAL *pfn_WSACloseEvent) (HANDLE hEvent);
480b0c5b
GV
6450int (PASCAL *pfn_socket) (int af, int type, int protocol);
6451int (PASCAL *pfn_bind) (SOCKET s, const struct sockaddr *addr, int namelen);
6452int (PASCAL *pfn_connect) (SOCKET s, const struct sockaddr *addr, int namelen);
6453int (PASCAL *pfn_ioctlsocket) (SOCKET s, long cmd, u_long *argp);
6454int (PASCAL *pfn_recv) (SOCKET s, char * buf, int len, int flags);
6455int (PASCAL *pfn_send) (SOCKET s, const char * buf, int len, int flags);
6456int (PASCAL *pfn_closesocket) (SOCKET s);
6457int (PASCAL *pfn_shutdown) (SOCKET s, int how);
6458int (PASCAL *pfn_WSACleanup) (void);
6459
6460u_short (PASCAL *pfn_htons) (u_short hostshort);
6461u_short (PASCAL *pfn_ntohs) (u_short netshort);
6462unsigned long (PASCAL *pfn_inet_addr) (const char * cp);
6463int (PASCAL *pfn_gethostname) (char * name, int namelen);
6464struct hostent * (PASCAL *pfn_gethostbyname) (const char * name);
6465struct servent * (PASCAL *pfn_getservbyname) (const char * name, const char * proto);
ecd270eb 6466int (PASCAL *pfn_getpeername) (SOCKET s, struct sockaddr *addr, int * namelen);
962955c5
JR
6467int (PASCAL *pfn_setsockopt) (SOCKET s, int level, int optname,
6468 const char * optval, int optlen);
6469int (PASCAL *pfn_listen) (SOCKET s, int backlog);
6470int (PASCAL *pfn_getsockname) (SOCKET s, struct sockaddr * name,
6471 int * namelen);
6472SOCKET (PASCAL *pfn_accept) (SOCKET s, struct sockaddr * addr, int * addrlen);
6473int (PASCAL *pfn_recvfrom) (SOCKET s, char * buf, int len, int flags,
6474 struct sockaddr * from, int * fromlen);
6475int (PASCAL *pfn_sendto) (SOCKET s, const char * buf, int len, int flags,
6476 const struct sockaddr * to, int tolen);
6477
f1614061
RS
6478/* SetHandleInformation is only needed to make sockets non-inheritable. */
6479BOOL (WINAPI *pfn_SetHandleInformation) (HANDLE object, DWORD mask, DWORD flags);
6480#ifndef HANDLE_FLAG_INHERIT
6481#define HANDLE_FLAG_INHERIT 1
6482#endif
480b0c5b 6483
f249a012
RS
6484HANDLE winsock_lib;
6485static int winsock_inuse;
480b0c5b 6486
f249a012 6487BOOL
480b0c5b
GV
6488term_winsock (void)
6489{
f249a012 6490 if (winsock_lib != NULL && winsock_inuse == 0)
480b0c5b 6491 {
3f940c5a 6492 release_listen_threads ();
f249a012
RS
6493 /* Not sure what would cause WSAENETDOWN, or even if it can happen
6494 after WSAStartup returns successfully, but it seems reasonable
6495 to allow unloading winsock anyway in that case. */
6496 if (pfn_WSACleanup () == 0 ||
6497 pfn_WSAGetLastError () == WSAENETDOWN)
6498 {
6499 if (FreeLibrary (winsock_lib))
6500 winsock_lib = NULL;
6501 return TRUE;
6502 }
480b0c5b 6503 }
f249a012 6504 return FALSE;
480b0c5b
GV
6505}
6506
f249a012
RS
6507BOOL
6508init_winsock (int load_now)
480b0c5b
GV
6509{
6510 WSADATA winsockData;
6511
f249a012
RS
6512 if (winsock_lib != NULL)
6513 return TRUE;
f1614061 6514
f1614061
RS
6515 pfn_SetHandleInformation
6516 = (void *) GetProcAddress (GetModuleHandle ("kernel32.dll"),
6517 "SetHandleInformation");
6518
64570b36 6519 winsock_lib = LoadLibrary ("Ws2_32.dll");
480b0c5b
GV
6520
6521 if (winsock_lib != NULL)
6522 {
6523 /* dynamically link to socket functions */
6524
6525#define LOAD_PROC(fn) \
6526 if ((pfn_##fn = (void *) GetProcAddress (winsock_lib, #fn)) == NULL) \
6527 goto fail;
6528
ed3751c8
JB
6529 LOAD_PROC (WSAStartup);
6530 LOAD_PROC (WSASetLastError);
6531 LOAD_PROC (WSAGetLastError);
6532 LOAD_PROC (WSAEventSelect);
6533 LOAD_PROC (WSACreateEvent);
6534 LOAD_PROC (WSACloseEvent);
6535 LOAD_PROC (socket);
6536 LOAD_PROC (bind);
6537 LOAD_PROC (connect);
6538 LOAD_PROC (ioctlsocket);
6539 LOAD_PROC (recv);
6540 LOAD_PROC (send);
6541 LOAD_PROC (closesocket);
6542 LOAD_PROC (shutdown);
6543 LOAD_PROC (htons);
6544 LOAD_PROC (ntohs);
6545 LOAD_PROC (inet_addr);
6546 LOAD_PROC (gethostname);
6547 LOAD_PROC (gethostbyname);
6548 LOAD_PROC (getservbyname);
6549 LOAD_PROC (getpeername);
6550 LOAD_PROC (WSACleanup);
6551 LOAD_PROC (setsockopt);
6552 LOAD_PROC (listen);
6553 LOAD_PROC (getsockname);
6554 LOAD_PROC (accept);
6555 LOAD_PROC (recvfrom);
6556 LOAD_PROC (sendto);
f249a012
RS
6557#undef LOAD_PROC
6558
480b0c5b
GV
6559 /* specify version 1.1 of winsock */
6560 if (pfn_WSAStartup (0x101, &winsockData) == 0)
6561 {
f249a012
RS
6562 if (winsockData.wVersion != 0x101)
6563 goto fail;
6564
6565 if (!load_now)
6566 {
6567 /* Report that winsock exists and is usable, but leave
6568 socket functions disabled. I am assuming that calling
6569 WSAStartup does not require any network interaction,
6570 and in particular does not cause or require a dial-up
6571 connection to be established. */
6572
6573 pfn_WSACleanup ();
6574 FreeLibrary (winsock_lib);
6575 winsock_lib = NULL;
6576 }
6577 winsock_inuse = 0;
6578 return TRUE;
480b0c5b
GV
6579 }
6580
6581 fail:
6582 FreeLibrary (winsock_lib);
f249a012 6583 winsock_lib = NULL;
480b0c5b 6584 }
f249a012
RS
6585
6586 return FALSE;
480b0c5b
GV
6587}
6588
6589
6590int h_errno = 0;
6591
f277993b
EZ
6592/* Function to map winsock error codes to errno codes for those errno
6593 code defined in errno.h (errno values not defined by errno.h are
6594 already in nt/inc/sys/socket.h). */
9bfb11f9 6595static void
b56ceb92 6596set_errno (void)
480b0c5b 6597{
f277993b
EZ
6598 int wsa_err;
6599
6600 h_errno = 0;
f249a012 6601 if (winsock_lib == NULL)
f277993b 6602 wsa_err = EINVAL;
480b0c5b 6603 else
f277993b 6604 wsa_err = pfn_WSAGetLastError ();
480b0c5b 6605
f277993b 6606 switch (wsa_err)
480b0c5b 6607 {
f277993b
EZ
6608 case WSAEACCES: errno = EACCES; break;
6609 case WSAEBADF: errno = EBADF; break;
6610 case WSAEFAULT: errno = EFAULT; break;
6611 case WSAEINTR: errno = EINTR; break;
6612 case WSAEINVAL: errno = EINVAL; break;
6613 case WSAEMFILE: errno = EMFILE; break;
6614 case WSAENAMETOOLONG: errno = ENAMETOOLONG; break;
6615 case WSAENOTEMPTY: errno = ENOTEMPTY; break;
6616 default: errno = wsa_err; break;
480b0c5b 6617 }
480b0c5b
GV
6618}
6619
9bfb11f9 6620static void
b56ceb92 6621check_errno (void)
480b0c5b 6622{
f277993b
EZ
6623 h_errno = 0;
6624 if (winsock_lib != NULL)
480b0c5b
GV
6625 pfn_WSASetLastError (0);
6626}
6627
d8fcc1b9
AI
6628/* Extend strerror to handle the winsock-specific error codes. */
6629struct {
6630 int errnum;
6631 char * msg;
6632} _wsa_errlist[] = {
1db5b1ad
JB
6633 {WSAEINTR , "Interrupted function call"},
6634 {WSAEBADF , "Bad file descriptor"},
6635 {WSAEACCES , "Permission denied"},
6636 {WSAEFAULT , "Bad address"},
6637 {WSAEINVAL , "Invalid argument"},
6638 {WSAEMFILE , "Too many open files"},
6639
6640 {WSAEWOULDBLOCK , "Resource temporarily unavailable"},
6641 {WSAEINPROGRESS , "Operation now in progress"},
6642 {WSAEALREADY , "Operation already in progress"},
6643 {WSAENOTSOCK , "Socket operation on non-socket"},
6644 {WSAEDESTADDRREQ , "Destination address required"},
6645 {WSAEMSGSIZE , "Message too long"},
6646 {WSAEPROTOTYPE , "Protocol wrong type for socket"},
6647 {WSAENOPROTOOPT , "Bad protocol option"},
6648 {WSAEPROTONOSUPPORT , "Protocol not supported"},
6649 {WSAESOCKTNOSUPPORT , "Socket type not supported"},
6650 {WSAEOPNOTSUPP , "Operation not supported"},
6651 {WSAEPFNOSUPPORT , "Protocol family not supported"},
6652 {WSAEAFNOSUPPORT , "Address family not supported by protocol family"},
6653 {WSAEADDRINUSE , "Address already in use"},
6654 {WSAEADDRNOTAVAIL , "Cannot assign requested address"},
6655 {WSAENETDOWN , "Network is down"},
6656 {WSAENETUNREACH , "Network is unreachable"},
6657 {WSAENETRESET , "Network dropped connection on reset"},
6658 {WSAECONNABORTED , "Software caused connection abort"},
6659 {WSAECONNRESET , "Connection reset by peer"},
6660 {WSAENOBUFS , "No buffer space available"},
6661 {WSAEISCONN , "Socket is already connected"},
6662 {WSAENOTCONN , "Socket is not connected"},
6663 {WSAESHUTDOWN , "Cannot send after socket shutdown"},
6664 {WSAETOOMANYREFS , "Too many references"}, /* not sure */
6665 {WSAETIMEDOUT , "Connection timed out"},
6666 {WSAECONNREFUSED , "Connection refused"},
6667 {WSAELOOP , "Network loop"}, /* not sure */
6668 {WSAENAMETOOLONG , "Name is too long"},
6669 {WSAEHOSTDOWN , "Host is down"},
6670 {WSAEHOSTUNREACH , "No route to host"},
6671 {WSAENOTEMPTY , "Buffer not empty"}, /* not sure */
6672 {WSAEPROCLIM , "Too many processes"},
6673 {WSAEUSERS , "Too many users"}, /* not sure */
6674 {WSAEDQUOT , "Double quote in host name"}, /* really not sure */
6675 {WSAESTALE , "Data is stale"}, /* not sure */
6676 {WSAEREMOTE , "Remote error"}, /* not sure */
6677
6678 {WSASYSNOTREADY , "Network subsystem is unavailable"},
6679 {WSAVERNOTSUPPORTED , "WINSOCK.DLL version out of range"},
6680 {WSANOTINITIALISED , "Winsock not initialized successfully"},
6681 {WSAEDISCON , "Graceful shutdown in progress"},
d8fcc1b9 6682#ifdef WSAENOMORE
1db5b1ad
JB
6683 {WSAENOMORE , "No more operations allowed"}, /* not sure */
6684 {WSAECANCELLED , "Operation cancelled"}, /* not sure */
6685 {WSAEINVALIDPROCTABLE , "Invalid procedure table from service provider"},
6686 {WSAEINVALIDPROVIDER , "Invalid service provider version number"},
6687 {WSAEPROVIDERFAILEDINIT , "Unable to initialize a service provider"},
6688 {WSASYSCALLFAILURE , "System call failure"},
6689 {WSASERVICE_NOT_FOUND , "Service not found"}, /* not sure */
6690 {WSATYPE_NOT_FOUND , "Class type not found"},
6691 {WSA_E_NO_MORE , "No more resources available"}, /* really not sure */
6692 {WSA_E_CANCELLED , "Operation already cancelled"}, /* really not sure */
6693 {WSAEREFUSED , "Operation refused"}, /* not sure */
d8fcc1b9 6694#endif
177c0ea7 6695
1db5b1ad
JB
6696 {WSAHOST_NOT_FOUND , "Host not found"},
6697 {WSATRY_AGAIN , "Authoritative host not found during name lookup"},
6698 {WSANO_RECOVERY , "Non-recoverable error during name lookup"},
6699 {WSANO_DATA , "Valid name, no data record of requested type"},
d8fcc1b9 6700
1db5b1ad 6701 {-1, NULL}
d8fcc1b9
AI
6702};
6703
6704char *
ed3751c8 6705sys_strerror (int error_no)
d8fcc1b9
AI
6706{
6707 int i;
6708 static char unknown_msg[40];
6709
a302c7ae
AI
6710 if (error_no >= 0 && error_no < sys_nerr)
6711 return sys_errlist[error_no];
d8fcc1b9
AI
6712
6713 for (i = 0; _wsa_errlist[i].errnum >= 0; i++)
6714 if (_wsa_errlist[i].errnum == error_no)
6715 return _wsa_errlist[i].msg;
6716
ed3751c8 6717 sprintf (unknown_msg, "Unidentified error: %d", error_no);
d8fcc1b9
AI
6718 return unknown_msg;
6719}
6720
480b0c5b
GV
6721/* [andrewi 3-May-96] I've had conflicting results using both methods,
6722 but I believe the method of keeping the socket handle separate (and
6723 insuring it is not inheritable) is the correct one. */
6724
480b0c5b 6725#define SOCK_HANDLE(fd) ((SOCKET) fd_info[fd].hnd)
480b0c5b 6726
bedf4aab 6727static int socket_to_fd (SOCKET s);
962955c5 6728
480b0c5b 6729int
ed3751c8 6730sys_socket (int af, int type, int protocol)
480b0c5b 6731{
962955c5 6732 SOCKET s;
480b0c5b 6733
f249a012 6734 if (winsock_lib == NULL)
480b0c5b 6735 {
f277993b 6736 errno = ENETDOWN;
480b0c5b
GV
6737 return INVALID_SOCKET;
6738 }
6739
6740 check_errno ();
6741
6742 /* call the real socket function */
962955c5 6743 s = pfn_socket (af, type, protocol);
177c0ea7 6744
480b0c5b 6745 if (s != INVALID_SOCKET)
f277993b 6746 return socket_to_fd (s);
480b0c5b 6747
962955c5
JR
6748 set_errno ();
6749 return -1;
6750}
6751
6752/* Convert a SOCKET to a file descriptor. */
bedf4aab 6753static int
962955c5
JR
6754socket_to_fd (SOCKET s)
6755{
6756 int fd;
6757 child_process * cp;
6758
6759 /* Although under NT 3.5 _open_osfhandle will accept a socket
6760 handle, if opened with SO_OPENTYPE == SO_SYNCHRONOUS_NONALERT,
6761 that does not work under NT 3.1. However, we can get the same
6762 effect by using a backdoor function to replace an existing
6763 descriptor handle with the one we want. */
6764
6765 /* allocate a file descriptor (with appropriate flags) */
6766 fd = _open ("NUL:", _O_RDWR);
6767 if (fd >= 0)
6768 {
962955c5
JR
6769 /* Make a non-inheritable copy of the socket handle. Note
6770 that it is possible that sockets aren't actually kernel
6771 handles, which appears to be the case on Windows 9x when
6772 the MS Proxy winsock client is installed. */
6773 {
6774 /* Apparently there is a bug in NT 3.51 with some service
6775 packs, which prevents using DuplicateHandle to make a
6776 socket handle non-inheritable (causes WSACleanup to
6777 hang). The work-around is to use SetHandleInformation
6778 instead if it is available and implemented. */
6779 if (pfn_SetHandleInformation)
480b0c5b 6780 {
962955c5
JR
6781 pfn_SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0);
6782 }
6783 else
6784 {
6785 HANDLE parent = GetCurrentProcess ();
6786 HANDLE new_s = INVALID_HANDLE_VALUE;
6787
6788 if (DuplicateHandle (parent,
6789 (HANDLE) s,
6790 parent,
6791 &new_s,
6792 0,
6793 FALSE,
6794 DUPLICATE_SAME_ACCESS))
f1614061 6795 {
962955c5
JR
6796 /* It is possible that DuplicateHandle succeeds even
6797 though the socket wasn't really a kernel handle,
6798 because a real handle has the same value. So
6799 test whether the new handle really is a socket. */
6800 long nonblocking = 0;
6801 if (pfn_ioctlsocket ((SOCKET) new_s, FIONBIO, &nonblocking) == 0)
ca149beb 6802 {
962955c5
JR
6803 pfn_closesocket (s);
6804 s = (SOCKET) new_s;
6805 }
6806 else
6807 {
6808 CloseHandle (new_s);
6809 }
177c0ea7 6810 }
480b0c5b 6811 }
962955c5 6812 }
bcf7fe2a 6813 eassert (fd < MAXDESC);
962955c5 6814 fd_info[fd].hnd = (HANDLE) s;
480b0c5b 6815
962955c5
JR
6816 /* set our own internal flags */
6817 fd_info[fd].flags = FILE_SOCKET | FILE_BINARY | FILE_READ | FILE_WRITE;
480b0c5b 6818
962955c5
JR
6819 cp = new_child ();
6820 if (cp)
6821 {
6822 cp->fd = fd;
6823 cp->status = STATUS_READ_ACKNOWLEDGED;
480b0c5b 6824
962955c5
JR
6825 /* attach child_process to fd_info */
6826 if (fd_info[ fd ].cp != NULL)
6827 {
6828 DebPrint (("sys_socket: fd_info[%d] apparently in use!\n", fd));
1088b922 6829 emacs_abort ();
480b0c5b
GV
6830 }
6831
962955c5
JR
6832 fd_info[ fd ].cp = cp;
6833
6834 /* success! */
6835 winsock_inuse++; /* count open sockets */
6836 return fd;
480b0c5b 6837 }
480b0c5b 6838
962955c5
JR
6839 /* clean up */
6840 _close (fd);
6841 }
f277993b 6842 else
962955c5 6843 pfn_closesocket (s);
f277993b 6844 errno = EMFILE;
480b0c5b
GV
6845 return -1;
6846}
6847
480b0c5b
GV
6848int
6849sys_bind (int s, const struct sockaddr * addr, int namelen)
6850{
f249a012 6851 if (winsock_lib == NULL)
480b0c5b 6852 {
f277993b 6853 errno = ENOTSOCK;
480b0c5b
GV
6854 return SOCKET_ERROR;
6855 }
6856
6857 check_errno ();
6858 if (fd_info[s].flags & FILE_SOCKET)
6859 {
6860 int rc = pfn_bind (SOCK_HANDLE (s), addr, namelen);
6861 if (rc == SOCKET_ERROR)
6862 set_errno ();
6863 return rc;
6864 }
f277993b 6865 errno = ENOTSOCK;
480b0c5b
GV
6866 return SOCKET_ERROR;
6867}
6868
480b0c5b
GV
6869int
6870sys_connect (int s, const struct sockaddr * name, int namelen)
6871{
f249a012 6872 if (winsock_lib == NULL)
480b0c5b 6873 {
f277993b 6874 errno = ENOTSOCK;
480b0c5b
GV
6875 return SOCKET_ERROR;
6876 }
6877
6878 check_errno ();
6879 if (fd_info[s].flags & FILE_SOCKET)
6880 {
6881 int rc = pfn_connect (SOCK_HANDLE (s), name, namelen);
6882 if (rc == SOCKET_ERROR)
6883 set_errno ();
6884 return rc;
6885 }
f277993b 6886 errno = ENOTSOCK;
480b0c5b
GV
6887 return SOCKET_ERROR;
6888}
6889
6890u_short
6891sys_htons (u_short hostshort)
6892{
f249a012 6893 return (winsock_lib != NULL) ?
480b0c5b
GV
6894 pfn_htons (hostshort) : hostshort;
6895}
6896
6897u_short
6898sys_ntohs (u_short netshort)
6899{
f249a012 6900 return (winsock_lib != NULL) ?
480b0c5b
GV
6901 pfn_ntohs (netshort) : netshort;
6902}
6903
6904unsigned long
6905sys_inet_addr (const char * cp)
6906{
f249a012 6907 return (winsock_lib != NULL) ?
480b0c5b
GV
6908 pfn_inet_addr (cp) : INADDR_NONE;
6909}
6910
6911int
6912sys_gethostname (char * name, int namelen)
6913{
f249a012 6914 if (winsock_lib != NULL)
f277993b
EZ
6915 {
6916 int retval;
6917
6918 check_errno ();
6919 retval = pfn_gethostname (name, namelen);
6920 if (retval == SOCKET_ERROR)
6921 set_errno ();
6922 return retval;
6923 }
480b0c5b
GV
6924
6925 if (namelen > MAX_COMPUTERNAME_LENGTH)
a302c7ae 6926 return !GetComputerName (name, (DWORD *)&namelen);
480b0c5b 6927
f277993b 6928 errno = EFAULT;
480b0c5b
GV
6929 return SOCKET_ERROR;
6930}
6931
6932struct hostent *
ed3751c8 6933sys_gethostbyname (const char * name)
480b0c5b
GV
6934{
6935 struct hostent * host;
f277993b 6936 int h_err = h_errno;
480b0c5b 6937
f249a012 6938 if (winsock_lib == NULL)
480b0c5b 6939 {
f277993b
EZ
6940 h_errno = NO_RECOVERY;
6941 errno = ENETDOWN;
480b0c5b
GV
6942 return NULL;
6943 }
6944
6945 check_errno ();
6946 host = pfn_gethostbyname (name);
6947 if (!host)
f277993b
EZ
6948 {
6949 set_errno ();
6950 h_errno = errno;
6951 }
6952 else
6953 h_errno = h_err;
480b0c5b
GV
6954 return host;
6955}
6956
6957struct servent *
ed3751c8 6958sys_getservbyname (const char * name, const char * proto)
480b0c5b
GV
6959{
6960 struct servent * serv;
6961
f249a012 6962 if (winsock_lib == NULL)
480b0c5b 6963 {
f277993b 6964 errno = ENETDOWN;
480b0c5b
GV
6965 return NULL;
6966 }
6967
6968 check_errno ();
6969 serv = pfn_getservbyname (name, proto);
6970 if (!serv)
6971 set_errno ();
6972 return serv;
6973}
6974
ecd270eb
JR
6975int
6976sys_getpeername (int s, struct sockaddr *addr, int * namelen)
6977{
6978 if (winsock_lib == NULL)
6979 {
f277993b 6980 errno = ENETDOWN;
ecd270eb
JR
6981 return SOCKET_ERROR;
6982 }
6983
6984 check_errno ();
6985 if (fd_info[s].flags & FILE_SOCKET)
6986 {
6987 int rc = pfn_getpeername (SOCK_HANDLE (s), addr, namelen);
6988 if (rc == SOCKET_ERROR)
6989 set_errno ();
6990 return rc;
6991 }
f277993b 6992 errno = ENOTSOCK;
ecd270eb
JR
6993 return SOCKET_ERROR;
6994}
6995
380961a6
GV
6996int
6997sys_shutdown (int s, int how)
6998{
380961a6
GV
6999 if (winsock_lib == NULL)
7000 {
f277993b 7001 errno = ENETDOWN;
380961a6
GV
7002 return SOCKET_ERROR;
7003 }
7004
7005 check_errno ();
7006 if (fd_info[s].flags & FILE_SOCKET)
7007 {
7008 int rc = pfn_shutdown (SOCK_HANDLE (s), how);
962955c5
JR
7009 if (rc == SOCKET_ERROR)
7010 set_errno ();
7011 return rc;
7012 }
f277993b 7013 errno = ENOTSOCK;
962955c5
JR
7014 return SOCKET_ERROR;
7015}
7016
7017int
a5a389bb 7018sys_setsockopt (int s, int level, int optname, const void * optval, int optlen)
962955c5
JR
7019{
7020 if (winsock_lib == NULL)
7021 {
f277993b 7022 errno = ENETDOWN;
962955c5
JR
7023 return SOCKET_ERROR;
7024 }
7025
7026 check_errno ();
7027 if (fd_info[s].flags & FILE_SOCKET)
7028 {
7029 int rc = pfn_setsockopt (SOCK_HANDLE (s), level, optname,
a5a389bb 7030 (const char *)optval, optlen);
962955c5
JR
7031 if (rc == SOCKET_ERROR)
7032 set_errno ();
7033 return rc;
7034 }
f277993b 7035 errno = ENOTSOCK;
177c0ea7 7036 return SOCKET_ERROR;
962955c5
JR
7037}
7038
7039int
7040sys_listen (int s, int backlog)
7041{
7042 if (winsock_lib == NULL)
7043 {
f277993b 7044 errno = ENETDOWN;
962955c5
JR
7045 return SOCKET_ERROR;
7046 }
7047
7048 check_errno ();
7049 if (fd_info[s].flags & FILE_SOCKET)
7050 {
7051 int rc = pfn_listen (SOCK_HANDLE (s), backlog);
7052 if (rc == SOCKET_ERROR)
7053 set_errno ();
26fb7bc4 7054 else
64570b36 7055 fd_info[s].flags |= FILE_LISTEN;
962955c5
JR
7056 return rc;
7057 }
f277993b 7058 errno = ENOTSOCK;
177c0ea7 7059 return SOCKET_ERROR;
962955c5
JR
7060}
7061
7062int
7063sys_getsockname (int s, struct sockaddr * name, int * namelen)
7064{
7065 if (winsock_lib == NULL)
7066 {
f277993b 7067 errno = ENETDOWN;
962955c5
JR
7068 return SOCKET_ERROR;
7069 }
7070
7071 check_errno ();
7072 if (fd_info[s].flags & FILE_SOCKET)
7073 {
7074 int rc = pfn_getsockname (SOCK_HANDLE (s), name, namelen);
7075 if (rc == SOCKET_ERROR)
7076 set_errno ();
7077 return rc;
7078 }
f277993b 7079 errno = ENOTSOCK;
177c0ea7 7080 return SOCKET_ERROR;
962955c5
JR
7081}
7082
7083int
7084sys_accept (int s, struct sockaddr * addr, int * addrlen)
7085{
7086 if (winsock_lib == NULL)
7087 {
f277993b 7088 errno = ENETDOWN;
962955c5
JR
7089 return -1;
7090 }
7091
7092 check_errno ();
26fb7bc4 7093 if (fd_info[s].flags & FILE_LISTEN)
962955c5 7094 {
a0ad1860 7095 SOCKET t = pfn_accept (SOCK_HANDLE (s), addr, addrlen);
64570b36
KS
7096 int fd = -1;
7097 if (t == INVALID_SOCKET)
7098 set_errno ();
7099 else
f277993b 7100 fd = socket_to_fd (t);
962955c5 7101
bcf7fe2a
EZ
7102 if (fd >= 0)
7103 {
7104 fd_info[s].cp->status = STATUS_READ_ACKNOWLEDGED;
7105 ResetEvent (fd_info[s].cp->char_avail);
7106 }
64570b36 7107 return fd;
962955c5 7108 }
f277993b 7109 errno = ENOTSOCK;
962955c5
JR
7110 return -1;
7111}
7112
7113int
7114sys_recvfrom (int s, char * buf, int len, int flags,
b56ceb92 7115 struct sockaddr * from, int * fromlen)
962955c5
JR
7116{
7117 if (winsock_lib == NULL)
7118 {
f277993b 7119 errno = ENETDOWN;
962955c5
JR
7120 return SOCKET_ERROR;
7121 }
7122
7123 check_errno ();
7124 if (fd_info[s].flags & FILE_SOCKET)
7125 {
7126 int rc = pfn_recvfrom (SOCK_HANDLE (s), buf, len, flags, from, fromlen);
7127 if (rc == SOCKET_ERROR)
7128 set_errno ();
7129 return rc;
7130 }
f277993b 7131 errno = ENOTSOCK;
962955c5
JR
7132 return SOCKET_ERROR;
7133}
7134
7135int
7136sys_sendto (int s, const char * buf, int len, int flags,
7137 const struct sockaddr * to, int tolen)
7138{
7139 if (winsock_lib == NULL)
7140 {
f277993b 7141 errno = ENETDOWN;
962955c5
JR
7142 return SOCKET_ERROR;
7143 }
7144
7145 check_errno ();
7146 if (fd_info[s].flags & FILE_SOCKET)
7147 {
7148 int rc = pfn_sendto (SOCK_HANDLE (s), buf, len, flags, to, tolen);
380961a6
GV
7149 if (rc == SOCKET_ERROR)
7150 set_errno ();
7151 return rc;
7152 }
f277993b 7153 errno = ENOTSOCK;
380961a6
GV
7154 return SOCKET_ERROR;
7155}
7156
ecd270eb 7157/* Windows does not have an fcntl function. Provide an implementation
067428c1 7158 good enough for Emacs. */
ecd270eb
JR
7159int
7160fcntl (int s, int cmd, int options)
7161{
067428c1
PE
7162 /* In the w32 Emacs port, fcntl (fd, F_DUPFD_CLOEXEC, fd1) is always
7163 invoked in a context where fd1 is closed and all descriptors less
7164 than fd1 are open, so sys_dup is an adequate implementation. */
7165 if (cmd == F_DUPFD_CLOEXEC)
7166 return sys_dup (s);
7167
ecd270eb
JR
7168 if (winsock_lib == NULL)
7169 {
f277993b 7170 errno = ENETDOWN;
ecd270eb
JR
7171 return -1;
7172 }
7173
7174 check_errno ();
7175 if (fd_info[s].flags & FILE_SOCKET)
7176 {
49cdacda 7177 if (cmd == F_SETFL && options == O_NONBLOCK)
ecd270eb
JR
7178 {
7179 unsigned long nblock = 1;
7180 int rc = pfn_ioctlsocket (SOCK_HANDLE (s), FIONBIO, &nblock);
7181 if (rc == SOCKET_ERROR)
9d4f32e8 7182 set_errno ();
ecd270eb
JR
7183 /* Keep track of the fact that we set this to non-blocking. */
7184 fd_info[s].flags |= FILE_NDELAY;
7185 return rc;
7186 }
7187 else
7188 {
f277993b 7189 errno = EINVAL;
ecd270eb
JR
7190 return SOCKET_ERROR;
7191 }
7192 }
f277993b 7193 errno = ENOTSOCK;
ecd270eb
JR
7194 return SOCKET_ERROR;
7195}
7196
480b0c5b
GV
7197
7198/* Shadow main io functions: we need to handle pipes and sockets more
7199 intelligently, and implement non-blocking mode as well. */
7200
7201int
7202sys_close (int fd)
7203{
7204 int rc;
7205
7559f399 7206 if (fd < 0)
480b0c5b
GV
7207 {
7208 errno = EBADF;
7209 return -1;
7210 }
7211
7559f399 7212 if (fd < MAXDESC && fd_info[fd].cp)
480b0c5b
GV
7213 {
7214 child_process * cp = fd_info[fd].cp;
7215
7216 fd_info[fd].cp = NULL;
7217
7218 if (CHILD_ACTIVE (cp))
7219 {
7220 /* if last descriptor to active child_process then cleanup */
7221 int i;
7222 for (i = 0; i < MAXDESC; i++)
7223 {
7224 if (i == fd)
7225 continue;
7226 if (fd_info[i].cp == cp)
7227 break;
7228 }
7229 if (i == MAXDESC)
7230 {
480b0c5b
GV
7231 if (fd_info[fd].flags & FILE_SOCKET)
7232 {
1088b922 7233 if (winsock_lib == NULL) emacs_abort ();
480b0c5b
GV
7234
7235 pfn_shutdown (SOCK_HANDLE (fd), 2);
7236 rc = pfn_closesocket (SOCK_HANDLE (fd));
7d701334 7237
f249a012 7238 winsock_inuse--; /* count open sockets */
480b0c5b 7239 }
299614f3
EZ
7240 /* If the process handle is NULL, it's either a socket
7241 or serial connection, or a subprocess that was
7242 already reaped by reap_subprocess, but whose
7243 resources were not yet freed, because its output was
7244 not fully read yet by the time it was reaped. (This
7245 usually happens with async subprocesses whose output
7246 is being read by Emacs.) Otherwise, this process was
7247 not reaped yet, so we set its FD to a negative value
7248 to make sure sys_select will eventually get to
7249 calling the SIGCHLD handler for it, which will then
7250 invoke waitpid and reap_subprocess. */
7251 if (cp->procinfo.hProcess == NULL)
7252 delete_child (cp);
7253 else
7254 cp->fd = -1;
480b0c5b
GV
7255 }
7256 }
7257 }
7258
224f4ec1
EZ
7259 if (fd >= 0 && fd < MAXDESC)
7260 fd_info[fd].flags = 0;
7261
480b0c5b 7262 /* Note that sockets do not need special treatment here (at least on
e9e23e23 7263 NT and Windows 95 using the standard tcp/ip stacks) - it appears that
480b0c5b
GV
7264 closesocket is equivalent to CloseHandle, which is to be expected
7265 because socket handles are fully fledged kernel handles. */
7266 rc = _close (fd);
7267
480b0c5b
GV
7268 return rc;
7269}
7270
7271int
7272sys_dup (int fd)
7273{
7274 int new_fd;
7275
7276 new_fd = _dup (fd);
7559f399 7277 if (new_fd >= 0 && new_fd < MAXDESC)
480b0c5b
GV
7278 {
7279 /* duplicate our internal info as well */
7280 fd_info[new_fd] = fd_info[fd];
7281 }
7282 return new_fd;
7283}
7284
480b0c5b
GV
7285int
7286sys_dup2 (int src, int dst)
7287{
7288 int rc;
7289
7290 if (dst < 0 || dst >= MAXDESC)
7291 {
7292 errno = EBADF;
7293 return -1;
7294 }
7295
7296 /* make sure we close the destination first if it's a pipe or socket */
7297 if (src != dst && fd_info[dst].flags != 0)
7298 sys_close (dst);
177c0ea7 7299
480b0c5b
GV
7300 rc = _dup2 (src, dst);
7301 if (rc == 0)
7302 {
7303 /* duplicate our internal info as well */
7304 fd_info[dst] = fd_info[src];
7305 }
7306 return rc;
7307}
7308
480b0c5b 7309int
067428c1 7310pipe2 (int * phandles, int pipe2_flags)
480b0c5b
GV
7311{
7312 int rc;
7313 unsigned flags;
480b0c5b 7314
067428c1
PE
7315 eassert (pipe2_flags == O_CLOEXEC);
7316
76b3903d
GV
7317 /* make pipe handles non-inheritable; when we spawn a child, we
7318 replace the relevant handle with an inheritable one. Also put
7319 pipes into binary mode; we will do text mode translation ourselves
7320 if required. */
7321 rc = _pipe (phandles, 0, _O_NOINHERIT | _O_BINARY);
480b0c5b
GV
7322
7323 if (rc == 0)
7324 {
cb72110d
JR
7325 /* Protect against overflow, since Windows can open more handles than
7326 our fd_info array has room for. */
7327 if (phandles[0] >= MAXDESC || phandles[1] >= MAXDESC)
7328 {
7329 _close (phandles[0]);
7330 _close (phandles[1]);
6e432f0c 7331 errno = EMFILE;
cb72110d
JR
7332 rc = -1;
7333 }
7334 else
7335 {
7336 flags = FILE_PIPE | FILE_READ | FILE_BINARY;
7337 fd_info[phandles[0]].flags = flags;
480b0c5b 7338
cb72110d
JR
7339 flags = FILE_PIPE | FILE_WRITE | FILE_BINARY;
7340 fd_info[phandles[1]].flags = flags;
7341 }
480b0c5b
GV
7342 }
7343
7344 return rc;
7345}
7346
7347/* Function to do blocking read of one byte, needed to implement
d3d14b40
EZ
7348 select. It is only allowed on communication ports, sockets, or
7349 pipes. */
480b0c5b
GV
7350int
7351_sys_read_ahead (int fd)
7352{
7353 child_process * cp;
7354 int rc;
7355
7356 if (fd < 0 || fd >= MAXDESC)
7357 return STATUS_READ_ERROR;
7358
7359 cp = fd_info[fd].cp;
7360
7361 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
7362 return STATUS_READ_ERROR;
7363
d888760c 7364 if ((fd_info[fd].flags & (FILE_PIPE | FILE_SERIAL | FILE_SOCKET)) == 0
480b0c5b
GV
7365 || (fd_info[fd].flags & FILE_READ) == 0)
7366 {
d888760c 7367 DebPrint (("_sys_read_ahead: internal error: fd %d is not a pipe, serial port, or socket!\n", fd));
1088b922 7368 emacs_abort ();
480b0c5b 7369 }
177c0ea7 7370
480b0c5b 7371 cp->status = STATUS_READ_IN_PROGRESS;
177c0ea7 7372
480b0c5b 7373 if (fd_info[fd].flags & FILE_PIPE)
f7554349 7374 {
f7554349
KH
7375 rc = _read (fd, &cp->chr, sizeof (char));
7376
7377 /* Give subprocess time to buffer some more output for us before
e9e23e23 7378 reporting that input is available; we need this because Windows 95
f7554349
KH
7379 connects DOS programs to pipes by making the pipe appear to be
7380 the normal console stdout - as a result most DOS programs will
d888760c 7381 write to stdout without buffering, ie. one character at a
fbd6baed 7382 time. Even some W32 programs do this - "dir" in a command
f7554349
KH
7383 shell on NT is very slow if we don't do this. */
7384 if (rc > 0)
7385 {
78806724 7386 int wait = w32_pipe_read_delay;
f7554349
KH
7387
7388 if (wait > 0)
7389 Sleep (wait);
7390 else if (wait < 0)
7391 while (++wait <= 0)
7392 /* Yield remainder of our time slice, effectively giving a
7393 temporary priority boost to the child process. */
7394 Sleep (0);
7395 }
7396 }
d888760c
GM
7397 else if (fd_info[fd].flags & FILE_SERIAL)
7398 {
7399 HANDLE hnd = fd_info[fd].hnd;
7400 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
7401 COMMTIMEOUTS ct;
7402
7403 /* Configure timeouts for blocking read. */
7404 if (!GetCommTimeouts (hnd, &ct))
6e432f0c
EZ
7405 {
7406 cp->status = STATUS_READ_ERROR;
7407 return STATUS_READ_ERROR;
7408 }
d888760c
GM
7409 ct.ReadIntervalTimeout = 0;
7410 ct.ReadTotalTimeoutMultiplier = 0;
7411 ct.ReadTotalTimeoutConstant = 0;
7412 if (!SetCommTimeouts (hnd, &ct))
6e432f0c
EZ
7413 {
7414 cp->status = STATUS_READ_ERROR;
7415 return STATUS_READ_ERROR;
7416 }
d888760c
GM
7417
7418 if (!ReadFile (hnd, &cp->chr, sizeof (char), (DWORD*) &rc, ovl))
7419 {
7420 if (GetLastError () != ERROR_IO_PENDING)
6e432f0c
EZ
7421 {
7422 cp->status = STATUS_READ_ERROR;
7423 return STATUS_READ_ERROR;
7424 }
d888760c 7425 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
6e432f0c
EZ
7426 {
7427 cp->status = STATUS_READ_ERROR;
7428 return STATUS_READ_ERROR;
7429 }
d888760c
GM
7430 }
7431 }
480b0c5b 7432 else if (fd_info[fd].flags & FILE_SOCKET)
ecd270eb
JR
7433 {
7434 unsigned long nblock = 0;
7435 /* We always want this to block, so temporarily disable NDELAY. */
7436 if (fd_info[fd].flags & FILE_NDELAY)
7437 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7438
7439 rc = pfn_recv (SOCK_HANDLE (fd), &cp->chr, sizeof (char), 0);
7440
7441 if (fd_info[fd].flags & FILE_NDELAY)
7442 {
7443 nblock = 1;
7444 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7445 }
7446 }
177c0ea7 7447
480b0c5b
GV
7448 if (rc == sizeof (char))
7449 cp->status = STATUS_READ_SUCCEEDED;
7450 else
7451 cp->status = STATUS_READ_FAILED;
7452
7453 return cp->status;
7454}
7455
9bfb11f9
KS
7456int
7457_sys_wait_accept (int fd)
64570b36
KS
7458{
7459 HANDLE hEv;
7460 child_process * cp;
7461 int rc;
7462
7463 if (fd < 0 || fd >= MAXDESC)
7464 return STATUS_READ_ERROR;
7465
7466 cp = fd_info[fd].cp;
7467
7468 if (cp == NULL || cp->fd != fd || cp->status != STATUS_READ_READY)
7469 return STATUS_READ_ERROR;
7470
7471 cp->status = STATUS_READ_FAILED;
7472
7473 hEv = pfn_WSACreateEvent ();
7474 rc = pfn_WSAEventSelect (SOCK_HANDLE (fd), hEv, FD_ACCEPT);
7475 if (rc != SOCKET_ERROR)
7476 {
3f940c5a
EZ
7477 do {
7478 rc = WaitForSingleObject (hEv, 500);
7479 Sleep (5);
7480 } while (rc == WAIT_TIMEOUT
7481 && cp->status != STATUS_READ_ERROR
7482 && cp->char_avail);
64570b36 7483 pfn_WSAEventSelect (SOCK_HANDLE (fd), NULL, 0);
64570b36
KS
7484 if (rc == WAIT_OBJECT_0)
7485 cp->status = STATUS_READ_SUCCEEDED;
7486 }
7046f191 7487 pfn_WSACloseEvent (hEv);
64570b36
KS
7488
7489 return cp->status;
7490}
7491
480b0c5b
GV
7492int
7493sys_read (int fd, char * buffer, unsigned int count)
7494{
7495 int nchars;
480b0c5b
GV
7496 int to_read;
7497 DWORD waiting;
76b3903d 7498 char * orig_buffer = buffer;
480b0c5b 7499
7559f399 7500 if (fd < 0)
480b0c5b
GV
7501 {
7502 errno = EBADF;
7503 return -1;
7504 }
7505
d888760c 7506 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
480b0c5b
GV
7507 {
7508 child_process *cp = fd_info[fd].cp;
7509
7510 if ((fd_info[fd].flags & FILE_READ) == 0)
7511 {
7512 errno = EBADF;
7513 return -1;
7514 }
7515
76b3903d
GV
7516 nchars = 0;
7517
7518 /* re-read CR carried over from last read */
7519 if (fd_info[fd].flags & FILE_LAST_CR)
7520 {
1088b922 7521 if (fd_info[fd].flags & FILE_BINARY) emacs_abort ();
76b3903d
GV
7522 *buffer++ = 0x0d;
7523 count--;
7524 nchars++;
f52eb3ef 7525 fd_info[fd].flags &= ~FILE_LAST_CR;
76b3903d
GV
7526 }
7527
480b0c5b
GV
7528 /* presence of a child_process structure means we are operating in
7529 non-blocking mode - otherwise we just call _read directly.
7530 Note that the child_process structure might be missing because
7531 reap_subprocess has been called; in this case the pipe is
7532 already broken, so calling _read on it is okay. */
7533 if (cp)
7534 {
7535 int current_status = cp->status;
7536
7537 switch (current_status)
7538 {
7539 case STATUS_READ_FAILED:
7540 case STATUS_READ_ERROR:
f52eb3ef
GV
7541 /* report normal EOF if nothing in buffer */
7542 if (nchars <= 0)
7543 fd_info[fd].flags |= FILE_AT_EOF;
7544 return nchars;
480b0c5b
GV
7545
7546 case STATUS_READ_READY:
7547 case STATUS_READ_IN_PROGRESS:
7548 DebPrint (("sys_read called when read is in progress\n"));
7549 errno = EWOULDBLOCK;
7550 return -1;
7551
7552 case STATUS_READ_SUCCEEDED:
7553 /* consume read-ahead char */
7554 *buffer++ = cp->chr;
7555 count--;
76b3903d 7556 nchars++;
480b0c5b
GV
7557 cp->status = STATUS_READ_ACKNOWLEDGED;
7558 ResetEvent (cp->char_avail);
7559
7560 case STATUS_READ_ACKNOWLEDGED:
7561 break;
7562
7563 default:
7564 DebPrint (("sys_read: bad status %d\n", current_status));
7565 errno = EBADF;
7566 return -1;
7567 }
7568
7569 if (fd_info[fd].flags & FILE_PIPE)
7570 {
7571 PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, &waiting, NULL);
7572 to_read = min (waiting, (DWORD) count);
f52eb3ef
GV
7573
7574 if (to_read > 0)
7575 nchars += _read (fd, buffer, to_read);
480b0c5b 7576 }
d888760c
GM
7577 else if (fd_info[fd].flags & FILE_SERIAL)
7578 {
7579 HANDLE hnd = fd_info[fd].hnd;
7580 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_read;
d888760c
GM
7581 int rc = 0;
7582 COMMTIMEOUTS ct;
7583
7584 if (count > 0)
7585 {
7586 /* Configure timeouts for non-blocking read. */
7587 if (!GetCommTimeouts (hnd, &ct))
7588 {
7589 errno = EIO;
7590 return -1;
7591 }
7592 ct.ReadIntervalTimeout = MAXDWORD;
7593 ct.ReadTotalTimeoutMultiplier = 0;
7594 ct.ReadTotalTimeoutConstant = 0;
7595 if (!SetCommTimeouts (hnd, &ct))
7596 {
7597 errno = EIO;
7598 return -1;
7599 }
7600
7601 if (!ResetEvent (ovl->hEvent))
7602 {
7603 errno = EIO;
7604 return -1;
7605 }
7606 if (!ReadFile (hnd, buffer, count, (DWORD*) &rc, ovl))
7607 {
7608 if (GetLastError () != ERROR_IO_PENDING)
7609 {
7610 errno = EIO;
7611 return -1;
7612 }
7613 if (!GetOverlappedResult (hnd, ovl, (DWORD*) &rc, TRUE))
7614 {
7615 errno = EIO;
7616 return -1;
7617 }
7618 }
7619 nchars += rc;
7620 }
7621 }
480b0c5b
GV
7622 else /* FILE_SOCKET */
7623 {
1088b922 7624 if (winsock_lib == NULL) emacs_abort ();
480b0c5b
GV
7625
7626 /* do the equivalent of a non-blocking read */
7627 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONREAD, &waiting);
76b3903d 7628 if (waiting == 0 && nchars == 0)
480b0c5b 7629 {
f277993b 7630 errno = EWOULDBLOCK;
480b0c5b
GV
7631 return -1;
7632 }
7633
480b0c5b
GV
7634 if (waiting)
7635 {
7636 /* always use binary mode for sockets */
76b3903d
GV
7637 int res = pfn_recv (SOCK_HANDLE (fd), buffer, count, 0);
7638 if (res == SOCKET_ERROR)
480b0c5b 7639 {
ed3751c8
JB
7640 DebPrint (("sys_read.recv failed with error %d on socket %ld\n",
7641 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
76b3903d
GV
7642 set_errno ();
7643 return -1;
480b0c5b 7644 }
76b3903d 7645 nchars += res;
480b0c5b
GV
7646 }
7647 }
480b0c5b
GV
7648 }
7649 else
f52eb3ef
GV
7650 {
7651 int nread = _read (fd, buffer, count);
7652 if (nread >= 0)
7653 nchars += nread;
7654 else if (nchars == 0)
7655 nchars = nread;
7656 }
76b3903d 7657
f52eb3ef
GV
7658 if (nchars <= 0)
7659 fd_info[fd].flags |= FILE_AT_EOF;
76b3903d 7660 /* Perform text mode translation if required. */
f52eb3ef 7661 else if ((fd_info[fd].flags & FILE_BINARY) == 0)
76b3903d
GV
7662 {
7663 nchars = crlf_to_lf (nchars, orig_buffer);
7664 /* If buffer contains only CR, return that. To be absolutely
7665 sure we should attempt to read the next char, but in
7666 practice a CR to be followed by LF would not appear by
7667 itself in the buffer. */
7668 if (nchars > 1 && orig_buffer[nchars - 1] == 0x0d)
7669 {
7670 fd_info[fd].flags |= FILE_LAST_CR;
7671 nchars--;
7672 }
76b3903d 7673 }
480b0c5b
GV
7674 }
7675 else
7676 nchars = _read (fd, buffer, count);
7677
76b3903d 7678 return nchars;
480b0c5b
GV
7679}
7680
d888760c
GM
7681/* From w32xfns.c */
7682extern HANDLE interrupt_handle;
7683
480b0c5b
GV
7684/* For now, don't bother with a non-blocking mode */
7685int
7686sys_write (int fd, const void * buffer, unsigned int count)
7687{
7688 int nchars;
7689
7559f399 7690 if (fd < 0)
480b0c5b
GV
7691 {
7692 errno = EBADF;
7693 return -1;
7694 }
7695
d888760c 7696 if (fd < MAXDESC && fd_info[fd].flags & (FILE_PIPE | FILE_SOCKET | FILE_SERIAL))
76b3903d
GV
7697 {
7698 if ((fd_info[fd].flags & FILE_WRITE) == 0)
7699 {
7700 errno = EBADF;
7701 return -1;
7702 }
7703
7704 /* Perform text mode translation if required. */
7705 if ((fd_info[fd].flags & FILE_BINARY) == 0)
7706 {
7707 char * tmpbuf = alloca (count * 2);
7708 unsigned char * src = (void *)buffer;
7709 unsigned char * dst = tmpbuf;
7710 int nbytes = count;
7711
7712 while (1)
7713 {
7714 unsigned char *next;
7715 /* copy next line or remaining bytes */
7716 next = _memccpy (dst, src, '\n', nbytes);
7717 if (next)
7718 {
7719 /* copied one line ending with '\n' */
7720 int copied = next - dst;
7721 nbytes -= copied;
7722 src += copied;
7723 /* insert '\r' before '\n' */
7724 next[-1] = '\r';
7725 next[0] = '\n';
7726 dst = next + 1;
7727 count++;
177c0ea7 7728 }
76b3903d
GV
7729 else
7730 /* copied remaining partial line -> now finished */
7731 break;
7732 }
7733 buffer = tmpbuf;
7734 }
7735 }
7736
d888760c
GM
7737 if (fd < MAXDESC && fd_info[fd].flags & FILE_SERIAL)
7738 {
7739 HANDLE hnd = (HANDLE) _get_osfhandle (fd);
7740 OVERLAPPED *ovl = &fd_info[fd].cp->ovl_write;
7741 HANDLE wait_hnd[2] = { interrupt_handle, ovl->hEvent };
7742 DWORD active = 0;
7743
7744 if (!WriteFile (hnd, buffer, count, (DWORD*) &nchars, ovl))
7745 {
7746 if (GetLastError () != ERROR_IO_PENDING)
7747 {
7748 errno = EIO;
7749 return -1;
7750 }
7751 if (detect_input_pending ())
7752 active = MsgWaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE,
7753 QS_ALLINPUT);
7754 else
7755 active = WaitForMultipleObjects (2, wait_hnd, FALSE, INFINITE);
7756 if (active == WAIT_OBJECT_0)
7757 { /* User pressed C-g, cancel write, then leave. Don't bother
7758 cleaning up as we may only get stuck in buggy drivers. */
7759 PurgeComm (hnd, PURGE_TXABORT | PURGE_TXCLEAR);
7760 CancelIo (hnd);
7761 errno = EIO;
7762 return -1;
7763 }
7764 if (active == WAIT_OBJECT_0 + 1
7765 && !GetOverlappedResult (hnd, ovl, (DWORD*) &nchars, TRUE))
7766 {
7767 errno = EIO;
7768 return -1;
7769 }
7770 }
7771 }
7d701334 7772 else if (fd < MAXDESC && fd_info[fd].flags & FILE_SOCKET)
480b0c5b 7773 {
30a32e0e 7774 unsigned long nblock = 0;
1088b922 7775 if (winsock_lib == NULL) emacs_abort ();
30a32e0e
JR
7776
7777 /* TODO: implement select() properly so non-blocking I/O works. */
7778 /* For now, make sure the write blocks. */
7779 if (fd_info[fd].flags & FILE_NDELAY)
7780 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7781
480b0c5b 7782 nchars = pfn_send (SOCK_HANDLE (fd), buffer, count, 0);
30a32e0e
JR
7783
7784 /* Set the socket back to non-blocking if it was before,
7785 for other operations that support it. */
7786 if (fd_info[fd].flags & FILE_NDELAY)
7787 {
7788 nblock = 1;
7789 pfn_ioctlsocket (SOCK_HANDLE (fd), FIONBIO, &nblock);
7790 }
7791
480b0c5b
GV
7792 if (nchars == SOCKET_ERROR)
7793 {
ed3751c8
JB
7794 DebPrint (("sys_write.send failed with error %d on socket %ld\n",
7795 pfn_WSAGetLastError (), SOCK_HANDLE (fd)));
480b0c5b
GV
7796 set_errno ();
7797 }
7798 }
7799 else
6e83d800
EZ
7800 {
7801 /* Some networked filesystems don't like too large writes, so
7802 break them into smaller chunks. See the Comments section of
7803 the MSDN documentation of WriteFile for details behind the
7804 choice of the value of CHUNK below. See also the thread
7805 http://thread.gmane.org/gmane.comp.version-control.git/145294
7806 in the git mailing list. */
7807 const unsigned char *p = buffer;
7808 const unsigned chunk = 30 * 1024 * 1024;
7809
7810 nchars = 0;
7811 while (count > 0)
7812 {
7813 unsigned this_chunk = count < chunk ? count : chunk;
7814 int n = _write (fd, p, this_chunk);
7815
7816 nchars += n;
7817 if (n < 0)
7818 {
7819 nchars = n;
7820 break;
7821 }
7822 else if (n < this_chunk)
7823 break;
7824 count -= n;
7825 p += n;
7826 }
7827 }
480b0c5b
GV
7828
7829 return nchars;
7830}
7831
3dffe395
EZ
7832\f
7833/* Emulation of SIOCGIFCONF and getifaddrs, see process.c. */
7834
7835extern Lisp_Object conv_sockaddr_to_lisp (struct sockaddr *, int);
7836
7837/* Return information about network interface IFNAME, or about all
7838 interfaces (if IFNAME is nil). */
7839static Lisp_Object
7840network_interface_get_info (Lisp_Object ifname)
7841{
7842 ULONG ainfo_len = sizeof (IP_ADAPTER_INFO);
7843 IP_ADAPTER_INFO *adapter, *ainfo = xmalloc (ainfo_len);
7844 DWORD retval = get_adapters_info (ainfo, &ainfo_len);
7845 Lisp_Object res = Qnil;
7846
7847 if (retval == ERROR_BUFFER_OVERFLOW)
7848 {
7849 ainfo = xrealloc (ainfo, ainfo_len);
7850 retval = get_adapters_info (ainfo, &ainfo_len);
7851 }
7852
7853 if (retval == ERROR_SUCCESS)
7854 {
7855 int eth_count = 0, tr_count = 0, fddi_count = 0, ppp_count = 0;
7856 int sl_count = 0, wlan_count = 0, lo_count = 0, ifx_count = 0;
7857 int if_num;
7858 struct sockaddr_in sa;
7859
7860 /* For the below, we need some winsock functions, so make sure
7861 the winsock DLL is loaded. If we cannot successfully load
7862 it, they will have no use of the information we provide,
7863 anyway, so punt. */
7864 if (!winsock_lib && !init_winsock (1))
7865 goto done;
7866
7867 for (adapter = ainfo; adapter; adapter = adapter->Next)
7868 {
7869 char namebuf[MAX_ADAPTER_NAME_LENGTH + 4];
7870 u_long ip_addr;
7871 /* Present Unix-compatible interface names, instead of the
7872 Windows names, which are really GUIDs not readable by
7873 humans. */
7874 static const char *ifmt[] = {
7875 "eth%d", "tr%d", "fddi%d", "ppp%d", "sl%d", "wlan%d",
7876 "lo", "ifx%d"
7877 };
7878 enum {
7879 NONE = -1,
7880 ETHERNET = 0,
7881 TOKENRING = 1,
7882 FDDI = 2,
7883 PPP = 3,
7884 SLIP = 4,
7885 WLAN = 5,
7886 LOOPBACK = 6,
7887 OTHER_IF = 7
7888 } ifmt_idx;
7889
7890 switch (adapter->Type)
7891 {
7892 case MIB_IF_TYPE_ETHERNET:
7893 /* Windows before Vista reports wireless adapters as
7894 Ethernet. Work around by looking at the Description
7895 string. */
7896 if (strstr (adapter->Description, "Wireless "))
7897 {
7898 ifmt_idx = WLAN;
7899 if_num = wlan_count++;
7900 }
7901 else
7902 {
7903 ifmt_idx = ETHERNET;
7904 if_num = eth_count++;
7905 }
7906 break;
7907 case MIB_IF_TYPE_TOKENRING:
7908 ifmt_idx = TOKENRING;
7909 if_num = tr_count++;
7910 break;
7911 case MIB_IF_TYPE_FDDI:
7912 ifmt_idx = FDDI;
7913 if_num = fddi_count++;
7914 break;
7915 case MIB_IF_TYPE_PPP:
7916 ifmt_idx = PPP;
7917 if_num = ppp_count++;
7918 break;
7919 case MIB_IF_TYPE_SLIP:
7920 ifmt_idx = SLIP;
7921 if_num = sl_count++;
7922 break;
7923 case IF_TYPE_IEEE80211:
7924 ifmt_idx = WLAN;
7925 if_num = wlan_count++;
7926 break;
7927 case MIB_IF_TYPE_LOOPBACK:
7928 if (lo_count < 0)
7929 {
7930 ifmt_idx = LOOPBACK;
7931 if_num = lo_count++;
7932 }
7933 else
7934 ifmt_idx = NONE;
7935 break;
7936 default:
7937 ifmt_idx = OTHER_IF;
7938 if_num = ifx_count++;
7939 break;
7940 }
7941 if (ifmt_idx == NONE)
7942 continue;
7943 sprintf (namebuf, ifmt[ifmt_idx], if_num);
7944
7945 sa.sin_family = AF_INET;
7946 ip_addr = sys_inet_addr (adapter->IpAddressList.IpAddress.String);
7947 if (ip_addr == INADDR_NONE)
7948 {
7949 /* Bogus address, skip this interface. */
7950 continue;
7951 }
7952 sa.sin_addr.s_addr = ip_addr;
7953 sa.sin_port = 0;
7954 if (NILP (ifname))
7955 res = Fcons (Fcons (build_string (namebuf),
7956 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
7957 sizeof (struct sockaddr))),
7958 res);
7959 else if (strcmp (namebuf, SSDATA (ifname)) == 0)
7960 {
7961 Lisp_Object hwaddr = Fmake_vector (make_number (6), Qnil);
7962 register struct Lisp_Vector *p = XVECTOR (hwaddr);
7963 Lisp_Object flags = Qnil;
7964 int n;
7965 u_long net_mask;
7966
7967 /* Flags. We guess most of them by type, since the
7968 Windows flags are different and hard to get by. */
7969 flags = Fcons (intern ("up"), flags);
7970 if (ifmt_idx == ETHERNET || ifmt_idx == WLAN)
7971 {
7972 flags = Fcons (intern ("broadcast"), flags);
7973 flags = Fcons (intern ("multicast"), flags);
7974 }
7975 flags = Fcons (intern ("running"), flags);
7976 if (ifmt_idx == PPP)
7977 {
7978 flags = Fcons (intern ("pointopoint"), flags);
7979 flags = Fcons (intern ("noarp"), flags);
7980 }
7981 if (adapter->HaveWins)
7982 flags = Fcons (intern ("WINS"), flags);
7983 if (adapter->DhcpEnabled)
7984 flags = Fcons (intern ("dynamic"), flags);
7985
7986 res = Fcons (flags, res);
7987
7988 /* Hardware address and its family. */
7989 for (n = 0; n < adapter->AddressLength; n++)
7990 p->u.contents[n] = make_number ((int) adapter->Address[n]);
7991 /* Windows does not support AF_LINK or AF_PACKET family
7992 of addresses. Use an arbitrary family number that is
7993 identical to what GNU/Linux returns. */
7994 res = Fcons (Fcons (make_number (1), hwaddr), res);
7995
7996 /* Network mask. */
7997 sa.sin_family = AF_INET;
7998 net_mask = sys_inet_addr (adapter->IpAddressList.IpMask.String);
7999 if (net_mask != INADDR_NONE)
8000 {
8001 sa.sin_addr.s_addr = net_mask;
8002 sa.sin_port = 0;
8003 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8004 sizeof (struct sockaddr)),
8005 res);
8006 }
8007 else
8008 res = Fcons (Qnil, res);
8009
8010 sa.sin_family = AF_INET;
8011 if (ip_addr != INADDR_NONE)
8012 {
8013 /* Broadcast address is only reported by
8014 GetAdaptersAddresses, which is of limited
8015 availability. Generate it on our own. */
8016 u_long bcast_addr = (ip_addr & net_mask) | ~net_mask;
8017
8018 sa.sin_addr.s_addr = bcast_addr;
8019 sa.sin_port = 0;
8020 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8021 sizeof (struct sockaddr)),
8022 res);
8023
8024 /* IP address. */
8025 sa.sin_addr.s_addr = ip_addr;
8026 sa.sin_port = 0;
8027 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8028 sizeof (struct sockaddr)),
8029 res);
8030 }
8031 else
8032 res = Fcons (Qnil, Fcons (Qnil, res));
8033 }
8034 }
8035 /* GetAdaptersInfo is documented to not report loopback
8036 interfaces, so we generate one out of thin air. */
8037 if (!lo_count)
8038 {
8039 sa.sin_family = AF_INET;
8040 sa.sin_port = 0;
8041 if (NILP (ifname))
8042 {
8043 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
8044 res = Fcons (Fcons (build_string ("lo"),
8045 conv_sockaddr_to_lisp ((struct sockaddr*) &sa,
8046 sizeof (struct sockaddr))),
8047 res);
8048 }
8049 else if (strcmp (SSDATA (ifname), "lo") == 0)
8050 {
8051 res = Fcons (Fcons (intern ("running"),
8052 Fcons (intern ("loopback"),
8053 Fcons (intern ("up"), Qnil))), Qnil);
8054 /* 772 is what 3 different GNU/Linux systems report for
8055 the loopback interface. */
8056 res = Fcons (Fcons (make_number (772),
8057 Fmake_vector (make_number (6),
8058 make_number (0))),
8059 res);
8060 sa.sin_addr.s_addr = sys_inet_addr ("255.0.0.0");
8061 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8062 sizeof (struct sockaddr)),
8063 res);
8064 sa.sin_addr.s_addr = sys_inet_addr ("0.0.0.0");
8065 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8066 sizeof (struct sockaddr)),
8067 res);
8068 sa.sin_addr.s_addr = sys_inet_addr ("127.0.0.1");
8069 res = Fcons (conv_sockaddr_to_lisp ((struct sockaddr *) &sa,
8070 sizeof (struct sockaddr)),
8071 res);
8072 }
8073
8074 }
8075 }
8076
8077 done:
8078 xfree (ainfo);
8079 return res;
8080}
8081
8082Lisp_Object
8083network_interface_list (void)
8084{
8085 return network_interface_get_info (Qnil);
8086}
8087
8088Lisp_Object
8089network_interface_info (Lisp_Object ifname)
8090{
8091 return network_interface_get_info (ifname);
8092}
8093
8094\f
97a93095
EZ
8095/* The Windows CRT functions are "optimized for speed", so they don't
8096 check for timezone and DST changes if they were last called less
8097 than 1 minute ago (see http://support.microsoft.com/kb/821231). So
8098 all Emacs features that repeatedly call time functions (e.g.,
8099 display-time) are in real danger of missing timezone and DST
8100 changes. Calling tzset before each localtime call fixes that. */
8101struct tm *
8102sys_localtime (const time_t *t)
8103{
8104 tzset ();
8105 return localtime (t);
8106}
8107
0898ca10
JB
8108
8109\f
d07ff9db
CY
8110/* Try loading LIBRARY_ID from the file(s) specified in
8111 Vdynamic_library_alist. If the library is loaded successfully,
8112 return the handle of the DLL, and record the filename in the
8113 property :loaded-from of LIBRARY_ID. If the library could not be
8114 found, or when it was already loaded (because the handle is not
8115 recorded anywhere, and so is lost after use), return NULL.
8116
8117 We could also save the handle in :loaded-from, but currently
8118 there's no use case for it. */
0898ca10 8119HMODULE
d07ff9db 8120w32_delayed_load (Lisp_Object library_id)
0898ca10
JB
8121{
8122 HMODULE library_dll = NULL;
8123
8124 CHECK_SYMBOL (library_id);
8125
d07ff9db
CY
8126 if (CONSP (Vdynamic_library_alist)
8127 && NILP (Fassq (library_id, Vlibrary_cache)))
0898ca10
JB
8128 {
8129 Lisp_Object found = Qnil;
d07ff9db 8130 Lisp_Object dlls = Fassq (library_id, Vdynamic_library_alist);
0898ca10
JB
8131
8132 if (CONSP (dlls))
8133 for (dlls = XCDR (dlls); CONSP (dlls); dlls = XCDR (dlls))
8134 {
8135 CHECK_STRING_CAR (dlls);
657d08d3 8136 if ((library_dll = LoadLibrary (SDATA (XCAR (dlls)))))
0898ca10 8137 {
2a8ce227
JB
8138 char name[MAX_PATH];
8139 DWORD len;
8140
8141 len = GetModuleFileNameA (library_dll, name, sizeof (name));
8142 found = Fcons (XCAR (dlls),
8143 (len > 0)
8144 /* Possibly truncated */
8145 ? make_specified_string (name, -1, len, 1)
8146 : Qnil);
0898ca10
JB
8147 break;
8148 }
8149 }
8150
8151 Fput (library_id, QCloaded_from, found);
8152 }
8153
8154 return library_dll;
8155}
8156
8157\f
76151e2c 8158void
b56ceb92 8159check_windows_init_file (void)
f52eb3ef 8160{
f52eb3ef
GV
8161 /* A common indication that Emacs is not installed properly is when
8162 it cannot find the Windows installation file. If this file does
8163 not exist in the expected place, tell the user. */
8164
c7aa8333
EZ
8165 if (!noninteractive && !inhibit_window_system
8166 /* Vload_path is not yet initialized when we are loading
8167 loadup.el. */
8168 && NILP (Vpurify_flag))
d54abccd 8169 {
d54abccd
GV
8170 Lisp_Object init_file;
8171 int fd;
f52eb3ef 8172
d54abccd 8173 init_file = build_string ("term/w32-win");
76151e2c 8174 fd = openp (Vload_path, init_file, Fget_load_suffixes (), NULL, Qnil);
177c0ea7 8175 if (fd < 0)
d54abccd 8176 {
76151e2c 8177 Lisp_Object load_path_print = Fprin1_to_string (Vload_path, Qnil);
d5db4077
KR
8178 char *init_file_name = SDATA (init_file);
8179 char *load_path = SDATA (load_path_print);
acc23b87
KS
8180 char *buffer = alloca (1024
8181 + strlen (init_file_name)
8182 + strlen (load_path));
d54abccd 8183
177c0ea7 8184 sprintf (buffer,
d54abccd
GV
8185 "The Emacs Windows initialization file \"%s.el\" "
8186 "could not be found in your Emacs installation. "
8187 "Emacs checked the following directories for this file:\n"
8188 "\n%s\n\n"
8189 "When Emacs cannot find this file, it usually means that it "
8190 "was not installed properly, or its distribution file was "
8191 "not unpacked properly.\nSee the README.W32 file in the "
8192 "top-level Emacs directory for more information.",
8193 init_file_name, load_path);
8194 MessageBox (NULL,
8195 buffer,
8196 "Emacs Abort Dialog",
8197 MB_OK | MB_ICONEXCLAMATION | MB_TASKMODAL);
1088b922 8198 /* Use the low-level system abort. */
d54abccd
GV
8199 abort ();
8200 }
8201 else
8202 {
a302c7ae 8203 _close (fd);
d54abccd 8204 }
f52eb3ef 8205 }
f52eb3ef 8206}
480b0c5b
GV
8207
8208void
16b22fef 8209term_ntproc (int ignored)
480b0c5b 8210{
16b22fef 8211 (void)ignored;
c06c382a
EZ
8212
8213 term_timers ();
8214
480b0c5b
GV
8215 /* shutdown the socket interface if necessary */
8216 term_winsock ();
52c7f9ee
JR
8217
8218 term_w32select ();
480b0c5b
GV
8219}
8220
8221void
16b22fef 8222init_ntproc (int dumping)
480b0c5b 8223{
c06c382a
EZ
8224 sigset_t initial_mask = 0;
8225
e1dbe924 8226 /* Initialize the socket interface now if available and requested by
f249a012 8227 the user by defining PRELOAD_WINSOCK; otherwise loading will be
fbd6baed 8228 delayed until open-network-stream is called (w32-has-winsock can
f249a012
RS
8229 also be used to dynamically load or reload winsock).
8230
8231 Conveniently, init_environment is called before us, so
8232 PRELOAD_WINSOCK can be set in the registry. */
8233
8234 /* Always initialize this correctly. */
8235 winsock_lib = NULL;
8236
8237 if (getenv ("PRELOAD_WINSOCK") != NULL)
8238 init_winsock (TRUE);
480b0c5b
GV
8239
8240 /* Initial preparation for subprocess support: replace our standard
8241 handles with non-inheritable versions. */
8242 {
8243 HANDLE parent;
8244 HANDLE stdin_save = INVALID_HANDLE_VALUE;
8245 HANDLE stdout_save = INVALID_HANDLE_VALUE;
8246 HANDLE stderr_save = INVALID_HANDLE_VALUE;
8247
8248 parent = GetCurrentProcess ();
8249
8250 /* ignore errors when duplicating and closing; typically the
8251 handles will be invalid when running as a gui program. */
177c0ea7
JB
8252 DuplicateHandle (parent,
8253 GetStdHandle (STD_INPUT_HANDLE),
480b0c5b 8254 parent,
177c0ea7
JB
8255 &stdin_save,
8256 0,
8257 FALSE,
480b0c5b 8258 DUPLICATE_SAME_ACCESS);
177c0ea7 8259
480b0c5b
GV
8260 DuplicateHandle (parent,
8261 GetStdHandle (STD_OUTPUT_HANDLE),
8262 parent,
8263 &stdout_save,
8264 0,
8265 FALSE,
8266 DUPLICATE_SAME_ACCESS);
177c0ea7 8267
480b0c5b
GV
8268 DuplicateHandle (parent,
8269 GetStdHandle (STD_ERROR_HANDLE),
8270 parent,
8271 &stderr_save,
8272 0,
8273 FALSE,
8274 DUPLICATE_SAME_ACCESS);
177c0ea7 8275
480b0c5b
GV
8276 fclose (stdin);
8277 fclose (stdout);
8278 fclose (stderr);
8279
8280 if (stdin_save != INVALID_HANDLE_VALUE)
62aba0d4 8281 _open_osfhandle ((intptr_t) stdin_save, O_TEXT);
480b0c5b 8282 else
76b3903d
GV
8283 _open ("nul", O_TEXT | O_NOINHERIT | O_RDONLY);
8284 _fdopen (0, "r");
480b0c5b
GV
8285
8286 if (stdout_save != INVALID_HANDLE_VALUE)
62aba0d4 8287 _open_osfhandle ((intptr_t) stdout_save, O_TEXT);
480b0c5b 8288 else
76b3903d
GV
8289 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
8290 _fdopen (1, "w");
480b0c5b
GV
8291
8292 if (stderr_save != INVALID_HANDLE_VALUE)
62aba0d4 8293 _open_osfhandle ((intptr_t) stderr_save, O_TEXT);
480b0c5b 8294 else
76b3903d
GV
8295 _open ("nul", O_TEXT | O_NOINHERIT | O_WRONLY);
8296 _fdopen (2, "w");
480b0c5b
GV
8297 }
8298
8299 /* unfortunately, atexit depends on implementation of malloc */
8300 /* atexit (term_ntproc); */
16b22fef 8301 if (!dumping)
c06c382a
EZ
8302 {
8303 /* Make sure we start with all signals unblocked. */
8304 sigprocmask (SIG_SETMASK, &initial_mask, NULL);
8305 signal (SIGABRT, term_ntproc);
8306 }
8307 init_timers ();
76b3903d
GV
8308
8309 /* determine which drives are fixed, for GetCachedVolumeInformation */
8310 {
8311 /* GetDriveType must have trailing backslash. */
8312 char drive[] = "A:\\";
8313
8314 /* Loop over all possible drive letters */
8315 while (*drive <= 'Z')
8316 {
8317 /* Record if this drive letter refers to a fixed drive. */
177c0ea7 8318 fixed_drives[DRIVE_INDEX (*drive)] =
76b3903d
GV
8319 (GetDriveType (drive) == DRIVE_FIXED);
8320
8321 (*drive)++;
8322 }
a302c7ae
AI
8323
8324 /* Reset the volume info cache. */
8325 volume_cache = NULL;
76b3903d 8326 }
480b0c5b
GV
8327}
8328
a8c3a596
JR
8329/*
8330 shutdown_handler ensures that buffers' autosave files are
8331 up to date when the user logs off, or the system shuts down.
8332*/
bedf4aab 8333static BOOL WINAPI
ed3751c8 8334shutdown_handler (DWORD type)
a8c3a596
JR
8335{
8336 /* Ctrl-C and Ctrl-Break are already suppressed, so don't handle them. */
8337 if (type == CTRL_CLOSE_EVENT /* User closes console window. */
8338 || type == CTRL_LOGOFF_EVENT /* User logs off. */
8339 || type == CTRL_SHUTDOWN_EVENT) /* User shutsdown. */
8340 {
8341 /* Shut down cleanly, making sure autosave files are up to date. */
1882aa38 8342 shut_down_emacs (0, Qnil);
a8c3a596
JR
8343 }
8344
7046f191 8345 /* Allow other handlers to handle this signal. */
a8c3a596
JR
8346 return FALSE;
8347}
8348
9785d95b
BK
8349/*
8350 globals_of_w32 is used to initialize those global variables that
8351 must always be initialized on startup even when the global variable
8352 initialized is non zero (see the function main in emacs.c).
8353*/
9bfb11f9 8354void
b56ceb92 8355globals_of_w32 (void)
9785d95b 8356{
74258518
JR
8357 HMODULE kernel32 = GetModuleHandle ("kernel32.dll");
8358
8359 get_process_times_fn = (GetProcessTimes_Proc)
8360 GetProcAddress (kernel32, "GetProcessTimes");
8361
cd3520a4 8362 DEFSYM (QCloaded_from, ":loaded-from");
0898ca10 8363
9785d95b
BK
8364 g_b_init_is_windows_9x = 0;
8365 g_b_init_open_process_token = 0;
8366 g_b_init_get_token_information = 0;
8367 g_b_init_lookup_account_sid = 0;
9d95a291
EZ
8368 g_b_init_get_sid_sub_authority = 0;
8369 g_b_init_get_sid_sub_authority_count = 0;
6dad7178 8370 g_b_init_get_security_info = 0;
8aaaec6b
EZ
8371 g_b_init_get_file_security = 0;
8372 g_b_init_get_security_descriptor_owner = 0;
8373 g_b_init_get_security_descriptor_group = 0;
8374 g_b_init_is_valid_sid = 0;
7c80d5ec
EZ
8375 g_b_init_create_toolhelp32_snapshot = 0;
8376 g_b_init_process32_first = 0;
8377 g_b_init_process32_next = 0;
8378 g_b_init_open_thread_token = 0;
8379 g_b_init_impersonate_self = 0;
8380 g_b_init_revert_to_self = 0;
8381 g_b_init_get_process_memory_info = 0;
8382 g_b_init_get_process_working_set_size = 0;
8383 g_b_init_global_memory_status = 0;
8384 g_b_init_global_memory_status_ex = 0;
f8b35b24
EZ
8385 g_b_init_equal_sid = 0;
8386 g_b_init_copy_sid = 0;
8387 g_b_init_get_length_sid = 0;
ad9e2d54
EZ
8388 g_b_init_get_native_system_info = 0;
8389 g_b_init_get_system_times = 0;
6dad7178 8390 g_b_init_create_symbolic_link = 0;
66447e07
EZ
8391 g_b_init_get_security_descriptor_dacl = 0;
8392 g_b_init_convert_sd_to_sddl = 0;
8393 g_b_init_convert_sddl_to_sd = 0;
8394 g_b_init_is_valid_security_descriptor = 0;
8395 g_b_init_set_file_security = 0;
3dffe395 8396 g_b_init_get_adapters_info = 0;
ad9e2d54 8397 num_of_processors = 0;
a8c3a596
JR
8398 /* The following sets a handler for shutdown notifications for
8399 console apps. This actually applies to Emacs in both console and
8400 GUI modes, since we had to fool windows into thinking emacs is a
8401 console application to get console mode to work. */
ed3751c8 8402 SetConsoleCtrlHandler (shutdown_handler, TRUE);
8aaaec6b
EZ
8403
8404 /* "None" is the default group name on standalone workstations. */
8405 strcpy (dflt_group_name, "None");
5c207910
EZ
8406
8407 /* Reset, in case it has some value inherited from dump time. */
8408 w32_stat_get_owner_group = 0;
03d58cca
EZ
8409
8410 /* If w32_unicode_filenames is non-zero, we will be using Unicode
8411 (a.k.a. "wide") APIs to invoke functions that accept file
8412 names. */
8413 if (is_windows_9x ())
8414 w32_unicode_filenames = 0;
8415 else
8416 w32_unicode_filenames = 1;
9785d95b
BK
8417}
8418
d888760c 8419/* For make-serial-process */
b56ceb92 8420int
4e604a5d 8421serial_open (Lisp_Object port_obj)
d888760c 8422{
4e604a5d 8423 char *port = SSDATA (port_obj);
d888760c
GM
8424 HANDLE hnd;
8425 child_process *cp;
8426 int fd = -1;
8427
8428 hnd = CreateFile (port, GENERIC_READ | GENERIC_WRITE, 0, 0,
8429 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
8430 if (hnd == INVALID_HANDLE_VALUE)
8431 error ("Could not open %s", port);
62aba0d4 8432 fd = (int) _open_osfhandle ((intptr_t) hnd, 0);
d888760c
GM
8433 if (fd == -1)
8434 error ("Could not open %s", port);
8435
8436 cp = new_child ();
8437 if (!cp)
8438 error ("Could not create child process");
8439 cp->fd = fd;
8440 cp->status = STATUS_READ_ACKNOWLEDGED;
8441 fd_info[ fd ].hnd = hnd;
8442 fd_info[ fd ].flags |=
8443 FILE_READ | FILE_WRITE | FILE_BINARY | FILE_SERIAL;
8444 if (fd_info[ fd ].cp != NULL)
8445 {
8446 error ("fd_info[fd = %d] is already in use", fd);
8447 }
8448 fd_info[ fd ].cp = cp;
8449 cp->ovl_read.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
8450 if (cp->ovl_read.hEvent == NULL)
8451 error ("Could not create read event");
8452 cp->ovl_write.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
8453 if (cp->ovl_write.hEvent == NULL)
8454 error ("Could not create write event");
8455
8456 return fd;
8457}
8458
8459/* For serial-process-configure */
8460void
9d4f32e8 8461serial_configure (struct Lisp_Process *p, Lisp_Object contact)
d888760c
GM
8462{
8463 Lisp_Object childp2 = Qnil;
8464 Lisp_Object tem = Qnil;
8465 HANDLE hnd;
8466 DCB dcb;
8467 COMMTIMEOUTS ct;
8468 char summary[4] = "???"; /* This usually becomes "8N1". */
8469
8470 if ((fd_info[ p->outfd ].flags & FILE_SERIAL) == 0)
8471 error ("Not a serial process");
8472 hnd = fd_info[ p->outfd ].hnd;
8473
4d2b044c 8474 childp2 = Fcopy_sequence (p->childp);
d888760c
GM
8475
8476 /* Initialize timeouts for blocking read and blocking write. */
8477 if (!GetCommTimeouts (hnd, &ct))
8478 error ("GetCommTimeouts() failed");
8479 ct.ReadIntervalTimeout = 0;
8480 ct.ReadTotalTimeoutMultiplier = 0;
8481 ct.ReadTotalTimeoutConstant = 0;
8482 ct.WriteTotalTimeoutMultiplier = 0;
8483 ct.WriteTotalTimeoutConstant = 0;
8484 if (!SetCommTimeouts (hnd, &ct))
8485 error ("SetCommTimeouts() failed");
8486 /* Read port attributes and prepare default configuration. */
8487 memset (&dcb, 0, sizeof (dcb));
8488 dcb.DCBlength = sizeof (DCB);
8489 if (!GetCommState (hnd, &dcb))
8490 error ("GetCommState() failed");
8491 dcb.fBinary = TRUE;
8492 dcb.fNull = FALSE;
8493 dcb.fAbortOnError = FALSE;
8494 /* dcb.XonLim and dcb.XoffLim are set by GetCommState() */
8495 dcb.ErrorChar = 0;
8496 dcb.EofChar = 0;
8497 dcb.EvtChar = 0;
8498
8499 /* Configure speed. */
8500 if (!NILP (Fplist_member (contact, QCspeed)))
8501 tem = Fplist_get (contact, QCspeed);
8502 else
4d2b044c 8503 tem = Fplist_get (p->childp, QCspeed);
d888760c
GM
8504 CHECK_NUMBER (tem);
8505 dcb.BaudRate = XINT (tem);
8506 childp2 = Fplist_put (childp2, QCspeed, tem);
8507
8508 /* Configure bytesize. */
8509 if (!NILP (Fplist_member (contact, QCbytesize)))
8510 tem = Fplist_get (contact, QCbytesize);
8511 else
4d2b044c 8512 tem = Fplist_get (p->childp, QCbytesize);
d888760c
GM
8513 if (NILP (tem))
8514 tem = make_number (8);
8515 CHECK_NUMBER (tem);
8516 if (XINT (tem) != 7 && XINT (tem) != 8)
8517 error (":bytesize must be nil (8), 7, or 8");
8518 dcb.ByteSize = XINT (tem);
8519 summary[0] = XINT (tem) + '0';
8520 childp2 = Fplist_put (childp2, QCbytesize, tem);
8521
8522 /* Configure parity. */
8523 if (!NILP (Fplist_member (contact, QCparity)))
8524 tem = Fplist_get (contact, QCparity);
8525 else
4d2b044c 8526 tem = Fplist_get (p->childp, QCparity);
d888760c
GM
8527 if (!NILP (tem) && !EQ (tem, Qeven) && !EQ (tem, Qodd))
8528 error (":parity must be nil (no parity), `even', or `odd'");
8529 dcb.fParity = FALSE;
8530 dcb.Parity = NOPARITY;
8531 dcb.fErrorChar = FALSE;
8532 if (NILP (tem))
8533 {
8534 summary[1] = 'N';
8535 }
8536 else if (EQ (tem, Qeven))
8537 {
8538 summary[1] = 'E';
8539 dcb.fParity = TRUE;
8540 dcb.Parity = EVENPARITY;
8541 dcb.fErrorChar = TRUE;
8542 }
8543 else if (EQ (tem, Qodd))
8544 {
8545 summary[1] = 'O';
8546 dcb.fParity = TRUE;
8547 dcb.Parity = ODDPARITY;
8548 dcb.fErrorChar = TRUE;
8549 }
8550 childp2 = Fplist_put (childp2, QCparity, tem);
8551
8552 /* Configure stopbits. */
8553 if (!NILP (Fplist_member (contact, QCstopbits)))
8554 tem = Fplist_get (contact, QCstopbits);
8555 else
4d2b044c 8556 tem = Fplist_get (p->childp, QCstopbits);
d888760c
GM
8557 if (NILP (tem))
8558 tem = make_number (1);
8559 CHECK_NUMBER (tem);
8560 if (XINT (tem) != 1 && XINT (tem) != 2)
8561 error (":stopbits must be nil (1 stopbit), 1, or 2");
8562 summary[2] = XINT (tem) + '0';
8563 if (XINT (tem) == 1)
8564 dcb.StopBits = ONESTOPBIT;
8565 else if (XINT (tem) == 2)
8566 dcb.StopBits = TWOSTOPBITS;
8567 childp2 = Fplist_put (childp2, QCstopbits, tem);
8568
8569 /* Configure flowcontrol. */
8570 if (!NILP (Fplist_member (contact, QCflowcontrol)))
8571 tem = Fplist_get (contact, QCflowcontrol);
8572 else
4d2b044c 8573 tem = Fplist_get (p->childp, QCflowcontrol);
d888760c
GM
8574 if (!NILP (tem) && !EQ (tem, Qhw) && !EQ (tem, Qsw))
8575 error (":flowcontrol must be nil (no flowcontrol), `hw', or `sw'");
8576 dcb.fOutxCtsFlow = FALSE;
8577 dcb.fOutxDsrFlow = FALSE;
8578 dcb.fDtrControl = DTR_CONTROL_DISABLE;
8579 dcb.fDsrSensitivity = FALSE;
8580 dcb.fTXContinueOnXoff = FALSE;
8581 dcb.fOutX = FALSE;
8582 dcb.fInX = FALSE;
8583 dcb.fRtsControl = RTS_CONTROL_DISABLE;
8584 dcb.XonChar = 17; /* Control-Q */
8585 dcb.XoffChar = 19; /* Control-S */
8586 if (NILP (tem))
8587 {
8588 /* Already configured. */
8589 }
8590 else if (EQ (tem, Qhw))
8591 {
8592 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
8593 dcb.fOutxCtsFlow = TRUE;
8594 }
8595 else if (EQ (tem, Qsw))
8596 {
8597 dcb.fOutX = TRUE;
8598 dcb.fInX = TRUE;
8599 }
8600 childp2 = Fplist_put (childp2, QCflowcontrol, tem);
8601
8602 /* Activate configuration. */
8603 if (!SetCommState (hnd, &dcb))
8604 error ("SetCommState() failed");
8605
8606 childp2 = Fplist_put (childp2, QCsummary, build_string (summary));
6a09a33b 8607 pset_childp (p, childp2);
d888760c
GM
8608}
8609
e061a11b
TZ
8610#ifdef HAVE_GNUTLS
8611
8612ssize_t
8613emacs_gnutls_pull (gnutls_transport_ptr_t p, void* buf, size_t sz)
8614{
d78cf5ed 8615 int n, err;
e061a11b 8616 SELECT_TYPE fdset;
43aac990 8617 struct timespec timeout;
e061a11b
TZ
8618 struct Lisp_Process *process = (struct Lisp_Process *)p;
8619 int fd = process->infd;
8620
d78cf5ed 8621 n = sys_read (fd, (char*)buf, sz);
e061a11b 8622
d78cf5ed
CB
8623 if (n >= 0)
8624 return n;
e061a11b 8625
d78cf5ed 8626 err = errno;
e061a11b 8627
d78cf5ed
CB
8628 /* Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
8629 if (err == EWOULDBLOCK)
8630 err = EAGAIN;
e061a11b 8631
d78cf5ed 8632 emacs_gnutls_transport_set_errno (process->gnutls_state, err);
e061a11b 8633
d78cf5ed 8634 return -1;
e061a11b 8635}
ab5796a9 8636
e061a11b
TZ
8637ssize_t
8638emacs_gnutls_push (gnutls_transport_ptr_t p, const void* buf, size_t sz)
8639{
8640 struct Lisp_Process *process = (struct Lisp_Process *)p;
42ce4c63 8641 int fd = process->outfd;
5e617bc2 8642 ssize_t n = sys_write (fd, buf, sz);
e061a11b
TZ
8643
8644 /* 0 or more bytes written means everything went fine. */
8645 if (n >= 0)
8646 return n;
8647
8648 /* Negative bytes written means we got an error in errno.
8649 Translate the WSAEWOULDBLOCK alias EWOULDBLOCK to EAGAIN. */
0898ca10
JB
8650 emacs_gnutls_transport_set_errno (process->gnutls_state,
8651 errno == EWOULDBLOCK ? EAGAIN : errno);
e061a11b
TZ
8652
8653 return -1;
8654}
8655#endif /* HAVE_GNUTLS */
8656
8657/* end of w32.c */