blob: a6431216314b5e960bc13f2c97fe8bc5e66086b2 [file] [log] [blame]
Renaud Paquayd5cec5e2016-11-01 11:24:03 -07001#
2# Copyright (C) 2016 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import errno
17
Renaud Paquay227ad2e2016-11-01 14:37:13 -070018from ctypes import WinDLL, get_last_error, FormatError, WinError, addressof
19from ctypes import c_buffer
20from ctypes.wintypes import BOOL, LPCWSTR, DWORD, HANDLE, POINTER, c_ubyte
21from ctypes.wintypes import WCHAR, USHORT, LPVOID, Structure, Union, ULONG
22from ctypes.wintypes import byref
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070023
24kernel32 = WinDLL('kernel32', use_last_error=True)
25
Renaud Paquay227ad2e2016-11-01 14:37:13 -070026LPDWORD = POINTER(DWORD)
27UCHAR = c_ubyte
28
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070029# Win32 error codes
30ERROR_SUCCESS = 0
Renaud Paquay227ad2e2016-11-01 14:37:13 -070031ERROR_NOT_SUPPORTED = 50
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070032ERROR_PRIVILEGE_NOT_HELD = 1314
33
34# Win32 API entry points
35CreateSymbolicLinkW = kernel32.CreateSymbolicLinkW
36CreateSymbolicLinkW.restype = BOOL
37CreateSymbolicLinkW.argtypes = (LPCWSTR, # lpSymlinkFileName In
38 LPCWSTR, # lpTargetFileName In
39 DWORD) # dwFlags In
40
41# Symbolic link creation flags
42SYMBOLIC_LINK_FLAG_FILE = 0x00
43SYMBOLIC_LINK_FLAG_DIRECTORY = 0x01
Renaud Paquay2b42d282018-10-01 14:59:48 -070044# symlink support for CreateSymbolicLink() starting with Windows 10 (1703, v10.0.14972)
45SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE = 0x02
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070046
Renaud Paquay227ad2e2016-11-01 14:37:13 -070047GetFileAttributesW = kernel32.GetFileAttributesW
48GetFileAttributesW.restype = DWORD
49GetFileAttributesW.argtypes = (LPCWSTR,) # lpFileName In
50
51INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF
52FILE_ATTRIBUTE_REPARSE_POINT = 0x00400
53
54CreateFileW = kernel32.CreateFileW
55CreateFileW.restype = HANDLE
56CreateFileW.argtypes = (LPCWSTR, # lpFileName In
57 DWORD, # dwDesiredAccess In
58 DWORD, # dwShareMode In
59 LPVOID, # lpSecurityAttributes In_opt
60 DWORD, # dwCreationDisposition In
61 DWORD, # dwFlagsAndAttributes In
62 HANDLE) # hTemplateFile In_opt
63
64CloseHandle = kernel32.CloseHandle
65CloseHandle.restype = BOOL
66CloseHandle.argtypes = (HANDLE,) # hObject In
67
68INVALID_HANDLE_VALUE = HANDLE(-1).value
69OPEN_EXISTING = 3
70FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
71FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000
72
73DeviceIoControl = kernel32.DeviceIoControl
74DeviceIoControl.restype = BOOL
75DeviceIoControl.argtypes = (HANDLE, # hDevice In
76 DWORD, # dwIoControlCode In
77 LPVOID, # lpInBuffer In_opt
78 DWORD, # nInBufferSize In
79 LPVOID, # lpOutBuffer Out_opt
80 DWORD, # nOutBufferSize In
81 LPDWORD, # lpBytesReturned Out_opt
82 LPVOID) # lpOverlapped Inout_opt
83
84# Device I/O control flags and options
85FSCTL_GET_REPARSE_POINT = 0x000900A8
86IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003
87IO_REPARSE_TAG_SYMLINK = 0xA000000C
88MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 0x4000
89
90
91class GENERIC_REPARSE_BUFFER(Structure):
92 _fields_ = (('DataBuffer', UCHAR * 1),)
93
94
95class SYMBOLIC_LINK_REPARSE_BUFFER(Structure):
96 _fields_ = (('SubstituteNameOffset', USHORT),
97 ('SubstituteNameLength', USHORT),
98 ('PrintNameOffset', USHORT),
99 ('PrintNameLength', USHORT),
100 ('Flags', ULONG),
101 ('PathBuffer', WCHAR * 1))
102
103 @property
104 def PrintName(self):
105 arrayt = WCHAR * (self.PrintNameLength // 2)
106 offset = type(self).PathBuffer.offset + self.PrintNameOffset
107 return arrayt.from_address(addressof(self) + offset).value
108
109
110class MOUNT_POINT_REPARSE_BUFFER(Structure):
111 _fields_ = (('SubstituteNameOffset', USHORT),
112 ('SubstituteNameLength', USHORT),
113 ('PrintNameOffset', USHORT),
114 ('PrintNameLength', USHORT),
115 ('PathBuffer', WCHAR * 1))
116
117 @property
118 def PrintName(self):
119 arrayt = WCHAR * (self.PrintNameLength // 2)
120 offset = type(self).PathBuffer.offset + self.PrintNameOffset
121 return arrayt.from_address(addressof(self) + offset).value
122
123
124class REPARSE_DATA_BUFFER(Structure):
125 class REPARSE_BUFFER(Union):
126 _fields_ = (('SymbolicLinkReparseBuffer', SYMBOLIC_LINK_REPARSE_BUFFER),
127 ('MountPointReparseBuffer', MOUNT_POINT_REPARSE_BUFFER),
128 ('GenericReparseBuffer', GENERIC_REPARSE_BUFFER))
129 _fields_ = (('ReparseTag', ULONG),
130 ('ReparseDataLength', USHORT),
131 ('Reserved', USHORT),
132 ('ReparseBuffer', REPARSE_BUFFER))
133 _anonymous_ = ('ReparseBuffer',)
134
Renaud Paquayd5cec5e2016-11-01 11:24:03 -0700135
136def create_filesymlink(source, link_name):
137 """Creates a Windows file symbolic link source pointing to link_name."""
138 _create_symlink(source, link_name, SYMBOLIC_LINK_FLAG_FILE)
139
140
141def create_dirsymlink(source, link_name):
142 """Creates a Windows directory symbolic link source pointing to link_name.
143 """
144 _create_symlink(source, link_name, SYMBOLIC_LINK_FLAG_DIRECTORY)
145
146
147def _create_symlink(source, link_name, dwFlags):
148 # Note: Win32 documentation for CreateSymbolicLink is incorrect.
149 # On success, the function returns "1".
150 # On error, the function returns some random value (e.g. 1280).
151 # The best bet seems to use "GetLastError" and check for error/success.
Renaud Paquay2b42d282018-10-01 14:59:48 -0700152 CreateSymbolicLinkW(link_name, source, dwFlags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)
Renaud Paquayd5cec5e2016-11-01 11:24:03 -0700153 code = get_last_error()
154 if code != ERROR_SUCCESS:
Renaud Paquay2b42d282018-10-01 14:59:48 -0700155 # See https://github.com/golang/go/pull/24307/files#diff-b87bc12e4da2497308f9ef746086e4f0
156 # "the unprivileged create flag is unsupported below Windows 10 (1703, v10.0.14972).
157 # retry without it."
158 CreateSymbolicLinkW(link_name, source, dwFlags)
159 code = get_last_error()
160 if code != ERROR_SUCCESS:
161 error_desc = FormatError(code).strip()
162 if code == ERROR_PRIVILEGE_NOT_HELD:
163 raise OSError(errno.EPERM, error_desc, link_name)
164 _raise_winerror(
165 code,
166 'Error creating symbolic link \"%s\"'.format(link_name))
Renaud Paquay227ad2e2016-11-01 14:37:13 -0700167
168
169def islink(path):
170 result = GetFileAttributesW(path)
171 if result == INVALID_FILE_ATTRIBUTES:
172 return False
173 return bool(result & FILE_ATTRIBUTE_REPARSE_POINT)
174
175
176def readlink(path):
177 reparse_point_handle = CreateFileW(path,
178 0,
179 0,
180 None,
181 OPEN_EXISTING,
182 FILE_FLAG_OPEN_REPARSE_POINT |
183 FILE_FLAG_BACKUP_SEMANTICS,
184 None)
185 if reparse_point_handle == INVALID_HANDLE_VALUE:
186 _raise_winerror(
187 get_last_error(),
188 'Error opening symblic link \"%s\"'.format(path))
189 target_buffer = c_buffer(MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
190 n_bytes_returned = DWORD()
191 io_result = DeviceIoControl(reparse_point_handle,
192 FSCTL_GET_REPARSE_POINT,
193 None,
194 0,
195 target_buffer,
196 len(target_buffer),
197 byref(n_bytes_returned),
198 None)
199 CloseHandle(reparse_point_handle)
200 if not io_result:
201 _raise_winerror(
202 get_last_error(),
203 'Error reading symblic link \"%s\"'.format(path))
204 rdb = REPARSE_DATA_BUFFER.from_buffer(target_buffer)
205 if rdb.ReparseTag == IO_REPARSE_TAG_SYMLINK:
206 return _preserve_encoding(path, rdb.SymbolicLinkReparseBuffer.PrintName)
207 elif rdb.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT:
208 return _preserve_encoding(path, rdb.MountPointReparseBuffer.PrintName)
209 # Unsupported reparse point type
210 _raise_winerror(
211 ERROR_NOT_SUPPORTED,
212 'Error reading symblic link \"%s\"'.format(path))
213
214
215def _preserve_encoding(source, target):
216 """Ensures target is the same string type (i.e. unicode or str) as source."""
217 if isinstance(source, unicode):
218 return unicode(target)
219 return str(target)
220
221
222def _raise_winerror(code, error_desc):
223 win_error_desc = FormatError(code).strip()
224 error_desc = "%s: %s".format(error_desc, win_error_desc)
225 raise WinError(code, error_desc)