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