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