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