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