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