blob: 7ab2bf04785f5cd7d6701634b9f33152d4e1014f [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
Роман Донченкоa84df062019-03-21 23:45:59 +030020from ctypes.wintypes import BOOL, BOOLEAN, LPCWSTR, DWORD, HANDLE, POINTER, c_ubyte
Renaud Paquay227ad2e2016-11-01 14:37:13 -070021from 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
Роман Донченкоa84df062019-03-21 23:45:59 +030036CreateSymbolicLinkW.restype = BOOLEAN
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070037CreateSymbolicLinkW.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):
Роман Донченкоa84df062019-03-21 23:45:59 +0300148 if not CreateSymbolicLinkW(link_name, source, dwFlags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE):
Renaud Paquay2b42d282018-10-01 14:59:48 -0700149 # See https://github.com/golang/go/pull/24307/files#diff-b87bc12e4da2497308f9ef746086e4f0
150 # "the unprivileged create flag is unsupported below Windows 10 (1703, v10.0.14972).
151 # retry without it."
Роман Донченкоa84df062019-03-21 23:45:59 +0300152 if not CreateSymbolicLinkW(link_name, source, dwFlags):
153 code = get_last_error()
Renaud Paquay2b42d282018-10-01 14:59:48 -0700154 error_desc = FormatError(code).strip()
155 if code == ERROR_PRIVILEGE_NOT_HELD:
156 raise OSError(errno.EPERM, error_desc, link_name)
157 _raise_winerror(
158 code,
159 'Error creating symbolic link \"%s\"'.format(link_name))
Renaud Paquay227ad2e2016-11-01 14:37:13 -0700160
161
162def islink(path):
163 result = GetFileAttributesW(path)
164 if result == INVALID_FILE_ATTRIBUTES:
165 return False
166 return bool(result & FILE_ATTRIBUTE_REPARSE_POINT)
167
168
169def readlink(path):
170 reparse_point_handle = CreateFileW(path,
171 0,
172 0,
173 None,
174 OPEN_EXISTING,
175 FILE_FLAG_OPEN_REPARSE_POINT |
176 FILE_FLAG_BACKUP_SEMANTICS,
177 None)
178 if reparse_point_handle == INVALID_HANDLE_VALUE:
179 _raise_winerror(
180 get_last_error(),
181 'Error opening symblic link \"%s\"'.format(path))
182 target_buffer = c_buffer(MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
183 n_bytes_returned = DWORD()
184 io_result = DeviceIoControl(reparse_point_handle,
185 FSCTL_GET_REPARSE_POINT,
186 None,
187 0,
188 target_buffer,
189 len(target_buffer),
190 byref(n_bytes_returned),
191 None)
192 CloseHandle(reparse_point_handle)
193 if not io_result:
194 _raise_winerror(
195 get_last_error(),
196 'Error reading symblic link \"%s\"'.format(path))
197 rdb = REPARSE_DATA_BUFFER.from_buffer(target_buffer)
198 if rdb.ReparseTag == IO_REPARSE_TAG_SYMLINK:
199 return _preserve_encoding(path, rdb.SymbolicLinkReparseBuffer.PrintName)
200 elif rdb.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT:
201 return _preserve_encoding(path, rdb.MountPointReparseBuffer.PrintName)
202 # Unsupported reparse point type
203 _raise_winerror(
204 ERROR_NOT_SUPPORTED,
205 'Error reading symblic link \"%s\"'.format(path))
206
207
208def _preserve_encoding(source, target):
209 """Ensures target is the same string type (i.e. unicode or str) as source."""
210 if isinstance(source, unicode):
211 return unicode(target)
212 return str(target)
213
214
215def _raise_winerror(code, error_desc):
216 win_error_desc = FormatError(code).strip()
217 error_desc = "%s: %s".format(error_desc, win_error_desc)
218 raise WinError(code, error_desc)