blob: 31e00c17879af1f96b7785d9f2caf12575527fce [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
Renaud Paquay227ad2e2016-11-01 14:37:13 -070019from ctypes import WinDLL, get_last_error, FormatError, WinError, addressof
20from ctypes import c_buffer
Роман Донченкоa84df062019-03-21 23:45:59 +030021from ctypes.wintypes import BOOL, BOOLEAN, LPCWSTR, DWORD, HANDLE, POINTER, c_ubyte
Renaud Paquay227ad2e2016-11-01 14:37:13 -070022from ctypes.wintypes import WCHAR, USHORT, LPVOID, Structure, Union, ULONG
23from ctypes.wintypes import byref
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070024
25kernel32 = WinDLL('kernel32', use_last_error=True)
26
Renaud Paquay227ad2e2016-11-01 14:37:13 -070027LPDWORD = POINTER(DWORD)
28UCHAR = c_ubyte
29
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070030# Win32 error codes
31ERROR_SUCCESS = 0
Renaud Paquay227ad2e2016-11-01 14:37:13 -070032ERROR_NOT_SUPPORTED = 50
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070033ERROR_PRIVILEGE_NOT_HELD = 1314
34
35# Win32 API entry points
36CreateSymbolicLinkW = kernel32.CreateSymbolicLinkW
Роман Донченкоa84df062019-03-21 23:45:59 +030037CreateSymbolicLinkW.restype = BOOLEAN
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070038CreateSymbolicLinkW.argtypes = (LPCWSTR, # lpSymlinkFileName In
39 LPCWSTR, # lpTargetFileName In
40 DWORD) # dwFlags In
41
42# Symbolic link creation flags
43SYMBOLIC_LINK_FLAG_FILE = 0x00
44SYMBOLIC_LINK_FLAG_DIRECTORY = 0x01
Renaud Paquay2b42d282018-10-01 14:59:48 -070045# symlink support for CreateSymbolicLink() starting with Windows 10 (1703, v10.0.14972)
46SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE = 0x02
Renaud Paquayd5cec5e2016-11-01 11:24:03 -070047
Renaud Paquay227ad2e2016-11-01 14:37:13 -070048GetFileAttributesW = kernel32.GetFileAttributesW
49GetFileAttributesW.restype = DWORD
50GetFileAttributesW.argtypes = (LPCWSTR,) # lpFileName In
51
52INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF
53FILE_ATTRIBUTE_REPARSE_POINT = 0x00400
54
55CreateFileW = kernel32.CreateFileW
56CreateFileW.restype = HANDLE
57CreateFileW.argtypes = (LPCWSTR, # lpFileName In
58 DWORD, # dwDesiredAccess In
59 DWORD, # dwShareMode In
60 LPVOID, # lpSecurityAttributes In_opt
61 DWORD, # dwCreationDisposition In
62 DWORD, # dwFlagsAndAttributes In
63 HANDLE) # hTemplateFile In_opt
64
65CloseHandle = kernel32.CloseHandle
66CloseHandle.restype = BOOL
67CloseHandle.argtypes = (HANDLE,) # hObject In
68
69INVALID_HANDLE_VALUE = HANDLE(-1).value
70OPEN_EXISTING = 3
71FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
72FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000
73
74DeviceIoControl = kernel32.DeviceIoControl
75DeviceIoControl.restype = BOOL
76DeviceIoControl.argtypes = (HANDLE, # hDevice In
77 DWORD, # dwIoControlCode In
78 LPVOID, # lpInBuffer In_opt
79 DWORD, # nInBufferSize In
80 LPVOID, # lpOutBuffer Out_opt
81 DWORD, # nOutBufferSize In
82 LPDWORD, # lpBytesReturned Out_opt
83 LPVOID) # lpOverlapped Inout_opt
84
85# Device I/O control flags and options
86FSCTL_GET_REPARSE_POINT = 0x000900A8
87IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003
88IO_REPARSE_TAG_SYMLINK = 0xA000000C
89MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 0x4000
90
91
92class GENERIC_REPARSE_BUFFER(Structure):
93 _fields_ = (('DataBuffer', UCHAR * 1),)
94
95
96class SYMBOLIC_LINK_REPARSE_BUFFER(Structure):
97 _fields_ = (('SubstituteNameOffset', USHORT),
98 ('SubstituteNameLength', USHORT),
99 ('PrintNameOffset', USHORT),
100 ('PrintNameLength', USHORT),
101 ('Flags', ULONG),
102 ('PathBuffer', WCHAR * 1))
103
104 @property
105 def PrintName(self):
106 arrayt = WCHAR * (self.PrintNameLength // 2)
107 offset = type(self).PathBuffer.offset + self.PrintNameOffset
108 return arrayt.from_address(addressof(self) + offset).value
109
Renaud Paquayd5cec5e2016-11-01 11:24:03 -0700110
Renaud Paquay227ad2e2016-11-01 14:37:13 -0700111class MOUNT_POINT_REPARSE_BUFFER(Structure):
112 _fields_ = (('SubstituteNameOffset', USHORT),
113 ('SubstituteNameLength', USHORT),
114 ('PrintNameOffset', USHORT),
115 ('PrintNameLength', USHORT),
116 ('PathBuffer', WCHAR * 1))
117
118 @property
119 def PrintName(self):
120 arrayt = WCHAR * (self.PrintNameLength // 2)
121 offset = type(self).PathBuffer.offset + self.PrintNameOffset
122 return arrayt.from_address(addressof(self) + offset).value
123
124
125class REPARSE_DATA_BUFFER(Structure):
126 class REPARSE_BUFFER(Union):
127 _fields_ = (('SymbolicLinkReparseBuffer', SYMBOLIC_LINK_REPARSE_BUFFER),
128 ('MountPointReparseBuffer', MOUNT_POINT_REPARSE_BUFFER),
129 ('GenericReparseBuffer', GENERIC_REPARSE_BUFFER))
130 _fields_ = (('ReparseTag', ULONG),
131 ('ReparseDataLength', USHORT),
132 ('Reserved', USHORT),
133 ('ReparseBuffer', REPARSE_BUFFER))
134 _anonymous_ = ('ReparseBuffer',)
135
136
Renaud Paquayd5cec5e2016-11-01 11:24:03 -0700137def create_filesymlink(source, link_name):
138 """Creates a Windows file symbolic link source pointing to link_name."""
139 _create_symlink(source, link_name, SYMBOLIC_LINK_FLAG_FILE)
140
141
142def create_dirsymlink(source, link_name):
143 """Creates a Windows directory symbolic link source pointing to link_name.
144 """
145 _create_symlink(source, link_name, SYMBOLIC_LINK_FLAG_DIRECTORY)
146
147
148def _create_symlink(source, link_name, dwFlags):
Роман Донченкоa84df062019-03-21 23:45:59 +0300149 if not CreateSymbolicLinkW(link_name, source, dwFlags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE):
Renaud Paquay2b42d282018-10-01 14:59:48 -0700150 # See https://github.com/golang/go/pull/24307/files#diff-b87bc12e4da2497308f9ef746086e4f0
151 # "the unprivileged create flag is unsupported below Windows 10 (1703, v10.0.14972).
152 # retry without it."
Роман Донченкоa84df062019-03-21 23:45:59 +0300153 if not CreateSymbolicLinkW(link_name, source, dwFlags):
154 code = get_last_error()
Renaud Paquay2b42d282018-10-01 14:59:48 -0700155 error_desc = FormatError(code).strip()
156 if code == ERROR_PRIVILEGE_NOT_HELD:
157 raise OSError(errno.EPERM, error_desc, link_name)
158 _raise_winerror(
159 code,
160 'Error creating symbolic link \"%s\"'.format(link_name))
Renaud Paquay227ad2e2016-11-01 14:37:13 -0700161
162
163def islink(path):
164 result = GetFileAttributesW(path)
165 if result == INVALID_FILE_ATTRIBUTES:
166 return False
167 return bool(result & FILE_ATTRIBUTE_REPARSE_POINT)
168
169
170def readlink(path):
171 reparse_point_handle = CreateFileW(path,
172 0,
173 0,
174 None,
175 OPEN_EXISTING,
176 FILE_FLAG_OPEN_REPARSE_POINT |
177 FILE_FLAG_BACKUP_SEMANTICS,
178 None)
179 if reparse_point_handle == INVALID_HANDLE_VALUE:
180 _raise_winerror(
181 get_last_error(),
182 'Error opening symblic link \"%s\"'.format(path))
183 target_buffer = c_buffer(MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
184 n_bytes_returned = DWORD()
185 io_result = DeviceIoControl(reparse_point_handle,
186 FSCTL_GET_REPARSE_POINT,
187 None,
188 0,
189 target_buffer,
190 len(target_buffer),
191 byref(n_bytes_returned),
192 None)
193 CloseHandle(reparse_point_handle)
194 if not io_result:
195 _raise_winerror(
196 get_last_error(),
197 'Error reading symblic link \"%s\"'.format(path))
198 rdb = REPARSE_DATA_BUFFER.from_buffer(target_buffer)
199 if rdb.ReparseTag == IO_REPARSE_TAG_SYMLINK:
200 return _preserve_encoding(path, rdb.SymbolicLinkReparseBuffer.PrintName)
201 elif rdb.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT:
202 return _preserve_encoding(path, rdb.MountPointReparseBuffer.PrintName)
203 # Unsupported reparse point type
204 _raise_winerror(
205 ERROR_NOT_SUPPORTED,
206 'Error reading symblic link \"%s\"'.format(path))
207
208
209def _preserve_encoding(source, target):
210 """Ensures target is the same string type (i.e. unicode or str) as source."""
211 if isinstance(source, unicode):
212 return unicode(target)
213 return str(target)
214
215
216def _raise_winerror(code, error_desc):
217 win_error_desc = FormatError(code).strip()
218 error_desc = "%s: %s".format(error_desc, win_error_desc)
219 raise WinError(code, error_desc)