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