blob: a6286374ea2d448467387855629caaf5c591268b [file] [log] [blame]
Mike Frysingerf6013762019-06-13 02:30:51 -04001# -*- coding:utf-8 -*-
Renaud Paquayd5cec5e2016-11-01 11:24:03 -07002#
3# Copyright (C) 2016 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17import errno
18
Rostislav Krasnyb71d61d2020-01-24 22:29:54 +020019from pyversion import is_python3
Renaud Paquay227ad2e2016-11-01 14:37:13 -070020from ctypes import WinDLL, get_last_error, FormatError, WinError, addressof
21from ctypes import c_buffer
Remy Böhmerdbd277c2020-01-07 08:48:55 +010022from ctypes.wintypes import BOOL, BOOLEAN, LPCWSTR, DWORD, HANDLE
23from ctypes.wintypes import WCHAR, USHORT, LPVOID, ULONG
24if is_python3():
25 from ctypes import c_ubyte, Structure, Union, byref
26 from ctypes.wintypes import LPDWORD
27else:
28 # For legacy Python2 different imports are needed.
29 from ctypes.wintypes import POINTER, c_ubyte, Structure, Union, byref
30 LPDWORD = POINTER(DWORD)
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070031
32kernel32 = WinDLL('kernel32', use_last_error=True)
33
Renaud Paquay227ad2e2016-11-01 14:37:13 -070034UCHAR = c_ubyte
35
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070036# Win32 error codes
37ERROR_SUCCESS = 0
Renaud Paquay227ad2e2016-11-01 14:37:13 -070038ERROR_NOT_SUPPORTED = 50
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070039ERROR_PRIVILEGE_NOT_HELD = 1314
40
41# Win32 API entry points
42CreateSymbolicLinkW = kernel32.CreateSymbolicLinkW
Роман Донченкоa84df062019-03-21 23:45:59 +030043CreateSymbolicLinkW.restype = BOOLEAN
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070044CreateSymbolicLinkW.argtypes = (LPCWSTR, # lpSymlinkFileName In
45 LPCWSTR, # lpTargetFileName In
46 DWORD) # dwFlags In
47
48# Symbolic link creation flags
49SYMBOLIC_LINK_FLAG_FILE = 0x00
50SYMBOLIC_LINK_FLAG_DIRECTORY = 0x01
Renaud Paquay2b42d282018-10-01 14:59:48 -070051# symlink support for CreateSymbolicLink() starting with Windows 10 (1703, v10.0.14972)
52SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE = 0x02
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070053
Renaud Paquay227ad2e2016-11-01 14:37:13 -070054GetFileAttributesW = kernel32.GetFileAttributesW
55GetFileAttributesW.restype = DWORD
56GetFileAttributesW.argtypes = (LPCWSTR,) # lpFileName In
57
58INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF
59FILE_ATTRIBUTE_REPARSE_POINT = 0x00400
60
61CreateFileW = kernel32.CreateFileW
62CreateFileW.restype = HANDLE
63CreateFileW.argtypes = (LPCWSTR, # lpFileName In
64 DWORD, # dwDesiredAccess In
65 DWORD, # dwShareMode In
66 LPVOID, # lpSecurityAttributes In_opt
67 DWORD, # dwCreationDisposition In
68 DWORD, # dwFlagsAndAttributes In
69 HANDLE) # hTemplateFile In_opt
70
71CloseHandle = kernel32.CloseHandle
72CloseHandle.restype = BOOL
73CloseHandle.argtypes = (HANDLE,) # hObject In
74
75INVALID_HANDLE_VALUE = HANDLE(-1).value
76OPEN_EXISTING = 3
77FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
78FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000
79
80DeviceIoControl = kernel32.DeviceIoControl
81DeviceIoControl.restype = BOOL
82DeviceIoControl.argtypes = (HANDLE, # hDevice In
83 DWORD, # dwIoControlCode In
84 LPVOID, # lpInBuffer In_opt
85 DWORD, # nInBufferSize In
86 LPVOID, # lpOutBuffer Out_opt
87 DWORD, # nOutBufferSize In
88 LPDWORD, # lpBytesReturned Out_opt
89 LPVOID) # lpOverlapped Inout_opt
90
91# Device I/O control flags and options
92FSCTL_GET_REPARSE_POINT = 0x000900A8
93IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003
94IO_REPARSE_TAG_SYMLINK = 0xA000000C
95MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 0x4000
96
97
98class GENERIC_REPARSE_BUFFER(Structure):
99 _fields_ = (('DataBuffer', UCHAR * 1),)
100
101
102class SYMBOLIC_LINK_REPARSE_BUFFER(Structure):
103 _fields_ = (('SubstituteNameOffset', USHORT),
104 ('SubstituteNameLength', USHORT),
105 ('PrintNameOffset', USHORT),
106 ('PrintNameLength', USHORT),
107 ('Flags', ULONG),
108 ('PathBuffer', WCHAR * 1))
109
110 @property
111 def PrintName(self):
112 arrayt = WCHAR * (self.PrintNameLength // 2)
113 offset = type(self).PathBuffer.offset + self.PrintNameOffset
114 return arrayt.from_address(addressof(self) + offset).value
115
116
117class MOUNT_POINT_REPARSE_BUFFER(Structure):
118 _fields_ = (('SubstituteNameOffset', USHORT),
119 ('SubstituteNameLength', USHORT),
120 ('PrintNameOffset', USHORT),
121 ('PrintNameLength', USHORT),
122 ('PathBuffer', WCHAR * 1))
123
124 @property
125 def PrintName(self):
126 arrayt = WCHAR * (self.PrintNameLength // 2)
127 offset = type(self).PathBuffer.offset + self.PrintNameOffset
128 return arrayt.from_address(addressof(self) + offset).value
129
130
131class REPARSE_DATA_BUFFER(Structure):
132 class REPARSE_BUFFER(Union):
133 _fields_ = (('SymbolicLinkReparseBuffer', SYMBOLIC_LINK_REPARSE_BUFFER),
134 ('MountPointReparseBuffer', MOUNT_POINT_REPARSE_BUFFER),
135 ('GenericReparseBuffer', GENERIC_REPARSE_BUFFER))
136 _fields_ = (('ReparseTag', ULONG),
137 ('ReparseDataLength', USHORT),
138 ('Reserved', USHORT),
139 ('ReparseBuffer', REPARSE_BUFFER))
140 _anonymous_ = ('ReparseBuffer',)
141
Renaud Paquayd5cec5e2016-11-01 11:24:03 -0700142
143def create_filesymlink(source, link_name):
144 """Creates a Windows file symbolic link source pointing to link_name."""
145 _create_symlink(source, link_name, SYMBOLIC_LINK_FLAG_FILE)
146
147
148def create_dirsymlink(source, link_name):
149 """Creates a Windows directory symbolic link source pointing to link_name.
150 """
151 _create_symlink(source, link_name, SYMBOLIC_LINK_FLAG_DIRECTORY)
152
153
154def _create_symlink(source, link_name, dwFlags):
David Pursehouse3cda50a2020-02-13 13:17:03 +0900155 if not CreateSymbolicLinkW(link_name, source,
156 dwFlags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE):
Renaud Paquay2b42d282018-10-01 14:59:48 -0700157 # See https://github.com/golang/go/pull/24307/files#diff-b87bc12e4da2497308f9ef746086e4f0
158 # "the unprivileged create flag is unsupported below Windows 10 (1703, v10.0.14972).
159 # retry without it."
Роман Донченкоa84df062019-03-21 23:45:59 +0300160 if not CreateSymbolicLinkW(link_name, source, dwFlags):
161 code = get_last_error()
Renaud Paquay2b42d282018-10-01 14:59:48 -0700162 error_desc = FormatError(code).strip()
163 if code == ERROR_PRIVILEGE_NOT_HELD:
164 raise OSError(errno.EPERM, error_desc, link_name)
165 _raise_winerror(
166 code,
167 'Error creating symbolic link \"%s\"'.format(link_name))
Renaud Paquay227ad2e2016-11-01 14:37:13 -0700168
169
170def islink(path):
171 result = GetFileAttributesW(path)
172 if result == INVALID_FILE_ATTRIBUTES:
173 return False
174 return bool(result & FILE_ATTRIBUTE_REPARSE_POINT)
175
176
177def readlink(path):
178 reparse_point_handle = CreateFileW(path,
179 0,
180 0,
181 None,
182 OPEN_EXISTING,
183 FILE_FLAG_OPEN_REPARSE_POINT |
184 FILE_FLAG_BACKUP_SEMANTICS,
185 None)
186 if reparse_point_handle == INVALID_HANDLE_VALUE:
187 _raise_winerror(
188 get_last_error(),
Rostislav Krasny9da67fe2020-01-24 23:15:09 +0200189 'Error opening symbolic link \"%s\"'.format(path))
Renaud Paquay227ad2e2016-11-01 14:37:13 -0700190 target_buffer = c_buffer(MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
191 n_bytes_returned = DWORD()
192 io_result = DeviceIoControl(reparse_point_handle,
193 FSCTL_GET_REPARSE_POINT,
194 None,
195 0,
196 target_buffer,
197 len(target_buffer),
198 byref(n_bytes_returned),
199 None)
200 CloseHandle(reparse_point_handle)
201 if not io_result:
202 _raise_winerror(
203 get_last_error(),
Rostislav Krasny9da67fe2020-01-24 23:15:09 +0200204 'Error reading symbolic link \"%s\"'.format(path))
Renaud Paquay227ad2e2016-11-01 14:37:13 -0700205 rdb = REPARSE_DATA_BUFFER.from_buffer(target_buffer)
206 if rdb.ReparseTag == IO_REPARSE_TAG_SYMLINK:
207 return _preserve_encoding(path, rdb.SymbolicLinkReparseBuffer.PrintName)
208 elif rdb.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT:
209 return _preserve_encoding(path, rdb.MountPointReparseBuffer.PrintName)
210 # Unsupported reparse point type
211 _raise_winerror(
212 ERROR_NOT_SUPPORTED,
Rostislav Krasny9da67fe2020-01-24 23:15:09 +0200213 'Error reading symbolic link \"%s\"'.format(path))
Renaud Paquay227ad2e2016-11-01 14:37:13 -0700214
215
216def _preserve_encoding(source, target):
217 """Ensures target is the same string type (i.e. unicode or str) as source."""
Rostislav Krasnyb71d61d2020-01-24 22:29:54 +0200218
219 if is_python3():
220 return target
221
David Pursehousea46bf7d2020-02-15 12:45:53 +0900222 if isinstance(source, unicode): # noqa: F821
223 return unicode(target) # noqa: F821
Renaud Paquay227ad2e2016-11-01 14:37:13 -0700224 return str(target)
225
226
227def _raise_winerror(code, error_desc):
228 win_error_desc = FormatError(code).strip()
229 error_desc = "%s: %s".format(error_desc, win_error_desc)
230 raise WinError(code, error_desc)