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