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