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