Renaud Paquay | d5cec5e | 2016-11-01 11:24:03 -0700 | [diff] [blame] | 1 | # |
| 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 | |
| 16 | import errno |
| 17 | |
Renaud Paquay | 227ad2e | 2016-11-01 14:37:13 -0700 | [diff] [blame] | 18 | from ctypes import WinDLL, get_last_error, FormatError, WinError, addressof |
| 19 | from ctypes import c_buffer |
| 20 | from ctypes.wintypes import BOOL, LPCWSTR, DWORD, HANDLE, POINTER, c_ubyte |
| 21 | from ctypes.wintypes import WCHAR, USHORT, LPVOID, Structure, Union, ULONG |
| 22 | from ctypes.wintypes import byref |
Renaud Paquay | d5cec5e | 2016-11-01 11:24:03 -0700 | [diff] [blame] | 23 | |
| 24 | kernel32 = WinDLL('kernel32', use_last_error=True) |
| 25 | |
Renaud Paquay | 227ad2e | 2016-11-01 14:37:13 -0700 | [diff] [blame] | 26 | LPDWORD = POINTER(DWORD) |
| 27 | UCHAR = c_ubyte |
| 28 | |
Renaud Paquay | d5cec5e | 2016-11-01 11:24:03 -0700 | [diff] [blame] | 29 | # Win32 error codes |
| 30 | ERROR_SUCCESS = 0 |
Renaud Paquay | 227ad2e | 2016-11-01 14:37:13 -0700 | [diff] [blame] | 31 | ERROR_NOT_SUPPORTED = 50 |
Renaud Paquay | d5cec5e | 2016-11-01 11:24:03 -0700 | [diff] [blame] | 32 | ERROR_PRIVILEGE_NOT_HELD = 1314 |
| 33 | |
| 34 | # Win32 API entry points |
| 35 | CreateSymbolicLinkW = kernel32.CreateSymbolicLinkW |
| 36 | CreateSymbolicLinkW.restype = BOOL |
| 37 | CreateSymbolicLinkW.argtypes = (LPCWSTR, # lpSymlinkFileName In |
| 38 | LPCWSTR, # lpTargetFileName In |
| 39 | DWORD) # dwFlags In |
| 40 | |
| 41 | # Symbolic link creation flags |
| 42 | SYMBOLIC_LINK_FLAG_FILE = 0x00 |
| 43 | SYMBOLIC_LINK_FLAG_DIRECTORY = 0x01 |
Renaud Paquay | 2b42d28 | 2018-10-01 14:59:48 -0700 | [diff] [blame] | 44 | # symlink support for CreateSymbolicLink() starting with Windows 10 (1703, v10.0.14972) |
| 45 | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE = 0x02 |
Renaud Paquay | d5cec5e | 2016-11-01 11:24:03 -0700 | [diff] [blame] | 46 | |
Renaud Paquay | 227ad2e | 2016-11-01 14:37:13 -0700 | [diff] [blame] | 47 | GetFileAttributesW = kernel32.GetFileAttributesW |
| 48 | GetFileAttributesW.restype = DWORD |
| 49 | GetFileAttributesW.argtypes = (LPCWSTR,) # lpFileName In |
| 50 | |
| 51 | INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF |
| 52 | FILE_ATTRIBUTE_REPARSE_POINT = 0x00400 |
| 53 | |
| 54 | CreateFileW = kernel32.CreateFileW |
| 55 | CreateFileW.restype = HANDLE |
| 56 | CreateFileW.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 | |
| 64 | CloseHandle = kernel32.CloseHandle |
| 65 | CloseHandle.restype = BOOL |
| 66 | CloseHandle.argtypes = (HANDLE,) # hObject In |
| 67 | |
| 68 | INVALID_HANDLE_VALUE = HANDLE(-1).value |
| 69 | OPEN_EXISTING = 3 |
| 70 | FILE_FLAG_BACKUP_SEMANTICS = 0x02000000 |
| 71 | FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000 |
| 72 | |
| 73 | DeviceIoControl = kernel32.DeviceIoControl |
| 74 | DeviceIoControl.restype = BOOL |
| 75 | DeviceIoControl.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 |
| 85 | FSCTL_GET_REPARSE_POINT = 0x000900A8 |
| 86 | IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003 |
| 87 | IO_REPARSE_TAG_SYMLINK = 0xA000000C |
| 88 | MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 0x4000 |
| 89 | |
| 90 | |
| 91 | class GENERIC_REPARSE_BUFFER(Structure): |
| 92 | _fields_ = (('DataBuffer', UCHAR * 1),) |
| 93 | |
| 94 | |
| 95 | class 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 | |
| 110 | class 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 | |
| 124 | class 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 Paquay | d5cec5e | 2016-11-01 11:24:03 -0700 | [diff] [blame] | 135 | |
| 136 | def 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 | |
| 141 | def 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 | |
| 147 | def _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 Paquay | 2b42d28 | 2018-10-01 14:59:48 -0700 | [diff] [blame] | 152 | CreateSymbolicLinkW(link_name, source, dwFlags | SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE) |
Renaud Paquay | d5cec5e | 2016-11-01 11:24:03 -0700 | [diff] [blame] | 153 | code = get_last_error() |
| 154 | if code != ERROR_SUCCESS: |
Renaud Paquay | 2b42d28 | 2018-10-01 14:59:48 -0700 | [diff] [blame] | 155 | # 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 Paquay | 227ad2e | 2016-11-01 14:37:13 -0700 | [diff] [blame] | 167 | |
| 168 | |
| 169 | def 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 | |
| 176 | def 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 | |
| 215 | def _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 | |
| 222 | def _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) |