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