blob: 8eb3d2c3997b670a6fbc1bab73f6838ab22c23d1 [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):
Роман Донченкоa84df062019-03-21 23:45:59 +0300155 if not CreateSymbolicLinkW(link_name, source, dwFlags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE):
Renaud Paquay2b42d282018-10-01 14:59:48 -0700156 # See https://github.com/golang/go/pull/24307/files#diff-b87bc12e4da2497308f9ef746086e4f0
157 # "the unprivileged create flag is unsupported below Windows 10 (1703, v10.0.14972).
158 # retry without it."
Роман Донченкоa84df062019-03-21 23:45:59 +0300159 if not CreateSymbolicLinkW(link_name, source, dwFlags):
160 code = get_last_error()
Renaud Paquay2b42d282018-10-01 14:59:48 -0700161 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(),
Rostislav Krasny9da67fe2020-01-24 23:15:09 +0200188 'Error opening symbolic link \"%s\"'.format(path))
Renaud Paquay227ad2e2016-11-01 14:37:13 -0700189 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(),
Rostislav Krasny9da67fe2020-01-24 23:15:09 +0200203 'Error reading symbolic link \"%s\"'.format(path))
Renaud Paquay227ad2e2016-11-01 14:37:13 -0700204 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,
Rostislav Krasny9da67fe2020-01-24 23:15:09 +0200212 'Error reading symbolic link \"%s\"'.format(path))
Renaud Paquay227ad2e2016-11-01 14:37:13 -0700213
214
215def _preserve_encoding(source, target):
216 """Ensures target is the same string type (i.e. unicode or str) as source."""
Rostislav Krasnyb71d61d2020-01-24 22:29:54 +0200217
218 if is_python3():
219 return target
220
Renaud Paquay227ad2e2016-11-01 14:37:13 -0700221 if isinstance(source, unicode):
222 return unicode(target)
223 return str(target)
224
225
226def _raise_winerror(code, error_desc):
227 win_error_desc = FormatError(code).strip()
228 error_desc = "%s: %s".format(error_desc, win_error_desc)
229 raise WinError(code, error_desc)