Repository: lcgamboa/USBIP-Virtual-USB-Device Branch: master Commit: 311603da9dbb Files: 14 Total size: 124.1 KB Directory structure: gitextract_pucyyekq/ ├── README.md ├── c/ │ ├── LICENSE │ ├── Makefile │ ├── Makefile.cross │ ├── cdc-acm.c │ ├── hid-keyboard.c │ ├── hid-mouse.c │ ├── usbip.c │ └── usbip.h ├── doc/ │ └── usbip_protocol.txt └── python/ ├── LICENSE ├── USBIP.py ├── hid-keyboard.py └── hid-mouse.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: README.md ================================================ USBIP hardware emulation (Virtual USB device) ============= Hack fixes for mouse hid work with Linux 4.2 (and Windows 10) keyboard hid added. in Linux use:
python hid-xxxx.py for python version
or
./hid-xxxx for c version
and
usbip attach -r 127.0.0.1 -b 1-1
(remember to load kernel modules usbip-core and vhci-hcd)
for list device use:
usbip list -r 127.0.0.1 More details on:
http://breaking-the-system.blogspot.com/2014/08/emulating-usb-devices-in-python-with-no.html
This code uses the USB/IP project: http://usbip.sourceforge.net/ to emulate usb devices.
In this example I showed how to emulate HID mouse device.
This code can be easily changed to support any usb device.
This code is very experimental, use with care.
In the HID example there is a bug with USB/IP driver that causes blue screen on de-attach:
http://sourceforge.net/p/usbip/discussion/418507/thread/7ff86875/?page=0
It doesnt happen with other devices I tested.
================================================ FILE: c/LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. ================================================ FILE: c/Makefile ================================================ CC=gcc CFLAGS= -Wall -DLINUX PROGS= hid-mouse hid-keyboard cdc-acm all: ${PROGS} hid-mouse: usbip.c hid-mouse.c ${CC} ${CFLAGS} usbip.c -c ${CC} ${CFLAGS} usbip.o hid-mouse.c -o hid-mouse hid-keyboard: usbip.c hid-keyboard.c ${CC} ${CFLAGS} usbip.c -c ${CC} ${CFLAGS} usbip.o hid-keyboard.c -o hid-keyboard cdc-acm: usbip.c cdc-acm.c ${CC} ${CFLAGS} usbip.c -c ${CC} ${CFLAGS} usbip.o cdc-acm.c -o cdc-acm clean: rm -f ${PROGS} core core.* *.o temp.* *.out typescript* ================================================ FILE: c/Makefile.cross ================================================ CC=i686-w64-mingw32-gcc CFLAGS= -Wall -mno-ms-bitfields PROGS= hid-mouse hid-keyboard cdc-acm all: ${PROGS} hid-mouse: usbip.c hid-mouse.c ${CC} ${CFLAGS} usbip.c -c ${CC} ${CFLAGS} usbip.o hid-mouse.c -o hid-mouse.exe -lws2_32 hid-keyboard: usbip.c hid-keyboard.c ${CC} ${CFLAGS} usbip.c -c ${CC} ${CFLAGS} usbip.o hid-keyboard.c -o hid-keyboard.exe -lws2_32 cdc-acm: usbip.c cdc-acm.c ${CC} ${CFLAGS} usbip.c -c ${CC} ${CFLAGS} usbip.o cdc-acm.c -o cdc-acm.exe -lws2_32 clean: rm -f ${PROGS} core core.* *.o temp.* *.out typescript* *.exe ================================================ FILE: c/cdc-acm.c ================================================ /* ######################################################################## USBIP hardware emulation ######################################################################## Copyright (c) : 2016 Luis Claudio Gambôa Lopes This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. For e-mail suggestions : lcgamboa@yahoo.com ######################################################################## */ #include #include #include #include #include "usbip.h" /* Device Descriptor */ const USB_DEVICE_DESCRIPTOR dev_dsc= { 0x12, // Size of this descriptor in bytes 0x01, // DEVICE descriptor type 0x0200, // USB Spec Release Number in BCD format 0x02, // Class Code 0x00, // Subclass code 0x00, // Protocol code 0x10, // Max packet size for EP0, see usb_config.h 0x2706, // Vendor ID 0x000A, // Product ID 0x0100, // Device release number in BCD format 0x01, // Manufacturer string index 0x03, // Product string index 0x00, // Device serial number string index 0x01 // Number of possible configurations }; const USB_DEVICE_QUALIFIER_DESCRIPTOR dev_qua = { 0x0A, // bLength 0x06, // bDescriptorType 0x0200, // bcdUSB 0x02, // bDeviceClass 0x00, // bDeviceSubClass 0x00, // bDeviceProtocol 0x10, // bMaxPacketSize 0x01, // iSerialNumber 0x00 //bNumConfigurations*/ }; /* Configuration 1 Descriptor */ const CONFIG_CDC configuration_cdc={{ /* Configuration Descriptor */ 0x09,//sizeof(USB_CFG_DSC), // Size of this descriptor in bytes USB_DESCRIPTOR_CONFIGURATION, // CONFIGURATION descriptor type sizeof(CONFIG_CDC), // Total length of data for this cfg 2, // Number of interfaces in this cfg 1, // Index value of this configuration 0, // Configuration string index 0xC0, 50, // Max power consumption (2X mA) },{ /* Interface Descriptor */ 0x09,//sizeof(USB_INTF_DSC), // Size of this descriptor in bytes USB_DESCRIPTOR_INTERFACE, // INTERFACE descriptor type 0, // Interface Number 0, // Alternate Setting Number 1, // Number of endpoints in this intf 0x02, // Class code 0x02, // Subclass code 0x01, // Protocol code 0 // Interface string index },{ /* CDC Class-Specific Descriptors */ /* Header Functional Descriptor */ 0x05, // bFNLength 0x24, // bDscType 0x00, // bDscSubType 0x0110 // bcdCDC },{ /* Call Management Functional Descriptor */ 0x05, // bFNLength 0x24, // bDscType 0x01, // bDscSubType 0x01, // bmCapabilities 0x01 // bDataInterface },{ /* Abstract Control Management Functional Descriptor */ 0x04, // bFNLength 0x24, // bDscType 0x02, // bDscSubType 0x02 // bmCapabilities },{ /* Union Functional Descriptor */ 0x05, // bFNLength 0x24, // bDscType 0x06, // bDscSubType 0x00, // bMasterIntf 0x01 // bSaveIntf0 },{ /* Endpoint Descriptor */ 0x07,/*sizeof(USB_EP_DSC)*/ USB_DESCRIPTOR_ENDPOINT, //Endpoint Descriptor 0x81, //EndpointAddress 0x03, //Attributes 0x0008, //size 0x0A //Interval },{ /* Interface Descriptor */ 0x09,//sizeof(USB_INTF_DSC), // Size of this descriptor in bytes USB_DESCRIPTOR_INTERFACE, // INTERFACE descriptor type 1, // Interface Number 0, // Alternate Setting Number 2, // Number of endpoints in this intf 0x0A, // Class code 0x00, // Subclass code 0x00, // Protocol code 2, // Interface string index },{ /* Endpoint Descriptor */ 0x07,/*sizeof(USB_EP_DSC)*/ USB_DESCRIPTOR_ENDPOINT, //Endpoint Descriptor 0x02, //EndpointAddress 0x02, //Attributes 0x0020, //size 0x00 //Interval },{ /* Endpoint Descriptor */ 0x07,/*sizeof(USB_EP_DSC)*/ USB_DESCRIPTOR_ENDPOINT, //Endpoint Descriptor 0x82, //EndpointAddress 0x02, //Attributes 0x0020, //size 0x00 //Interval }}; const unsigned char string_0[] = { // available languages descriptor 0x04, USB_DESCRIPTOR_STRING, 0x09, 0x04 }; const unsigned char string_1[] = { // 0x0A, USB_DESCRIPTOR_STRING, // bLength, bDscType 'T', 0x00, // 'e', 0x00, // 's', 0x00, // 't', 0x00, // }; const unsigned char string_2[] = { // 0x10, USB_DESCRIPTOR_STRING, // 'U', 0x00, // 'S', 0x00, // 'B', 0x00, // ' ', 0x00, // 'C', 0x00, // 'D', 0x00, // 'C', 0x00, // }; const unsigned char string_3[] = { // 0x18, USB_DESCRIPTOR_STRING, // 'V', 0x00, // 'i', 0x00, // 'r', 0x00, // 't', 0x00, // 'u', 0x00, // 'a', 0x00, // 'l', 0x00, // ' ', 0x00, // 'U', 0x00, // 'S', 0x00, // 'B', 0x00, // }; const char *configuration = (const char *)&configuration_cdc; const USB_INTERFACE_DESCRIPTOR *interfaces[]={ &configuration_cdc.dev_int0, &configuration_cdc.dev_int1}; const unsigned char *strings[]={string_0, string_1, string_2, string_3}; #define BSIZE 64 char buffer[BSIZE+1]; int bsize=0; void handle_data(int sockfd, USBIP_RET_SUBMIT *usb_req, int bl) { if(usb_req->ep == 0x01) { printf("EP1 received \n"); if(usb_req->direction == 0) //input { printf("direction=input\n"); bsize=recv (sockfd, (char *) buffer , bl, 0); send_usb_req(sockfd, usb_req,"", 0, 0); buffer[bsize+1]=0; //string terminator printf("received (%s)\n",buffer); } else { printf("direction=output\n"); } //not supported send_usb_req(sockfd, usb_req, "", 0, 0); usleep(500); } if((usb_req->ep == 0x02)) { printf("EP2 received \n"); if(usb_req->direction == 0) //input { int i; printf("direction=input\n"); bsize=recv (sockfd, (char *) buffer , bl, 0); send_usb_req(sockfd, usb_req,"", 0, 0); buffer[bsize+1]=0; //string terminator printf("received (%s)\n",buffer); for(i=0;ibmRequestType == 0x21)//Abstract Control Model Requests { if(control_req->bRequest == 0x20) //SET_LINE_CODING { printf("SET_LINE_CODING\n"); if ((recv (sockfd, (char *) &linec , control_req->wLength, 0)) != control_req->wLength) { printf ("receive error : %s \n", strerror (errno)); exit(-1); }; send_usb_req(sockfd,usb_req,"",0,0); } if(control_req->bRequest == 0x21) //GET_LINE_CODING { printf("GET_LINE_CODING\n"); send_usb_req(sockfd,usb_req,(char *)&linec,7,0); } if(control_req->bRequest == 0x22) //SET_LINE_CONTROL_STATE { linecs=control_req->wValue0; printf("SET_LINE_CONTROL_STATE 0x%02X\n", linecs); send_usb_req(sockfd,usb_req,"",0,0); } if(control_req->bRequest == 0x23) //SEND_BREAK { printf("SEND_BREAK\n"); send_usb_req(sockfd,usb_req,"",0,0); } } }; int main() { printf("cdc started....\n"); usbip_run(&dev_dsc); } ================================================ FILE: c/hid-keyboard.c ================================================ /* ######################################################################## USBIP hardware emulation ######################################################################## Copyright (c) : 2016 Luis Claudio Gambôa Lopes This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. For e-mail suggestions : lcgamboa@yahoo.com ######################################################################## */ #include #include #include #include #include "usbip.h" /* Device Descriptor */ const USB_DEVICE_DESCRIPTOR dev_dsc= { 0x12, // Size of this descriptor in bytes 0x01, // DEVICE descriptor type 0x0110, // USB Spec Release Number in BCD format 0x00, // Class Code 0x00, // Subclass code 0x00, // Protocol code 0x08, // Max packet size for EP0, see usb_config.h 0x2706, // Vendor ID 0x0100, // Product ID: Mouse in a circle fw demo 0x0000, // Device release number in BCD format 0x00, // Manufacturer string index 0x00, // Product string index 0x00, // Device serial number string index 0x01 // Number of possible configurations }; /* Configuration 1 Descriptor */ const CONFIG_HID configuration_hid={{ /* Configuration Descriptor */ 0x09,//sizeof(USB_CFG_DSC), // Size of this descriptor in bytes USB_DESCRIPTOR_CONFIGURATION, // CONFIGURATION descriptor type 0x0022, // Total length of data for this cfg 1, // Number of interfaces in this cfg 1, // Index value of this configuration 0, // Configuration string index 0x80, 50, // Max power consumption (2X mA) },{ /* Interface Descriptor */ 0x09,//sizeof(USB_INTF_DSC), // Size of this descriptor in bytes USB_DESCRIPTOR_INTERFACE, // INTERFACE descriptor type 0, // Interface Number 0, // Alternate Setting Number 1, // Number of endpoints in this intf 0x03, // Class code 0x01, // Subclass code 0x01, // Protocol code 0, // Interface string index },{ /* HID Class-Specific Descriptor */ 0x09, // Size of this descriptor in bytes RRoj hack 0x21, // HID descriptor type 0x0001, // HID Spec Release Number in BCD format (1.11) 0x00, // Country Code (0x00 for Not supported) 0x01, // Number of class descriptors, see usbcfg.h 0x22, // Report descriptor type 0x003F, // Size of the report descriptor },{ /* Endpoint Descriptor */ 0x07,/*sizeof(USB_EP_DSC)*/ USB_DESCRIPTOR_ENDPOINT, //Endpoint Descriptor 0x81, //EndpointAddress 0x03, //Attributes 0x0008, //size 0xFF //Interval }}; const char *configuration = (const char *)&configuration_hid; const USB_INTERFACE_DESCRIPTOR *interfaces[]={ &configuration_hid.dev_int }; const unsigned char *strings[]={}; const USB_DEVICE_QUALIFIER_DESCRIPTOR dev_qua={}; //Class specific descriptor - HID keyboard const byte keyboard_report[0x3F]={ 0x05, 0x01, 0x09, 0x06, //Usage Page (Generic Desktop), 0xA1, 0x01, //Usage (Keyboard), 0x05, 0x07, //Collection (Application), 0x19, 0xE0, //Usage Page (Key Codes); 0x29, 0xE7, //Usage Minimum (224), 0x15, 0x00, //Usage Maximum (231), 0x25, 0x01, //Logical Minimum (0), 0x75, 0x01, //Logical Maximum (1), 0x95, 0x08, //Report Size (1), 0x81, 0x02, //Report Count (8), 0x95, 0x01, //Input (Data, Variable, Absolute), 0x75, 0x08, //Report Count (1), 0x81, 0x01, //Report Size (8), 0x95, 0x05, //Input (Constant), 0x75, 0x01, //Report Count (5), 0x05, 0x08, //Report Size (1), 0x19, 0x01, //Usage Page (Page# for LEDs), 0x29, 0x05, //Usage Minimum (1), 0x91, 0x02, //Usage Maximum (5), 0x95, 0x01, //Output (Data, Variable, Absolute), 0x75, 0x03, //Report Count (1), 0x91, 0x01, //Report Size (3), 0x95, 0x06, //Output (Constant), 0x75, 0x08, //Report Count (6), 0x15, 0x00, //Report Size (8), 0x25, 0x65, //Logical Minimum (0), 0x05, 0x07, //Logical Maximum(101), 0x19, 0x00, //Usage Page (Key Codes), 0x29, 0x65, //Usage Minimum (0), 0x81, 0x00, //Usage Maximum (101), #Input (Data, Array), 0xC0}; //End Collection void handle_data(int sockfd, USBIP_RET_SUBMIT *usb_req, int bl) { // Sending random keyboard data // Send data only for 5 seconds static int count=0; char return_val[8]; printf("data\n"); memset(return_val,0,8); if (count < 20) { if((count % 2 ) == 0) return_val[2]=(char)((((25l*rand())/RAND_MAX))+4); send_usb_req(sockfd, usb_req, return_val, 8, 0); } usleep(250000); count=count+1; }; void handle_unknown_control(int sockfd, StandardDeviceRequest * control_req, USBIP_RET_SUBMIT *usb_req) { if(control_req->bmRequestType == 0x81) { if(control_req->bRequest == 0x6) //# Get Descriptor { if(control_req->wValue1 == 0x22) // send initial report { printf("send initial report\n"); send_usb_req(sockfd,usb_req,(char *) keyboard_report, 0x3F, 0); } } } if(control_req->bmRequestType == 0x21) // Host Request { if(control_req->bRequest == 0x0a) // set idle { printf("Idle\n"); // Idle send_usb_req(sockfd,usb_req,"",0,0); } if(control_req->bRequest == 0x09) // set report { printf("set report\n"); char data[20]; if ((recv (sockfd, data , control_req->wLength, 0)) != control_req->wLength) { printf ("receive error : %s \n", strerror (errno)); exit(-1); }; send_usb_req(sockfd,usb_req,"",0,0); } } }; int main() { printf("hid keyboard started....\n"); usbip_run(&dev_dsc); } ================================================ FILE: c/hid-mouse.c ================================================ /* ######################################################################## USBIP hardware emulation ######################################################################## Copyright (c) : 2016 Luis Claudio Gambôa Lopes This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. For e-mail suggestions : lcgamboa@yahoo.com ######################################################################## */ #include #include #include #include "usbip.h" /* Device Descriptor */ const USB_DEVICE_DESCRIPTOR dev_dsc= { 0x12, // Size of this descriptor in bytes 0x01, // DEVICE descriptor type 0x0110, // USB Spec Release Number in BCD format 0x00, // Class Code 0x00, // Subclass code 0x00, // Protocol code 0x08, // Max packet size for EP0, see usb_config.h 0x2706, // Vendor ID 0x0000, // Product ID: Mouse in a circle fw demo 0x0000, // Device release number in BCD format 0x00, // Manufacturer string index 0x00, // Product string index 0x00, // Device serial number string index 0x01 // Number of possible configurations }; /* Configuration 1 Descriptor */ const CONFIG_HID configuration_hid={ { /* Configuration Descriptor */ 0x09,//sizeof(USB_CFG_DSC), // Size of this descriptor in bytes USB_DESCRIPTOR_CONFIGURATION, // CONFIGURATION descriptor type 0x0022, // Total length of data for this cfg 1, // Number of interfaces in this cfg 1, // Index value of this configuration 0, // Configuration string index 0x80, //Configuration characteristics 50 // Max power consumption (2X mA) },{ /* Interface Descriptor */ 0x09,//sizeof(USB_INTF_DSC), // Size of this descriptor in bytes USB_DESCRIPTOR_INTERFACE, // INTERFACE descriptor type 0, // Interface Number 0, // Alternate Setting Number 1, // Number of endpoints in this intf 0x03, // Class code 0x01, // Subclass code 0x02, // Protocol code 0x00 // Interface string index },{ /* HID Class-Specific Descriptor */ 0x09, // Size of this descriptor in bytes RRoj hack 0x21, // HID descriptor type 0x0001, // HID Spec Release Number in BCD format (1.11) 0x00, // Country Code (0x00 for Not supported) 0x01, // Number of class descriptors, see usbcfg.h 0x22, // Report descriptor type 0x0034 // Size of the report descriptor },{ /* Endpoint Descriptor */ 0x07,/*sizeof(USB_EP_DSC)*/ USB_DESCRIPTOR_ENDPOINT, //Endpoint Descriptor 0x81, //EndpointAddress 0x03, //Attributes 0x0008, //size 0xFF //Interval }}; const char *configuration = (const char *) &configuration_hid; const USB_INTERFACE_DESCRIPTOR *interfaces[]={ &configuration_hid.dev_int }; const unsigned char *strings[]={}; const USB_DEVICE_QUALIFIER_DESCRIPTOR dev_qua={}; //Class specific descriptor - HID mouse const byte mouse_report[0x34]={ 0x05, 0x01, /* Usage Page (Generic Desktop) */ 0x09, 0x02, /* Usage (Mouse) */ 0xA1, 0x01, /* Collection (Application) */ 0x09, 0x01, /* Usage (Pointer) */ 0xA1, 0x00, /* Collection (Physical) */ 0x05, 0x09, /* Usage Page (Buttons) */ 0x19, 0x01, /* Usage Minimum (01) */ 0x29, 0x03, /* Usage Maximum (03) */ 0x15, 0x00, /* Logical Minimum (0) */ 0x25, 0x01, /* Logical Maximum (1) */ 0x95, 0x03, /* Report Count (3) */ 0x75, 0x01, /* Report Size (1) */ 0x81, 0x02, /* Input (Data, Variable, Absolute) */ 0x95, 0x01, /* Report Count (1) */ 0x75, 0x05, /* Report Size (5) */ 0x81, 0x01, /* Input (Constant) ;5 bit padding */ 0x05, 0x01, /* Usage Page (Generic Desktop) */ 0x09, 0x30, /* Usage (X) */ 0x09, 0x31, /* Usage (Y) */ 0x09, 0x38, /* Logical Minimum (-127) */ 0x15, 0x81, /* Logical Maximum (127) */ 0x25, 0x7F, /* Report Size (8) */ 0x75, 0x08, /* Report Count (3) */ 0x95, 0x03, /* Input (Data, Variable, Relative) */ 0x81, 0x06, 0xC0, 0xC0}; void handle_data(int sockfd, USBIP_RET_SUBMIT *usb_req, int bl) { // Sending random mouse data // Send data only for 5 seconds static int count=0; char return_val[4]; printf("data\n"); if (count < 20) { return_val[0]= 0; return_val[1]=(char)((((10l*rand())/RAND_MAX))-5); return_val[2]=(char)((((10l*rand())/RAND_MAX))-5); return_val[3]= 0; send_usb_req(sockfd, usb_req, return_val, 4, 0); usleep(250000); } count=count+1; }; void handle_unknown_control(int sockfd, StandardDeviceRequest * control_req, USBIP_RET_SUBMIT *usb_req) { if(control_req->bmRequestType == 0x81) { if(control_req->bRequest == 0x6) //# Get Descriptor { if(control_req->wValue1 == 0x22) // send initial report { printf("send initial report\n"); send_usb_req(sockfd,usb_req,(char *) mouse_report, 0x34, 0); } } } if(control_req->bmRequestType == 0x21) // Host Request { if(control_req->bRequest == 0x0a) // set idle { printf("Idle\n"); // Idle send_usb_req(sockfd,usb_req,"",0,0); } } }; int main() { printf("hid mouse started....\n"); usbip_run(&dev_dsc); } ================================================ FILE: c/usbip.c ================================================ /* ######################################################################## USBIP hardware emulation ######################################################################## Copyright (c) : 2016 Luis Claudio Gambôa Lopes This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. For e-mail suggestions : lcgamboa@yahoo.com ######################################################################## */ //system headers dependent #include"usbip.h" #ifdef _DEBUG void print_recv(char* buff,int size,const char* desc) { int i,j; printf("----------recv %s (%i)-----------\n",desc,size); j=1; for(i=0; i< size; i++) { printf("0x%02X ",(unsigned char)buff[i]); if(j > 7) { printf("\n"); j=0; }; j++; } printf("\n-------------------------\n"); } #endif #ifndef LINUX WORD wVersionRequested = 2; WSADATA wsaData; #endif void handle_device_list(const USB_DEVICE_DESCRIPTOR *dev_dsc, OP_REP_DEVLIST *list) { CONFIG_GEN * conf= (CONFIG_GEN *)configuration; int i; list->header.version=htons(273); list->header.command=htons(5); list->header.status=0; list->header.nExportedDevice=htonl(1); memset(list->device.usbPath,0,256); strcpy(list->device.usbPath,"/sys/devices/pci0000:00/0000:00:01.2/usb1/1-1"); memset(list->device.busID,0,32); strcpy(list->device.busID,"1-1"); list->device.busnum=htonl(1); list->device.devnum=htonl(2); list->device.speed=htonl(2); list->device.idVendor=htons(dev_dsc->idVendor); list->device.idProduct=htons(dev_dsc->idProduct); list->device.bcdDevice=htons(dev_dsc->bcdDevice); list->device.bDeviceClass=dev_dsc->bDeviceClass; list->device.bDeviceSubClass=dev_dsc->bDeviceSubClass; list->device.bDeviceProtocol=dev_dsc->bDeviceProtocol; list->device.bConfigurationValue=conf->dev_conf.bConfigurationValue; list->device.bNumConfigurations=dev_dsc->bNumConfigurations; list->device.bNumInterfaces=conf->dev_conf.bNumInterfaces; list->interfaces=malloc(list->device.bNumInterfaces*sizeof(OP_REP_DEVLIST_INTERFACE)); for(i=0;idevice.bNumInterfaces;i++) { list->interfaces[i].bInterfaceClass=interfaces[i]->bInterfaceClass; list->interfaces[i].bInterfaceSubClass=interfaces[i]->bInterfaceSubClass; list->interfaces[i].bInterfaceProtocol=interfaces[i]->bInterfaceProtocol; list->interfaces[i].padding=0; } }; void handle_attach(const USB_DEVICE_DESCRIPTOR *dev_dsc, OP_REP_IMPORT *rep) { CONFIG_GEN * conf= (CONFIG_GEN *)configuration; rep->version=htons(273); rep->command=htons(3); rep->status=0; memset(rep->usbPath,0,256); strcpy(rep->usbPath,"/sys/devices/pci0000:00/0000:00:01.2/usb1/1-1"); memset(rep->busID,0,32); strcpy(rep->busID,"1-1"); rep->busnum=htonl(1); rep->devnum=htonl(2); rep->speed=htonl(2); rep->idVendor=dev_dsc->idVendor; rep->idProduct=dev_dsc->idProduct; rep->bcdDevice=dev_dsc->bcdDevice; rep->bDeviceClass=dev_dsc->bDeviceClass; rep->bDeviceSubClass=dev_dsc->bDeviceSubClass; rep->bDeviceProtocol=dev_dsc->bDeviceProtocol; rep->bNumConfigurations=dev_dsc->bNumConfigurations; rep->bConfigurationValue=conf->dev_conf.bConfigurationValue; rep->bNumInterfaces=conf->dev_conf.bNumInterfaces; } void pack(int * data, int size) { int i; size=size/4; for(i=0;icommand=0x3; usb_req->status=status; usb_req->actual_length=size; usb_req->start_frame=0x0; usb_req->number_of_packets=0x0; usb_req->setup=0x0; usb_req->devid=0x0; usb_req->direction=0x0; usb_req->ep=0x0; pack((int *)usb_req, sizeof(USBIP_RET_SUBMIT)); if (send (sockfd, (char *)usb_req, sizeof(USBIP_RET_SUBMIT), 0) != sizeof(USBIP_RET_SUBMIT)) { printf ("send error : %s \n", strerror (errno)); exit(-1); }; if(size > 0) { if (send (sockfd, data, size, 0) != size) { printf ("send error : %s \n", strerror (errno)); exit(-1); }; } } int handle_get_descriptor(int sockfd, StandardDeviceRequest * control_req, USBIP_RET_SUBMIT *usb_req) { int handled = 0; printf("handle_get_descriptor %u [%u]\n",control_req->wValue1,control_req->wValue0 ); if(control_req->wValue1 == 0x1) // Device { printf("Device\n"); handled = 1; send_usb_req(sockfd,usb_req, (char *)&dev_dsc, sizeof(USB_DEVICE_DESCRIPTOR)/*control_req->wLength*/, 0); } if(control_req->wValue1 == 0x2) // configuration { printf("Configuration\n"); handled = 1; send_usb_req(sockfd,usb_req, (char *) configuration, control_req->wLength ,0); } if(control_req->wValue1 == 0x3) // string { char str[255]; int i; memset(str,0,255); for(i=0;i< (*strings[control_req->wValue0]/2) -1;i++) str[i]=strings[control_req->wValue0][i*2+2]; printf("String (%s)\n",str); handled = 1; send_usb_req(sockfd,usb_req, (char *) strings[control_req->wValue0] ,*strings[control_req->wValue0] ,0); } if(control_req->wValue1 == 0x6) // qualifier { printf("Qualifier\n"); handled = 1; send_usb_req(sockfd,usb_req, (char *) &dev_qua , control_req->wLength ,0); } if(control_req->wValue1 == 0xA) // config status ??? { printf("Unknow\n"); handled = 1; send_usb_req(sockfd,usb_req,"",0,1); } return handled; } int handle_set_configuration(int sockfd, StandardDeviceRequest * control_req, USBIP_RET_SUBMIT *usb_req) { int handled = 0; printf("handle_set_configuration %u[%u]\n",control_req->wValue1,control_req->wValue0 ); handled = 1; send_usb_req(sockfd, usb_req, "", 0, 0); return handled; } //http://www.usbmadesimple.co.uk/ums_4.htm void handle_usb_control(int sockfd, USBIP_RET_SUBMIT *usb_req) { int handled = 0; StandardDeviceRequest control_req; #ifdef LINUX printf("%016llX\n",usb_req->setup); #else printf("%016I64X\n",usb_req->setup); #endif control_req.bmRequestType= (usb_req->setup & 0xFF00000000000000)>>56; control_req.bRequest= (usb_req->setup & 0x00FF000000000000)>>48; control_req.wValue0= (usb_req->setup & 0x0000FF0000000000)>>40; control_req.wValue1= (usb_req->setup & 0x000000FF00000000)>>32; control_req.wIndex0= (usb_req->setup & 0x00000000FF000000)>>24; control_req.wIndex1= (usb_req->setup & 0x0000000000FF0000)>>16; control_req.wLength= ntohs(usb_req->setup & 0x000000000000FFFF); printf(" UC Request Type %u\n",control_req.bmRequestType); printf(" UC Request %u\n",control_req.bRequest); printf(" UC Value %u[%u]\n",control_req.wValue1,control_req.wValue0); printf(" UCIndex %u-%u\n",control_req.wIndex1,control_req.wIndex0); printf(" UC Length %u\n",control_req.wLength); if(control_req.bmRequestType == 0x80) // Host Request { if(control_req.bRequest == 0x06) // Get Descriptor { handled = handle_get_descriptor(sockfd, &control_req, usb_req); } if(control_req.bRequest == 0x00) // Get STATUS { char data[2]; data[0]=0x01; data[1]=0x00; send_usb_req(sockfd,usb_req, data, 2 , 0); handled = 1; printf("GET_STATUS\n"); } } if(control_req.bmRequestType == 0x00) // { if(control_req.bRequest == 0x09) // Set Configuration { handled = handle_set_configuration(sockfd, &control_req, usb_req); } } if(control_req.bmRequestType == 0x01) { if(control_req.bRequest == 0x0B) //SET_INTERFACE { printf("SET_INTERFACE\n"); send_usb_req(sockfd,usb_req,"",0,1); handled=1; } } if(! handled) handle_unknown_control(sockfd, &control_req, usb_req); } void handle_usb_request(int sockfd, USBIP_RET_SUBMIT *ret, int bl) { if(ret->ep == 0) { printf("#control requests\n"); handle_usb_control(sockfd, ret); } else { printf("#data requests\n"); handle_data(sockfd, ret, bl); } }; void usbip_run (const USB_DEVICE_DESCRIPTOR *dev_dsc) /* simple TCP server */ { struct sockaddr_in serv, cli; int listenfd, sockfd, nb; #ifdef LINUX unsigned int clilen; #else int clilen; #endif unsigned char attached; #ifndef LINUX WSAStartup (wVersionRequested, &wsaData); if (wsaData.wVersion != wVersionRequested) { fprintf (stderr, "\n Wrong version\n"); exit (-1); } #endif if ((listenfd = socket (PF_INET, SOCK_STREAM, 0)) < 0) { printf ("socket error : %s \n", strerror (errno)); exit (1); }; int reuse = 1; if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) < 0) perror("setsockopt(SO_REUSEADDR) failed"); memset (&serv, 0, sizeof (serv)); serv.sin_family = AF_INET; serv.sin_addr.s_addr = htonl (INADDR_ANY); serv.sin_port = htons (TCP_SERV_PORT); if (bind (listenfd, (sockaddr *) & serv, sizeof (serv)) < 0) { printf ("bind error : %s \n", strerror (errno)); exit (1); }; if (listen (listenfd, SOMAXCONN) < 0) { printf ("listen error : %s \n", strerror (errno)); exit (1); }; for (;;) { clilen = sizeof (cli); if ( (sockfd = accept (listenfd, (sockaddr *) & cli, & clilen)) < 0) { printf ("accept error : %s \n", strerror (errno)); exit (1); }; printf("Connection address:%s\n",inet_ntoa(cli.sin_addr)); attached=0; while(1) { if(! attached) { OP_REQ_DEVLIST req; if ((nb = recv (sockfd, (char *)&req, sizeof(OP_REQ_DEVLIST), 0)) != sizeof(OP_REQ_DEVLIST)) { //printf ("receive error : %s \n", strerror (errno)); break; }; #ifdef _DEBUG print_recv((char *)&req, sizeof(OP_REQ_DEVLIST),"OP_REQ_DEVLIST"); #endif req.command=ntohs(req.command); printf("Header Packet\n"); printf("command: 0x%02X\n",req.command); if(req.command == 0x8005) { OP_REP_DEVLIST list; printf("list of devices\n"); handle_device_list(dev_dsc,&list); if (send (sockfd, (char *)&list.header, sizeof(OP_REP_DEVLIST_HEADER), 0) != sizeof(OP_REP_DEVLIST_HEADER)) { printf ("send error : %s \n", strerror (errno)); break; }; if (send (sockfd, (char *)&list.device, sizeof(OP_REP_DEVLIST_DEVICE), 0) != sizeof(OP_REP_DEVLIST_DEVICE)) { printf ("send error : %s \n", strerror (errno)); break; }; if (send (sockfd, (char *)list.interfaces, sizeof(OP_REP_DEVLIST_INTERFACE)*list.device.bNumInterfaces, 0) != sizeof(OP_REP_DEVLIST_INTERFACE)*list.device.bNumInterfaces) { printf ("send error : %s \n", strerror (errno)); break; }; free(list.interfaces); } else if(req.command == 0x8003) { char busid[32]; OP_REP_IMPORT rep; printf("attach device\n"); if ((nb = recv (sockfd, busid, 32, 0)) != 32) { printf ("receive error : %s \n", strerror (errno)); break; }; #ifdef _DEBUG print_recv(busid, 32,"Busid"); #endif handle_attach(dev_dsc,&rep); if (send (sockfd, (char *)&rep, sizeof(OP_REP_IMPORT), 0) != sizeof(OP_REP_IMPORT)) { printf ("send error : %s \n", strerror (errno)); break; }; attached = 1; } } else { printf("------------------------------------------------\n"); printf("handles requests\n"); USBIP_CMD_SUBMIT cmd; USBIP_RET_SUBMIT usb_req; if ((nb = recv (sockfd, (char *)&cmd, sizeof(USBIP_CMD_SUBMIT), 0)) != sizeof(USBIP_CMD_SUBMIT)) { printf ("receive error : %s \n", strerror (errno)); break; }; #ifdef _DEBUG print_recv((char *)&cmd, sizeof(USBIP_CMD_SUBMIT),"USBIP_CMD_SUBMIT"); #endif unpack((int *)&cmd,sizeof(USBIP_CMD_SUBMIT)); printf("usbip cmd %u\n",cmd.command); printf("usbip seqnum %u\n",cmd.seqnum); printf("usbip devid %u\n",cmd.devid); printf("usbip direction %u\n",cmd.direction); printf("usbip ep %u\n",cmd.ep); printf("usbip flags %u\n",cmd.transfer_flags); printf("usbip number of packets %u\n",cmd.number_of_packets); printf("usbip interval %u\n",cmd.interval); #ifdef LINUX printf("usbip setup %llu\n",cmd.setup); #else printf("usbip setup %I64u\n",cmd.setup); #endif printf("usbip buffer lenght %u\n",cmd.transfer_buffer_length); usb_req.command=0; usb_req.seqnum=cmd.seqnum; usb_req.devid=cmd.devid; usb_req.direction=cmd.direction; usb_req.ep=cmd.ep; usb_req.status=0; usb_req.actual_length=0; usb_req.start_frame=0; usb_req.number_of_packets=0; usb_req.error_count=0; usb_req.setup=cmd.setup; if(cmd.command == 1) handle_usb_request(sockfd, &usb_req, cmd.transfer_buffer_length); if(cmd.command == 2) //unlink urb { printf("####################### Unlink URB %u (not working!!!)\n",cmd.transfer_flags); //FIXME /* USBIP_RET_UNLINK ret; printf("####################### Unlink URB %u\n",cmd.transfer_flags); ret.command=htonl(0x04); ret.devid=htonl(cmd.devid); ret.direction=htonl(cmd.direction); ret.ep=htonl(cmd.ep); ret.seqnum=htonl(cmd.seqnum); ret.status=htonl(1); if (send (sockfd, (char *)&ret, sizeof(USBIP_RET_UNLINK), 0) != sizeof(USBIP_RET_UNLINK)) { printf ("send error : %s \n", strerror (errno)); exit(-1); }; */ } if(cmd.command > 2) { printf("Unknown USBIP cmd!\n"); close (sockfd); #ifndef LINUX WSACleanup (); #endif return; }; } } close (sockfd); }; #ifndef LINUX WSACleanup (); #endif }; ================================================ FILE: c/usbip.h ================================================ /* ######################################################################## USBIP hardware emulation ######################################################################## Copyright (c) : 2016 Luis Claudio Gambôa Lopes This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. For e-mail suggestions : lcgamboa@yahoo.com ######################################################################## */ #ifdef LINUX #include #include #include #include #include #define min(a,b) ((a) < (b) ? (a) : (b)) #else #include #endif //system headers independent #include #include #include #include #include #include //defines #define TCP_SERV_PORT 3240 typedef struct sockaddr sockaddr; //USB definitions #define byte unsigned char #define word unsigned short // USB Descriptors #define USB_DESCRIPTOR_DEVICE 0x01 // Device Descriptor. #define USB_DESCRIPTOR_CONFIGURATION 0x02 // Configuration Descriptor. #define USB_DESCRIPTOR_STRING 0x03 // String Descriptor. #define USB_DESCRIPTOR_INTERFACE 0x04 // Interface Descriptor. #define USB_DESCRIPTOR_ENDPOINT 0x05 // Endpoint Descriptor. #define USB_DESCRIPTOR_DEVICE_QUALIFIER 0x06 // Device Qualifier. typedef struct __attribute__ ((__packed__)) _USB_DEVICE_DESCRIPTOR { byte bLength; // Length of this descriptor. byte bDescriptorType; // DEVICE descriptor type (USB_DESCRIPTOR_DEVICE). word bcdUSB; // USB Spec Release Number (BCD). byte bDeviceClass; // Class code (assigned by the USB-IF). 0xFF-Vendor specific. byte bDeviceSubClass; // Subclass code (assigned by the USB-IF). byte bDeviceProtocol; // Protocol code (assigned by the USB-IF). 0xFF-Vendor specific. byte bMaxPacketSize0; // Maximum packet size for endpoint 0. word idVendor; // Vendor ID (assigned by the USB-IF). word idProduct; // Product ID (assigned by the manufacturer). word bcdDevice; // Device release number (BCD). byte iManufacturer; // Index of String Descriptor describing the manufacturer. byte iProduct; // Index of String Descriptor describing the product. byte iSerialNumber; // Index of String Descriptor with the device's serial number. byte bNumConfigurations; // Number of possible configurations. } USB_DEVICE_DESCRIPTOR; typedef struct __attribute__ ((__packed__)) _USB_CONFIGURATION_DESCRIPTOR { byte bLength; // Length of this descriptor. byte bDescriptorType; // CONFIGURATION descriptor type (USB_DESCRIPTOR_CONFIGURATION). word wTotalLength; // Total length of all descriptors for this configuration. byte bNumInterfaces; // Number of interfaces in this configuration. byte bConfigurationValue; // Value of this configuration (1 based). byte iConfiguration; // Index of String Descriptor describing the configuration. byte bmAttributes; // Configuration characteristics. byte bMaxPower; // Maximum power consumed by this configuration. } USB_CONFIGURATION_DESCRIPTOR; typedef struct __attribute__ ((__packed__)) _USB_INTERFACE_DESCRIPTOR { byte bLength; // Length of this descriptor. byte bDescriptorType; // INTERFACE descriptor type (USB_DESCRIPTOR_INTERFACE). byte bInterfaceNumber; // Number of this interface (0 based). byte bAlternateSetting; // Value of this alternate interface setting. byte bNumEndpoints; // Number of endpoints in this interface. byte bInterfaceClass; // Class code (assigned by the USB-IF). 0xFF-Vendor specific. byte bInterfaceSubClass; // Subclass code (assigned by the USB-IF). byte bInterfaceProtocol; // Protocol code (assigned by the USB-IF). 0xFF-Vendor specific. byte iInterface; // Index of String Descriptor describing the interface. } USB_INTERFACE_DESCRIPTOR; typedef struct __attribute__ ((__packed__)) _USB_ENDPOINT_DESCRIPTOR { byte bLength; // Length of this descriptor. byte bDescriptorType; // ENDPOINT descriptor type (USB_DESCRIPTOR_ENDPOINT). byte bEndpointAddress; // Endpoint address. Bit 7 indicates direction (0=OUT, 1=IN). byte bmAttributes; // Endpoint transfer type. word wMaxPacketSize; // Maximum packet size. byte bInterval; // Polling interval in frames. } USB_ENDPOINT_DESCRIPTOR; typedef struct __attribute__ ((__packed__)) _USB_DEVICE_QUALIFIER_DESCRIPTOR { byte bLength; // Size of this descriptor byte bType; // Type, always USB_DESCRIPTOR_DEVICE_QUALIFIER word bcdUSB; // USB spec version, in BCD byte bDeviceClass; // Device class code byte bDeviceSubClass; // Device sub-class code byte bDeviceProtocol; // Device protocol byte bMaxPacketSize0; // EP0, max packet size byte bNumConfigurations; // Number of "other-speed" configurations byte bReserved; // Always zero (0) } USB_DEVICE_QUALIFIER_DESCRIPTOR; //Generic Configuration typedef struct __attribute__ ((__packed__)) _CONFIG_GEN { USB_CONFIGURATION_DESCRIPTOR dev_conf; USB_INTERFACE_DESCRIPTOR dev_int; } CONFIG_GEN; //HID typedef struct __attribute__ ((__packed__)) _USB_HID_DESCRIPTOR { byte bLength; byte bDescriptorType; word bcdHID; byte bCountryCode; byte bNumDescriptors; byte bRPDescriptorType; word wRPDescriptorLength; } USB_HID_DESCRIPTOR; //Configuration typedef struct __attribute__ ((__packed__)) _CONFIG_HID { USB_CONFIGURATION_DESCRIPTOR dev_conf; USB_INTERFACE_DESCRIPTOR dev_int; USB_HID_DESCRIPTOR dev_hid; USB_ENDPOINT_DESCRIPTOR dev_ep; } CONFIG_HID; //CDC /* Functional Descriptor Structure - See CDC Specification 1.1 for details */ /* Header Functional Descriptor */ typedef struct __attribute__ ((__packed__)) _USB_CDC_HEADER_FN_DSC { byte bFNLength; byte bDscType; byte bDscSubType; word bcdCDC; } USB_CDC_HEADER_FN_DSC; /* Abstract Control Management Functional Descriptor */ typedef struct __attribute__ ((__packed__)) _USB_CDC_ACM_FN_DSC { byte bFNLength; byte bDscType; byte bDscSubType; byte bmCapabilities; } USB_CDC_ACM_FN_DSC; /* Union Functional Descriptor */ typedef struct __attribute__ ((__packed__)) _USB_CDC_UNION_FN_DSC { byte bFNLength; byte bDscType; byte bDscSubType; byte bMasterIntf; byte bSaveIntf0; } USB_CDC_UNION_FN_DSC; /* Call Management Functional Descriptor */ typedef struct __attribute__ ((__packed__)) _USB_CDC_CALL_MGT_FN_DSC { byte bFNLength; byte bDscType; byte bDscSubType; byte bmCapabilities; byte bDataInterface; } USB_CDC_CALL_MGT_FN_DSC; //Configuration typedef struct __attribute__ ((__packed__)) _CONFIG_CDC { USB_CONFIGURATION_DESCRIPTOR dev_conf0; USB_INTERFACE_DESCRIPTOR dev_int0; USB_CDC_HEADER_FN_DSC cdc_header; USB_CDC_CALL_MGT_FN_DSC cdc_call_mgt; USB_CDC_ACM_FN_DSC cdc_acm; USB_CDC_UNION_FN_DSC cdc_union; USB_ENDPOINT_DESCRIPTOR dev_ep0; USB_INTERFACE_DESCRIPTOR dev_int1; USB_ENDPOINT_DESCRIPTOR dev_ep1; USB_ENDPOINT_DESCRIPTOR dev_ep2; } CONFIG_CDC; //================================================================================= //USBIP data struct typedef struct __attribute__ ((__packed__)) _OP_REQ_DEVLIST { word version; word command; int status; } OP_REQ_DEVLIST; typedef struct __attribute__ ((__packed__)) _OP_REP_DEVLIST_HEADER { word version; word command; int status; int nExportedDevice; }OP_REP_DEVLIST_HEADER; //================= for each device typedef struct __attribute__ ((__packed__)) _OP_REP_DEVLIST_DEVICE { char usbPath[256]; char busID[32]; int busnum; int devnum; int speed; word idVendor; word idProduct; word bcdDevice; byte bDeviceClass; byte bDeviceSubClass; byte bDeviceProtocol; byte bConfigurationValue; byte bNumConfigurations; byte bNumInterfaces; }OP_REP_DEVLIST_DEVICE; //================== for each interface typedef struct __attribute__ ((__packed__)) _OP_REP_DEVLIST_INTERFACE { byte bInterfaceClass; byte bInterfaceSubClass; byte bInterfaceProtocol; byte padding; }OP_REP_DEVLIST_INTERFACE; typedef struct __attribute__ ((__packed__)) _OP_REP_DEVLIST { OP_REP_DEVLIST_HEADER header; OP_REP_DEVLIST_DEVICE device; //only one! OP_REP_DEVLIST_INTERFACE *interfaces; }OP_REP_DEVLIST; typedef struct __attribute__ ((__packed__)) _OP_REQ_IMPORT { word version; word command; int status; char busID[32]; }OP_REQ_IMPORT; typedef struct __attribute__ ((__packed__)) _OP_REP_IMPORT { word version; word command; int status; //------------- if not ok, finish here char usbPath[256]; char busID[32]; int busnum; int devnum; int speed; word idVendor; word idProduct; word bcdDevice; byte bDeviceClass; byte bDeviceSubClass; byte bDeviceProtocol; byte bConfigurationValue; byte bNumConfigurations; byte bNumInterfaces; }OP_REP_IMPORT; typedef struct __attribute__ ((__packed__)) _USBIP_CMD_SUBMIT { int command; int seqnum; int devid; int direction; int ep; int transfer_flags; int transfer_buffer_length; int start_frame; int number_of_packets; int interval; long long setup; }USBIP_CMD_SUBMIT; /* + Allowed transfer_flags | value | control | interrupt | bulk | isochronous + -------------------------+------------+---------+-----------+----------+------------- + URB_SHORT_NOT_OK | 0x00000001 | only in | only in | only in | no + URB_ISO_ASAP | 0x00000002 | no | no | no | yes + URB_NO_TRANSFER_DMA_MAP | 0x00000004 | yes | yes | yes | yes + URB_NO_FSBR | 0x00000020 | yes | no | no | no + URB_ZERO_PACKET | 0x00000040 | no | no | only out | no + URB_NO_INTERRUPT | 0x00000080 | yes | yes | yes | yes + URB_FREE_BUFFER | 0x00000100 | yes | yes | yes | yes + URB_DIR_MASK | 0x00000200 | yes | yes | yes | yes */ typedef struct __attribute__ ((__packed__)) _USBIP_RET_SUBMIT { int command; int seqnum; int devid; int direction; int ep; int status; int actual_length; int start_frame; int number_of_packets; int error_count; long long setup; }USBIP_RET_SUBMIT; typedef struct __attribute__ ((__packed__)) _USBIP_CMD_UNLINK { int command; int seqnum; int devid; int direction; int ep; int seqnum_urb; }USBIP_CMD_UNLINK; typedef struct __attribute__ ((__packed__)) _USBIP_RET_UNLINK { int command; int seqnum; int devid; int direction; int ep; int status; }USBIP_RET_UNLINK; typedef struct __attribute__ ((__packed__)) _StandardDeviceRequest { byte bmRequestType; byte bRequest; byte wValue0; byte wValue1; byte wIndex0; byte wIndex1; word wLength; }StandardDeviceRequest; void send_usb_req(int sockfd, USBIP_RET_SUBMIT * usb_req, char * data, unsigned int size, unsigned int status); void usbip_run (const USB_DEVICE_DESCRIPTOR *dev_dsc); //implemented by user extern const USB_DEVICE_DESCRIPTOR dev_dsc; extern const USB_DEVICE_QUALIFIER_DESCRIPTOR dev_qua; extern const char * configuration; extern const USB_INTERFACE_DESCRIPTOR *interfaces[]; extern const unsigned char *strings[]; void handle_data(int sockfd, USBIP_RET_SUBMIT *usb_req, int bl); void handle_unknown_control(int sockfd, StandardDeviceRequest * control_req, USBIP_RET_SUBMIT *usb_req); ================================================ FILE: doc/usbip_protocol.txt ================================================ PRELIMINARY DRAFT, MAY CONTAIN MISTAKES! 28 Jun 2011 The USB/IP protocol follows a server/client architecture. The server exports the USB devices and the clients imports them. The device driver for the exported USB device runs on the client machine. The client may ask for the list of the exported USB devices. To get the list the client opens a TCP/IP connection towards the server, and sends an OP_REQ_DEVLIST packet on top of the TCP/IP connection (so the actual OP_REQ_DEVLIST may be sent in one or more pieces at the low level transport layer). The server sends back the OP_REP_DEVLIST packet which lists the exported USB devices. Finally the TCP/IP connection is closed. virtual host controller usb host "client" "server" (imports USB devices) (exports USB devices) | | | OP_REQ_DEVLIST | | ----------------------------------------------> | | | | OP_REP_DEVLIST | | <---------------------------------------------- | | | Once the client knows the list of exported USB devices it may decide to use one of them. First the client opens a TCP/IP connection towards the server and sends an OP_REQ_IMPORT packet. The server replies with OP_REP_IMPORT. If the import was successful the TCP/IP connection remains open and will be used to trasfer the URB traffic between the client and the server. The client may send two types of packets: the USBIP_CMD_SUBMIT to submit an URB, and USBIP_CMD_UNLINK to unlink a previously submitted URB. The answers of the server may be USBIP_RET_SUBMIT and USBIP_RET_UNLINK respectively. virtual host controller usb host "client" "server" (imports USB devices) (exports USB devices) | | | OP_REQ_IMPORT | | ----------------------------------------------> | | | | OP_REP_IMPORT | | <---------------------------------------------- | | | | | | USBIP_CMD_SUBMIT(seqnum = n) | | ----------------------------------------------> | | | | USBIP_RET_SUBMIT(seqnum = n) | | <---------------------------------------------- | | . | | : | | | | USBIP_CMD_SUBMIT(seqnum = m) | | ----------------------------------------------> | | | | USBIP_CMD_SUBMIT(seqnum = m+1) | | ----------------------------------------------> | | | | USBIP_CMD_SUBMIT(seqnum = m+2) | | ----------------------------------------------> | | | | USBIP_RET_SUBMIT(seqnum = m) | | <---------------------------------------------- | | | | USBIP_CMD_SUBMIT(seqnum = m+3) | | ----------------------------------------------> | | | | USBIP_RET_SUBMIT(seqnum = m+1) | | <---------------------------------------------- | | | | USBIP_CMD_SUBMIT(seqnum = m+4) | | ----------------------------------------------> | | | | USBIP_RET_SUBMIT(seqnum = m+2) | | <---------------------------------------------- | | . | | : | | | | USBIP_CMD_UNLINK | | ----------------------------------------------> | | | | USBIP_RET_UNLINK | | <---------------------------------------------- | | | The fields are in network (big endian) byte order meaning that the most significant byte (MSB) is stored at the lowest address. OP_REQ_DEVLIST: Retrieve the list of exported USB devices. Offset | Length | Value | Description -----------+--------+------------+--------------------------------------------------- 0 | 2 | 0x0100 | Binary-coded decimal USBIP version number: v1.0.0 -----------+--------+------------+--------------------------------------------------- 2 | 2 | 0x8005 | Command code: Retrieve the list of exported USB | | | devices. -----------+--------+------------+--------------------------------------------------- 4 | 4 | 0x00000000 | Status: unused, shall be set to 0 OP_REP_DEVLIST: Reply with the list of exported USB devices. Offset | Length | Value | Description -----------+--------+------------+--------------------------------------------------- 0 | 2 | 0x0100 | Binary-coded decimal USBIP version number: v1.0.0. -----------+--------+------------+--------------------------------------------------- 2 | 2 | 0x0005 | Reply code: The list of exported USB devices. -----------+--------+------------+--------------------------------------------------- 4 | 4 | 0x00000000 | Status: 0 for OK -----------+--------+------------+--------------------------------------------------- 8 | 4 | n | Number of exported devices: 0 means no exported | | | devices. -----------+--------+------------+--------------------------------------------------- 0x0C | | | From now on the exported n devices are described, | | | if any. If no devices are exported the message | | | ends with the previous "number of exported | | | devices" field. -----------+--------+------------+--------------------------------------------------- | 256 | | path: Path of the device on the host exporting the | | | USB device, string closed with zero byte, e.g. | | | "/sys/devices/pci0000:00/0000:00:1d.1/usb3/3-2" | | | The unused bytes shall be filled with zero | | | bytes. -----------+--------+------------+--------------------------------------------------- 0x10C | 32 | | busid: Bus ID of the exported device, string | | | closed with zero byte, e.g. "3-2". The unused | | | bytes shall be filled with zero bytes. -----------+--------+------------+--------------------------------------------------- 0x12C | 4 | | busnum -----------+--------+------------+--------------------------------------------------- 0x130 | 4 | | devnum -----------+--------+------------+--------------------------------------------------- 0x134 | 4 | | speed -----------+--------+------------+--------------------------------------------------- 0x138 | 2 | | idVendor -----------+--------+------------+--------------------------------------------------- 0x13A | 2 | | idProduct -----------+--------+------------+--------------------------------------------------- 0x13C | 2 | | bcdDevice -----------+--------+------------+--------------------------------------------------- 0x13E | 1 | | bDeviceClass -----------+--------+------------+--------------------------------------------------- 0x13F | 1 | | bDeviceSubClass -----------+--------+------------+--------------------------------------------------- 0x140 | 1 | | bDeviceProtocol -----------+--------+------------+--------------------------------------------------- 0x141 | 1 | | bConfigurationValue -----------+--------+------------+--------------------------------------------------- 0x142 | 1 | | bNumConfigurations -----------+--------+------------+--------------------------------------------------- 0x143 | 1 | | bNumInterfaces -----------+--------+------------+--------------------------------------------------- 0x144 | | m_0 | From now on each interface is described, all | | | together bNumInterfaces times, with the | | | the following 4 fields: -----------+--------+------------+--------------------------------------------------- | 1 | | bInterfaceClass -----------+--------+------------+--------------------------------------------------- 0x145 | 1 | | bInterfaceSubClass -----------+--------+------------+--------------------------------------------------- 0x146 | 1 | | bInterfaceProtocol -----------+--------+------------+--------------------------------------------------- 0x147 | 1 | | padding byte for alignment, shall be set to zero -----------+--------+------------+--------------------------------------------------- 0xC + | | | The second exported USB device starts at i=1 i*0x138 + | | | with the busid field. m_(i-1)*4 | | | OP_REQ_IMPORT: Request to import (attach) a remote USB device. Offset | Length | Value | Description -----------+--------+------------+--------------------------------------------------- 0 | 2 | 0x0100 | Binary-coded decimal USBIP version number: v1.0.0 -----------+--------+------------+--------------------------------------------------- 2 | 2 | 0x8003 | Command code: import a remote USB device. -----------+--------+------------+--------------------------------------------------- 4 | 4 | 0x00000000 | Status: unused, shall be set to 0 -----------+--------+------------+--------------------------------------------------- 8 | 32 | | busid: the busid of the exported device on the | | | remote host. The possible values are taken | | | from the message field OP_REP_DEVLIST.busid. | | | A string closed with zero, the unused bytes | | | shall be filled with zeros. -----------+--------+------------+--------------------------------------------------- OP_REP_IMPORT: Reply to import (attach) a remote USB device. Offset | Length | Value | Description -----------+--------+------------+--------------------------------------------------- 0 | 2 | 0x0100 | Binary-coded decimal USBIP version number: v1.0.0 -----------+--------+------------+--------------------------------------------------- 2 | 2 | 0x0003 | Reply code: Reply to import. -----------+--------+------------+--------------------------------------------------- 4 | 4 | 0x00000000 | Status: 0 for OK | | | 1 for error -----------+--------+------------+--------------------------------------------------- 8 | | | From now on comes the details of the imported | | | device, if the previous status field was OK (0), | | | otherwise the reply ends with the status field. -----------+--------+------------+--------------------------------------------------- | 256 | | path: Path of the device on the host exporting the | | | USB device, string closed with zero byte, e.g. | | | "/sys/devices/pci0000:00/0000:00:1d.1/usb3/3-2" | | | The unused bytes shall be filled with zero | | | bytes. -----------+--------+------------+--------------------------------------------------- 0x108 | 32 | | busid: Bus ID of the exported device, string | | | closed with zero byte, e.g. "3-2". The unused | | | bytes shall be filled with zero bytes. -----------+--------+------------+--------------------------------------------------- 0x128 | 4 | | busnum -----------+--------+------------+--------------------------------------------------- 0x12C | 4 | | devnum -----------+--------+------------+--------------------------------------------------- 0x130 | 4 | | speed -----------+--------+------------+--------------------------------------------------- 0x134 | 2 | | idVendor -----------+--------+------------+--------------------------------------------------- 0x136 | 2 | | idProduct -----------+--------+------------+--------------------------------------------------- 0x138 | 2 | | bcdDevice -----------+--------+------------+--------------------------------------------------- 0x139 | 1 | | bDeviceClass -----------+--------+------------+--------------------------------------------------- 0x13A | 1 | | bDeviceSubClass -----------+--------+------------+--------------------------------------------------- 0x13B | 1 | | bDeviceProtocol -----------+--------+------------+--------------------------------------------------- 0x13C | 1 | | bConfigurationValue -----------+--------+------------+--------------------------------------------------- 0x13D | 1 | | bNumConfigurations -----------+--------+------------+--------------------------------------------------- 0x13E | 1 | | bNumInterfaces USBIP_CMD_SUBMIT: Submit an URB Offset | Length | Value | Description -----------+--------+------------+--------------------------------------------------- 0 | 4 | 0x00000001 | command: Submit an URB -----------+--------+------------+--------------------------------------------------- 4 | 4 | | seqnum: the sequence number of the URB to submit -----------+--------+------------+--------------------------------------------------- 8 | 4 | | devid -----------+--------+------------+--------------------------------------------------- 0xC | 4 | | direction: 0: USBIP_DIR_OUT | | | 1: USBIP_DIR_IN -----------+--------+------------+--------------------------------------------------- 0x10 | 4 | | ep: endpoint number, possible values are: 0...15 -----------+--------+------------+--------------------------------------------------- 0x14 | 4 | | transfer_flags: possible values depend on the | | | URB transfer type, see below -----------+--------+------------+--------------------------------------------------- 0x18 | 4 | | transfer_buffer_length -----------+--------+------------+--------------------------------------------------- 0x1C | 4 | | start_frame: specify the selected frame to | | | transmit an ISO frame, ignored if URB_ISO_ASAP | | | is specified at transfer_flags -----------+--------+------------+--------------------------------------------------- 0x20 | 4 | | number_of_packets: number of ISO packets -----------+--------+------------+--------------------------------------------------- 0x24 | 4 | | interval: maximum time for the request on the | | | server-side host controller -----------+--------+------------+--------------------------------------------------- 0x28 | 8 | | setup: data bytes for USB setup, filled with | | | zeros if not used -----------+--------+------------+--------------------------------------------------- 0x30 | | | URB data. For ISO transfers the padding between | | | each ISO packets is not transmitted. Allowed transfer_flags | value | control | interrupt | bulk | isochronous -------------------------+------------+---------+-----------+----------+------------- URB_SHORT_NOT_OK | 0x00000001 | only in | only in | only in | no URB_ISO_ASAP | 0x00000002 | no | no | no | yes URB_NO_TRANSFER_DMA_MAP | 0x00000004 | yes | yes | yes | yes URB_NO_FSBR | 0x00000020 | yes | no | no | no URB_ZERO_PACKET | 0x00000040 | no | no | only out | no URB_NO_INTERRUPT | 0x00000080 | yes | yes | yes | yes URB_FREE_BUFFER | 0x00000100 | yes | yes | yes | yes URB_DIR_MASK | 0x00000200 | yes | yes | yes | yes USBIP_RET_SUBMIT: Reply for submitting an URB Offset | Length | Value | Description -----------+--------+------------+--------------------------------------------------- 0 | 4 | 0x00000003 | command -----------+--------+------------+--------------------------------------------------- 4 | 4 | | seqnum: URB sequence number -----------+--------+------------+--------------------------------------------------- 8 | 4 | | devid -----------+--------+------------+--------------------------------------------------- 0xC | 4 | | direction: 0: USBIP_DIR_OUT | | | 1: USBIP_DIR_IN -----------+--------+------------+--------------------------------------------------- 0x10 | 4 | | ep: endpoint number -----------+--------+------------+--------------------------------------------------- 0x14 | 4 | | status: zero for successful URB transaction, | | | otherwise some kind of error happened. -----------+--------+------------+--------------------------------------------------- 0x18 | 4 | n | actual_length: number of URB data bytes -----------+--------+------------+--------------------------------------------------- 0x1C | 4 | | start_frame: for an ISO frame the actually | | | selected frame for transmit. -----------+--------+------------+--------------------------------------------------- 0x20 | 4 | | number_of_packets -----------+--------+------------+--------------------------------------------------- 0x24 | 4 | | error_count -----------+--------+------------+--------------------------------------------------- 0x28 | 8 | | setup: data bytes for USB setup, filled with | | | zeros if not used -----------+--------+------------+--------------------------------------------------- 0x30 | n | | URB data bytes. For ISO transfers the padding | | | between each ISO packets is not transmitted. USBIP_CMD_UNLINK: Unlink an URB Offset | Length | Value | Description -----------+--------+------------+--------------------------------------------------- 0 | 4 | 0x00000002 | command: URB unlink command -----------+--------+------------+--------------------------------------------------- 4 | 4 | | seqnum: URB sequence number to unlink: FIXME: is this so? -----------+--------+------------+--------------------------------------------------- 8 | 4 | | devid -----------+--------+------------+--------------------------------------------------- 0xC | 4 | | direction: 0: USBIP_DIR_OUT | | | 1: USBIP_DIR_IN -----------+--------+------------+--------------------------------------------------- 0x10 | 4 | | ep: endpoint number: zero -----------+--------+------------+--------------------------------------------------- 0x14 | 4 | | seqnum: the URB sequence number given previously | | | at USBIP_CMD_SUBMIT.seqnum field -----------+--------+------------+--------------------------------------------------- 0x30 | n | | URB data bytes. For ISO transfers the padding | | | between each ISO packets is not transmitted. USBIP_RET_UNLINK: Reply for URB unlink Offset | Length | Value | Description -----------+--------+------------+--------------------------------------------------- 0 | 4 | 0x00000004 | command: reply for the URB unlink command -----------+--------+------------+--------------------------------------------------- 4 | 4 | | seqnum: the unlinked URB sequence number -----------+--------+------------+--------------------------------------------------- 8 | 4 | | devid -----------+--------+------------+--------------------------------------------------- 0xC | 4 | | direction: 0: USBIP_DIR_OUT | | | 1: USBIP_DIR_IN -----------+--------+------------+--------------------------------------------------- 0x10 | 4 | | ep: endpoint number -----------+--------+------------+--------------------------------------------------- 0x14 | 4 | | status: This is the value contained in the | | | urb->status in the URB completition handler. | | | FIXME: a better explanation needed. -----------+--------+------------+--------------------------------------------------- 0x30 | n | | URB data bytes. For ISO transfers the padding | | | between each ISO packets is not transmitted. ================================================ FILE: python/LICENSE ================================================ Copyright (c) 2014 Yaron Shani . All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. This software is provided ``as is'' and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall author or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. ================================================ FILE: python/USBIP.py ================================================ import socket import struct import types class BaseStucture: def __init__(self, **kwargs): self.init_from_dict(**kwargs) for field in self._fields_: if len(field) > 2: if not hasattr(self, field[0]): setattr(self, field[0], field[2]) def init_from_dict(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) def size(self): return struct.calcsize(self.format()) def format(self): pack_format = '>' for field in self._fields_: if type(field[1]) is types.InstanceType: if BaseStucture in field[1].__class__.__bases__: pack_format += str(field[1].size()) + 's' elif 'si' == field[1]: pack_format += 'c' elif '<' in field[1]: pack_format += field[1][1:] else: pack_format += field[1] return pack_format def pack(self): values = [] for field in self._fields_: if type(field[1]) is types.InstanceType: if BaseStucture in field[1].__class__.__bases__: values.append(getattr(self, field[0], 0).pack()) else: if 'si' == field[1]: values.append(chr(getattr(self, field[0], 0))) else: values.append(getattr(self, field[0], 0)) return struct.pack(self.format(), *values) def unpack(self, buf): values = struct.unpack(self.format(), buf) i=0 keys_vals = {} for val in values: if '<' in self._fields_[i][1][0]: val = struct.unpack('<' +self._fields_[i][1][1], struct.pack('>' + self._fields_[i][1][1], val))[0] keys_vals[self._fields_[i][0]]=val i+=1 self.init_from_dict(**keys_vals) def int_to_hex_string(val): sval= format(val, 'x') if len(sval) < 16: for i in range(len(sval),16): sval= '0'+sval #sval= sval+'0' print sval return sval.decode('hex') class USBIPHeader(BaseStucture): _fields_ = [ ('version', 'H', 273), ('command', 'H'), ('status', 'I') ] class USBInterface(BaseStucture): _fields_ = [ ('bInterfaceClass', 'B'), ('bInterfaceSubClass', 'B'), ('bInterfaceProtocol', 'B'), ('align', 'B', 0) ] class OPREPDevList(BaseStucture): _fields_ = [ ('base', USBIPHeader()), ('nExportedDevice', 'I'), ('usbPath', '256s'), ('busID', '32s'), ('busnum', 'I'), ('devnum', 'I'), ('speed', 'I'), ('idVendor', 'H'), ('idProduct', 'H'), ('bcdDevice', 'H'), ('bDeviceClass', 'B'), ('bDeviceSubClass', 'B'), ('bDeviceProtocol', 'B'), ('bConfigurationValue', 'B'), ('bNumConfigurations', 'B'), ('bNumInterfaces', 'B'), ('interfaces', USBInterface()) ] class OPREPImport(BaseStucture): _fields_ = [ ('base', USBIPHeader()), ('usbPath', '256s'), ('busID', '32s'), ('busnum', 'I'), ('devnum', 'I'), ('speed', 'I'), ('idVendor', 'H'), ('idProduct', 'H'), ('bcdDevice', 'H'), ('bDeviceClass', 'B'), ('bDeviceSubClass', 'B'), ('bDeviceProtocol', 'B'), ('bConfigurationValue', 'B'), ('bNumConfigurations', 'B'), ('bNumInterfaces', 'B') ] class USBIPRETSubmit(BaseStucture): _fields_ = [ ('command', 'I'), ('seqnum', 'I'), ('devid', 'I'), ('direction', 'I'), ('ep', 'I'), ('status', 'I'), ('actual_length', 'I'), ('start_frame', 'I'), ('number_of_packets', 'I'), ('error_count', 'I'), ('setup', 'Q') ] def pack(self): packed_data = BaseStucture.pack(self) packed_data += self.data return packed_data class USBIPCMDSubmit(BaseStucture): _fields_ = [ ('command', 'I'), ('seqnum', 'I'), ('devid', 'I'), ('direction', 'I'), ('ep', 'I'), ('transfer_flags', 'I'), ('transfer_buffer_length', 'I'), ('start_frame', 'I'), ('number_of_packets', 'I'), ('interval', 'I'), ('setup', 'Q') ] class USBIPUnlinkReq(BaseStucture): _fields_ = [ ('command', 'I', 0x2), ('seqnum', 'I'), ('devid', 'I', 0x2), ('direction', 'I'), ('ep', 'I'), ('transfer_flags', 'I'), ('transfer_buffer_length', 'I'), ('start_frame', 'I'), ('number_of_packets', 'I'), ('interval', 'I'), ('setup', 'Q') ] class StandardDeviceRequest(BaseStucture): _fields_ = [ ('bmRequestType', 'B'), ('bRequest', 'B'), ('wValue', 'H'), ('wIndex', 'H'), ('wLength', '= 0: return val else: return 256+val def handle_data(self, usb_req): # Sending random keyboard data # Send data only for 5 seconds #if (datetime.datetime.now() - self.start_time).seconds < 10: print "handle data" global count if count < 100: if (count % 2) == 0: return_val = "\x00\x00" + str(chr(random.randint(4,29))) + "\x00\x00\x00\x00\x00" else: return_val = "\x00\x00\x00\x00\x00\x00\x00\x00" self.send_usb_req(usb_req, return_val, len(return_val)) time.sleep(0.05) count=count+1 def handle_unknown_control(self, control_req, usb_req): if control_req.bmRequestType == 0x81: if control_req.bRequest == 0x6: # Get Descriptor if control_req.wValue == 0x22: # send initial report print 'send initial report' ret=self.generate_keyboard_report() self.send_usb_req(usb_req, ret, len(ret)) if control_req.bmRequestType == 0x21: # Host Request if control_req.bRequest == 0x0a: # set idle print 'Idle' # Idle self.send_usb_req(usb_req, '', 0,0) pass if control_req.bRequest == 0x09: # set report print 'set report' data = usb_container.usb_devices[0].connection.recv(control_req.wLength) #use data ? self.send_usb_req(usb_req, '', 0,0) pass usb_Dev = USBHID() usb_container = USBContainer() usb_container.add_usb_device(usb_Dev) # Supports only one device! usb_container.run() # Run in cmd: usbip.exe -a 127.0.0.1 "1-1" ================================================ FILE: python/hid-mouse.py ================================================ import time import random import datetime from USBIP import BaseStucture, USBDevice, InterfaceDescriptor, DeviceConfigurations, EndPoint, USBContainer #data event counter count =0 # Emulating USB mouse # HID Configuration class HIDClass(BaseStucture): _fields_ = [ ('bLength', 'B', 9), ('bDescriptorType', 'B', 0x21), # HID ('bcdHID', 'H'), ('bCountryCode', 'B'), ('bNumDescriptors', 'B'), ('bDescriptprType2', 'B'), ('wDescriptionLength', 'H'), ] hid_class = HIDClass(bcdHID=0x0100, # Mouse bCountryCode=0x0, bNumDescriptors=0x1, bDescriptprType2=0x22, # Report wDescriptionLength=0x3400) # Little endian interface_d = InterfaceDescriptor(bAlternateSetting=0, bNumEndpoints=1, bInterfaceClass=3, # class HID bInterfaceSubClass=1, bInterfaceProtocol=2, iInterface=0) end_point = EndPoint(bEndpointAddress=0x81, bmAttributes=0x3, wMaxPacketSize=0x0800, # Little endian bInterval=0xFF) # interval to report configuration = DeviceConfigurations(wTotalLength=0x2200, bNumInterfaces=0x1, bConfigurationValue=0x1, iConfiguration=0x0, # No string bmAttributes=0x80, # valid self powered bMaxPower=50) # 100 mah current interface_d.descriptions = [hid_class] # Supports only one description interface_d.endpoints = [end_point] # Supports only one endpoint configuration.interfaces = [interface_d] # Supports only one interface class USBHID(USBDevice): vendorID = 0x0627 productID = 0x0 bcdDevice = 0x0 bcdUSB = 0x0 bNumConfigurations = 0x1 bNumInterfaces = 0x1 bConfigurationValue = 0x1 configurations = [] bDeviceClass = 0x0 bDeviceSubClass = 0x0 bDeviceProtocol = 0x0 configurations = [configuration] # Supports only one configuration def __init__(self): USBDevice.__init__(self) self.start_time = datetime.datetime.now() def generate_mouse_report(self): arr = [0x05, 0x01, # Usage Page (Generic Desktop) 0x09, 0x02, # Usage (Mouse) 0xa1, 0x01, # Collection (Application) 0x09, 0x01, # Usage (Pointer) 0xa1, 0x00, # Collection (Physical) 0x05, 0x09, # Usage Page (Button) 0x19, 0x01, # Usage Minimum (1) 0x29, 0x03, # Usage Maximum (3) 0x15, 0x00, # Logical Minimum (0) 0x25, 0x01, # Logical Maximum (1) 0x95, 0x03, # Report Count (3) 0x75, 0x01, # Report Size (1) 0x81, 0x02, # Input (Data, Variable, Absolute) 0x95, 0x01, # Report Count (1) 0x75, 0x05, # Report Size (5) 0x81, 0x01, # Input (Constant) 0x05, 0x01, # Usage Page (Generic Desktop) 0x09, 0x30, # Usage (X) 0x09, 0x31, # Usage (Y) 0x09, 0x38, # Usage (Wheel) 0x15, 0x81, # Logical Minimum (-0x7f) 0x25, 0x7f, # Logical Maximum (0x7f) 0x75, 0x08, # Report Size (8) 0x95, 0x03, # Report Count (3) 0x81, 0x06, # Input (Data, Variable, Relative) 0xc0, # End Collection 0xc0] # End Collection return_val = '' for val in arr: return_val+=chr(val) return return_val def comp(self,val): if val >= 0: return val else: return 256+val def handle_data(self, usb_req): # Sending random mouse data # Send data only for 5 seconds #if (datetime.datetime.now() - self.start_time).seconds < 10: global count if count < 100: return_val = chr(0x0) + chr(self.comp(random.randint(-5, 5))) + chr(self.comp(random.randint(-5, 5))) + chr(0) self.send_usb_req(usb_req, return_val, len(return_val)) time.sleep(0.05) count=count+1 def handle_unknown_control(self, control_req, usb_req): if control_req.bmRequestType == 0x81: if control_req.bRequest == 0x6: # Get Descriptor if control_req.wValue == 0x22: # send initial report print 'send initial report' ret=self.generate_mouse_report() self.send_usb_req(usb_req, ret, len(ret)) if control_req.bmRequestType == 0x21: # Host Request if control_req.bRequest == 0x0a: # set idle print 'Idle' # Idle #self.send_ok(usb_req) self.send_usb_req(usb_req,'',0,0); pass usb_Dev = USBHID() usb_container = USBContainer() usb_container.add_usb_device(usb_Dev) # Supports only one device! usb_container.run() # Run in cmd: usbip.exe -a 127.0.0.1 "1-1"