├── LICENSE
├── README.md
├── config.yaml
├── hotplugger.py
├── monitor.py
└── qemu.py
/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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Hotplugger: Real USB Port Passthrough for VFIO/QEMU!
2 |
3 | Welcome to Hotplugger! This app, as the name might tell you, is a combination of some scripts (python, yaml, udev rules and some QEMU args) to allow you to pass through an actual USB port into a VM. Instead of passing the USB root hub (which could have the side effect of passing *all the ports*, including the ones you didn't want to) or another PCIe hub or something, you can just pass a specific USB port to a VM and have the others free for anything else. Plus, it saves you from using the `vfio-pci` driver for the USB root hub, so you can keep using it for evdev or other things on the VM host.
4 |
5 | # Requirements
6 |
7 | * `monitor.py` and `hotplugger.py` require **Python 3**
8 |
9 | * Only tested with QEMU 5.0.0 and 6.0.0. Untested with other versions.
10 |
11 | * Your QEMU machine must expose a QMP socket like this. The `path=` argument is important, we'll use that filename. It can be either relative or absolute, just make sure you can find and have access to it.
12 |
13 | ```
14 | -chardev socket,id=mon1,server=on,wait=off,path=./qmp-sock
15 | -mon chardev=mon1,mode=control,pretty=on
16 | ```
17 |
18 | * Add one or more USB hubs to the guest VM. Using `nec-usb-xhci` is preferable for Win10 machines:
19 |
20 | ```
21 | -device nec-usb-xhci,id=xhci0
22 | -device nec-usb-xhci,id=xhci1
23 | ```
24 |
25 | This creates two hubs: `xhci0.0` and `xhci1.0`. Why? See caveat below:
26 |
27 | ### Important caveat with `nec-usb-xhci`:
28 |
29 | It seems that `nec-usb-xhci` has 4 USB ports hardcoded and that cannot be changed. So, each time an USB device is added to the guest, QEMU will add the USB devices to the hub **until** it fills up, **BUT** it won't add the last device to the last available port. Instead, an USB 1.1 hub will be added to that port (to avoid running out of USB ports). This has the downside that if you are adding an USB 3.0 device, it will end up being connected to a **virtual** USB 1.1 hub, therefore slowing down its speed to 12Mb/s and if the device does not support that, Windows may fail to recognize or even use it.
30 |
31 | So in the example above, two XHCI hubs are created manually. This gives us either 6 USB 3.0, or 8 USB 1.1-2.0 ports, depending on what's connected and if QEMU doesn't whine about a speed mismatch. If it does, the device will be connected to the next available XHCI hub.
32 |
33 | # Quick start (Ubuntu 20.10)
34 |
35 | 1. `git clone https://github.com/darkguy2008/hotplugger.git`
36 |
37 | 2. (Optional) run `python3 monitor.py` and follow the prompts. Basically once you hit Enter you have to plug and unplug an USB device (a thumb drive or audio device preferred) into the USB ports that you want to know their `DEVPATH` route from. This will help you identify them so you can write them into `config.yaml` in the `ports` array. This array only accepts `DEVPATH` routes that `UDEV` generates.
38 |
39 | 3. Edit `config.yaml`. **It must stay in the same folder as `monitor.py` and `hotplugger.py`**. Using the following file as example:
40 |
41 | ```
42 | virtual_machines:
43 |
44 | windows:
45 | socket: /home/user/vm/windows/qmp-sock
46 | delay: 1
47 | hubs:
48 | - xhci0.0
49 | - xhci1.0
50 | ports:
51 | - /devices/pci0000:00/0000:00:14.0/usb3/3-3
52 | - /devices/pci0000:00/0000:00:14.0/usb3/3-4
53 | ```
54 |
55 | This is for a Windows VM where its UNIX QEMU QMP socket is located at `/home/user/vm/windows/qmp-sock`, with a 1-second delay after a device is plugged to actually do the hotplugging to QEMU, with two virtual XHCI hubs that will receive all the USB devices in the 2 USB ports denoted as `/devices/pci0000:00/0000:00:14.0/usb3/3-3` and `/devices/pci0000:00/0000:00:14.0/usb3/3-4` . To figure this out, I ran `monitor.py` and got this output:
56 |
57 | ```
58 | Monitoring USB ports...
59 | ^C
60 | DEVPATH=/devices/pci0000:00/0000:00:14.0/usb3/3-3
61 | DEVPATH=/devices/pci0000:00/0000:00:14.0/usb3/3-3/3-1:1.0
62 | DEVPATH=/devices/pci0000:00/0000:00:14.0/usb3/3-4
63 | DEVPATH=/devices/pci0000:00/0000:00:14.0/usb3/3-4/3-1:1.0
64 | DEVPATH=/devices/pci0000:00/0000:00:14.0/usb3/3-4/3-1:1.1
65 | ```
66 |
67 | So this means that I have to enter **only** the shortest entries: `/devices/pci0000:00/0000:00:14.0/usb3/3-3` and `/devices/pci0000:00/0000:00:14.0/usb3/3-4`
68 |
69 | 4. Create an `/etc/udev/rules.d/99-zzz-local.rules` file with the following content:
70 |
71 | ```
72 | SUBSYSTEM=="usb", ACTION=="add", RUN+="/bin/bash -c 'python3 /path-to-hotplugger/hotplugger.py >> /tmp/hotplugger.log' 2>&1"
73 | SUBSYSTEM=="usb", ACTION=="remove", RUN+="/bin/bash -c 'python3 /path-to-hotplugger/hotplugger.py >> /tmp/hotplugger.log' 2>&1"
74 | ```
75 |
76 | Make sure to change `path-to-hotplugger` with the path where you cloned the repo to, or installed the package. It can be simplified, but this one is useful in case you want to debug and see what's going on. Otherwise, proceed with a simpler file:
77 |
78 | ```
79 | SUBSYSTEM=="usb", ACTION=="add", RUN+="/bin/bash -c 'python3 /path-to-hotplugger/hotplugger.py'"
80 | SUBSYSTEM=="usb", ACTION=="remove", RUN+="/bin/bash -c 'python3 /path-to-hotplugger/hotplugger.py'"
81 | ```
82 |
83 | 5. Have a coffee! ☕
84 |
85 | # Libvirt setup
86 |
87 | This is a work in progress, but here's some steps to get you started:
88 |
89 | 1. Edit your VM's XML config like this:
90 |
91 | 1. ```xml
92 |
93 | QEMUGuest1
94 | c7a5fdbd-edaf-9455-926a-d65c16db1809
95 | ...
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 | ```
104 |
105 | Add the `xmlns` attribute and the QEMU commandline arguments like that. The `/tmp/my-vm-sock` is the name of an unix domain socket. You can use any, just make sure to also put the same path in the `config.yaml` file.
106 |
107 | 2. If you get a permissions issue, edit `/etc/libvirt/qemu.conf` and add `security_driver = "none"`to it to fix apparmor being annoying about it.
108 |
109 | ### How it works
110 |
111 | 1. The `udev` rule launches the script on *every* USB event. For each USB `add`/`remove` action there's around 3 to 5+ events. This allows the app to act at any step in the action lifecycle.
112 | 2. In the first step it gets the kernel environment variables from `udev` and stores them in a temp file. In those variables, the `DEVPATH`, the `DEVNUM` (host address in QEMU, it seems to change and is sequential...) and the `BUSNUM` (bus address in QEMU) are captured. For the subsequent events, the following steps are run:
113 | 1. It requests QEMU through the Unix socket and the `info usbhost` QMP command the USB info from the host. This gives it an extra field: The host **port** where the device is also connected to. Since I got the `host` and `bus` addresses in the first event, I can use that to parse through the `info usbhost` command's output and find the **port** connected to the device.
114 | 2. If the port is found, using the `device_add` command, a new `usb-host` device is added using the USB `bus` and `port` we got in the previous step, and assigns it a predictable ID that it can use to unplug the device afterwards.
115 | 3. The temp file is cleared once the `device_add` command has run successfully.
116 |
117 | Steps 2.1, 2.2 and 2.3 are run on every `udev` event. For instance, for an audio device it gets 3 or 4 events: One for the HID device, and two or so for the audio devices. My audio device (Corsair Void Elite Wireless) has both stereo audio and a communications device (mono audio, for mic) so for a single dongle like that I get those many events. Since these steps are ran on all the events, there's multiple chances to do the hotplug action. When one of them succeeds, the others will silently fail as QEMU will say that the same device ID is being used, so all is good.
118 |
119 | ## Troubleshooting
120 |
121 | If for some reason the app doesn't seem to work, try these methods:
122 |
123 | * Remove the `tmp` folder where `hotplugger.py` is located
124 | * Reboot the computer
125 | * Reboot `udev`: `sudo udevadm control --reload-rules && sudo udevadm trigger`
126 | * View `udev`'s logfile: `sudo service udev restart && sudo udevadm control --log-priority=debug && journalctl -f | grep -i hotplugger`
127 | * If you want to see what will be run when you plug a device, try with this command to simulate an `udev` event: `udevadm test $(udevadm info -a --path=/devices/pci0000:00/0000:00:14.0/usb3/3-1/3-1:1.0) --action=add` replacing `--path` with the path of the USB port down to the device itself (in this case, I had a device connected to the `usb3/3-1` port, identified as `3-1:1.0`.
128 |
129 | ## Thank you!
130 |
131 | A lot of work and sleepless nights were involved in this procedure, so if this app helps you in any way or another, please consider sending a small donation, it helps a lot in these tough times!
132 |
133 | [
](https://www.paypal.com/donate?hosted_button_id=H2YLSRHBQJ94G)
134 |
135 | ## Changelog
136 |
137 | (2020-02-09)
138 |
139 | * More python mad skillz were learned, and therefore used.
140 | * It seems the USB IDs for QEMU were duplicated so when you unplugged a device, others would do too because the first plug of the new device already matched the ID of the device that was already plugged in, so when you unplugged the new device, the one in the same hub was unplugged too. I know it's confusing but so it was when debugging it. You don't have to understand it, just be happy it's now fixed, lol!
141 | * Figured out that `DEVNAME` is a valid unique ID per USB device per USB port, so I'm using that instead.
142 | * The app will now cycle through the defined USB hubs for that VM (so you can have 1 or more XHCI hubs) in the case that when plugging the device it would receive the warning "`Warning: speed mismatch trying to attach usb device "DEVICE" (high speed) to bus "xhci0.0", port "4.2" (full speed)`". In this case, it will remove it from the hub and attempt to plug it on the next one. Maybe some verification could be done here from `info usbhost` and check the device's USB speed, then checking with `info usb` the allocated ports and find out if a hub is full or has a `QEMU Root USB Hub` to decide the next hub to add the device to. It doesn't affect me much now, so I'm leaving that on the backburner for now.
143 |
144 | (2020-02-05)
145 |
146 | * Initial changelog writing
147 | * App was refactored a bit with improved python mad skillz. It also seems to be a bit more stable and robust, it doesn't hang much anymore and USB detection seems to work better. This is due to the fact that I added a stupid 1-second delay after all the USB UDEV events have gone through. Since there's no way to know when UDEV has "finished" sending all the events (and there could be a lot more) the commands being sent to QEMU to add the device will have to wait 1 second now. While it's not ideal, it should be enough to avoid a VM hanging up and I can live with that.
148 |
--------------------------------------------------------------------------------
/config.yaml:
--------------------------------------------------------------------------------
1 | virtual_machines:
2 |
3 | windows:
4 | socket: /home/user/vm/windows/qmp-sock
5 | delay: 1
6 | hubs:
7 | - xhci0.0
8 | - xhci1.0
9 | ports:
10 | - /devices/pci0000:00/0000:00:14.0/usb3/3-3
11 | - /devices/pci0000:00/0000:00:14.0/usb3/3-4
12 |
--------------------------------------------------------------------------------
/hotplugger.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | import re
3 | import os
4 | import ast
5 | import sys
6 | import yaml
7 | import json
8 | import time
9 | import pprint
10 | from pathlib import Path
11 | from qemu import *
12 |
13 | configFilename = Path(__file__).parent / "config.yaml"
14 | tmpFolderPath = Path(__file__).parent / "tmp"
15 |
16 |
17 | def printp(dict):
18 | pprint.pprint(dict, width=1)
19 |
20 |
21 | def sanitizeDevpath(devpath):
22 | return devpath.replace('/', '_').replace(':', '_')
23 |
24 |
25 | def sanitize(str):
26 | return "".join(re.findall("[a-zA-Z0-9]+", str))
27 |
28 |
29 | def loadConfig():
30 | with open(configFilename) as file:
31 | return yaml.load(file, Loader=yaml.FullLoader)
32 |
33 |
34 | def savePortDeviceMetadata(metadata, devpath):
35 | if not os.path.exists(tmpFolderPath):
36 | os.makedirs(tmpFolderPath)
37 | usbdefPath = f"{tmpFolderPath}/{sanitizeDevpath(devpath)}"
38 | print(f"Saving port metadata to {usbdefPath} ...")
39 | f = open(usbdefPath, "w")
40 | f.write(json.dumps(metadata))
41 | f.close()
42 |
43 |
44 | def loadPortDeviceMetadata(config, devpath):
45 | for rootKey, rootValue in config.items():
46 | for k, v in rootValue.items():
47 | for port in v['ports']:
48 | if devpath.find(port) >= 0:
49 | print(f"Found {devpath} in port {port}")
50 |
51 | if not os.path.exists(tmpFolderPath):
52 | os.makedirs(tmpFolderPath)
53 | metadataFiles = [f for f in os.listdir(tmpFolderPath) if os.path.isfile(os.path.join(tmpFolderPath, f))]
54 | metadataFiles.sort(key=len, reverse=True)
55 | print(f"Metadata files:")
56 | printp(metadataFiles)
57 |
58 | usbDefPathFile = sanitizeDevpath(devpath)
59 | for f in metadataFiles:
60 | metadataFilename = os.path.join(tmpFolderPath, f)
61 | if usbDefPathFile.find(f) >= 0:
62 | print(f"Found {devpath} in {metadataFilename}")
63 | with open(metadataFilename) as metadataFile:
64 | rv = json.loads(metadataFile.read())
65 | rv["SOCKET"] = rootValue[k]['socket']
66 | rv["FILENAME"] = metadataFilename
67 | rv["HUBS"] = rootValue[k]['hubs']
68 | rv["DELAY"] = rootValue[k]['delay']
69 | return rv
70 |
71 |
72 | def plug():
73 |
74 | print('==================================================================')
75 | print('PLUG')
76 | print('==================================================================')
77 | printp(dict(os.environ))
78 | print('==================================================================')
79 | config = loadConfig()
80 | devpath = os.environ['DEVPATH']
81 | is_usb_port = (os.getenv('DEVNUM') or '') != '' and (os.getenv('BUSNUM') or '') != ''
82 | print(f"Is USB Port? {is_usb_port}")
83 |
84 | if is_usb_port == True:
85 | savePortDeviceMetadata(json.loads(json.dumps(dict(os.environ))), devpath)
86 | else:
87 | metadata = loadPortDeviceMetadata(config, devpath)
88 | if not metadata:
89 | print(f"Metadata file for {devpath} not found")
90 | else:
91 | print(metadata)
92 |
93 | print(f"Connecting to QEMU at {metadata['SOCKET']}...")
94 | with QEMU(metadata["SOCKET"]) as qemu:
95 | usbhost = qemu.hmp("info usbhost")
96 | print(usbhost)
97 |
98 | hostport = 0
99 | hostaddr = metadata['DEVNUM'].lstrip('0')
100 | hostbus = metadata['BUSNUM'].lstrip('0')
101 | print(f"Looking for USB Bus: {hostbus}, Addr {hostaddr} ...")
102 |
103 | for line in usbhost.splitlines():
104 | if line.find(f"Bus {hostbus}") >= 0:
105 | if line.find(f"Addr {hostaddr}") >= 0:
106 | print('FOUND IN', line)
107 | hostport_search = re.search(".*Port.*?([\d\.]*),", line, re.IGNORECASE)
108 | hostport = hostport_search.group(1)
109 | break
110 | print(f"Found USB Bus: {hostbus}, Addr {hostaddr}, Port {hostport}")
111 |
112 | if hostport != 0:
113 | print(f"Plugging USB device in port {hostport}...")
114 |
115 | with QEMU(metadata["SOCKET"]) as qemu:
116 |
117 | device_id = sanitize(metadata['DEVNAME'])
118 | print(f"Device ID = {device_id}")
119 | for guesthub in metadata["HUBS"]:
120 | time.sleep(int(metadata["DELAY"]))
121 | result = qemu.hmp(f"device_add driver=usb-host,bus={guesthub},hostbus={hostbus},hostport={hostport},id={device_id}")
122 | if result.find("speed mismatch trying to attach usb device") >= 0:
123 | qemu.hmp(f"device_del {device_id}")
124 | else:
125 | print(f"Device plugged in on hub {guesthub}. Current USB devices on guest:")
126 | print(qemu.hmp("info usb"))
127 | break
128 |
129 | if Path(metadata["FILENAME"]).exists():
130 | os.remove(metadata["FILENAME"])
131 |
132 |
133 | def unplug():
134 |
135 | print('==================================================================')
136 | print('UNPLUG')
137 | print('==================================================================')
138 | printp(dict(os.environ))
139 | print('==================================================================')
140 | config = loadConfig()
141 | devpath = os.environ['DEVPATH']
142 | if (os.getenv('DEVNAME') or '') != '':
143 | for rootKey, rootValue in config.items():
144 | for k, v in rootValue.items():
145 | socket = rootValue[k]['socket']
146 | socketFile = Path(socket)
147 | if socketFile.exists():
148 | print(f"Connecting to QEMU at {socket}...")
149 | with QEMU(socket) as qemu:
150 | usbhost = qemu.hmp("info usbhost")
151 | print(usbhost)
152 |
153 | with QEMU(socket) as qemu:
154 | device_id = sanitize(os.environ["DEVNAME"])
155 | qemu.hmp(f"device_del {device_id}")
156 | print(f"Device unplugged from {k}")
157 | print(qemu.hmp("info usb"))
158 | usbDefPathFile = os.path.join(tmpFolderPath, sanitizeDevpath(devpath))
159 | if Path(usbDefPathFile).exists():
160 | os.remove(usbDefPathFile)
161 |
162 |
163 | action = os.environ['ACTION']
164 | if action == 'add':
165 | plug()
166 | elif action == 'remove':
167 | unplug()
168 | else:
169 | print("")
170 | print("Device plug/unplug helper script")
171 | print("")
172 | print("This should be run by an udev rules file you create that will trigger on every")
173 | print("USB command. For more info have a look at the README file.")
174 |
--------------------------------------------------------------------------------
/monitor.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | import sys
3 | import signal
4 | import subprocess
5 |
6 | print("")
7 | print("Using both an USB 3.0 and an USB 2.0 device (could be a thumb drive,")
8 | print("an audio device or any other simple USB device), plug or unplug the")
9 | print("device in the ports that you are interested for VM passthrough.")
10 | print("")
11 | print("Press Control + C when finished. The app will then print the device")
12 | print("path of the USB ports. Also make sure that 'udevadm' is installed.")
13 | print("")
14 | print("Monitoring USB ports...")
15 |
16 | ###########################
17 | # This gets the UDEV events
18 | ###########################
19 |
20 | listout = []
21 |
22 |
23 | def handle(sig, _):
24 | if sig == signal.SIGINT:
25 | print("")
26 |
27 |
28 | signal.signal(signal.SIGINT, handle)
29 | proc = subprocess.Popen(
30 | ["udevadm", "monitor", "-k", "-u", "-p", "-s", "usb"], stdout=subprocess.PIPE)
31 |
32 | while True:
33 | line = proc.stdout.readline()
34 | if not line:
35 | break
36 | if line.startswith(b'DEVPATH'):
37 | listout.append(line)
38 |
39 | proc.wait()
40 |
41 | ######################################
42 | # This gets an unique list of DEVPATHs
43 | ######################################
44 |
45 |
46 |
47 | # function to get unique values
48 |
49 | def unique(input_list):
50 |
51 | # leave only unique entries
52 | return list(dict.fromkeys(input_list))
53 |
54 |
55 |
56 | # function to remove the netries that are not useful for udev
57 |
58 | def remove_unnecessary(input_list):
59 |
60 | # copy to avoid modifying the input list
61 | output_list = list(input_list)
62 |
63 | # traverse for all elements
64 | for element in output_list:
65 | # remove long entries as they are not useful for udev
66 | for potential_prefix in output_list:
67 | if element != potential_prefix and element.startswith(potential_prefix):
68 | output_list.remove(element)
69 |
70 | return output_list
71 |
72 |
73 | if __name__ == '__main__':
74 | listout = [x.decode('utf-8').strip() for x in listout]
75 | uniq = unique(listout)
76 | filtered = remove_unnecessary(uniq)
77 |
78 | print("\nFound these USB ports:")
79 | print(*filtered, sep='\n')
80 | print("")
81 |
82 | orig_stdout = sys.stdout
83 | with open("usb.portlist", "w+") as f:
84 | sys.stdout = f
85 | print(*filtered, sep='\n')
86 | sys.stdout = orig_stdout
87 |
88 | print("Results were saved to 'usb.portlist'.")
89 |
--------------------------------------------------------------------------------
/qemu.py:
--------------------------------------------------------------------------------
1 | import json
2 | import fcntl
3 | import socket
4 | from pathlib import Path
5 |
6 | class QEMU:
7 |
8 | client = None
9 | socket = None
10 |
11 |
12 | def __init__(self, unixSocket):
13 | self.socket = unixSocket
14 |
15 |
16 | def __enter__(self):
17 | self.client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
18 | self.client.settimeout(1)
19 | self.client.setblocking(1)
20 | self.client.connect(self.socket)
21 | self.read(self.client)
22 | self.qmp({ "execute": "qmp_capabilities" })
23 | return self
24 |
25 |
26 | def __exit__(self, _type, value, tb):
27 | self.client.close()
28 |
29 |
30 | def read(self, socket):
31 | f = ''
32 | obj = None
33 | while True:
34 | f += self.client.recv(1).decode()
35 | try:
36 | if len(f.strip()) > 0:
37 | obj = json.loads(f.strip())
38 | print('RECV <-', obj)
39 | break
40 | except:
41 | pass
42 | return obj
43 |
44 |
45 | def qmp(self, command):
46 | message = f"{json.dumps(command)}\n"
47 | print(f"SEND -> {message.strip()}")
48 | self.client.send(str.encode(message))
49 | return self.read(self.client)
50 |
51 |
52 | def hmp(self, command):
53 | result = self.qmp({ "execute": "human-monitor-command", "arguments": { "command-line": f"{command}" } })
54 | return result['return'] if 'return' in result else result
55 |
56 |
--------------------------------------------------------------------------------