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