├── README.md ├── LICENSE └── pyusbip.py /README.md: -------------------------------------------------------------------------------- 1 | # pyusbip 2 | 3 | `pyusbip` is a userspace USBIP server implementation based on `python-libusb1`. (In USBIP, the 'server' has the physical USB device attached, and the 'client' has only a network cable attached; i.e., you run this if you have a USB device attached to your local machine that you'd like to be able to use on a different computer.) 4 | 5 | It has been tested (for small values of "tested") on Mac OS X; it is, at least, sufficient to forward a Lattice MachXO3 eval kit to the Lattice programmer software. 6 | 7 | ## Usage instructions 8 | 9 | Following is a rough recipe for getting started with forwarding a USB device using `pyusbip`. 10 | 11 | * Make sure that you have `python-libusb1` installed: `pip install libusb1`. 12 | * As necessary on your platform, give yourself permission to access the USB device. 13 | * Launch pyusbip: `python3 pyusbip.py` 14 | * Forward the port to another machine: `ssh you@target_machine -C -R 3240:127.0.0.1:3240` 15 | * Find the device you want: `sudo usbip list -r 127.0.0.1` 16 | * Attach the device you want: `sudo usbip attach -r 127.0.0.1 -b 20-4` 17 | * Enjoy! 18 | 19 | ## Limitations 20 | 21 | `pyusbip` has many limitations. Much of the protocol is unimplemented; `pyusbip` simply disconnects a device and drops a connection if it trips on that. In some cases, protocol violations in USBIP can cause the Linux kernel's entire USB stack to crash (!); for instance, if `pyusbip` gets stuck transmitting half of a response URB, you may need to reboot the remote end before it'll come back to life. Following is a list of known limitations in `pyusbip`: 22 | 23 | * `pyusbip` gives up on a device if it can't claim all interfaces, rather than failing URBs with `-EPERM` or some such. (This is a problem when exporting, say, a ST-Link board that also has a mass storage device, from OS X.) 24 | * `pyusbip`'s control traffic is synchronous. 25 | * `pyusbip` does not keep track of what type of endpoint it's talking to, and as such, always sends bulk requests, even to interrupt or isochronous endpoints. 26 | * `pyusbip` does not implement isochronous endpoints at all. 27 | * Error handling usually results in forcing a device disconnect, rather than doing anything reasonable. 28 | * `UNLINK` requests may send a spurious URB reply, which could confuse some clients. 29 | * Comments are ... sparse. 30 | * Code architecture is suspicious. 31 | 32 | ## Contact 33 | 34 | `pyusbip` is unsupported. Please use [the GitHub repository](https://github.com/jwise/pyusbip) to submit patches. If you need to, you can [contact the author](https://joshuawise.com/contact). 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /pyusbip.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # pyusbip 4 | # USBIP server in Python 5 | # 6 | # Copyright (c) 2018 Joshua Wise 7 | # 8 | # Licensed under the Apache License, Version 2.0 (the "License"); 9 | # you may not use this file except in compliance with the License. 10 | # You may obtain a copy of the License at 11 | # 12 | # http://www.apache.org/licenses/LICENSE-2.0 13 | # 14 | # Unless required by applicable law or agreed to in writing, software 15 | # distributed under the License is distributed on an "AS IS" BASIS, 16 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | # See the License for the specific language governing permissions and 18 | # limitations under the License. 19 | 20 | import asyncio 21 | import usb1 22 | import struct 23 | import traceback 24 | 25 | USBIP_HOST = '127.0.0.1' 26 | USBIP_PORT = 3240 27 | 28 | USBIP_REQUEST = 0x8000 29 | USBIP_REPLY = 0x0000 30 | 31 | USBIP_OP_UNSPEC = 0x00 32 | USBIP_OP_DEVINFO = 0x02 33 | USBIP_OP_IMPORT = 0x03 34 | USBIP_OP_EXPORT = 0x06 35 | USBIP_OP_UNEXPORT = 0x07 36 | USBIP_OP_DEVLIST = 0x05 37 | 38 | USBIP_CMD_SUBMIT = 0x0001 39 | USBIP_CMD_UNLINK = 0x0002 40 | USBIP_RET_SUBMIT = 0x0003 41 | USBIP_RET_UNLINK = 0x0004 42 | USBIP_RESET_DEV = 0xFFFF 43 | 44 | USBIP_DIR_OUT = 0 45 | USBIP_DIR_IN = 1 46 | 47 | USBIP_ST_OK = 0x00 48 | USBIP_ST_NA = 0x01 49 | 50 | USBIP_BUS_ID_SIZE = 32 51 | USBIP_DEV_PATH_MAX = 256 52 | 53 | USBIP_VERSION = 0x0111 54 | 55 | USBIP_SPEED_UNKNOWN = 0 56 | USBIP_SPEED_LOW = 1 57 | USBIP_SPEED_FULL = 2 58 | USBIP_SPEED_HIGH = 3 59 | USBIP_SPEED_VARIABLE = 4 60 | 61 | USB_RECIP_DEVICE = 0x00 62 | USB_RECIP_INTERFACE = 0x01 63 | USB_REQ_SET_ADDRESS = 0x05 64 | USB_REQ_SET_CONFIGURATION = 0x09 65 | USB_REQ_SET_INTERFACE = 0x0B 66 | 67 | USB_ENOENT = 2 68 | USB_EPIPE = 32 69 | 70 | usbctx = usb1.USBContext() 71 | usbctx.open() 72 | 73 | class USBIPUnimplementedException(Exception): 74 | def __init__(self, message): 75 | self.message = message 76 | 77 | class USBIPProtocolErrorException(Exception): 78 | def __init__(self, message): 79 | self.message = message 80 | 81 | class USBIPDevice: 82 | def __init__(self, devid, hnd): 83 | self.devid = devid 84 | self.hnd = hnd 85 | 86 | class USBIPPending: 87 | def __init__(self, seqnum, device, xfer): 88 | self.seqnum = seqnum 89 | self.device = device 90 | self.xfer = xfer 91 | 92 | class USBIPConnection: 93 | def __init__(self, reader, writer): 94 | self.reader = reader 95 | self.writer = writer 96 | self.devices = {} 97 | self.urbs = {} 98 | 99 | def say(self, str): 100 | addr = self.writer.get_extra_info('peername') 101 | print('{}: {}'.format(addr, str)) 102 | 103 | def pack_device_desc(self, dev, interfaces = True): 104 | """Takes a usb1 device and packs it into a struct usb_device (and 105 | optionally, struct usb_interfaces).""" 106 | 107 | path = "pyusbip/{}/{}".format(dev.getBusNumber(), dev.getDeviceAddress()) 108 | busid = "{}-{}".format(dev.getBusNumber(), dev.getDeviceAddress()) 109 | busnum = dev.getBusNumber() 110 | devnum = dev.getDeviceAddress() 111 | speed = { 112 | usb1.SPEED_UNKNOWN: USBIP_SPEED_UNKNOWN, 113 | usb1.SPEED_LOW: USBIP_SPEED_LOW, 114 | usb1.SPEED_FULL: USBIP_SPEED_FULL, 115 | usb1.SPEED_HIGH: USBIP_SPEED_HIGH, 116 | usb1.SPEED_SUPER: USBIP_SPEED_HIGH, 117 | usb1.SPEED_SUPER_PLUS:USBIP_SPEED_HIGH, 118 | }[dev.getDeviceSpeed()] 119 | 120 | idVendor = dev.getVendorID() 121 | idProduct = dev.getProductID() 122 | bcdDevice = dev.getbcdDevice() 123 | 124 | bDeviceClass = dev.getDeviceClass() 125 | bDeviceSubClass = dev.getDeviceSubClass() 126 | bDeviceProtocol = dev.getDeviceProtocol() 127 | configs = list(dev.iterConfigurations()) 128 | try: 129 | hnd = dev.open() 130 | bConfigurationValue = hnd.getConfiguration() 131 | hnd.close() 132 | except Exception: 133 | bConfigurationValue = configs[0].getConfigurationValue() 134 | bNumConfigurations = dev.getNumConfigurations() 135 | 136 | # Sigh, find it. 137 | config = configs[0] 138 | for _config in configs: 139 | if _config.getConfigurationValue() == bConfigurationValue: 140 | config = _config 141 | break 142 | bNumInterfaces = config.getNumInterfaces() 143 | 144 | data = struct.pack(">256s32sIIIHHHBBBBBB", 145 | path.encode(), busid.encode(), 146 | busnum, devnum, speed, 147 | idVendor, idProduct, bcdDevice, 148 | bDeviceClass, bDeviceSubClass, bDeviceProtocol, bConfigurationValue, bNumConfigurations, bNumInterfaces) 149 | 150 | if interfaces: 151 | for ifc in config.iterInterfaces(): 152 | set = list(ifc)[0] 153 | data += struct.pack(">BBBB", set.getClass(), set.getSubClass(), set.getProtocol(), 0) 154 | 155 | return data 156 | 157 | def handle_op_devlist(self): 158 | devlist = usbctx.getDeviceList() 159 | 160 | resp = struct.pack(">HHII", USBIP_VERSION, USBIP_OP_DEVLIST | USBIP_REPLY, USBIP_ST_OK, len(devlist)) 161 | for dev in devlist: 162 | resp += self.pack_device_desc(dev) 163 | 164 | self.writer.write(resp) 165 | 166 | def handle_op_import(self, busid): 167 | # We kind of do this the hard way -- rather than looking up by bus 168 | # id / device address, we instead just compare the string. Life is 169 | # too short to extend python-libusb1. 170 | devlist = usbctx.getDeviceList() 171 | for dev in devlist: 172 | dev_busid = "{}-{}".format(dev.getBusNumber(), dev.getDeviceAddress()) 173 | if busid == dev_busid: 174 | hnd = dev.open() 175 | self.say('opened device {}'.format(busid)) 176 | devid = dev.getBusNumber() << 16 | dev.getDeviceAddress() 177 | self.devices[devid] = USBIPDevice(devid, hnd) 178 | resp = struct.pack(">HHI", USBIP_VERSION, USBIP_OP_IMPORT | USBIP_REPLY, USBIP_ST_OK) 179 | resp += self.pack_device_desc(dev, interfaces = False) 180 | self.writer.write(resp) 181 | return 182 | 183 | self.say('device not found') 184 | resp = struct.pack(">HHI", USBIP_VERSION, USBIP_OP_IMPORT | USBIP_REPLY, USBIP_ST_NA) 185 | self.writer.write(resp) 186 | 187 | async def handle_urb_submit(self, seqnum, dev, direction, ep): 188 | op_submit = ">Iiiii8s" 189 | data = await self.reader.readexactly(struct.calcsize(op_submit)) 190 | (transfer_flags, buflen, start_frame, number_of_packets, interval, setup) = struct.unpack(op_submit, data) 191 | 192 | if number_of_packets != 0: 193 | raise USBIPUnimplementedException("ISO number_of_packets {}".format(number_of_packets)) 194 | 195 | if direction == USBIP_DIR_OUT: 196 | buf = await self.reader.readexactly(buflen) 197 | 198 | (bRequestType, bRequest, wValue, wIndex, wLength) = struct.unpack(" {}'.format(wIndex, wValue)) 231 | dev.hnd.claimInterface(wIndex) 232 | dev.hnd.setInterfaceAltSetting(wIndex, wValue) 233 | fakeit = True 234 | 235 | try: 236 | if direction == USBIP_DIR_IN: 237 | data = dev.hnd.controlRead(bRequestType, bRequest, wValue, wIndex, wLength) 238 | resp = struct.pack(">IIIIIiiiii8s", 239 | USBIP_RET_SUBMIT, seqnum, 240 | 0, 0, 0, 241 | #dev.devid, direction, ep, 242 | 0, len(data), 0, 0, 0, 243 | b'') 244 | resp += data 245 | self.say("wrote response with {}/{} bytes".format(len(data), wLength)) 246 | self.writer.write(resp) 247 | else: 248 | if fakeit: 249 | wlen = 0 250 | else: 251 | wlen = dev.hnd.controlWrite(bRequestType, bRequest, wValue, wIndex, buf) 252 | resp = struct.pack(">IIIIIiiiii8s", 253 | USBIP_RET_SUBMIT, seqnum, 254 | 0, 0, 0, 255 | 0, wlen, 0, 0, 0, 256 | b'') 257 | self.say("wrote {}/{} bytes".format(wlen, wLength)) 258 | self.writer.write(resp) 259 | except usb1.USBErrorPipe: 260 | resp = struct.pack(">IIIIIiiiii8s", 261 | USBIP_RET_SUBMIT, seqnum, 262 | 0, 0, 0, 263 | -USB_EPIPE, 0, 0, 0, 0, 264 | b'') 265 | self.say('EPIPE') 266 | self.writer.write(resp) 267 | else: 268 | # Ok, a request on another endpoint. These are asynchronous. 269 | xfer = dev.hnd.getTransfer() 270 | 271 | if direction == USBIP_DIR_IN: 272 | def callback(xfer_): 273 | self.say('callback IN seqnum {:x} status {} len {} buflen {}'.format(seqnum, xfer.getStatus(), xfer.getActualLength(), len(xfer.getBuffer()))) 274 | resp = struct.pack(">IIIIIiiiii8s", 275 | USBIP_RET_SUBMIT, seqnum, 276 | 0, 0, 0, 277 | -xfer.getStatus(), xfer.getActualLength(), 0, 0, 0, 278 | b'') 279 | resp += xfer.getBuffer()[:xfer.getActualLength()] 280 | self.writer.write(resp) 281 | del self.urbs[seqnum] 282 | xfer.setBulk(ep | 0x80, buflen, callback) 283 | xfer.submit() 284 | self.urbs[seqnum] = USBIPPending(seqnum, dev, xfer) 285 | else: 286 | def callback(xfer_): 287 | self.say('callback OUT seqnum {:x} status {} '.format(seqnum, xfer.getStatus())) 288 | resp = struct.pack(">IIIIIiiiii8s", 289 | USBIP_RET_SUBMIT, seqnum, 290 | 0, 0, 0, 291 | -xfer.getStatus(), xfer.getActualLength(), 0, 0, 0, 292 | b'') 293 | self.writer.write(resp) 294 | del self.urbs[seqnum] 295 | xfer.setBulk(ep, buf, callback) 296 | xfer.submit() 297 | self.urbs[seqnum] = USBIPPending(seqnum, dev, xfer) 298 | 299 | async def handle_urb_unlink(self, seqnum, dev, direction, ep): 300 | op_submit = ">Iiiii8s" 301 | data = await self.reader.readexactly(struct.calcsize(op_submit)) 302 | (sseqnum, buflen, start_frame, number_of_packets, interval, setup) = struct.unpack(op_submit, data) 303 | 304 | self.say("seq {:x}: UNLINK".format(sseqnum)) 305 | 306 | if sseqnum not in self.urbs: 307 | rv = -USB_ENOENT 308 | else: 309 | rv = 0 310 | self.urbs[sseqnum].xfer.cancel() 311 | 312 | resp = struct.pack(">IIIIIiiiii8s", 313 | USBIP_RET_UNLINK, seqnum, 314 | 0, 0, 0, 315 | rv, 0, 0, 0, 0, 316 | b'') 317 | 318 | async def handle_packet(self): 319 | """ 320 | Handle a USBIP packet. 321 | """ 322 | 323 | # Try to read a header of some kind. We can tell because if it's an 324 | # URB, the |op_common.version| is overlayed with the 325 | # |usbip_header_basic.command|, and so the |.version| is 0x0000; 326 | # otherwise, it's supposed to be 0x0106. 327 | 328 | try: 329 | data = await self.reader.readexactly(2) 330 | except asyncio.exceptions.IncompleteReadError: 331 | return False 332 | 333 | (version, ) = struct.unpack(">H", data) 334 | if version == 0x0000: 335 | # Note that we've already trimmed the version. 336 | op_common = ">HIIII"; 337 | data = await self.reader.readexactly(struct.calcsize(op_common)) 338 | (opcode, seqnum, devid, direction, ep) = struct.unpack(op_common, data) 339 | 340 | if devid not in self.devices: 341 | raise USBIPProtocolErrorException('devid unattached {:x}'.format(devid)) 342 | dev = self.devices[devid] 343 | 344 | if opcode == USBIP_CMD_SUBMIT: 345 | await self.handle_urb_submit(seqnum, dev, direction, ep) 346 | elif opcode == USBIP_CMD_UNLINK: 347 | await self.handle_urb_unlink(seqnum, dev, direction, ep) 348 | elif opcode == USBIP_RESET_DEV: 349 | raise USBIPUnimplementedException("URB_RESET_DEV") 350 | else: 351 | raise USBIPProtocolErrorException('bad USBIP URB {:x}'.format(opcode)) 352 | elif (version & 0xff00) == 0x0100: 353 | # Note that we've already trimmed the version. 354 | op_common = ">HI" 355 | data = await self.reader.readexactly(struct.calcsize(op_common)) 356 | (opcode, status) = struct.unpack(op_common, data) 357 | 358 | if opcode == USBIP_OP_UNSPEC | USBIP_REQUEST: 359 | self.writer.write(struct.pack(">HHI", version, USBIP_OP_UNSPEC | USBIP_REPLY, USBIP_ST_OK)) 360 | elif opcode == USBIP_OP_DEVINFO | USBIP_REQUEST: 361 | data = await self.reader.readexactly(USBIP_BUS_ID_SIZE) 362 | raise USBIPUnimplementedException("DEVINFO") 363 | # writer.write(struct.pack(">HHI", version, USBIP_OP_DEVINFO | USBIP_REPLY, USBIP_ST_NA) 364 | elif opcode == USBIP_OP_DEVLIST | USBIP_REQUEST: 365 | self.say('DEVLIST') 366 | # XXX: in theory, op_devlist_request has a _reserved, but they don't seem to xmit it? 367 | # data = await self.reader.readexactly(4) # reserved 368 | self.handle_op_devlist() 369 | elif opcode == USBIP_OP_IMPORT | USBIP_REQUEST: 370 | data = (await self.reader.readexactly(USBIP_BUS_ID_SIZE)).decode().rstrip('\0') 371 | self.say('IMPORT {}'.format(data)) 372 | self.handle_op_import(data) 373 | else: 374 | raise USBIPProtocolErrorException('bad USBIP op {:x}'.format(opcode)) 375 | else: 376 | raise USBIPProtocolErrorException("unsupported USBIP version {:02x}".format(version)) 377 | 378 | return True 379 | 380 | async def connection(self): 381 | self.say('connect') 382 | 383 | while True: 384 | try: 385 | success = await self.handle_packet() 386 | await self.writer.drain() 387 | if not success: 388 | break 389 | except Exception as e: 390 | traceback.print_exc() 391 | self.say('force disconnect due to exception') 392 | break 393 | 394 | self.say('disconnect') 395 | for i in self.devices: 396 | self.devices[i].hnd.close() 397 | self.devices[i] = None 398 | await self.writer.drain() 399 | self.writer.close() 400 | 401 | async def usbip_connection(reader, writer): 402 | conn = USBIPConnection(reader, writer) 403 | await conn.connection() 404 | 405 | loop = asyncio.new_event_loop() 406 | coro = asyncio.start_server(usbip_connection, USBIP_HOST, USBIP_PORT) 407 | server = loop.run_until_complete(coro) 408 | 409 | def usb_callback(): 410 | usbctx.handleEventsTimeout() 411 | 412 | def usb_added(fd, events): 413 | print('adding fd {} for {}'.format(fd, events)) 414 | loop.add_reader(fd, usb_callback) 415 | 416 | def usb_removed(fd, events): 417 | print('removing fd {} for {}'.format(fd, events)) 418 | loop.remove_reader(fd) 419 | 420 | for fd, events in usbctx.getPollFDList(): 421 | usb_added(fd, events) 422 | usbctx.setPollFDNotifiers(usb_added, usb_removed) 423 | 424 | print('Serving on {}'.format(server.sockets[0].getsockname())) 425 | try: 426 | loop.run_forever() 427 | except KeyboardInterrupt: 428 | pass 429 | 430 | print('Shutting down...') 431 | server.close() 432 | loop.run_until_complete(server.wait_closed()) 433 | loop.close() --------------------------------------------------------------------------------