windows_winusb.c 163 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554
  1. /*
  2. * windows backend for libusb 1.0
  3. * Copyright © 2009-2012 Pete Batard <pete@akeo.ie>
  4. * Copyright © 2016-2018 Chris Dickens <christopher.a.dickens@gmail.com>
  5. * With contributions from Michael Plante, Orin Eman et al.
  6. * Parts of this code adapted from libusb-win32-v1 by Stephan Meyer
  7. * HID Reports IOCTLs inspired from HIDAPI by Alan Ott, Signal 11 Software
  8. * Hash table functions adapted from glibc, by Ulrich Drepper et al.
  9. * Major code testing contribution by Xiaofan Chen
  10. *
  11. * This library is free software; you can redistribute it and/or
  12. * modify it under the terms of the GNU Lesser General Public
  13. * License as published by the Free Software Foundation; either
  14. * version 2.1 of the License, or (at your option) any later version.
  15. *
  16. * This library is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  19. * Lesser General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Lesser General Public
  22. * License along with this library; if not, write to the Free Software
  23. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  24. */
  25. #include <config.h>
  26. #include <windows.h>
  27. #include <setupapi.h>
  28. #include <ctype.h>
  29. #include <stdio.h>
  30. #include "libusbi.h"
  31. #include "windows_winusb.h"
  32. #define HANDLE_VALID(h) (((h) != NULL) && ((h) != INVALID_HANDLE_VALUE))
  33. // The below macro is used in conjunction with safe loops.
  34. #define LOOP_BREAK(err) \
  35. { \
  36. r = err; \
  37. continue; \
  38. }
  39. // WinUSB-like API prototypes
  40. static bool winusbx_init(struct libusb_context *ctx);
  41. static void winusbx_exit(void);
  42. static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle);
  43. static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle);
  44. static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface);
  45. static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface);
  46. static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface);
  47. static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
  48. static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting);
  49. static int winusbx_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer);
  50. static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
  51. static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
  52. static int winusbx_cancel_transfer(int sub_api, struct usbi_transfer *itransfer);
  53. static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
  54. static enum libusb_transfer_status winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, DWORD length);
  55. // HID API prototypes
  56. static bool hid_init(struct libusb_context *ctx);
  57. static void hid_exit(void);
  58. static int hid_open(int sub_api, struct libusb_device_handle *dev_handle);
  59. static void hid_close(int sub_api, struct libusb_device_handle *dev_handle);
  60. static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface);
  61. static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface);
  62. static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting);
  63. static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
  64. static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
  65. static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
  66. static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
  67. static enum libusb_transfer_status hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, DWORD length);
  68. // Composite API prototypes
  69. static int composite_open(int sub_api, struct libusb_device_handle *dev_handle);
  70. static void composite_close(int sub_api, struct libusb_device_handle *dev_handle);
  71. static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface);
  72. static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting);
  73. static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface);
  74. static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer);
  75. static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer);
  76. static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer);
  77. static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint);
  78. static int composite_cancel_transfer(int sub_api, struct usbi_transfer *itransfer);
  79. static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle);
  80. static enum libusb_transfer_status composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, DWORD length);
  81. static usbi_mutex_t autoclaim_lock;
  82. // API globals
  83. static struct winusb_interface WinUSBX[SUB_API_MAX];
  84. #define CHECK_WINUSBX_AVAILABLE(sub_api) \
  85. do { \
  86. if (sub_api == SUB_API_NOTSET) \
  87. sub_api = priv->sub_api; \
  88. if (WinUSBX[sub_api].hDll == NULL) \
  89. return LIBUSB_ERROR_ACCESS; \
  90. } while (0)
  91. #define CHECK_HID_AVAILABLE \
  92. do { \
  93. if (DLL_HANDLE_NAME(hid) == NULL) \
  94. return LIBUSB_ERROR_ACCESS; \
  95. } while (0)
  96. #if defined(ENABLE_LOGGING)
  97. static const char *guid_to_string(const GUID *guid, char guid_string[MAX_GUID_STRING_LENGTH])
  98. {
  99. if (guid == NULL) {
  100. guid_string[0] = '\0';
  101. return guid_string;
  102. }
  103. sprintf(guid_string, "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
  104. (unsigned int)guid->Data1, guid->Data2, guid->Data3,
  105. guid->Data4[0], guid->Data4[1], guid->Data4[2], guid->Data4[3],
  106. guid->Data4[4], guid->Data4[5], guid->Data4[6], guid->Data4[7]);
  107. return guid_string;
  108. }
  109. #endif
  110. static bool string_to_guid(const char guid_string[MAX_GUID_STRING_LENGTH], GUID *guid)
  111. {
  112. unsigned short tmp[4];
  113. int num_chars = -1;
  114. char extra;
  115. int r;
  116. // Unfortunately MinGW complains that '%hhx' is not a valid format specifier,
  117. // even though Visual Studio 2013 and later support it. Rather than complicating
  118. // the logic in this function with '#ifdef's, use a temporary array on the stack
  119. // to store the conversions.
  120. r = sscanf(guid_string, "{%8x-%4hx-%4hx-%4hx-%4hx%4hx%4hx}%n%c",
  121. (unsigned int *)&guid->Data1, &guid->Data2, &guid->Data3,
  122. &tmp[0], &tmp[1], &tmp[2], &tmp[3], &num_chars, &extra);
  123. if ((r != 7) || (num_chars != 38))
  124. return false;
  125. // Extract the bytes from the 2-byte shorts
  126. guid->Data4[0] = (unsigned char)((tmp[0] >> 8) & 0xFF);
  127. guid->Data4[1] = (unsigned char)(tmp[0] & 0xFF);
  128. guid->Data4[2] = (unsigned char)((tmp[1] >> 8) & 0xFF);
  129. guid->Data4[3] = (unsigned char)(tmp[1] & 0xFF);
  130. guid->Data4[4] = (unsigned char)((tmp[2] >> 8) & 0xFF);
  131. guid->Data4[5] = (unsigned char)(tmp[2] & 0xFF);
  132. guid->Data4[6] = (unsigned char)((tmp[3] >> 8) & 0xFF);
  133. guid->Data4[7] = (unsigned char)(tmp[3] & 0xFF);
  134. return true;
  135. }
  136. /*
  137. * Normalize Microsoft's paths: return a duplicate of the given path
  138. * with all characters converted to uppercase
  139. */
  140. static char *normalize_path(const char *path)
  141. {
  142. char *ret_path = _strdup(path);
  143. char *p;
  144. if (ret_path == NULL)
  145. return NULL;
  146. for (p = ret_path; *p != '\0'; p++)
  147. *p = (char)toupper((unsigned char)*p);
  148. return ret_path;
  149. }
  150. /*
  151. * Cfgmgr32, AdvAPI32, OLE32 and SetupAPI DLL functions
  152. */
  153. static bool init_dlls(struct libusb_context *ctx)
  154. {
  155. DLL_GET_HANDLE(ctx, Cfgmgr32);
  156. DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Parent, true);
  157. DLL_LOAD_FUNC(Cfgmgr32, CM_Get_Child, true);
  158. // Prefixed to avoid conflict with header files
  159. DLL_GET_HANDLE(ctx, AdvAPI32);
  160. DLL_LOAD_FUNC_PREFIXED(AdvAPI32, p, RegQueryValueExA, true);
  161. DLL_LOAD_FUNC_PREFIXED(AdvAPI32, p, RegCloseKey, true);
  162. DLL_GET_HANDLE(ctx, SetupAPI);
  163. DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetClassDevsA, true);
  164. DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiEnumDeviceInfo, true);
  165. DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiEnumDeviceInterfaces, true);
  166. DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetDeviceInstanceIdA, true);
  167. DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetDeviceInterfaceDetailA, true);
  168. DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiGetDeviceRegistryPropertyA, true);
  169. DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiDestroyDeviceInfoList, true);
  170. DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiOpenDevRegKey, true);
  171. DLL_LOAD_FUNC_PREFIXED(SetupAPI, p, SetupDiOpenDeviceInterfaceRegKey, true);
  172. return true;
  173. }
  174. static void exit_dlls(void)
  175. {
  176. DLL_FREE_HANDLE(SetupAPI);
  177. DLL_FREE_HANDLE(AdvAPI32);
  178. DLL_FREE_HANDLE(Cfgmgr32);
  179. }
  180. /*
  181. * enumerate interfaces for the whole USB class
  182. *
  183. * Parameters:
  184. * dev_info: a pointer to a dev_info list
  185. * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
  186. * enumerator: the generic USB class for which to retrieve interface details
  187. * index: zero based index of the interface in the device info list
  188. *
  189. * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
  190. * structure returned and call this function repeatedly using the same guid (with an
  191. * incremented index starting at zero) until all interfaces have been returned.
  192. */
  193. static bool get_devinfo_data(struct libusb_context *ctx,
  194. HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data, const char *enumerator, unsigned _index)
  195. {
  196. if (_index == 0) {
  197. *dev_info = pSetupDiGetClassDevsA(NULL, enumerator, NULL, DIGCF_PRESENT|DIGCF_ALLCLASSES);
  198. if (*dev_info == INVALID_HANDLE_VALUE) {
  199. usbi_err(ctx, "could not obtain device info set for PnP enumerator '%s': %s",
  200. enumerator, windows_error_str(0));
  201. return false;
  202. }
  203. }
  204. dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
  205. if (!pSetupDiEnumDeviceInfo(*dev_info, _index, dev_info_data)) {
  206. if (GetLastError() != ERROR_NO_MORE_ITEMS)
  207. usbi_err(ctx, "could not obtain device info data for PnP enumerator '%s' index %u: %s",
  208. enumerator, _index, windows_error_str(0));
  209. pSetupDiDestroyDeviceInfoList(*dev_info);
  210. *dev_info = INVALID_HANDLE_VALUE;
  211. return false;
  212. }
  213. return true;
  214. }
  215. /*
  216. * enumerate interfaces for a specific GUID
  217. *
  218. * Parameters:
  219. * dev_info: a pointer to a dev_info list
  220. * dev_info_data: a pointer to an SP_DEVINFO_DATA to be filled (or NULL if not needed)
  221. * guid: the GUID for which to retrieve interface details
  222. * index: zero based index of the interface in the device info list
  223. *
  224. * Note: it is the responsibility of the caller to free the DEVICE_INTERFACE_DETAIL_DATA
  225. * structure returned and call this function repeatedly using the same guid (with an
  226. * incremented index starting at zero) until all interfaces have been returned.
  227. */
  228. static int get_interface_details(struct libusb_context *ctx, HDEVINFO dev_info,
  229. PSP_DEVINFO_DATA dev_info_data, LPCGUID guid, DWORD *_index, char **dev_interface_path)
  230. {
  231. SP_DEVICE_INTERFACE_DATA dev_interface_data;
  232. PSP_DEVICE_INTERFACE_DETAIL_DATA_A dev_interface_details;
  233. char guid_string[MAX_GUID_STRING_LENGTH];
  234. DWORD size;
  235. dev_info_data->cbSize = sizeof(SP_DEVINFO_DATA);
  236. dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
  237. for (;;) {
  238. if (!pSetupDiEnumDeviceInfo(dev_info, *_index, dev_info_data)) {
  239. if (GetLastError() != ERROR_NO_MORE_ITEMS) {
  240. usbi_err(ctx, "Could not obtain device info data for %s index %lu: %s",
  241. guid_to_string(guid, guid_string), ULONG_CAST(*_index), windows_error_str(0));
  242. return LIBUSB_ERROR_OTHER;
  243. }
  244. // No more devices
  245. return LIBUSB_SUCCESS;
  246. }
  247. // Always advance the index for the next iteration
  248. (*_index)++;
  249. if (pSetupDiEnumDeviceInterfaces(dev_info, dev_info_data, guid, 0, &dev_interface_data))
  250. break;
  251. if (GetLastError() != ERROR_NO_MORE_ITEMS) {
  252. usbi_err(ctx, "Could not obtain interface data for %s devInst %lX: %s",
  253. guid_to_string(guid, guid_string), ULONG_CAST(dev_info_data->DevInst), windows_error_str(0));
  254. return LIBUSB_ERROR_OTHER;
  255. }
  256. // Device does not have an interface matching this GUID, skip
  257. }
  258. // Read interface data (dummy + actual) to access the device path
  259. if (!pSetupDiGetDeviceInterfaceDetailA(dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
  260. // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
  261. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
  262. usbi_err(ctx, "could not access interface data (dummy) for %s devInst %lX: %s",
  263. guid_to_string(guid, guid_string), ULONG_CAST(dev_info_data->DevInst), windows_error_str(0));
  264. return LIBUSB_ERROR_OTHER;
  265. }
  266. } else {
  267. usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong");
  268. return LIBUSB_ERROR_OTHER;
  269. }
  270. dev_interface_details = malloc(size);
  271. if (dev_interface_details == NULL) {
  272. usbi_err(ctx, "could not allocate interface data for %s devInst %lX",
  273. guid_to_string(guid, guid_string), ULONG_CAST(dev_info_data->DevInst));
  274. return LIBUSB_ERROR_NO_MEM;
  275. }
  276. dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
  277. if (!pSetupDiGetDeviceInterfaceDetailA(dev_info, &dev_interface_data,
  278. dev_interface_details, size, NULL, NULL)) {
  279. usbi_err(ctx, "could not access interface data (actual) for %s devInst %lX: %s",
  280. guid_to_string(guid, guid_string), ULONG_CAST(dev_info_data->DevInst), windows_error_str(0));
  281. free(dev_interface_details);
  282. return LIBUSB_ERROR_OTHER;
  283. }
  284. *dev_interface_path = normalize_path(dev_interface_details->DevicePath);
  285. free(dev_interface_details);
  286. if (*dev_interface_path == NULL) {
  287. usbi_err(ctx, "could not allocate interface path for %s devInst %lX",
  288. guid_to_string(guid, guid_string), ULONG_CAST(dev_info_data->DevInst));
  289. return LIBUSB_ERROR_NO_MEM;
  290. }
  291. return LIBUSB_SUCCESS;
  292. }
  293. /* For libusb0 filter */
  294. static int get_interface_details_filter(struct libusb_context *ctx, HDEVINFO *dev_info,
  295. DWORD _index, char *filter_path, char **dev_interface_path)
  296. {
  297. const GUID *libusb0_guid = &GUID_DEVINTERFACE_LIBUSB0_FILTER;
  298. SP_DEVICE_INTERFACE_DATA dev_interface_data;
  299. PSP_DEVICE_INTERFACE_DETAIL_DATA_A dev_interface_details;
  300. HKEY hkey_dev_interface;
  301. DWORD size;
  302. int err = LIBUSB_ERROR_OTHER;
  303. if (_index == 0) {
  304. *dev_info = pSetupDiGetClassDevsA(libusb0_guid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
  305. if (*dev_info == INVALID_HANDLE_VALUE) {
  306. usbi_err(ctx, "could not obtain device info set: %s", windows_error_str(0));
  307. return LIBUSB_ERROR_OTHER;
  308. }
  309. }
  310. dev_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
  311. if (!pSetupDiEnumDeviceInterfaces(*dev_info, NULL, libusb0_guid, _index, &dev_interface_data)) {
  312. if (GetLastError() != ERROR_NO_MORE_ITEMS) {
  313. usbi_err(ctx, "Could not obtain interface data for index %lu: %s",
  314. ULONG_CAST(_index), windows_error_str(0));
  315. goto err_exit;
  316. }
  317. pSetupDiDestroyDeviceInfoList(*dev_info);
  318. *dev_info = INVALID_HANDLE_VALUE;
  319. return LIBUSB_SUCCESS;
  320. }
  321. // Read interface data (dummy + actual) to access the device path
  322. if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, NULL, 0, &size, NULL)) {
  323. // The dummy call should fail with ERROR_INSUFFICIENT_BUFFER
  324. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
  325. usbi_err(ctx, "could not access interface data (dummy) for index %lu: %s",
  326. ULONG_CAST(_index), windows_error_str(0));
  327. goto err_exit;
  328. }
  329. } else {
  330. usbi_err(ctx, "program assertion failed - http://msdn.microsoft.com/en-us/library/ms792901.aspx is wrong");
  331. goto err_exit;
  332. }
  333. dev_interface_details = malloc(size);
  334. if (dev_interface_details == NULL) {
  335. usbi_err(ctx, "could not allocate interface data for index %lu", ULONG_CAST(_index));
  336. err = LIBUSB_ERROR_NO_MEM;
  337. goto err_exit;
  338. }
  339. dev_interface_details->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
  340. if (!pSetupDiGetDeviceInterfaceDetailA(*dev_info, &dev_interface_data, dev_interface_details, size, NULL, NULL)) {
  341. usbi_err(ctx, "could not access interface data (actual) for index %lu: %s",
  342. ULONG_CAST(_index), windows_error_str(0));
  343. free(dev_interface_details);
  344. goto err_exit;
  345. }
  346. *dev_interface_path = normalize_path(dev_interface_details->DevicePath);
  347. free(dev_interface_details);
  348. if (*dev_interface_path == NULL) {
  349. usbi_err(ctx, "could not allocate interface path for index %lu", ULONG_CAST(_index));
  350. err = LIBUSB_ERROR_NO_MEM;
  351. goto err_exit;
  352. }
  353. // [trobinso] lookup the libusb0 symbolic index.
  354. hkey_dev_interface = pSetupDiOpenDeviceInterfaceRegKey(*dev_info, &dev_interface_data, 0, KEY_READ);
  355. if (hkey_dev_interface != INVALID_HANDLE_VALUE) {
  356. DWORD libusb0_symboliclink_index = 0;
  357. DWORD value_length = sizeof(DWORD);
  358. LONG status;
  359. status = pRegQueryValueExA(hkey_dev_interface, "LUsb0", NULL, NULL,
  360. (LPBYTE)&libusb0_symboliclink_index, &value_length);
  361. if (status == ERROR_SUCCESS) {
  362. if (libusb0_symboliclink_index < 256) {
  363. // libusb0.sys is connected to this device instance.
  364. // If the the device interface guid is {F9F3FF14-AE21-48A0-8A25-8011A7A931D9} then it's a filter.
  365. sprintf(filter_path, "\\\\.\\libusb0-%04u", (unsigned int)libusb0_symboliclink_index);
  366. usbi_dbg(ctx, "assigned libusb0 symbolic link %s", filter_path);
  367. } else {
  368. // libusb0.sys was connected to this device instance at one time; but not anymore.
  369. }
  370. }
  371. pRegCloseKey(hkey_dev_interface);
  372. } else {
  373. usbi_warn(ctx, "could not open device interface registry key for index %lu: %s",
  374. ULONG_CAST(_index), windows_error_str(0));
  375. // TODO: should this be an error?
  376. }
  377. return LIBUSB_SUCCESS;
  378. err_exit:
  379. pSetupDiDestroyDeviceInfoList(*dev_info);
  380. *dev_info = INVALID_HANDLE_VALUE;
  381. return err;
  382. }
  383. /*
  384. * Returns the first known ancestor of a device
  385. */
  386. static struct libusb_device *get_ancestor(struct libusb_context *ctx,
  387. DEVINST devinst, PDEVINST _parent_devinst)
  388. {
  389. struct libusb_device *dev = NULL;
  390. DEVINST parent_devinst;
  391. while (dev == NULL) {
  392. if (CM_Get_Parent(&parent_devinst, devinst, 0) != CR_SUCCESS)
  393. break;
  394. devinst = parent_devinst;
  395. dev = usbi_get_device_by_session_id(ctx, (unsigned long)devinst);
  396. }
  397. if ((dev != NULL) && (_parent_devinst != NULL))
  398. *_parent_devinst = devinst;
  399. return dev;
  400. }
  401. /*
  402. * Determine which interface the given endpoint address belongs to
  403. */
  404. static int get_interface_by_endpoint(struct libusb_config_descriptor *conf_desc, uint8_t ep)
  405. {
  406. const struct libusb_interface *intf;
  407. const struct libusb_interface_descriptor *intf_desc;
  408. uint8_t i, k;
  409. int j;
  410. for (i = 0; i < conf_desc->bNumInterfaces; i++) {
  411. intf = &conf_desc->interface[i];
  412. for (j = 0; j < intf->num_altsetting; j++) {
  413. intf_desc = &intf->altsetting[j];
  414. for (k = 0; k < intf_desc->bNumEndpoints; k++) {
  415. if (intf_desc->endpoint[k].bEndpointAddress == ep) {
  416. usbi_dbg(NULL, "found endpoint %02X on interface %d", intf_desc->bInterfaceNumber, i);
  417. return intf_desc->bInterfaceNumber;
  418. }
  419. }
  420. }
  421. }
  422. usbi_dbg(NULL, "endpoint %02X not found on any interface", ep);
  423. return LIBUSB_ERROR_NOT_FOUND;
  424. }
  425. /*
  426. * Open a device and associate the HANDLE with the context's I/O completion port
  427. */
  428. static HANDLE windows_open(struct libusb_device_handle *dev_handle, const char *path, DWORD access)
  429. {
  430. struct libusb_context *ctx = HANDLE_CTX(dev_handle);
  431. struct windows_context_priv *priv = usbi_get_context_priv(ctx);
  432. HANDLE handle;
  433. handle = CreateFileA(path, access, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
  434. if (handle == INVALID_HANDLE_VALUE)
  435. return handle;
  436. if (CreateIoCompletionPort(handle, priv->completion_port, (ULONG_PTR)dev_handle, 0) == NULL) {
  437. usbi_err(ctx, "failed to associate handle to I/O completion port: %s", windows_error_str(0));
  438. CloseHandle(handle);
  439. return INVALID_HANDLE_VALUE;
  440. }
  441. return handle;
  442. }
  443. /*
  444. * Populate the endpoints addresses of the device_priv interface helper structs
  445. */
  446. static int windows_assign_endpoints(struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting)
  447. {
  448. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  449. struct libusb_config_descriptor *conf_desc;
  450. const struct libusb_interface_descriptor *if_desc;
  451. int i, r;
  452. r = libusb_get_active_config_descriptor(dev_handle->dev, &conf_desc);
  453. if (r != LIBUSB_SUCCESS) {
  454. usbi_warn(HANDLE_CTX(dev_handle), "could not read config descriptor: error %d", r);
  455. return r;
  456. }
  457. if (iface >= conf_desc->bNumInterfaces) {
  458. usbi_err(HANDLE_CTX(dev_handle), "interface %d out of range for device", iface);
  459. return LIBUSB_ERROR_NOT_FOUND;
  460. }
  461. if_desc = &conf_desc->interface[iface].altsetting[altsetting];
  462. safe_free(priv->usb_interface[iface].endpoint);
  463. if (if_desc->bNumEndpoints == 0) {
  464. usbi_dbg(HANDLE_CTX(dev_handle), "no endpoints found for interface %u", iface);
  465. } else {
  466. priv->usb_interface[iface].endpoint = malloc(if_desc->bNumEndpoints);
  467. if (priv->usb_interface[iface].endpoint == NULL) {
  468. libusb_free_config_descriptor(conf_desc);
  469. return LIBUSB_ERROR_NO_MEM;
  470. }
  471. priv->usb_interface[iface].nb_endpoints = if_desc->bNumEndpoints;
  472. for (i = 0; i < if_desc->bNumEndpoints; i++) {
  473. priv->usb_interface[iface].endpoint[i] = if_desc->endpoint[i].bEndpointAddress;
  474. usbi_dbg(HANDLE_CTX(dev_handle), "(re)assigned endpoint %02X to interface %u", priv->usb_interface[iface].endpoint[i], iface);
  475. }
  476. }
  477. libusb_free_config_descriptor(conf_desc);
  478. // Extra init may be required to configure endpoints
  479. if (priv->apib->configure_endpoints)
  480. r = priv->apib->configure_endpoints(SUB_API_NOTSET, dev_handle, iface);
  481. if (r == LIBUSB_SUCCESS)
  482. priv->usb_interface[iface].current_altsetting = altsetting;
  483. return r;
  484. }
  485. // Lookup for a match in the list of API driver names
  486. // return -1 if not found, driver match number otherwise
  487. static int get_sub_api(char *driver, int api)
  488. {
  489. const char sep_str[2] = {LIST_SEPARATOR, 0};
  490. char *tok, *tmp_str;
  491. size_t len = strlen(driver);
  492. int i;
  493. if (len == 0)
  494. return SUB_API_NOTSET;
  495. tmp_str = _strdup(driver);
  496. if (tmp_str == NULL)
  497. return SUB_API_NOTSET;
  498. tok = strtok(tmp_str, sep_str);
  499. while (tok != NULL) {
  500. for (i = 0; i < usb_api_backend[api].nb_driver_names; i++) {
  501. if (_stricmp(tok, usb_api_backend[api].driver_name_list[i]) == 0) {
  502. free(tmp_str);
  503. return i;
  504. }
  505. }
  506. tok = strtok(NULL, sep_str);
  507. }
  508. free(tmp_str);
  509. return SUB_API_NOTSET;
  510. }
  511. /*
  512. * auto-claiming and auto-release helper functions
  513. */
  514. static int auto_claim(struct libusb_transfer *transfer, int *interface_number, int api_type)
  515. {
  516. struct winusb_device_handle_priv *handle_priv =
  517. get_winusb_device_handle_priv(transfer->dev_handle);
  518. struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
  519. int current_interface = *interface_number;
  520. int r = LIBUSB_SUCCESS;
  521. switch (api_type) {
  522. case USB_API_WINUSBX:
  523. case USB_API_HID:
  524. break;
  525. default:
  526. return LIBUSB_ERROR_INVALID_PARAM;
  527. }
  528. usbi_mutex_lock(&autoclaim_lock);
  529. if (current_interface < 0) { // No serviceable interface was found
  530. for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
  531. // Must claim an interface of the same API type
  532. if ((priv->usb_interface[current_interface].apib->id == api_type)
  533. && (libusb_claim_interface(transfer->dev_handle, current_interface) == LIBUSB_SUCCESS)) {
  534. usbi_dbg(TRANSFER_CTX(transfer), "auto-claimed interface %d for control request", current_interface);
  535. if (handle_priv->autoclaim_count[current_interface] != 0)
  536. usbi_err(TRANSFER_CTX(transfer), "program assertion failed - autoclaim_count was nonzero");
  537. handle_priv->autoclaim_count[current_interface]++;
  538. break;
  539. }
  540. }
  541. if (current_interface == USB_MAXINTERFACES) {
  542. usbi_err(TRANSFER_CTX(transfer), "could not auto-claim any interface");
  543. r = LIBUSB_ERROR_NOT_FOUND;
  544. }
  545. } else {
  546. // If we have a valid interface that was autoclaimed, we must increment
  547. // its autoclaim count so that we can prevent an early release.
  548. if (handle_priv->autoclaim_count[current_interface] != 0)
  549. handle_priv->autoclaim_count[current_interface]++;
  550. }
  551. usbi_mutex_unlock(&autoclaim_lock);
  552. *interface_number = current_interface;
  553. return r;
  554. }
  555. static void auto_release(struct usbi_transfer *itransfer)
  556. {
  557. struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
  558. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  559. libusb_device_handle *dev_handle = transfer->dev_handle;
  560. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  561. int r;
  562. usbi_mutex_lock(&autoclaim_lock);
  563. if (handle_priv->autoclaim_count[transfer_priv->interface_number] > 0) {
  564. handle_priv->autoclaim_count[transfer_priv->interface_number]--;
  565. if (handle_priv->autoclaim_count[transfer_priv->interface_number] == 0) {
  566. r = libusb_release_interface(dev_handle, transfer_priv->interface_number);
  567. if (r == LIBUSB_SUCCESS)
  568. usbi_dbg(ITRANSFER_CTX(itransfer), "auto-released interface %d", transfer_priv->interface_number);
  569. else
  570. usbi_dbg(ITRANSFER_CTX(itransfer), "failed to auto-release interface %d (%s)",
  571. transfer_priv->interface_number, libusb_error_name((enum libusb_error)r));
  572. }
  573. }
  574. usbi_mutex_unlock(&autoclaim_lock);
  575. }
  576. /*
  577. * init: libusb backend init function
  578. */
  579. static int winusb_init(struct libusb_context *ctx)
  580. {
  581. int i;
  582. // Load DLL imports
  583. if (!init_dlls(ctx)) {
  584. usbi_err(ctx, "could not resolve DLL functions");
  585. return LIBUSB_ERROR_OTHER;
  586. }
  587. // Initialize the low level APIs (we don't care about errors at this stage)
  588. for (i = 0; i < USB_API_MAX; i++) {
  589. if (usb_api_backend[i].init && !usb_api_backend[i].init(ctx))
  590. usbi_warn(ctx, "error initializing %s backend",
  591. usb_api_backend[i].designation);
  592. }
  593. // We need a lock for proper auto-release
  594. usbi_mutex_init(&autoclaim_lock);
  595. return LIBUSB_SUCCESS;
  596. }
  597. /*
  598. * exit: libusb backend deinitialization function
  599. */
  600. static void winusb_exit(struct libusb_context *ctx)
  601. {
  602. int i;
  603. UNUSED(ctx);
  604. usbi_mutex_destroy(&autoclaim_lock);
  605. for (i = 0; i < USB_API_MAX; i++) {
  606. if (usb_api_backend[i].exit)
  607. usb_api_backend[i].exit();
  608. }
  609. exit_dlls();
  610. }
  611. /*
  612. * fetch and cache all the config descriptors through I/O
  613. */
  614. static void cache_config_descriptors(struct libusb_device *dev, HANDLE hub_handle)
  615. {
  616. struct libusb_context *ctx = DEVICE_CTX(dev);
  617. struct winusb_device_priv *priv = usbi_get_device_priv(dev);
  618. DWORD size, ret_size;
  619. uint8_t i, num_configurations;
  620. USB_CONFIGURATION_DESCRIPTOR_SHORT cd_buf_short; // dummy request
  621. PUSB_DESCRIPTOR_REQUEST cd_buf_actual = NULL; // actual request
  622. PUSB_CONFIGURATION_DESCRIPTOR cd_data;
  623. num_configurations = dev->device_descriptor.bNumConfigurations;
  624. if (num_configurations == 0)
  625. return;
  626. assert(sizeof(USB_DESCRIPTOR_REQUEST) == USB_DESCRIPTOR_REQUEST_SIZE);
  627. priv->config_descriptor = calloc(num_configurations, sizeof(PUSB_CONFIGURATION_DESCRIPTOR));
  628. if (priv->config_descriptor == NULL) {
  629. usbi_err(ctx, "could not allocate configuration descriptor array for '%s'", priv->dev_id);
  630. return;
  631. }
  632. for (i = 0; i <= num_configurations; i++) {
  633. safe_free(cd_buf_actual);
  634. if (i == num_configurations)
  635. break;
  636. size = sizeof(cd_buf_short);
  637. memset(&cd_buf_short.desc, 0, sizeof(cd_buf_short.desc));
  638. cd_buf_short.req.ConnectionIndex = (ULONG)dev->port_number;
  639. cd_buf_short.req.SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
  640. cd_buf_short.req.SetupPacket.bRequest = LIBUSB_REQUEST_GET_DESCRIPTOR;
  641. cd_buf_short.req.SetupPacket.wValue = (LIBUSB_DT_CONFIG << 8) | i;
  642. cd_buf_short.req.SetupPacket.wIndex = 0;
  643. cd_buf_short.req.SetupPacket.wLength = (USHORT)sizeof(USB_CONFIGURATION_DESCRIPTOR);
  644. // Dummy call to get the required data size. Initial failures are reported as info rather
  645. // than error as they can occur for non-penalizing situations, such as with some hubs.
  646. // coverity[tainted_data_argument]
  647. if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, &cd_buf_short, size,
  648. &cd_buf_short, size, &ret_size, NULL)) {
  649. usbi_info(ctx, "could not access configuration descriptor %u (dummy) for '%s': %s", i, priv->dev_id, windows_error_str(0));
  650. continue;
  651. }
  652. if ((ret_size != size) || (cd_buf_short.desc.wTotalLength < sizeof(USB_CONFIGURATION_DESCRIPTOR))) {
  653. usbi_info(ctx, "unexpected configuration descriptor %u size (dummy) for '%s'", i, priv->dev_id);
  654. continue;
  655. }
  656. size = sizeof(USB_DESCRIPTOR_REQUEST) + cd_buf_short.desc.wTotalLength;
  657. cd_buf_actual = malloc(size);
  658. if (cd_buf_actual == NULL) {
  659. usbi_err(ctx, "could not allocate configuration descriptor %u buffer for '%s'", i, priv->dev_id);
  660. continue;
  661. }
  662. // Actual call
  663. cd_buf_actual->ConnectionIndex = (ULONG)dev->port_number;
  664. cd_buf_actual->SetupPacket.bmRequest = LIBUSB_ENDPOINT_IN;
  665. cd_buf_actual->SetupPacket.bRequest = LIBUSB_REQUEST_GET_DESCRIPTOR;
  666. cd_buf_actual->SetupPacket.wValue = (LIBUSB_DT_CONFIG << 8) | i;
  667. cd_buf_actual->SetupPacket.wIndex = 0;
  668. cd_buf_actual->SetupPacket.wLength = cd_buf_short.desc.wTotalLength;
  669. if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, cd_buf_actual, size,
  670. cd_buf_actual, size, &ret_size, NULL)) {
  671. usbi_err(ctx, "could not access configuration descriptor %u (actual) for '%s': %s", i, priv->dev_id, windows_error_str(0));
  672. continue;
  673. }
  674. cd_data = (PUSB_CONFIGURATION_DESCRIPTOR)((UCHAR *)cd_buf_actual + USB_DESCRIPTOR_REQUEST_SIZE);
  675. if ((size != ret_size) || (cd_data->wTotalLength != cd_buf_short.desc.wTotalLength)) {
  676. usbi_err(ctx, "unexpected configuration descriptor %u size (actual) for '%s'", i, priv->dev_id);
  677. continue;
  678. }
  679. if (cd_data->bDescriptorType != LIBUSB_DT_CONFIG) {
  680. usbi_err(ctx, "descriptor %u not a configuration descriptor for '%s'", i, priv->dev_id);
  681. continue;
  682. }
  683. usbi_dbg(ctx, "cached config descriptor %u (bConfigurationValue=%u, %u bytes)",
  684. i, cd_data->bConfigurationValue, cd_data->wTotalLength);
  685. // Cache the descriptor
  686. priv->config_descriptor[i] = cd_data;
  687. cd_buf_actual = NULL;
  688. }
  689. }
  690. #define ROOT_HUB_FS_CONFIG_DESC_LENGTH 0x19
  691. #define ROOT_HUB_HS_CONFIG_DESC_LENGTH 0x19
  692. #define ROOT_HUB_SS_CONFIG_DESC_LENGTH 0x1f
  693. #define CONFIG_DESC_WTOTAL_LENGTH_OFFSET 0x02
  694. #define CONFIG_DESC_EP_MAX_PACKET_OFFSET 0x16
  695. #define CONFIG_DESC_EP_BINTERVAL_OFFSET 0x18
  696. static const uint8_t root_hub_config_descriptor_template[] = {
  697. // Configuration Descriptor
  698. LIBUSB_DT_CONFIG_SIZE, // bLength
  699. LIBUSB_DT_CONFIG, // bDescriptorType
  700. 0x00, 0x00, // wTotalLength (filled in)
  701. 0x01, // bNumInterfaces
  702. 0x01, // bConfigurationValue
  703. 0x00, // iConfiguration
  704. 0xc0, // bmAttributes (reserved + self-powered)
  705. 0x00, // bMaxPower
  706. // Interface Descriptor
  707. LIBUSB_DT_INTERFACE_SIZE, // bLength
  708. LIBUSB_DT_INTERFACE, // bDescriptorType
  709. 0x00, // bInterfaceNumber
  710. 0x00, // bAlternateSetting
  711. 0x01, // bNumEndpoints
  712. LIBUSB_CLASS_HUB, // bInterfaceClass
  713. 0x00, // bInterfaceSubClass
  714. 0x00, // bInterfaceProtocol
  715. 0x00, // iInterface
  716. // Endpoint Descriptor
  717. LIBUSB_DT_ENDPOINT_SIZE, // bLength
  718. LIBUSB_DT_ENDPOINT, // bDescriptorType
  719. 0x81, // bEndpointAddress
  720. 0x03, // bmAttributes (Interrupt)
  721. 0x00, 0x00, // wMaxPacketSize (filled in)
  722. 0x00, // bInterval (filled in)
  723. // SuperSpeed Endpoint Companion Descriptor
  724. LIBUSB_DT_SS_ENDPOINT_COMPANION_SIZE, // bLength
  725. LIBUSB_DT_SS_ENDPOINT_COMPANION, // bDescriptorType
  726. 0x00, // bMaxBurst
  727. 0x00, // bmAttributes
  728. 0x02, 0x00 // wBytesPerInterval
  729. };
  730. static int alloc_root_hub_config_desc(struct libusb_device *dev, ULONG num_ports,
  731. uint8_t config_desc_length, uint8_t ep_interval)
  732. {
  733. struct winusb_device_priv *priv = usbi_get_device_priv(dev);
  734. uint8_t *ptr;
  735. priv->config_descriptor = malloc(sizeof(*priv->config_descriptor));
  736. if (priv->config_descriptor == NULL)
  737. return LIBUSB_ERROR_NO_MEM;
  738. // Most config descriptors come from cache_config_descriptors() which obtains the
  739. // descriptors from the hub using an allocated USB_DESCRIPTOR_REQUEST structure.
  740. // To avoid an extra malloc + memcpy we just hold on to the USB_DESCRIPTOR_REQUEST
  741. // structure we already have and back up the pointer in windows_device_priv_release()
  742. // when freeing the descriptors. To keep a single execution path, we need to offset
  743. // the pointer here by the same amount.
  744. ptr = malloc(USB_DESCRIPTOR_REQUEST_SIZE + config_desc_length);
  745. if (ptr == NULL)
  746. return LIBUSB_ERROR_NO_MEM;
  747. ptr += USB_DESCRIPTOR_REQUEST_SIZE;
  748. memcpy(ptr, root_hub_config_descriptor_template, config_desc_length);
  749. ptr[CONFIG_DESC_WTOTAL_LENGTH_OFFSET] = config_desc_length;
  750. ptr[CONFIG_DESC_EP_MAX_PACKET_OFFSET] = (uint8_t)((num_ports + 7) / 8);
  751. ptr[CONFIG_DESC_EP_BINTERVAL_OFFSET] = ep_interval;
  752. priv->config_descriptor[0] = (PUSB_CONFIGURATION_DESCRIPTOR)ptr;
  753. priv->active_config = 1;
  754. return 0;
  755. }
  756. static int init_root_hub(struct libusb_device *dev)
  757. {
  758. struct libusb_context *ctx = DEVICE_CTX(dev);
  759. struct winusb_device_priv *priv = usbi_get_device_priv(dev);
  760. USB_NODE_CONNECTION_INFORMATION_EX conn_info;
  761. USB_NODE_CONNECTION_INFORMATION_EX_V2 conn_info_v2;
  762. USB_NODE_INFORMATION hub_info;
  763. enum libusb_speed speed = LIBUSB_SPEED_UNKNOWN;
  764. uint8_t config_desc_length;
  765. uint8_t ep_interval;
  766. HANDLE handle;
  767. ULONG port_number, num_ports;
  768. DWORD size;
  769. int r;
  770. // Determining the speed of a root hub is painful. Microsoft does not directly report the speed
  771. // capabilities of the root hub itself, only its ports and/or connected devices. Therefore we
  772. // are forced to query each individual port of the root hub to try and infer the root hub's
  773. // speed. Note that we have to query all ports because the presence of a device on that port
  774. // changes if/how Windows returns any useful speed information.
  775. handle = CreateFileA(priv->path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
  776. if (handle == INVALID_HANDLE_VALUE) {
  777. usbi_err(ctx, "could not open root hub %s: %s", priv->path, windows_error_str(0));
  778. return LIBUSB_ERROR_ACCESS;
  779. }
  780. if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_INFORMATION, NULL, 0, &hub_info, sizeof(hub_info), &size, NULL)) {
  781. usbi_warn(ctx, "could not get root hub info for '%s': %s", priv->dev_id, windows_error_str(0));
  782. CloseHandle(handle);
  783. return LIBUSB_ERROR_ACCESS;
  784. }
  785. num_ports = hub_info.u.HubInformation.HubDescriptor.bNumberOfPorts;
  786. usbi_dbg(ctx, "root hub '%s' reports %lu ports", priv->dev_id, ULONG_CAST(num_ports));
  787. if (windows_version >= WINDOWS_8) {
  788. // Windows 8 and later is better at reporting the speed capabilities of the root hub,
  789. // but it is not perfect. If no device is attached to the port being queried, the
  790. // returned information will only indicate whether that port supports USB 3.0 signalling.
  791. // That is not enough information to distinguish between SuperSpeed and SuperSpeed Plus.
  792. for (port_number = 1; port_number <= num_ports; port_number++) {
  793. conn_info_v2.ConnectionIndex = port_number;
  794. conn_info_v2.Length = sizeof(conn_info_v2);
  795. conn_info_v2.SupportedUsbProtocols.Usb300 = 1;
  796. if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX_V2,
  797. &conn_info_v2, sizeof(conn_info_v2), &conn_info_v2, sizeof(conn_info_v2), &size, NULL)) {
  798. usbi_warn(ctx, "could not get node connection information (V2) for root hub '%s' port %lu: %s",
  799. priv->dev_id, ULONG_CAST(port_number), windows_error_str(0));
  800. break;
  801. }
  802. if (conn_info_v2.Flags.DeviceIsSuperSpeedPlusCapableOrHigher)
  803. speed = MAX(speed, LIBUSB_SPEED_SUPER_PLUS);
  804. else if (conn_info_v2.Flags.DeviceIsSuperSpeedCapableOrHigher || conn_info_v2.SupportedUsbProtocols.Usb300)
  805. speed = MAX(speed, LIBUSB_SPEED_SUPER);
  806. else if (conn_info_v2.SupportedUsbProtocols.Usb200)
  807. speed = MAX(speed, LIBUSB_SPEED_HIGH);
  808. else
  809. speed = MAX(speed, LIBUSB_SPEED_FULL);
  810. }
  811. if (speed != LIBUSB_SPEED_UNKNOWN)
  812. goto make_descriptors;
  813. }
  814. // At this point the speed is still not known, most likely because we are executing on
  815. // Windows 7 or earlier. The following hackery peeks into the root hub's Device ID and
  816. // tries to extract speed information from it, based on observed naming conventions.
  817. // If this does not work, we will query individual ports of the root hub.
  818. if (strstr(priv->dev_id, "ROOT_HUB31") != NULL)
  819. speed = LIBUSB_SPEED_SUPER_PLUS;
  820. else if (strstr(priv->dev_id, "ROOT_HUB30") != NULL)
  821. speed = LIBUSB_SPEED_SUPER;
  822. else if (strstr(priv->dev_id, "ROOT_HUB20") != NULL)
  823. speed = LIBUSB_SPEED_HIGH;
  824. if (speed != LIBUSB_SPEED_UNKNOWN)
  825. goto make_descriptors;
  826. // Windows only reports speed information about a connected device. This means that a root
  827. // hub with no connected devices or devices that are all operating at a speed less than the
  828. // highest speed that the root hub supports will not give us the correct speed.
  829. for (port_number = 1; port_number <= num_ports; port_number++) {
  830. conn_info.ConnectionIndex = port_number;
  831. if (!DeviceIoControl(handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, &conn_info, sizeof(conn_info),
  832. &conn_info, sizeof(conn_info), &size, NULL)) {
  833. usbi_warn(ctx, "could not get node connection information for root hub '%s' port %lu: %s",
  834. priv->dev_id, ULONG_CAST(port_number), windows_error_str(0));
  835. continue;
  836. }
  837. if (conn_info.ConnectionStatus != DeviceConnected)
  838. continue;
  839. if (conn_info.Speed == UsbHighSpeed) {
  840. speed = LIBUSB_SPEED_HIGH;
  841. break;
  842. }
  843. }
  844. make_descriptors:
  845. CloseHandle(handle);
  846. dev->device_descriptor.bLength = LIBUSB_DT_DEVICE_SIZE;
  847. dev->device_descriptor.bDescriptorType = LIBUSB_DT_DEVICE;
  848. dev->device_descriptor.bDeviceClass = LIBUSB_CLASS_HUB;
  849. if ((dev->device_descriptor.idVendor == 0) && (dev->device_descriptor.idProduct == 0)) {
  850. dev->device_descriptor.idVendor = 0x1d6b; // Linux Foundation
  851. dev->device_descriptor.idProduct = (uint16_t)speed;
  852. }
  853. dev->device_descriptor.bcdDevice = 0x0100;
  854. dev->device_descriptor.bNumConfigurations = 1;
  855. switch (speed) {
  856. case LIBUSB_SPEED_SUPER_PLUS:
  857. dev->device_descriptor.bcdUSB = 0x0310;
  858. config_desc_length = ROOT_HUB_SS_CONFIG_DESC_LENGTH;
  859. ep_interval = 0x0c; // 256ms
  860. break;
  861. case LIBUSB_SPEED_SUPER:
  862. dev->device_descriptor.bcdUSB = 0x0300;
  863. config_desc_length = ROOT_HUB_SS_CONFIG_DESC_LENGTH;
  864. ep_interval = 0x0c; // 256ms
  865. break;
  866. case LIBUSB_SPEED_HIGH:
  867. dev->device_descriptor.bcdUSB = 0x0200;
  868. config_desc_length = ROOT_HUB_HS_CONFIG_DESC_LENGTH;
  869. ep_interval = 0x0c; // 256ms
  870. break;
  871. case LIBUSB_SPEED_LOW: // Not used, but keeps compiler happy
  872. case LIBUSB_SPEED_UNKNOWN:
  873. // This case means absolutely no information about this root hub was determined.
  874. // There is not much choice than to be pessimistic and label this as a
  875. // full-speed device.
  876. speed = LIBUSB_SPEED_FULL;
  877. // fallthrough
  878. case LIBUSB_SPEED_FULL:
  879. dev->device_descriptor.bcdUSB = 0x0110;
  880. config_desc_length = ROOT_HUB_FS_CONFIG_DESC_LENGTH;
  881. ep_interval = 0xff; // 255ms
  882. break;
  883. default: // Impossible, buts keeps compiler happy
  884. usbi_err(ctx, "program assertion failed - unknown root hub speed");
  885. return LIBUSB_ERROR_INVALID_PARAM;
  886. }
  887. if (speed >= LIBUSB_SPEED_SUPER) {
  888. dev->device_descriptor.bDeviceProtocol = 0x03; // USB 3.0 Hub
  889. dev->device_descriptor.bMaxPacketSize0 = 0x09; // 2^9 bytes
  890. } else {
  891. dev->device_descriptor.bMaxPacketSize0 = 0x40; // 64 bytes
  892. }
  893. dev->speed = speed;
  894. r = alloc_root_hub_config_desc(dev, num_ports, config_desc_length, ep_interval);
  895. if (r)
  896. usbi_err(ctx, "could not allocate config descriptor for root hub '%s'", priv->dev_id);
  897. return r;
  898. }
  899. /*
  900. * Populate a libusb device structure
  901. */
  902. static int init_device(struct libusb_device *dev, struct libusb_device *parent_dev,
  903. uint8_t port_number, DEVINST devinst)
  904. {
  905. struct libusb_context *ctx = NULL;
  906. struct libusb_device *tmp_dev;
  907. struct winusb_device_priv *priv, *parent_priv, *tmp_priv;
  908. USB_NODE_CONNECTION_INFORMATION_EX conn_info;
  909. USB_NODE_CONNECTION_INFORMATION_EX_V2 conn_info_v2;
  910. HANDLE hub_handle;
  911. DWORD size;
  912. uint8_t bus_number, depth;
  913. int r;
  914. int ginfotimeout;
  915. priv = usbi_get_device_priv(dev);
  916. // If the device is already initialized, we can stop here
  917. if (priv->initialized)
  918. return LIBUSB_SUCCESS;
  919. if (parent_dev != NULL) { // Not a HCD root hub
  920. ctx = DEVICE_CTX(dev);
  921. parent_priv = usbi_get_device_priv(parent_dev);
  922. if (parent_priv->apib->id != USB_API_HUB) {
  923. usbi_warn(ctx, "parent for device '%s' is not a hub", priv->dev_id);
  924. return LIBUSB_ERROR_NOT_FOUND;
  925. }
  926. // Calculate depth and fetch bus number
  927. bus_number = parent_dev->bus_number;
  928. if (bus_number == 0) {
  929. tmp_dev = get_ancestor(ctx, devinst, &devinst);
  930. if (tmp_dev != parent_dev) {
  931. usbi_err(ctx, "program assertion failed - first ancestor is not parent");
  932. return LIBUSB_ERROR_NOT_FOUND;
  933. }
  934. libusb_unref_device(tmp_dev);
  935. for (depth = 1; bus_number == 0; depth++) {
  936. tmp_dev = get_ancestor(ctx, devinst, &devinst);
  937. if (tmp_dev == NULL) {
  938. usbi_warn(ctx, "ancestor for device '%s' not found at depth %u", priv->dev_id, depth);
  939. return LIBUSB_ERROR_NO_DEVICE;
  940. }
  941. if (tmp_dev->bus_number != 0) {
  942. bus_number = tmp_dev->bus_number;
  943. tmp_priv = usbi_get_device_priv(tmp_dev);
  944. depth += tmp_priv->depth;
  945. }
  946. libusb_unref_device(tmp_dev);
  947. }
  948. } else {
  949. depth = parent_priv->depth + 1;
  950. }
  951. if (bus_number == 0) {
  952. usbi_err(ctx, "program assertion failed - bus number not found for '%s'", priv->dev_id);
  953. return LIBUSB_ERROR_NOT_FOUND;
  954. }
  955. dev->bus_number = bus_number;
  956. dev->port_number = port_number;
  957. dev->parent_dev = parent_dev;
  958. priv->depth = depth;
  959. hub_handle = CreateFileA(parent_priv->path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
  960. if (hub_handle == INVALID_HANDLE_VALUE) {
  961. usbi_warn(ctx, "could not open hub %s: %s", parent_priv->path, windows_error_str(0));
  962. return LIBUSB_ERROR_ACCESS;
  963. }
  964. conn_info.ConnectionIndex = (ULONG)port_number;
  965. // coverity[tainted_data_argument]
  966. ginfotimeout = 20;
  967. do {
  968. if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, &conn_info, sizeof(conn_info),
  969. &conn_info, sizeof(conn_info), &size, NULL)) {
  970. usbi_warn(ctx, "could not get node connection information for device '%s': %s",
  971. priv->dev_id, windows_error_str(0));
  972. CloseHandle(hub_handle);
  973. return LIBUSB_ERROR_NO_DEVICE;
  974. }
  975. if (conn_info.ConnectionStatus == NoDeviceConnected) {
  976. usbi_err(ctx, "device '%s' is no longer connected!", priv->dev_id);
  977. CloseHandle(hub_handle);
  978. return LIBUSB_ERROR_NO_DEVICE;
  979. }
  980. if ((conn_info.DeviceDescriptor.bLength != LIBUSB_DT_DEVICE_SIZE)
  981. || (conn_info.DeviceDescriptor.bDescriptorType != LIBUSB_DT_DEVICE)) {
  982. SleepEx(50, TRUE);
  983. continue;
  984. }
  985. static_assert(sizeof(dev->device_descriptor) == sizeof(conn_info.DeviceDescriptor),
  986. "mismatch between libusb and OS device descriptor sizes");
  987. memcpy(&dev->device_descriptor, &conn_info.DeviceDescriptor, LIBUSB_DT_DEVICE_SIZE);
  988. usbi_localize_device_descriptor(&dev->device_descriptor);
  989. priv->active_config = conn_info.CurrentConfigurationValue;
  990. if (priv->active_config == 0) {
  991. usbi_dbg(ctx, "0x%x:0x%x found %u configurations (not configured)",
  992. dev->device_descriptor.idVendor,
  993. dev->device_descriptor.idProduct,
  994. dev->device_descriptor.bNumConfigurations);
  995. SleepEx(50, TRUE);
  996. }
  997. } while (priv->active_config == 0 && --ginfotimeout >= 0);
  998. if ((conn_info.DeviceDescriptor.bLength != LIBUSB_DT_DEVICE_SIZE)
  999. || (conn_info.DeviceDescriptor.bDescriptorType != LIBUSB_DT_DEVICE)) {
  1000. usbi_err(ctx, "device '%s' has invalid descriptor!", priv->dev_id);
  1001. CloseHandle(hub_handle);
  1002. return LIBUSB_ERROR_OTHER;
  1003. }
  1004. if (priv->active_config == 0) {
  1005. usbi_info(ctx, "0x%x:0x%x found %u configurations but device isn't configured, "
  1006. "forcing current configuration to 1",
  1007. dev->device_descriptor.idVendor,
  1008. dev->device_descriptor.idProduct,
  1009. dev->device_descriptor.bNumConfigurations);
  1010. priv->active_config = 1;
  1011. } else {
  1012. usbi_dbg(ctx, "found %u configurations (current config: %u)", dev->device_descriptor.bNumConfigurations, priv->active_config);
  1013. }
  1014. // Cache as many config descriptors as we can
  1015. cache_config_descriptors(dev, hub_handle);
  1016. // In their great wisdom, Microsoft decided to BREAK the USB speed report between Windows 7 and Windows 8
  1017. if (windows_version >= WINDOWS_8) {
  1018. conn_info_v2.ConnectionIndex = (ULONG)port_number;
  1019. conn_info_v2.Length = sizeof(USB_NODE_CONNECTION_INFORMATION_EX_V2);
  1020. conn_info_v2.SupportedUsbProtocols.Usb300 = 1;
  1021. if (!DeviceIoControl(hub_handle, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX_V2,
  1022. &conn_info_v2, sizeof(conn_info_v2), &conn_info_v2, sizeof(conn_info_v2), &size, NULL)) {
  1023. usbi_warn(ctx, "could not get node connection information (V2) for device '%s': %s",
  1024. priv->dev_id, windows_error_str(0));
  1025. } else if (conn_info_v2.Flags.DeviceIsOperatingAtSuperSpeedPlusOrHigher) {
  1026. conn_info.Speed = UsbSuperSpeedPlus;
  1027. } else if (conn_info_v2.Flags.DeviceIsOperatingAtSuperSpeedOrHigher) {
  1028. conn_info.Speed = UsbSuperSpeed;
  1029. }
  1030. }
  1031. CloseHandle(hub_handle);
  1032. if (conn_info.DeviceAddress > UINT8_MAX)
  1033. usbi_err(ctx, "program assertion failed - device address overflow");
  1034. dev->device_address = (uint8_t)conn_info.DeviceAddress;
  1035. switch (conn_info.Speed) {
  1036. case UsbLowSpeed: dev->speed = LIBUSB_SPEED_LOW; break;
  1037. case UsbFullSpeed: dev->speed = LIBUSB_SPEED_FULL; break;
  1038. case UsbHighSpeed: dev->speed = LIBUSB_SPEED_HIGH; break;
  1039. case UsbSuperSpeed: dev->speed = LIBUSB_SPEED_SUPER; break;
  1040. case UsbSuperSpeedPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
  1041. default:
  1042. usbi_warn(ctx, "unknown device speed %u", conn_info.Speed);
  1043. break;
  1044. }
  1045. } else {
  1046. r = init_root_hub(dev);
  1047. if (r)
  1048. return r;
  1049. }
  1050. r = usbi_sanitize_device(dev);
  1051. if (r)
  1052. return r;
  1053. priv->initialized = true;
  1054. usbi_dbg(ctx, "(bus: %u, addr: %u, depth: %u, port: %u): '%s'",
  1055. dev->bus_number, dev->device_address, priv->depth, dev->port_number, priv->dev_id);
  1056. return LIBUSB_SUCCESS;
  1057. }
  1058. static bool get_dev_port_number(HDEVINFO dev_info, SP_DEVINFO_DATA *dev_info_data, DWORD *port_nr)
  1059. {
  1060. char buffer[MAX_KEY_LENGTH];
  1061. DWORD size;
  1062. // First try SPDRP_LOCATION_INFORMATION, which returns a REG_SZ. The string *may* have a format
  1063. // similar to "Port_#0002.Hub_#000D", in which case we can extract the port number. However, we
  1064. // cannot extract the port if the returned string does not follow this format.
  1065. if (pSetupDiGetDeviceRegistryPropertyA(dev_info, dev_info_data, SPDRP_LOCATION_INFORMATION,
  1066. NULL, (PBYTE)buffer, sizeof(buffer), NULL)) {
  1067. // Check for the required format.
  1068. if (strncmp(buffer, "Port_#", 6) == 0) {
  1069. *port_nr = atoi(buffer + 6);
  1070. return true;
  1071. }
  1072. }
  1073. // Next try SPDRP_LOCATION_PATHS, which returns a REG_MULTI_SZ (but we only examine the first
  1074. // string in it). Each path has a format similar to,
  1075. // "PCIROOT(B2)#PCI(0300)#PCI(0000)#USBROOT(0)#USB(1)#USB(2)#USBMI(3)", and the port number is
  1076. // the number within the last "USB(x)" token.
  1077. if (pSetupDiGetDeviceRegistryPropertyA(dev_info, dev_info_data, SPDRP_LOCATION_PATHS,
  1078. NULL, (PBYTE)buffer, sizeof(buffer), NULL)) {
  1079. // Find the last "#USB(x)" substring
  1080. for (char *token = strrchr(buffer, '#'); token != NULL; token = strrchr(buffer, '#')) {
  1081. if (strncmp(token, "#USB(", 5) == 0) {
  1082. *port_nr = atoi(token + 5);
  1083. return true;
  1084. }
  1085. // Shorten the string and try again.
  1086. *token = '\0';
  1087. }
  1088. }
  1089. // Lastly, try SPDRP_ADDRESS, which returns a REG_DWORD. The address *may* be the port number,
  1090. // which is true for the Microsoft driver but may not be true for other drivers. However, we
  1091. // have no other options here but to accept what it returns.
  1092. return pSetupDiGetDeviceRegistryPropertyA(dev_info, dev_info_data, SPDRP_ADDRESS,
  1093. NULL, (PBYTE)port_nr, sizeof(*port_nr), &size) && (size == sizeof(*port_nr));
  1094. }
  1095. static int enumerate_hcd_root_hub(struct libusb_context *ctx, const char *dev_id,
  1096. uint8_t bus_number, DEVINST devinst)
  1097. {
  1098. struct libusb_device *dev;
  1099. struct winusb_device_priv *priv;
  1100. unsigned long session_id;
  1101. DEVINST child_devinst;
  1102. if (CM_Get_Child(&child_devinst, devinst, 0) != CR_SUCCESS) {
  1103. usbi_warn(ctx, "could not get child devinst for '%s'", dev_id);
  1104. return LIBUSB_SUCCESS;
  1105. }
  1106. session_id = (unsigned long)child_devinst;
  1107. dev = usbi_get_device_by_session_id(ctx, session_id);
  1108. if (dev == NULL) {
  1109. usbi_err(ctx, "program assertion failed - HCD '%s' child not found", dev_id);
  1110. return LIBUSB_SUCCESS;
  1111. }
  1112. if (dev->bus_number == 0) {
  1113. // Only do this once
  1114. usbi_dbg(ctx, "assigning HCD '%s' bus number %u", dev_id, bus_number);
  1115. dev->bus_number = bus_number;
  1116. if (sscanf(dev_id, "PCI\\VEN_%04hx&DEV_%04hx%*s", &dev->device_descriptor.idVendor, &dev->device_descriptor.idProduct) != 2)
  1117. usbi_warn(ctx, "could not infer VID/PID of HCD root hub from '%s'", dev_id);
  1118. priv = usbi_get_device_priv(dev);
  1119. priv->root_hub = true;
  1120. }
  1121. libusb_unref_device(dev);
  1122. return LIBUSB_SUCCESS;
  1123. }
  1124. // Returns the api type, or 0 if not found/unsupported
  1125. static void get_api_type(HDEVINFO *dev_info, SP_DEVINFO_DATA *dev_info_data,
  1126. int *api, int *sub_api)
  1127. {
  1128. // Precedence for filter drivers vs driver is in the order of this array
  1129. struct driver_lookup lookup[3] = {
  1130. {"\0\0", SPDRP_SERVICE, "driver"},
  1131. {"\0\0", SPDRP_UPPERFILTERS, "upper filter driver"},
  1132. {"\0\0", SPDRP_LOWERFILTERS, "lower filter driver"}
  1133. };
  1134. DWORD size, reg_type;
  1135. unsigned k, l;
  1136. int i, j;
  1137. // Check the service & filter names to know the API we should use
  1138. for (k = 0; k < 3; k++) {
  1139. if (pSetupDiGetDeviceRegistryPropertyA(*dev_info, dev_info_data, lookup[k].reg_prop,
  1140. &reg_type, (PBYTE)lookup[k].list, MAX_KEY_LENGTH, &size)) {
  1141. // Turn the REG_SZ SPDRP_SERVICE into REG_MULTI_SZ
  1142. if (lookup[k].reg_prop == SPDRP_SERVICE)
  1143. // our buffers are MAX_KEY_LENGTH + 1 so we can overflow if needed
  1144. lookup[k].list[strlen(lookup[k].list) + 1] = 0;
  1145. // MULTI_SZ is a pain to work with. Turn it into something much more manageable
  1146. // NB: none of the driver names we check against contain LIST_SEPARATOR,
  1147. // (currently ';'), so even if an unsupported one does, it's not an issue
  1148. for (l = 0; (lookup[k].list[l] != 0) || (lookup[k].list[l + 1] != 0); l++) {
  1149. if (lookup[k].list[l] == 0)
  1150. lookup[k].list[l] = LIST_SEPARATOR;
  1151. }
  1152. usbi_dbg(NULL, "%s(s): %s", lookup[k].designation, lookup[k].list);
  1153. } else {
  1154. if (GetLastError() != ERROR_INVALID_DATA)
  1155. usbi_dbg(NULL, "could not access %s: %s", lookup[k].designation, windows_error_str(0));
  1156. lookup[k].list[0] = 0;
  1157. }
  1158. }
  1159. for (i = 2; i < USB_API_MAX; i++) {
  1160. for (k = 0; k < 3; k++) {
  1161. j = get_sub_api(lookup[k].list, i);
  1162. if (j >= 0) {
  1163. usbi_dbg(NULL, "matched %s name against %s", lookup[k].designation,
  1164. (i != USB_API_WINUSBX) ? usb_api_backend[i].designation : usb_api_backend[i].driver_name_list[j]);
  1165. *api = i;
  1166. *sub_api = j;
  1167. return;
  1168. }
  1169. }
  1170. }
  1171. }
  1172. static int set_composite_interface(struct libusb_context *ctx, struct libusb_device *dev,
  1173. char *dev_interface_path, char *device_id, int api, int sub_api)
  1174. {
  1175. struct winusb_device_priv *priv = usbi_get_device_priv(dev);
  1176. int interface_number;
  1177. const char *mi_str;
  1178. // Because MI_## are not necessarily in sequential order (some composite
  1179. // devices will have only MI_00 & MI_03 for instance), we retrieve the actual
  1180. // interface number from the path's MI value
  1181. mi_str = strstr(device_id, "MI_");
  1182. if ((mi_str != NULL) && isdigit((unsigned char)mi_str[3]) && isdigit((unsigned char)mi_str[4])) {
  1183. interface_number = ((mi_str[3] - '0') * 10) + (mi_str[4] - '0');
  1184. } else {
  1185. usbi_warn(ctx, "failure to read interface number for %s, using default value", device_id);
  1186. interface_number = 0;
  1187. }
  1188. if (interface_number >= USB_MAXINTERFACES) {
  1189. usbi_warn(ctx, "interface %d too large - ignoring interface path %s", interface_number, dev_interface_path);
  1190. return LIBUSB_ERROR_ACCESS;
  1191. }
  1192. if (priv->usb_interface[interface_number].path != NULL) {
  1193. if (api == USB_API_HID) {
  1194. // HID devices can have multiple collections (COL##) for each MI_## interface
  1195. usbi_dbg(ctx, "interface[%d] already set - ignoring HID collection: %s",
  1196. interface_number, device_id);
  1197. return LIBUSB_ERROR_ACCESS;
  1198. }
  1199. // In other cases, just use the latest data
  1200. safe_free(priv->usb_interface[interface_number].path);
  1201. }
  1202. usbi_dbg(ctx, "interface[%d] = %s", interface_number, dev_interface_path);
  1203. priv->usb_interface[interface_number].path = dev_interface_path;
  1204. priv->usb_interface[interface_number].apib = &usb_api_backend[api];
  1205. priv->usb_interface[interface_number].sub_api = sub_api;
  1206. if ((api == USB_API_HID) && (priv->hid == NULL)) {
  1207. priv->hid = calloc(1, sizeof(struct hid_device_priv));
  1208. if (priv->hid == NULL)
  1209. return LIBUSB_ERROR_NO_MEM;
  1210. }
  1211. return LIBUSB_SUCCESS;
  1212. }
  1213. static int set_hid_interface(struct libusb_context *ctx, struct libusb_device *dev,
  1214. char *dev_interface_path)
  1215. {
  1216. struct winusb_device_priv *priv = usbi_get_device_priv(dev);
  1217. uint8_t i;
  1218. if (priv->hid == NULL) {
  1219. usbi_err(ctx, "program assertion failed - parent is not HID");
  1220. return LIBUSB_ERROR_NO_DEVICE;
  1221. } else if (priv->hid->nb_interfaces == USB_MAXINTERFACES) {
  1222. usbi_err(ctx, "program assertion failed - max USB interfaces reached for HID device");
  1223. return LIBUSB_ERROR_NO_DEVICE;
  1224. }
  1225. for (i = 0; i < priv->hid->nb_interfaces; i++) {
  1226. if ((priv->usb_interface[i].path != NULL) && strcmp(priv->usb_interface[i].path, dev_interface_path) == 0) {
  1227. usbi_dbg(ctx, "interface[%u] already set to %s", i, dev_interface_path);
  1228. return LIBUSB_ERROR_ACCESS;
  1229. }
  1230. }
  1231. priv->usb_interface[priv->hid->nb_interfaces].path = dev_interface_path;
  1232. priv->usb_interface[priv->hid->nb_interfaces].apib = &usb_api_backend[USB_API_HID];
  1233. usbi_dbg(ctx, "interface[%u] = %s", priv->hid->nb_interfaces, dev_interface_path);
  1234. priv->hid->nb_interfaces++;
  1235. return LIBUSB_SUCCESS;
  1236. }
  1237. /*
  1238. * get_device_list: libusb backend device enumeration function
  1239. */
  1240. static int winusb_get_device_list(struct libusb_context *ctx, struct discovered_devs **_discdevs)
  1241. {
  1242. struct discovered_devs *discdevs;
  1243. HDEVINFO *dev_info, dev_info_intf, dev_info_enum;
  1244. SP_DEVINFO_DATA dev_info_data;
  1245. DWORD _index = 0;
  1246. GUID hid_guid;
  1247. int r = LIBUSB_SUCCESS;
  1248. int api, sub_api;
  1249. unsigned int pass, i, j;
  1250. char enumerator[16];
  1251. char dev_id[MAX_PATH_LENGTH];
  1252. struct libusb_device *dev, *parent_dev;
  1253. struct winusb_device_priv *priv, *parent_priv;
  1254. char *dev_interface_path = NULL;
  1255. unsigned long session_id;
  1256. DWORD size, port_nr, reg_type, install_state;
  1257. HKEY key;
  1258. char guid_string[MAX_GUID_STRING_LENGTH];
  1259. GUID *if_guid;
  1260. LONG s;
  1261. #define HUB_PASS 0
  1262. #define DEV_PASS 1
  1263. #define HCD_PASS 2
  1264. #define GEN_PASS 3
  1265. #define HID_PASS 4
  1266. #define EXT_PASS 5
  1267. // Keep a list of guids that will be enumerated
  1268. #define GUID_SIZE_STEP 8
  1269. const GUID **guid_list, **new_guid_list;
  1270. unsigned int guid_size = GUID_SIZE_STEP;
  1271. unsigned int nb_guids;
  1272. // Keep a list of PnP enumerator strings that are found
  1273. const char *usb_enumerator[8] = { "USB" };
  1274. unsigned int nb_usb_enumerators = 1;
  1275. unsigned int usb_enum_index = 0;
  1276. // Keep a list of newly allocated devs to unref
  1277. #define UNREF_SIZE_STEP 16
  1278. libusb_device **unref_list, **new_unref_list;
  1279. unsigned int unref_size = UNREF_SIZE_STEP;
  1280. unsigned int unref_cur = 0;
  1281. // PASS 1 : (re)enumerate HCDs (allows for HCD hotplug)
  1282. // PASS 2 : (re)enumerate HUBS
  1283. // PASS 3 : (re)enumerate generic USB devices (including driverless)
  1284. // and list additional USB device interface GUIDs to explore
  1285. // PASS 4 : (re)enumerate master USB devices that have a device interface
  1286. // PASS 5+: (re)enumerate device interfaced GUIDs (including HID) and
  1287. // set the device interfaces.
  1288. // Init the GUID table
  1289. guid_list = malloc(guid_size * sizeof(void *));
  1290. if (guid_list == NULL) {
  1291. usbi_err(ctx, "failed to alloc guid list");
  1292. return LIBUSB_ERROR_NO_MEM;
  1293. }
  1294. guid_list[HUB_PASS] = &GUID_DEVINTERFACE_USB_HUB;
  1295. guid_list[DEV_PASS] = &GUID_DEVINTERFACE_USB_DEVICE;
  1296. guid_list[HCD_PASS] = &GUID_DEVINTERFACE_USB_HOST_CONTROLLER;
  1297. guid_list[GEN_PASS] = NULL;
  1298. if (HidD_GetHidGuid != NULL) {
  1299. HidD_GetHidGuid(&hid_guid);
  1300. guid_list[HID_PASS] = &hid_guid;
  1301. } else {
  1302. guid_list[HID_PASS] = NULL;
  1303. }
  1304. nb_guids = EXT_PASS;
  1305. unref_list = malloc(unref_size * sizeof(void *));
  1306. if (unref_list == NULL) {
  1307. usbi_err(ctx, "failed to alloc unref list");
  1308. free((void *)guid_list);
  1309. return LIBUSB_ERROR_NO_MEM;
  1310. }
  1311. dev_info_intf = pSetupDiGetClassDevsA(NULL, NULL, NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
  1312. if (dev_info_intf == INVALID_HANDLE_VALUE) {
  1313. usbi_err(ctx, "failed to obtain device info list: %s", windows_error_str(0));
  1314. free(unref_list);
  1315. free((void *)guid_list);
  1316. return LIBUSB_ERROR_OTHER;
  1317. }
  1318. for (pass = 0; ((pass < nb_guids) && (r == LIBUSB_SUCCESS)); pass++) {
  1319. //#define ENUM_DEBUG
  1320. #if defined(ENABLE_LOGGING) && defined(ENUM_DEBUG)
  1321. const char * const passname[] = {"HUB", "DEV", "HCD", "GEN", "HID", "EXT"};
  1322. usbi_dbg(ctx, "#### PROCESSING %ss %s", passname[MIN(pass, EXT_PASS)], guid_to_string(guid_list[pass], guid_string));
  1323. #endif
  1324. if ((pass == HID_PASS) && (guid_list[HID_PASS] == NULL))
  1325. continue;
  1326. dev_info = (pass != GEN_PASS) ? &dev_info_intf : &dev_info_enum;
  1327. for (i = 0; ; i++) {
  1328. // safe loop: free up any (unprotected) dynamic resource
  1329. // NB: this is always executed before breaking the loop
  1330. safe_free(dev_interface_path);
  1331. priv = parent_priv = NULL;
  1332. dev = parent_dev = NULL;
  1333. // Safe loop: end of loop conditions
  1334. if (r != LIBUSB_SUCCESS)
  1335. break;
  1336. if ((pass == HCD_PASS) && (i == UINT8_MAX)) {
  1337. usbi_warn(ctx, "program assertion failed - found more than %u buses, skipping the rest", UINT8_MAX);
  1338. break;
  1339. }
  1340. if (pass != GEN_PASS) {
  1341. // Except for GEN, all passes deal with device interfaces
  1342. r = get_interface_details(ctx, *dev_info, &dev_info_data, guid_list[pass], &_index, &dev_interface_path);
  1343. if ((r != LIBUSB_SUCCESS) || (dev_interface_path == NULL)) {
  1344. _index = 0;
  1345. break;
  1346. }
  1347. } else {
  1348. // Workaround for a Nec/Renesas USB 3.0 driver bug where root hubs are
  1349. // being listed under the "NUSB3" PnP Symbolic Name rather than "USB".
  1350. // The Intel USB 3.0 driver behaves similar, but uses "IUSB3"
  1351. // The Intel Alpine Ridge USB 3.1 driver uses "IARUSB3"
  1352. for (; usb_enum_index < nb_usb_enumerators; usb_enum_index++) {
  1353. if (get_devinfo_data(ctx, dev_info, &dev_info_data, usb_enumerator[usb_enum_index], i))
  1354. break;
  1355. i = 0;
  1356. }
  1357. if (usb_enum_index == nb_usb_enumerators)
  1358. break;
  1359. }
  1360. // Read the Device ID path
  1361. if (!pSetupDiGetDeviceInstanceIdA(*dev_info, &dev_info_data, dev_id, sizeof(dev_id), NULL)) {
  1362. usbi_warn(ctx, "could not read the device instance ID for devInst %lX, skipping",
  1363. ULONG_CAST(dev_info_data.DevInst));
  1364. continue;
  1365. }
  1366. #ifdef ENUM_DEBUG
  1367. usbi_dbg(ctx, "PRO: %s", dev_id);
  1368. #endif
  1369. // Set API to use or get additional data from generic pass
  1370. api = USB_API_UNSUPPORTED;
  1371. sub_api = SUB_API_NOTSET;
  1372. switch (pass) {
  1373. case HCD_PASS:
  1374. break;
  1375. case HUB_PASS:
  1376. api = USB_API_HUB;
  1377. // Fetch the PnP enumerator class for this hub
  1378. // This will allow us to enumerate all classes during the GEN pass
  1379. if (!pSetupDiGetDeviceRegistryPropertyA(*dev_info, &dev_info_data, SPDRP_ENUMERATOR_NAME,
  1380. NULL, (PBYTE)enumerator, sizeof(enumerator), NULL)) {
  1381. usbi_err(ctx, "could not read enumerator string for device '%s': %s", dev_id, windows_error_str(0));
  1382. LOOP_BREAK(LIBUSB_ERROR_OTHER);
  1383. }
  1384. for (j = 0; j < nb_usb_enumerators; j++) {
  1385. if (strcmp(usb_enumerator[j], enumerator) == 0)
  1386. break;
  1387. }
  1388. if (j == nb_usb_enumerators) {
  1389. usbi_dbg(ctx, "found new PnP enumerator string '%s'", enumerator);
  1390. if (nb_usb_enumerators < ARRAYSIZE(usb_enumerator)) {
  1391. usb_enumerator[nb_usb_enumerators] = _strdup(enumerator);
  1392. if (usb_enumerator[nb_usb_enumerators] != NULL) {
  1393. nb_usb_enumerators++;
  1394. } else {
  1395. usbi_err(ctx, "could not allocate enumerator string '%s'", enumerator);
  1396. LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
  1397. }
  1398. } else {
  1399. usbi_warn(ctx, "too many enumerator strings, some devices may not be accessible");
  1400. }
  1401. }
  1402. break;
  1403. case GEN_PASS:
  1404. // We use the GEN pass to detect driverless devices...
  1405. if (!pSetupDiGetDeviceRegistryPropertyA(*dev_info, &dev_info_data, SPDRP_DRIVER,
  1406. NULL, NULL, 0, NULL) && (GetLastError() != ERROR_INSUFFICIENT_BUFFER)) {
  1407. usbi_info(ctx, "The following device has no driver: '%s'", dev_id);
  1408. usbi_info(ctx, "libusb will not be able to access it");
  1409. }
  1410. // ...and to add the additional device interface GUIDs
  1411. key = pSetupDiOpenDevRegKey(*dev_info, &dev_info_data, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
  1412. if (key == INVALID_HANDLE_VALUE)
  1413. break;
  1414. // Look for both DeviceInterfaceGUIDs *and* DeviceInterfaceGUID, in that order
  1415. // If multiple GUIDs just process the first and ignore the others
  1416. size = sizeof(guid_string);
  1417. s = pRegQueryValueExA(key, "DeviceInterfaceGUIDs", NULL, &reg_type,
  1418. (LPBYTE)guid_string, &size);
  1419. if (s == ERROR_FILE_NOT_FOUND)
  1420. s = pRegQueryValueExA(key, "DeviceInterfaceGUID", NULL, &reg_type,
  1421. (LPBYTE)guid_string, &size);
  1422. pRegCloseKey(key);
  1423. if (s == ERROR_FILE_NOT_FOUND) {
  1424. break; /* no DeviceInterfaceGUID registered */
  1425. } else if (s != ERROR_SUCCESS && s != ERROR_MORE_DATA) {
  1426. usbi_warn(ctx, "unexpected error from pRegQueryValueExA for '%s'", dev_id);
  1427. break;
  1428. }
  1429. // https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regqueryvalueexa#remarks
  1430. // - "string may not have been stored with the proper terminating null characters"
  1431. // - "Note that REG_MULTI_SZ strings could have two terminating null characters"
  1432. if ((reg_type == REG_SZ && size >= sizeof(guid_string) - sizeof(char))
  1433. || (reg_type == REG_MULTI_SZ && size >= sizeof(guid_string) - 2 * sizeof(char))) {
  1434. if (nb_guids == guid_size) {
  1435. new_guid_list = realloc((void *)guid_list, (guid_size + GUID_SIZE_STEP) * sizeof(void *));
  1436. if (new_guid_list == NULL) {
  1437. usbi_err(ctx, "failed to realloc guid list");
  1438. LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
  1439. }
  1440. guid_list = new_guid_list;
  1441. guid_size += GUID_SIZE_STEP;
  1442. }
  1443. if_guid = malloc(sizeof(*if_guid));
  1444. if (if_guid == NULL) {
  1445. usbi_err(ctx, "failed to alloc if_guid");
  1446. LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
  1447. }
  1448. if (!string_to_guid(guid_string, if_guid)) {
  1449. usbi_warn(ctx, "device '%s' has malformed DeviceInterfaceGUID string '%s', skipping", dev_id, guid_string);
  1450. free(if_guid);
  1451. } else {
  1452. // Check if we've already seen this GUID
  1453. for (j = EXT_PASS; j < nb_guids; j++) {
  1454. if (memcmp(guid_list[j], if_guid, sizeof(*if_guid)) == 0)
  1455. break;
  1456. }
  1457. if (j == nb_guids) {
  1458. usbi_dbg(ctx, "extra GUID: %s", guid_string);
  1459. guid_list[nb_guids++] = if_guid;
  1460. } else {
  1461. // Duplicate, ignore
  1462. free(if_guid);
  1463. }
  1464. }
  1465. } else {
  1466. usbi_warn(ctx, "unexpected type/size of DeviceInterfaceGUID for '%s'", dev_id);
  1467. }
  1468. break;
  1469. case HID_PASS:
  1470. api = USB_API_HID;
  1471. break;
  1472. default:
  1473. // Get the API type (after checking that the driver installation is OK)
  1474. if ((!pSetupDiGetDeviceRegistryPropertyA(*dev_info, &dev_info_data, SPDRP_INSTALL_STATE,
  1475. NULL, (PBYTE)&install_state, sizeof(install_state), &size)) || (size != sizeof(install_state))) {
  1476. usbi_warn(ctx, "could not detect installation state of driver for '%s': %s",
  1477. dev_id, windows_error_str(0));
  1478. } else if (install_state != 0) {
  1479. usbi_warn(ctx, "driver for device '%s' is reporting an issue (code: %lu) - skipping",
  1480. dev_id, ULONG_CAST(install_state));
  1481. continue;
  1482. }
  1483. get_api_type(dev_info, &dev_info_data, &api, &sub_api);
  1484. break;
  1485. }
  1486. // Find parent device (for the passes that need it)
  1487. if (pass >= GEN_PASS) {
  1488. parent_dev = get_ancestor(ctx, dev_info_data.DevInst, NULL);
  1489. if (parent_dev == NULL) {
  1490. // Root hubs will not have a parent
  1491. dev = usbi_get_device_by_session_id(ctx, (unsigned long)dev_info_data.DevInst);
  1492. if (dev != NULL) {
  1493. priv = usbi_get_device_priv(dev);
  1494. if (priv->root_hub)
  1495. goto track_unref;
  1496. libusb_unref_device(dev);
  1497. }
  1498. usbi_dbg(ctx, "unlisted ancestor for '%s' (non USB HID, newly connected, etc.) - ignoring", dev_id);
  1499. continue;
  1500. }
  1501. parent_priv = usbi_get_device_priv(parent_dev);
  1502. // virtual USB devices are also listed during GEN - don't process these yet
  1503. if ((pass == GEN_PASS) && (parent_priv->apib->id != USB_API_HUB)) {
  1504. libusb_unref_device(parent_dev);
  1505. continue;
  1506. }
  1507. }
  1508. // Create new or match existing device, using the devInst as session id
  1509. if ((pass <= GEN_PASS) && (pass != HCD_PASS)) { // For subsequent passes, we'll lookup the parent
  1510. // These are the passes that create "new" devices
  1511. session_id = (unsigned long)dev_info_data.DevInst;
  1512. dev = usbi_get_device_by_session_id(ctx, session_id);
  1513. if (dev == NULL) {
  1514. alloc_device:
  1515. usbi_dbg(ctx, "allocating new device for session [%lX]", session_id);
  1516. dev = usbi_alloc_device(ctx, session_id);
  1517. if (dev == NULL)
  1518. LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
  1519. priv = winusb_device_priv_init(dev);
  1520. priv->dev_id = _strdup(dev_id);
  1521. priv->class_guid = dev_info_data.ClassGuid;
  1522. if (priv->dev_id == NULL) {
  1523. libusb_unref_device(dev);
  1524. LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
  1525. }
  1526. } else {
  1527. usbi_dbg(ctx, "found existing device for session [%lX]", session_id);
  1528. priv = usbi_get_device_priv(dev);
  1529. if (strcmp(priv->dev_id, dev_id) != 0) {
  1530. usbi_dbg(ctx, "device instance ID for session [%lX] changed", session_id);
  1531. usbi_disconnect_device(dev);
  1532. libusb_unref_device(dev);
  1533. goto alloc_device;
  1534. }
  1535. if (!IsEqualGUID(&priv->class_guid, &dev_info_data.ClassGuid)) {
  1536. usbi_dbg(ctx, "device class GUID for session [%lX] changed", session_id);
  1537. usbi_disconnect_device(dev);
  1538. libusb_unref_device(dev);
  1539. goto alloc_device;
  1540. }
  1541. }
  1542. track_unref:
  1543. // Keep track of devices that need unref
  1544. if (unref_cur == unref_size) {
  1545. new_unref_list = realloc(unref_list, (unref_size + UNREF_SIZE_STEP) * sizeof(void *));
  1546. if (new_unref_list == NULL) {
  1547. usbi_err(ctx, "could not realloc list for unref - aborting");
  1548. LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
  1549. }
  1550. unref_list = new_unref_list;
  1551. unref_size += UNREF_SIZE_STEP;
  1552. }
  1553. unref_list[unref_cur++] = dev;
  1554. }
  1555. // Setup device
  1556. switch (pass) {
  1557. case HUB_PASS:
  1558. case DEV_PASS:
  1559. // If the device has already been setup, don't do it again
  1560. if (priv->path != NULL)
  1561. break;
  1562. // Take care of API initialization
  1563. priv->path = dev_interface_path;
  1564. dev_interface_path = NULL;
  1565. priv->apib = &usb_api_backend[api];
  1566. priv->sub_api = sub_api;
  1567. switch (api) {
  1568. case USB_API_COMPOSITE:
  1569. case USB_API_HUB:
  1570. break;
  1571. case USB_API_HID:
  1572. priv->hid = calloc(1, sizeof(struct hid_device_priv));
  1573. if (priv->hid == NULL)
  1574. LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
  1575. break;
  1576. default:
  1577. // For other devices, the first interface is the same as the device
  1578. priv->usb_interface[0].path = _strdup(priv->path);
  1579. if (priv->usb_interface[0].path == NULL)
  1580. LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
  1581. // The following is needed if we want API calls to work for both simple
  1582. // and composite devices.
  1583. for (j = 0; j < USB_MAXINTERFACES; j++)
  1584. priv->usb_interface[j].apib = &usb_api_backend[api];
  1585. break;
  1586. }
  1587. break;
  1588. case HCD_PASS:
  1589. r = enumerate_hcd_root_hub(ctx, dev_id, (uint8_t)(i + 1), dev_info_data.DevInst);
  1590. break;
  1591. case GEN_PASS:
  1592. port_nr = 0;
  1593. if (!get_dev_port_number(*dev_info, &dev_info_data, &port_nr))
  1594. usbi_warn(ctx, "could not retrieve port number for device '%s': %s", dev_id, windows_error_str(0));
  1595. r = init_device(dev, parent_dev, (uint8_t)port_nr, dev_info_data.DevInst);
  1596. if (r == LIBUSB_SUCCESS) {
  1597. // Append device to the list of discovered devices
  1598. discdevs = discovered_devs_append(*_discdevs, dev);
  1599. if (!discdevs)
  1600. LOOP_BREAK(LIBUSB_ERROR_NO_MEM);
  1601. *_discdevs = discdevs;
  1602. } else {
  1603. // Failed to initialize a single device doesn't stop us from enumerating all other devices,
  1604. // but we skip it (don't add to list of discovered devices)
  1605. usbi_warn(ctx, "failed to initialize device '%s'", priv->dev_id);
  1606. r = LIBUSB_SUCCESS;
  1607. }
  1608. break;
  1609. default: // HID_PASS and later
  1610. if (parent_priv->apib->id == USB_API_HID || parent_priv->apib->id == USB_API_COMPOSITE) {
  1611. if (parent_priv->apib->id == USB_API_HID) {
  1612. usbi_dbg(ctx, "setting HID interface for [%lX]:", parent_dev->session_data);
  1613. r = set_hid_interface(ctx, parent_dev, dev_interface_path);
  1614. } else {
  1615. usbi_dbg(ctx, "setting composite interface for [%lX]:", parent_dev->session_data);
  1616. r = set_composite_interface(ctx, parent_dev, dev_interface_path, dev_id, api, sub_api);
  1617. }
  1618. switch (r) {
  1619. case LIBUSB_SUCCESS:
  1620. dev_interface_path = NULL;
  1621. break;
  1622. case LIBUSB_ERROR_ACCESS:
  1623. // interface has already been set => make sure dev_interface_path is freed then
  1624. r = LIBUSB_SUCCESS;
  1625. break;
  1626. default:
  1627. LOOP_BREAK(r);
  1628. break;
  1629. }
  1630. }
  1631. libusb_unref_device(parent_dev);
  1632. break;
  1633. }
  1634. }
  1635. }
  1636. pSetupDiDestroyDeviceInfoList(dev_info_intf);
  1637. // Free any additional GUIDs
  1638. for (pass = EXT_PASS; pass < nb_guids; pass++)
  1639. free((void *)guid_list[pass]);
  1640. free((void *)guid_list);
  1641. // Free any PnP enumerator strings
  1642. for (i = 1; i < nb_usb_enumerators; i++)
  1643. free((void *)usb_enumerator[i]);
  1644. // Unref newly allocated devs
  1645. for (i = 0; i < unref_cur; i++)
  1646. libusb_unref_device(unref_list[i]);
  1647. free(unref_list);
  1648. return r;
  1649. }
  1650. static int winusb_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, void *buffer, size_t len)
  1651. {
  1652. struct winusb_device_priv *priv = usbi_get_device_priv(dev);
  1653. PUSB_CONFIGURATION_DESCRIPTOR config_header;
  1654. if ((priv->config_descriptor == NULL) || (priv->config_descriptor[config_index] == NULL))
  1655. return LIBUSB_ERROR_NOT_FOUND;
  1656. config_header = priv->config_descriptor[config_index];
  1657. len = MIN(len, config_header->wTotalLength);
  1658. memcpy(buffer, config_header, len);
  1659. return (int)len;
  1660. }
  1661. static int winusb_get_config_descriptor_by_value(struct libusb_device *dev, uint8_t bConfigurationValue,
  1662. void **buffer)
  1663. {
  1664. struct winusb_device_priv *priv = usbi_get_device_priv(dev);
  1665. PUSB_CONFIGURATION_DESCRIPTOR config_header;
  1666. uint8_t index;
  1667. if (priv->config_descriptor == NULL)
  1668. return LIBUSB_ERROR_NOT_FOUND;
  1669. for (index = 0; index < dev->device_descriptor.bNumConfigurations; index++) {
  1670. config_header = priv->config_descriptor[index];
  1671. if (config_header == NULL)
  1672. continue;
  1673. if (config_header->bConfigurationValue == bConfigurationValue) {
  1674. *buffer = config_header;
  1675. return (int)config_header->wTotalLength;
  1676. }
  1677. }
  1678. return LIBUSB_ERROR_NOT_FOUND;
  1679. }
  1680. /*
  1681. * return the cached copy of the active config descriptor
  1682. */
  1683. static int winusb_get_active_config_descriptor(struct libusb_device *dev, void *buffer, size_t len)
  1684. {
  1685. struct winusb_device_priv *priv = usbi_get_device_priv(dev);
  1686. void *config_desc;
  1687. int r;
  1688. if (priv->active_config == 0)
  1689. return LIBUSB_ERROR_NOT_FOUND;
  1690. r = winusb_get_config_descriptor_by_value(dev, priv->active_config, &config_desc);
  1691. if (r < 0)
  1692. return r;
  1693. len = MIN(len, (size_t)r);
  1694. memcpy(buffer, config_desc, len);
  1695. return (int)len;
  1696. }
  1697. static int winusb_open(struct libusb_device_handle *dev_handle)
  1698. {
  1699. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  1700. CHECK_SUPPORTED_API(priv->apib, open);
  1701. return priv->apib->open(SUB_API_NOTSET, dev_handle);
  1702. }
  1703. static void winusb_close(struct libusb_device_handle *dev_handle)
  1704. {
  1705. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  1706. if (priv->apib->close)
  1707. priv->apib->close(SUB_API_NOTSET, dev_handle);
  1708. }
  1709. static int winusb_get_configuration(struct libusb_device_handle *dev_handle, uint8_t *config)
  1710. {
  1711. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  1712. *config = priv->active_config;
  1713. return LIBUSB_SUCCESS;
  1714. }
  1715. /*
  1716. * from http://msdn.microsoft.com/en-us/library/ms793522.aspx: "The port driver
  1717. * does not currently expose a service that allows higher-level drivers to set
  1718. * the configuration."
  1719. */
  1720. static int winusb_set_configuration(struct libusb_device_handle *dev_handle, uint8_t config)
  1721. {
  1722. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  1723. int r = LIBUSB_SUCCESS;
  1724. r = libusb_control_transfer(dev_handle, LIBUSB_ENDPOINT_OUT |
  1725. LIBUSB_REQUEST_TYPE_STANDARD | LIBUSB_RECIPIENT_DEVICE,
  1726. LIBUSB_REQUEST_SET_CONFIGURATION, config,
  1727. 0, NULL, 0, 1000);
  1728. if (r == LIBUSB_SUCCESS)
  1729. priv->active_config = config;
  1730. return r;
  1731. }
  1732. static int winusb_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface)
  1733. {
  1734. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  1735. int r;
  1736. CHECK_SUPPORTED_API(priv->apib, claim_interface);
  1737. safe_free(priv->usb_interface[iface].endpoint);
  1738. priv->usb_interface[iface].nb_endpoints = 0;
  1739. r = priv->apib->claim_interface(SUB_API_NOTSET, dev_handle, iface);
  1740. if (r == LIBUSB_SUCCESS)
  1741. r = windows_assign_endpoints(dev_handle, iface, 0);
  1742. return r;
  1743. }
  1744. static int winusb_set_interface_altsetting(struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting)
  1745. {
  1746. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  1747. int r;
  1748. CHECK_SUPPORTED_API(priv->apib, set_interface_altsetting);
  1749. safe_free(priv->usb_interface[iface].endpoint);
  1750. priv->usb_interface[iface].nb_endpoints = 0;
  1751. r = priv->apib->set_interface_altsetting(SUB_API_NOTSET, dev_handle, iface, altsetting);
  1752. if (r == LIBUSB_SUCCESS)
  1753. r = windows_assign_endpoints(dev_handle, iface, altsetting);
  1754. return r;
  1755. }
  1756. static int winusb_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface)
  1757. {
  1758. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  1759. CHECK_SUPPORTED_API(priv->apib, release_interface);
  1760. return priv->apib->release_interface(SUB_API_NOTSET, dev_handle, iface);
  1761. }
  1762. static int winusb_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint)
  1763. {
  1764. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  1765. CHECK_SUPPORTED_API(priv->apib, clear_halt);
  1766. return priv->apib->clear_halt(SUB_API_NOTSET, dev_handle, endpoint);
  1767. }
  1768. static int winusb_reset_device(struct libusb_device_handle *dev_handle)
  1769. {
  1770. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  1771. CHECK_SUPPORTED_API(priv->apib, reset_device);
  1772. return priv->apib->reset_device(SUB_API_NOTSET, dev_handle);
  1773. }
  1774. static void winusb_destroy_device(struct libusb_device *dev)
  1775. {
  1776. winusb_device_priv_release(dev);
  1777. }
  1778. static void winusb_clear_transfer_priv(struct usbi_transfer *itransfer)
  1779. {
  1780. struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
  1781. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1782. struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
  1783. int sub_api = priv->sub_api;
  1784. safe_free(transfer_priv->hid_buffer);
  1785. if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS && sub_api == SUB_API_WINUSB) {
  1786. if (transfer_priv->isoch_buffer_handle != NULL) {
  1787. if (WinUSBX[sub_api].UnregisterIsochBuffer(transfer_priv->isoch_buffer_handle)) {
  1788. transfer_priv->isoch_buffer_handle = NULL;
  1789. } else {
  1790. usbi_warn(TRANSFER_CTX(transfer), "failed to unregister WinUSB isoch buffer: %s", windows_error_str(0));
  1791. }
  1792. }
  1793. }
  1794. safe_free(transfer_priv->iso_context);
  1795. // When auto claim is in use, attempt to release the auto-claimed interface
  1796. auto_release(itransfer);
  1797. }
  1798. static int winusb_submit_transfer(struct usbi_transfer *itransfer)
  1799. {
  1800. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1801. struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
  1802. int (*transfer_fn)(int, struct usbi_transfer *);
  1803. switch (transfer->type) {
  1804. case LIBUSB_TRANSFER_TYPE_CONTROL:
  1805. transfer_fn = priv->apib->submit_control_transfer;
  1806. break;
  1807. case LIBUSB_TRANSFER_TYPE_BULK:
  1808. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  1809. transfer_fn = priv->apib->submit_bulk_transfer;
  1810. break;
  1811. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  1812. transfer_fn = priv->apib->submit_iso_transfer;
  1813. break;
  1814. default:
  1815. // Should not get here since windows_submit_transfer() validates
  1816. // the transfer->type field
  1817. usbi_err(TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
  1818. return LIBUSB_ERROR_INVALID_PARAM;
  1819. }
  1820. if (transfer_fn == NULL) {
  1821. usbi_warn(TRANSFER_CTX(transfer),
  1822. "unsupported transfer type %d (unrecognized device driver)",
  1823. transfer->type);
  1824. return LIBUSB_ERROR_NOT_SUPPORTED;
  1825. }
  1826. return transfer_fn(SUB_API_NOTSET, itransfer);
  1827. }
  1828. static int winusb_cancel_transfer(struct usbi_transfer *itransfer)
  1829. {
  1830. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1831. struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
  1832. CHECK_SUPPORTED_API(priv->apib, cancel_transfer);
  1833. return priv->apib->cancel_transfer(SUB_API_NOTSET, itransfer);
  1834. }
  1835. static enum libusb_transfer_status winusb_copy_transfer_data(struct usbi_transfer *itransfer, DWORD length)
  1836. {
  1837. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  1838. struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
  1839. if (priv->apib->copy_transfer_data == NULL) {
  1840. usbi_err(TRANSFER_CTX(transfer), "program assertion failed - no function to copy transfer data");
  1841. return LIBUSB_TRANSFER_ERROR;
  1842. }
  1843. return priv->apib->copy_transfer_data(SUB_API_NOTSET, itransfer, length);
  1844. }
  1845. // NB: MSVC6 does not support named initializers.
  1846. const struct windows_backend winusb_backend = {
  1847. winusb_init,
  1848. winusb_exit,
  1849. winusb_get_device_list,
  1850. winusb_open,
  1851. winusb_close,
  1852. winusb_get_active_config_descriptor,
  1853. winusb_get_config_descriptor,
  1854. winusb_get_config_descriptor_by_value,
  1855. winusb_get_configuration,
  1856. winusb_set_configuration,
  1857. winusb_claim_interface,
  1858. winusb_release_interface,
  1859. winusb_set_interface_altsetting,
  1860. winusb_clear_halt,
  1861. winusb_reset_device,
  1862. winusb_destroy_device,
  1863. winusb_submit_transfer,
  1864. winusb_cancel_transfer,
  1865. winusb_clear_transfer_priv,
  1866. winusb_copy_transfer_data,
  1867. };
  1868. /*
  1869. * USB API backends
  1870. */
  1871. static const char * const composite_driver_names[] = {"USBCCGP"};
  1872. static const char * const winusbx_driver_names[] = {"libusbK", "libusb0", "WinUSB"};
  1873. static const char * const hid_driver_names[] = {"HIDUSB", "MOUHID", "KBDHID"};
  1874. const struct windows_usb_api_backend usb_api_backend[USB_API_MAX] = {
  1875. {
  1876. USB_API_UNSUPPORTED,
  1877. "Unsupported API",
  1878. NULL, /* driver_name_list */
  1879. 0, /* nb_driver_names */
  1880. NULL, /* init */
  1881. NULL, /* exit */
  1882. NULL, /* open */
  1883. NULL, /* close */
  1884. NULL, /* configure_endpoints */
  1885. NULL, /* claim_interface */
  1886. NULL, /* set_interface_altsetting */
  1887. NULL, /* release_interface */
  1888. NULL, /* clear_halt */
  1889. NULL, /* reset_device */
  1890. NULL, /* submit_bulk_transfer */
  1891. NULL, /* submit_iso_transfer */
  1892. NULL, /* submit_control_transfer */
  1893. NULL, /* cancel_transfer */
  1894. NULL, /* copy_transfer_data */
  1895. },
  1896. {
  1897. USB_API_HUB,
  1898. "HUB API",
  1899. NULL, /* driver_name_list */
  1900. 0, /* nb_driver_names */
  1901. NULL, /* init */
  1902. NULL, /* exit */
  1903. NULL, /* open */
  1904. NULL, /* close */
  1905. NULL, /* configure_endpoints */
  1906. NULL, /* claim_interface */
  1907. NULL, /* set_interface_altsetting */
  1908. NULL, /* release_interface */
  1909. NULL, /* clear_halt */
  1910. NULL, /* reset_device */
  1911. NULL, /* submit_bulk_transfer */
  1912. NULL, /* submit_iso_transfer */
  1913. NULL, /* submit_control_transfer */
  1914. NULL, /* cancel_transfer */
  1915. NULL, /* copy_transfer_data */
  1916. },
  1917. {
  1918. USB_API_COMPOSITE,
  1919. "Composite API",
  1920. composite_driver_names,
  1921. ARRAYSIZE(composite_driver_names),
  1922. NULL, /* init */
  1923. NULL, /* exit */
  1924. composite_open,
  1925. composite_close,
  1926. NULL, /* configure_endpoints */
  1927. composite_claim_interface,
  1928. composite_set_interface_altsetting,
  1929. composite_release_interface,
  1930. composite_clear_halt,
  1931. composite_reset_device,
  1932. composite_submit_bulk_transfer,
  1933. composite_submit_iso_transfer,
  1934. composite_submit_control_transfer,
  1935. composite_cancel_transfer,
  1936. composite_copy_transfer_data,
  1937. },
  1938. {
  1939. USB_API_WINUSBX,
  1940. "WinUSB-like APIs",
  1941. winusbx_driver_names,
  1942. ARRAYSIZE(winusbx_driver_names),
  1943. winusbx_init,
  1944. winusbx_exit,
  1945. winusbx_open,
  1946. winusbx_close,
  1947. winusbx_configure_endpoints,
  1948. winusbx_claim_interface,
  1949. winusbx_set_interface_altsetting,
  1950. winusbx_release_interface,
  1951. winusbx_clear_halt,
  1952. winusbx_reset_device,
  1953. winusbx_submit_bulk_transfer,
  1954. winusbx_submit_iso_transfer,
  1955. winusbx_submit_control_transfer,
  1956. winusbx_cancel_transfer,
  1957. winusbx_copy_transfer_data,
  1958. },
  1959. {
  1960. USB_API_HID,
  1961. "HID API",
  1962. hid_driver_names,
  1963. ARRAYSIZE(hid_driver_names),
  1964. hid_init,
  1965. hid_exit,
  1966. hid_open,
  1967. hid_close,
  1968. NULL, /* configure_endpoints */
  1969. hid_claim_interface,
  1970. hid_set_interface_altsetting,
  1971. hid_release_interface,
  1972. hid_clear_halt,
  1973. hid_reset_device,
  1974. hid_submit_bulk_transfer,
  1975. NULL, /* submit_iso_transfer */
  1976. hid_submit_control_transfer,
  1977. NULL, /* cancel_transfer */
  1978. hid_copy_transfer_data,
  1979. },
  1980. };
  1981. /*
  1982. * WinUSB-like (WinUSB, libusb0/libusbK through libusbk DLL) API functions
  1983. */
  1984. #define WinUSB_Set(h, fn, required) \
  1985. do { \
  1986. WinUSBX[SUB_API_WINUSB].fn = (WinUsb_##fn##_t)GetProcAddress(h, "WinUsb_" #fn); \
  1987. if (required && (WinUSBX[SUB_API_WINUSB].fn == NULL)) { \
  1988. usbi_err(ctx, "GetProcAddress() failed for WinUsb_%s", #fn); \
  1989. goto cleanup_winusb; \
  1990. } \
  1991. } while (0)
  1992. #define libusbK_Set(sub_api, fn, required) \
  1993. do { \
  1994. pLibK_GetProcAddress((PVOID *)&WinUSBX[sub_api].fn, sub_api, KUSB_FNID_##fn); \
  1995. if (required && (WinUSBX[sub_api].fn == NULL)) { \
  1996. usbi_err(ctx, "LibK_GetProcAddress() failed for LibK_%s", #fn); \
  1997. goto cleanup_libusbk; \
  1998. } \
  1999. } while (0)
  2000. static bool winusbx_init(struct libusb_context *ctx)
  2001. {
  2002. HMODULE hWinUSB, hlibusbK;
  2003. hWinUSB = load_system_library(ctx, "WinUSB");
  2004. if (hWinUSB != NULL) {
  2005. WinUSB_Set(hWinUSB, AbortPipe, true);
  2006. WinUSB_Set(hWinUSB, ControlTransfer, true);
  2007. WinUSB_Set(hWinUSB, FlushPipe, true);
  2008. WinUSB_Set(hWinUSB, Free, true);
  2009. WinUSB_Set(hWinUSB, GetAssociatedInterface, true);
  2010. WinUSB_Set(hWinUSB, Initialize, true);
  2011. WinUSB_Set(hWinUSB, ReadPipe, true);
  2012. WinUSB_Set(hWinUSB, ResetPipe, true);
  2013. WinUSB_Set(hWinUSB, SetCurrentAlternateSetting, true);
  2014. WinUSB_Set(hWinUSB, SetPipePolicy, true);
  2015. WinUSB_Set(hWinUSB, WritePipe, true);
  2016. // Check for isochronous transfers support (available starting with Windows 8.1)
  2017. WinUSB_Set(hWinUSB, ReadIsochPipeAsap, false);
  2018. if (WinUSBX[SUB_API_WINUSB].ReadIsochPipeAsap != NULL) {
  2019. WinUSB_Set(hWinUSB, QueryPipeEx, true);
  2020. WinUSB_Set(hWinUSB, RegisterIsochBuffer, true);
  2021. WinUSB_Set(hWinUSB, UnregisterIsochBuffer, true);
  2022. WinUSB_Set(hWinUSB, WriteIsochPipeAsap, true);
  2023. }
  2024. WinUSBX[SUB_API_WINUSB].hDll = hWinUSB;
  2025. usbi_info(ctx, "WinUSB DLL available (%s isoch support)",
  2026. (WinUSBX[SUB_API_WINUSB].ReadIsochPipeAsap != NULL) ? "with" : "without");
  2027. cleanup_winusb:
  2028. if (WinUSBX[SUB_API_WINUSB].hDll == NULL) {
  2029. usbi_err(ctx, "failed to initialize WinUSB");
  2030. memset(&WinUSBX[SUB_API_WINUSB], 0, sizeof(WinUSBX[SUB_API_WINUSB]));
  2031. FreeLibrary(hWinUSB);
  2032. hWinUSB = NULL;
  2033. }
  2034. } else {
  2035. usbi_info(ctx, "WinUSB DLL is not available");
  2036. }
  2037. hlibusbK = load_system_library(ctx, "libusbK");
  2038. if (hlibusbK != NULL) {
  2039. LibK_GetVersion_t pLibK_GetVersion;
  2040. LibK_GetProcAddress_t pLibK_GetProcAddress;
  2041. int sub_api = 0;
  2042. pLibK_GetVersion = (LibK_GetVersion_t)GetProcAddress(hlibusbK, "LibK_GetVersion");
  2043. if (pLibK_GetVersion != NULL) {
  2044. KLIB_VERSION LibK_Version;
  2045. pLibK_GetVersion(&LibK_Version);
  2046. usbi_dbg(ctx, "libusbK DLL found, version: %d.%d.%d.%d", LibK_Version.Major, LibK_Version.Minor,
  2047. LibK_Version.Micro, LibK_Version.Nano);
  2048. } else {
  2049. usbi_dbg(ctx, "libusbK DLL found, version unknown");
  2050. }
  2051. pLibK_GetProcAddress = (LibK_GetProcAddress_t)GetProcAddress(hlibusbK, "LibK_GetProcAddress");
  2052. if (pLibK_GetProcAddress == NULL) {
  2053. usbi_err(ctx, "LibK_GetProcAddress() not found in libusbK DLL");
  2054. goto cleanup_libusbk;
  2055. }
  2056. // NB: The below for loop works because the sub_api value for WinUSB
  2057. // is a higher value than that of libusbK and libusb0
  2058. for (; sub_api < SUB_API_WINUSB; sub_api++) {
  2059. libusbK_Set(sub_api, AbortPipe, true);
  2060. libusbK_Set(sub_api, ControlTransfer, true);
  2061. libusbK_Set(sub_api, FlushPipe, true);
  2062. libusbK_Set(sub_api, Free, true);
  2063. libusbK_Set(sub_api, GetAssociatedInterface, true);
  2064. libusbK_Set(sub_api, Initialize, true);
  2065. libusbK_Set(sub_api, ReadPipe, true);
  2066. libusbK_Set(sub_api, ResetPipe, true);
  2067. libusbK_Set(sub_api, SetCurrentAlternateSetting, true);
  2068. libusbK_Set(sub_api, SetPipePolicy, true);
  2069. libusbK_Set(sub_api, WritePipe, true);
  2070. // Optional isochronous support
  2071. libusbK_Set(sub_api, IsoReadPipe, false);
  2072. if (WinUSBX[sub_api].IsoReadPipe != NULL)
  2073. libusbK_Set(sub_api, IsoWritePipe, true);
  2074. // Optional device reset support
  2075. libusbK_Set(sub_api, ResetDevice, false);
  2076. WinUSBX[sub_api].hDll = hlibusbK;
  2077. }
  2078. cleanup_libusbk:
  2079. if (sub_api < SUB_API_WINUSB) {
  2080. usbi_err(ctx, "failed to initialize libusbK");
  2081. while (sub_api >= 0) {
  2082. memset(&WinUSBX[sub_api], 0, sizeof(WinUSBX[sub_api]));
  2083. sub_api--;
  2084. }
  2085. FreeLibrary(hlibusbK);
  2086. hlibusbK = NULL;
  2087. }
  2088. } else {
  2089. usbi_info(ctx, "libusbK DLL is not available");
  2090. }
  2091. if ((hWinUSB == NULL) && (hlibusbK == NULL)) {
  2092. usbi_warn(ctx, "neither WinUSB nor libusbK DLLs were found, "
  2093. "you will not be able to access devices outside of enumeration");
  2094. return false;
  2095. }
  2096. return true;
  2097. }
  2098. static void winusbx_exit(void)
  2099. {
  2100. bool loaded = false;
  2101. HMODULE hDll;
  2102. hDll = WinUSBX[SUB_API_LIBUSBK].hDll;
  2103. if (hDll != NULL) {
  2104. FreeLibrary(hDll);
  2105. loaded = true;
  2106. }
  2107. hDll = WinUSBX[SUB_API_WINUSB].hDll;
  2108. if (hDll != NULL) {
  2109. FreeLibrary(hDll);
  2110. loaded = true;
  2111. }
  2112. // Reset the WinUSBX API structures if something was loaded
  2113. if (loaded)
  2114. memset(&WinUSBX, 0, sizeof(WinUSBX));
  2115. }
  2116. // NB: open and close must ensure that they only handle interface of
  2117. // the right API type, as these functions can be called wholesale from
  2118. // composite_open(), with interfaces belonging to different APIs
  2119. static int winusbx_open(int sub_api, struct libusb_device_handle *dev_handle)
  2120. {
  2121. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  2122. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  2123. HANDLE file_handle;
  2124. int i;
  2125. CHECK_WINUSBX_AVAILABLE(sub_api);
  2126. // WinUSB requires a separate handle for each interface
  2127. for (i = 0; i < USB_MAXINTERFACES; i++) {
  2128. if ((priv->usb_interface[i].path != NULL)
  2129. && (priv->usb_interface[i].apib->id == USB_API_WINUSBX)) {
  2130. file_handle = windows_open(dev_handle, priv->usb_interface[i].path, GENERIC_READ | GENERIC_WRITE);
  2131. if (file_handle == INVALID_HANDLE_VALUE) {
  2132. usbi_err(HANDLE_CTX(dev_handle), "could not open device %s (interface %d): %s", priv->usb_interface[i].path, i, windows_error_str(0));
  2133. switch (GetLastError()) {
  2134. case ERROR_FILE_NOT_FOUND: // The device was disconnected
  2135. return LIBUSB_ERROR_NO_DEVICE;
  2136. case ERROR_ACCESS_DENIED:
  2137. return LIBUSB_ERROR_ACCESS;
  2138. default:
  2139. return LIBUSB_ERROR_IO;
  2140. }
  2141. }
  2142. handle_priv->interface_handle[i].dev_handle = file_handle;
  2143. }
  2144. }
  2145. return LIBUSB_SUCCESS;
  2146. }
  2147. static void winusbx_close(int sub_api, struct libusb_device_handle *dev_handle)
  2148. {
  2149. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  2150. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  2151. HANDLE handle;
  2152. int i;
  2153. if (sub_api == SUB_API_NOTSET)
  2154. sub_api = priv->sub_api;
  2155. if (WinUSBX[sub_api].hDll == NULL)
  2156. return;
  2157. if (priv->apib->id == USB_API_COMPOSITE) {
  2158. // If this is a composite device, just free and close all WinUSB-like
  2159. // interfaces directly (each is independent and not associated with another)
  2160. for (i = 0; i < USB_MAXINTERFACES; i++) {
  2161. if (priv->usb_interface[i].apib->id == USB_API_WINUSBX) {
  2162. handle = handle_priv->interface_handle[i].api_handle;
  2163. if (HANDLE_VALID(handle))
  2164. WinUSBX[sub_api].Free(handle);
  2165. handle = handle_priv->interface_handle[i].dev_handle;
  2166. if (HANDLE_VALID(handle))
  2167. CloseHandle(handle);
  2168. }
  2169. }
  2170. } else {
  2171. // If this is a WinUSB device, free all interfaces above interface 0,
  2172. // then free and close interface 0 last
  2173. for (i = 1; i < USB_MAXINTERFACES; i++) {
  2174. handle = handle_priv->interface_handle[i].api_handle;
  2175. if (HANDLE_VALID(handle))
  2176. WinUSBX[sub_api].Free(handle);
  2177. }
  2178. handle = handle_priv->interface_handle[0].api_handle;
  2179. if (HANDLE_VALID(handle))
  2180. WinUSBX[sub_api].Free(handle);
  2181. handle = handle_priv->interface_handle[0].dev_handle;
  2182. if (HANDLE_VALID(handle))
  2183. CloseHandle(handle);
  2184. }
  2185. }
  2186. static int winusbx_configure_endpoints(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface)
  2187. {
  2188. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  2189. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  2190. HANDLE winusb_handle = handle_priv->interface_handle[iface].api_handle;
  2191. UCHAR policy;
  2192. ULONG timeout = 0;
  2193. uint8_t endpoint_address;
  2194. int i;
  2195. CHECK_WINUSBX_AVAILABLE(sub_api);
  2196. // With handle and endpoints set (in parent), we can setup the default pipe properties
  2197. // see http://download.microsoft.com/download/D/1/D/D1DD7745-426B-4CC3-A269-ABBBE427C0EF/DVC-T705_DDC08.pptx
  2198. for (i = -1; i < priv->usb_interface[iface].nb_endpoints; i++) {
  2199. endpoint_address = (i == -1) ? 0 : priv->usb_interface[iface].endpoint[i];
  2200. if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
  2201. PIPE_TRANSFER_TIMEOUT, sizeof(ULONG), &timeout))
  2202. usbi_dbg(HANDLE_CTX(dev_handle), "failed to set PIPE_TRANSFER_TIMEOUT for control endpoint %02X", endpoint_address);
  2203. if ((i == -1) || (sub_api == SUB_API_LIBUSB0))
  2204. continue; // Other policies don't apply to control endpoint or libusb0
  2205. policy = false;
  2206. handle_priv->interface_handle[iface].zlp[endpoint_address] = WINUSB_ZLP_UNSET;
  2207. if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
  2208. SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy))
  2209. usbi_dbg(HANDLE_CTX(dev_handle), "failed to disable SHORT_PACKET_TERMINATE for endpoint %02X", endpoint_address);
  2210. if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
  2211. IGNORE_SHORT_PACKETS, sizeof(UCHAR), &policy))
  2212. usbi_dbg(HANDLE_CTX(dev_handle), "failed to disable IGNORE_SHORT_PACKETS for endpoint %02X", endpoint_address);
  2213. policy = true;
  2214. /* ALLOW_PARTIAL_READS must be enabled due to likely libusbK bug. See:
  2215. https://sourceforge.net/mailarchive/message.php?msg_id=29736015 */
  2216. if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
  2217. ALLOW_PARTIAL_READS, sizeof(UCHAR), &policy))
  2218. usbi_dbg(HANDLE_CTX(dev_handle), "failed to enable ALLOW_PARTIAL_READS for endpoint %02X", endpoint_address);
  2219. if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
  2220. AUTO_CLEAR_STALL, sizeof(UCHAR), &policy))
  2221. usbi_dbg(HANDLE_CTX(dev_handle), "failed to enable AUTO_CLEAR_STALL for endpoint %02X", endpoint_address);
  2222. if (sub_api == SUB_API_LIBUSBK) {
  2223. if (!WinUSBX[sub_api].SetPipePolicy(winusb_handle, endpoint_address,
  2224. ISO_ALWAYS_START_ASAP, sizeof(UCHAR), &policy))
  2225. usbi_dbg(HANDLE_CTX(dev_handle), "failed to enable ISO_ALWAYS_START_ASAP for endpoint %02X", endpoint_address);
  2226. }
  2227. }
  2228. return LIBUSB_SUCCESS;
  2229. }
  2230. static int winusbx_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface)
  2231. {
  2232. struct libusb_context *ctx = HANDLE_CTX(dev_handle);
  2233. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  2234. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  2235. bool is_using_usbccgp = (priv->apib->id == USB_API_COMPOSITE);
  2236. HDEVINFO dev_info;
  2237. char *dev_interface_path = NULL;
  2238. char *dev_interface_path_guid_start;
  2239. char filter_path[] = "\\\\.\\libusb0-0000";
  2240. bool found_filter = false;
  2241. HANDLE file_handle, winusb_handle;
  2242. DWORD err, _index;
  2243. int r;
  2244. CHECK_WINUSBX_AVAILABLE(sub_api);
  2245. // If the device is composite, but using the default Windows composite parent driver (usbccgp)
  2246. // or if it's the first WinUSB-like interface, we get a handle through Initialize().
  2247. if ((is_using_usbccgp) || (iface == 0)) {
  2248. // composite device (independent interfaces) or interface 0
  2249. file_handle = handle_priv->interface_handle[iface].dev_handle;
  2250. if (!HANDLE_VALID(file_handle))
  2251. return LIBUSB_ERROR_NOT_FOUND;
  2252. if (!WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
  2253. handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
  2254. err = GetLastError();
  2255. switch (err) {
  2256. case ERROR_BAD_COMMAND:
  2257. // The device was disconnected
  2258. usbi_err(ctx, "could not access interface %u: %s", iface, windows_error_str(0));
  2259. return LIBUSB_ERROR_NO_DEVICE;
  2260. default:
  2261. // it may be that we're using the libusb0 filter driver.
  2262. // TODO: can we move this whole business into the K/0 DLL?
  2263. r = LIBUSB_SUCCESS;
  2264. for (_index = 0; ; _index++) {
  2265. safe_free(dev_interface_path);
  2266. if (found_filter)
  2267. break;
  2268. r = get_interface_details_filter(ctx, &dev_info, _index, filter_path, &dev_interface_path);
  2269. if ((r != LIBUSB_SUCCESS) || (dev_interface_path == NULL))
  2270. break;
  2271. // ignore GUID part
  2272. dev_interface_path_guid_start = strchr(dev_interface_path, '{');
  2273. if (dev_interface_path_guid_start == NULL)
  2274. continue;
  2275. *dev_interface_path_guid_start = '\0';
  2276. if (strncmp(dev_interface_path, priv->usb_interface[iface].path, strlen(dev_interface_path)) == 0) {
  2277. file_handle = windows_open(dev_handle, filter_path, GENERIC_READ | GENERIC_WRITE);
  2278. if (file_handle != INVALID_HANDLE_VALUE) {
  2279. if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
  2280. // Replace the existing file handle with the working one
  2281. CloseHandle(handle_priv->interface_handle[iface].dev_handle);
  2282. handle_priv->interface_handle[iface].dev_handle = file_handle;
  2283. found_filter = true;
  2284. } else {
  2285. usbi_err(ctx, "could not initialize filter driver for %s", filter_path);
  2286. CloseHandle(file_handle);
  2287. }
  2288. } else {
  2289. usbi_err(ctx, "could not open device %s: %s", filter_path, windows_error_str(0));
  2290. }
  2291. }
  2292. }
  2293. if (r != LIBUSB_SUCCESS)
  2294. return r;
  2295. if (!found_filter) {
  2296. usbi_err(ctx, "could not access interface %u: %s", iface, windows_error_str(err));
  2297. return LIBUSB_ERROR_ACCESS;
  2298. }
  2299. }
  2300. }
  2301. handle_priv->interface_handle[iface].api_handle = winusb_handle;
  2302. } else {
  2303. // For all other interfaces, use GetAssociatedInterface()
  2304. winusb_handle = handle_priv->interface_handle[0].api_handle;
  2305. // It is a requirement for multiple interface devices on Windows that, to you
  2306. // must first claim the first interface before you claim the others
  2307. if (!HANDLE_VALID(winusb_handle)) {
  2308. file_handle = handle_priv->interface_handle[0].dev_handle;
  2309. if (WinUSBX[sub_api].Initialize(file_handle, &winusb_handle)) {
  2310. handle_priv->interface_handle[0].api_handle = winusb_handle;
  2311. usbi_warn(ctx, "auto-claimed interface 0 (required to claim %u with WinUSB)", iface);
  2312. } else {
  2313. usbi_warn(ctx, "failed to auto-claim interface 0 (required to claim %u with WinUSB): %s", iface, windows_error_str(0));
  2314. return LIBUSB_ERROR_ACCESS;
  2315. }
  2316. }
  2317. if (!WinUSBX[sub_api].GetAssociatedInterface(winusb_handle, (UCHAR)(iface - 1),
  2318. &handle_priv->interface_handle[iface].api_handle)) {
  2319. handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
  2320. switch (GetLastError()) {
  2321. case ERROR_NO_MORE_ITEMS: // invalid iface
  2322. return LIBUSB_ERROR_NOT_FOUND;
  2323. case ERROR_BAD_COMMAND: // The device was disconnected
  2324. return LIBUSB_ERROR_NO_DEVICE;
  2325. case ERROR_ALREADY_EXISTS: // already claimed
  2326. return LIBUSB_ERROR_BUSY;
  2327. default:
  2328. usbi_err(ctx, "could not claim interface %u: %s", iface, windows_error_str(0));
  2329. return LIBUSB_ERROR_ACCESS;
  2330. }
  2331. }
  2332. handle_priv->interface_handle[iface].dev_handle = handle_priv->interface_handle[0].dev_handle;
  2333. }
  2334. usbi_dbg(ctx, "claimed interface %u", iface);
  2335. handle_priv->active_interface = iface;
  2336. return LIBUSB_SUCCESS;
  2337. }
  2338. static int winusbx_release_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface)
  2339. {
  2340. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  2341. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  2342. HANDLE winusb_handle;
  2343. CHECK_WINUSBX_AVAILABLE(sub_api);
  2344. winusb_handle = handle_priv->interface_handle[iface].api_handle;
  2345. if (!HANDLE_VALID(winusb_handle))
  2346. return LIBUSB_ERROR_NOT_FOUND;
  2347. WinUSBX[sub_api].Free(winusb_handle);
  2348. handle_priv->interface_handle[iface].api_handle = INVALID_HANDLE_VALUE;
  2349. return LIBUSB_SUCCESS;
  2350. }
  2351. /*
  2352. * Return the first valid interface (of the same API type), for control transfers
  2353. */
  2354. static int get_valid_interface(struct libusb_device_handle *dev_handle, int api_id)
  2355. {
  2356. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  2357. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  2358. int i;
  2359. if ((api_id < USB_API_WINUSBX) || (api_id > USB_API_HID)) {
  2360. usbi_dbg(HANDLE_CTX(dev_handle), "unsupported API ID");
  2361. return -1;
  2362. }
  2363. for (i = 0; i < USB_MAXINTERFACES; i++) {
  2364. if (HANDLE_VALID(handle_priv->interface_handle[i].dev_handle)
  2365. && HANDLE_VALID(handle_priv->interface_handle[i].api_handle)
  2366. && (priv->usb_interface[i].apib->id == api_id))
  2367. return i;
  2368. }
  2369. return -1;
  2370. }
  2371. /*
  2372. * Check a specific interface is valid (of the same API type), for control transfers
  2373. */
  2374. static int check_valid_interface(struct libusb_device_handle *dev_handle, unsigned short interface, int api_id)
  2375. {
  2376. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  2377. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  2378. if (interface >= USB_MAXINTERFACES)
  2379. return -1;
  2380. if ((api_id < USB_API_WINUSBX) || (api_id > USB_API_HID)) {
  2381. usbi_dbg(HANDLE_CTX(dev_handle), "unsupported API ID");
  2382. return -1;
  2383. }
  2384. // try the requested interface
  2385. if (HANDLE_VALID(handle_priv->interface_handle[interface].dev_handle)
  2386. && HANDLE_VALID(handle_priv->interface_handle[interface].api_handle)
  2387. && (priv->usb_interface[interface].apib->id == api_id))
  2388. return interface;
  2389. return -1;
  2390. }
  2391. /*
  2392. * Lookup interface by endpoint address. -1 if not found
  2393. */
  2394. static int interface_by_endpoint(struct winusb_device_priv *priv,
  2395. struct winusb_device_handle_priv *handle_priv, uint8_t endpoint_address)
  2396. {
  2397. int i, j;
  2398. for (i = 0; i < USB_MAXINTERFACES; i++) {
  2399. if (!HANDLE_VALID(handle_priv->interface_handle[i].api_handle))
  2400. continue;
  2401. if (priv->usb_interface[i].endpoint == NULL)
  2402. continue;
  2403. for (j = 0; j < priv->usb_interface[i].nb_endpoints; j++) {
  2404. if (priv->usb_interface[i].endpoint[j] == endpoint_address)
  2405. return i;
  2406. }
  2407. }
  2408. return -1;
  2409. }
  2410. static int winusbx_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
  2411. {
  2412. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  2413. struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
  2414. struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
  2415. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(transfer->dev_handle);
  2416. PWINUSB_SETUP_PACKET setup = (PWINUSB_SETUP_PACKET)transfer->buffer;
  2417. ULONG size, transferred;
  2418. HANDLE winusb_handle;
  2419. OVERLAPPED *overlapped;
  2420. int current_interface;
  2421. CHECK_WINUSBX_AVAILABLE(sub_api);
  2422. size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
  2423. // Windows places upper limits on the control transfer size
  2424. // See: https://docs.microsoft.com/en-us/windows-hardware/drivers/usbcon/usb-bandwidth-allocation#maximum-transfer-size
  2425. if (size > MAX_CTRL_BUFFER_LENGTH)
  2426. return LIBUSB_ERROR_INVALID_PARAM;
  2427. if ((setup->RequestType & 0x1F) == LIBUSB_RECIPIENT_INTERFACE)
  2428. current_interface = check_valid_interface(transfer->dev_handle, setup->Index & 0xff, USB_API_WINUSBX);
  2429. else
  2430. current_interface = get_valid_interface(transfer->dev_handle, USB_API_WINUSBX);
  2431. if (current_interface < 0) {
  2432. if (auto_claim(transfer, &current_interface, USB_API_WINUSBX) != LIBUSB_SUCCESS)
  2433. return LIBUSB_ERROR_NOT_FOUND;
  2434. }
  2435. usbi_dbg(ITRANSFER_CTX(itransfer), "will use interface %d", current_interface);
  2436. transfer_priv->interface_number = (uint8_t)current_interface;
  2437. winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
  2438. set_transfer_priv_handle(itransfer, handle_priv->interface_handle[current_interface].dev_handle);
  2439. overlapped = get_transfer_priv_overlapped(itransfer);
  2440. // Sending of set configuration control requests from WinUSB creates issues, except when using libusb0.sys
  2441. if (sub_api != SUB_API_LIBUSB0
  2442. && (LIBUSB_REQ_TYPE(setup->RequestType) == LIBUSB_REQUEST_TYPE_STANDARD)
  2443. && (setup->Request == LIBUSB_REQUEST_SET_CONFIGURATION)) {
  2444. if (setup->Value != priv->active_config) {
  2445. usbi_warn(TRANSFER_CTX(transfer), "cannot set configuration other than the default one");
  2446. return LIBUSB_ERROR_NOT_SUPPORTED;
  2447. }
  2448. windows_force_sync_completion(itransfer, 0);
  2449. } else {
  2450. if (!WinUSBX[sub_api].ControlTransfer(winusb_handle, *setup, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, size, &transferred, overlapped)) {
  2451. if (GetLastError() != ERROR_IO_PENDING) {
  2452. usbi_warn(TRANSFER_CTX(transfer), "ControlTransfer failed: %s", windows_error_str(0));
  2453. return LIBUSB_ERROR_IO;
  2454. }
  2455. } else {
  2456. windows_force_sync_completion(itransfer, transferred);
  2457. }
  2458. }
  2459. return LIBUSB_SUCCESS;
  2460. }
  2461. static int winusbx_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting)
  2462. {
  2463. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  2464. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  2465. HANDLE winusb_handle;
  2466. CHECK_WINUSBX_AVAILABLE(sub_api);
  2467. winusb_handle = handle_priv->interface_handle[iface].api_handle;
  2468. if (!HANDLE_VALID(winusb_handle)) {
  2469. usbi_err(HANDLE_CTX(dev_handle), "interface must be claimed first");
  2470. return LIBUSB_ERROR_NOT_FOUND;
  2471. }
  2472. if (!WinUSBX[sub_api].SetCurrentAlternateSetting(winusb_handle, altsetting)) {
  2473. usbi_err(HANDLE_CTX(dev_handle), "SetCurrentAlternateSetting failed: %s", windows_error_str(0));
  2474. return LIBUSB_ERROR_IO;
  2475. }
  2476. return LIBUSB_SUCCESS;
  2477. }
  2478. static void WINAPI winusbx_native_iso_transfer_continue_stream_callback(struct libusb_transfer *transfer)
  2479. {
  2480. // If this callback is invoked, this means that we attempted to set ContinueStream
  2481. // to TRUE when calling Read/WriteIsochPipeAsap in winusbx_do_iso_transfer.
  2482. // The role of this callback is to fallback to ContinueStream = FALSE if the transfer
  2483. // did not succeed.
  2484. struct winusb_transfer_priv *transfer_priv =
  2485. get_winusb_transfer_priv(LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer));
  2486. bool fallback = (transfer->status != LIBUSB_TRANSFER_COMPLETED);
  2487. int idx;
  2488. // Restore the user callback
  2489. transfer->callback = transfer_priv->iso_user_callback;
  2490. for (idx = 0; idx < transfer->num_iso_packets && !fallback; idx++) {
  2491. if (transfer->iso_packet_desc[idx].status != LIBUSB_TRANSFER_COMPLETED)
  2492. fallback = true;
  2493. }
  2494. if (!fallback) {
  2495. // If the transfer was successful, we restore the user callback and call it.
  2496. if (transfer->callback)
  2497. transfer->callback(transfer);
  2498. } else {
  2499. // If the transfer wasn't successful we reschedule the transfer while forcing it
  2500. // not to continue the stream. This might results in a 5-ms delay.
  2501. transfer_priv->iso_break_stream = TRUE;
  2502. libusb_submit_transfer(transfer);
  2503. }
  2504. }
  2505. static int winusbx_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer)
  2506. {
  2507. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  2508. struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
  2509. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(transfer->dev_handle);
  2510. struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
  2511. HANDLE winusb_handle;
  2512. OVERLAPPED *overlapped;
  2513. BOOL ret;
  2514. int current_interface;
  2515. CHECK_WINUSBX_AVAILABLE(sub_api);
  2516. current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
  2517. if (current_interface < 0) {
  2518. usbi_err(TRANSFER_CTX(transfer), "unable to match endpoint to an open interface - cancelling transfer");
  2519. return LIBUSB_ERROR_NOT_FOUND;
  2520. }
  2521. usbi_dbg(TRANSFER_CTX(transfer), "matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
  2522. transfer_priv->interface_number = (uint8_t)current_interface;
  2523. winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
  2524. set_transfer_priv_handle(itransfer, handle_priv->interface_handle[current_interface].dev_handle);
  2525. overlapped = get_transfer_priv_overlapped(itransfer);
  2526. if ((sub_api == SUB_API_LIBUSBK) || (sub_api == SUB_API_LIBUSB0)) {
  2527. int i;
  2528. UINT offset;
  2529. size_t iso_ctx_size;
  2530. PKISO_CONTEXT iso_context;
  2531. if (WinUSBX[sub_api].IsoReadPipe == NULL) {
  2532. usbi_warn(TRANSFER_CTX(transfer), "libusbK DLL does not support isoch transfers");
  2533. return LIBUSB_ERROR_NOT_SUPPORTED;
  2534. }
  2535. iso_ctx_size = sizeof(KISO_CONTEXT) + (transfer->num_iso_packets * sizeof(KISO_PACKET));
  2536. transfer_priv->iso_context = iso_context = calloc(1, iso_ctx_size);
  2537. if (transfer_priv->iso_context == NULL)
  2538. return LIBUSB_ERROR_NO_MEM;
  2539. // start ASAP
  2540. iso_context->StartFrame = 0;
  2541. iso_context->NumberOfPackets = (SHORT)transfer->num_iso_packets;
  2542. // convert the transfer packet lengths to iso_packet offsets
  2543. offset = 0;
  2544. for (i = 0; i < transfer->num_iso_packets; i++) {
  2545. iso_context->IsoPackets[i].offset = offset;
  2546. offset += transfer->iso_packet_desc[i].length;
  2547. }
  2548. if (IS_XFERIN(transfer)) {
  2549. usbi_dbg(TRANSFER_CTX(transfer), "reading %d iso packets", transfer->num_iso_packets);
  2550. ret = WinUSBX[sub_api].IsoReadPipe(winusb_handle, transfer->endpoint, transfer->buffer, transfer->length, overlapped, iso_context);
  2551. } else {
  2552. usbi_dbg(TRANSFER_CTX(transfer), "writing %d iso packets", transfer->num_iso_packets);
  2553. ret = WinUSBX[sub_api].IsoWritePipe(winusb_handle, transfer->endpoint, transfer->buffer, transfer->length, overlapped, iso_context);
  2554. }
  2555. if (!ret && GetLastError() != ERROR_IO_PENDING) {
  2556. usbi_err(TRANSFER_CTX(transfer), "IsoReadPipe/IsoWritePipe failed: %s", windows_error_str(0));
  2557. return LIBUSB_ERROR_IO;
  2558. }
  2559. return LIBUSB_SUCCESS;
  2560. } else if (sub_api == SUB_API_WINUSB) {
  2561. WINUSB_PIPE_INFORMATION_EX pipe_info_ex = { 0 };
  2562. WINUSB_ISOCH_BUFFER_HANDLE buffer_handle;
  2563. ULONG iso_transfer_size_multiple;
  2564. int out_transfer_length = 0;
  2565. int idx;
  2566. // Depending on the version of Microsoft WinUSB, isochronous transfers may not be supported.
  2567. if (WinUSBX[sub_api].ReadIsochPipeAsap == NULL) {
  2568. usbi_warn(TRANSFER_CTX(transfer), "WinUSB DLL does not support isoch transfers");
  2569. return LIBUSB_ERROR_NOT_SUPPORTED;
  2570. }
  2571. if (sizeof(struct libusb_iso_packet_descriptor) != sizeof(USBD_ISO_PACKET_DESCRIPTOR)) {
  2572. usbi_err(TRANSFER_CTX(transfer), "size of WinUsb and libusb isoch packet descriptors don't match");
  2573. return LIBUSB_ERROR_NOT_SUPPORTED;
  2574. }
  2575. // Query the pipe extended information to find the pipe index corresponding to the endpoint.
  2576. for (idx = 0; idx < priv->usb_interface[current_interface].nb_endpoints; ++idx) {
  2577. ret = WinUSBX[sub_api].QueryPipeEx(winusb_handle, (UINT8)priv->usb_interface[current_interface].current_altsetting, (UCHAR)idx, &pipe_info_ex);
  2578. if (!ret) {
  2579. usbi_err(TRANSFER_CTX(transfer), "couldn't query interface settings for USB pipe with index %d. Error: %s", idx, windows_error_str(0));
  2580. return LIBUSB_ERROR_NOT_FOUND;
  2581. }
  2582. if (pipe_info_ex.PipeId == transfer->endpoint && pipe_info_ex.PipeType == UsbdPipeTypeIsochronous)
  2583. break;
  2584. }
  2585. // Make sure we found the index.
  2586. if (idx == priv->usb_interface[current_interface].nb_endpoints) {
  2587. usbi_err(TRANSFER_CTX(transfer), "couldn't find isoch endpoint 0x%02x", transfer->endpoint);
  2588. return LIBUSB_ERROR_NOT_FOUND;
  2589. }
  2590. if (IS_XFERIN(transfer)) {
  2591. int interval = pipe_info_ex.Interval;
  2592. // For high-speed and SuperSpeed device, the interval is 2**(bInterval-1).
  2593. if (transfer->dev_handle->dev->speed >= LIBUSB_SPEED_HIGH)
  2594. interval = (1 << (pipe_info_ex.Interval - 1));
  2595. // WinUSB only supports isoch transfers spanning a full USB frames. Later, we might be smarter about this
  2596. // and allocate a temporary buffer. However, this is harder than it seems as its destruction would depend on overlapped
  2597. // IO...
  2598. if (transfer->dev_handle->dev->speed >= LIBUSB_SPEED_HIGH) // Microframes (125us)
  2599. iso_transfer_size_multiple = (pipe_info_ex.MaximumBytesPerInterval * 8) / interval;
  2600. else // Normal Frames (1ms)
  2601. iso_transfer_size_multiple = pipe_info_ex.MaximumBytesPerInterval / interval;
  2602. if (transfer->length % iso_transfer_size_multiple != 0) {
  2603. usbi_err(TRANSFER_CTX(transfer), "length of isoch buffer must be a multiple of the MaximumBytesPerInterval * 8 / Interval");
  2604. return LIBUSB_ERROR_INVALID_PARAM;
  2605. }
  2606. } else {
  2607. // If this is an OUT transfer, we make sure the isoch packets are contiguous as this isn't supported otherwise.
  2608. bool size_should_be_zero = false;
  2609. for (idx = 0; idx < transfer->num_iso_packets; ++idx) {
  2610. if ((size_should_be_zero && transfer->iso_packet_desc[idx].length != 0) ||
  2611. (transfer->iso_packet_desc[idx].length != pipe_info_ex.MaximumBytesPerInterval && idx + 1 < transfer->num_iso_packets && transfer->iso_packet_desc[idx + 1].length > 0)) {
  2612. usbi_err(TRANSFER_CTX(transfer), "isoch packets for OUT transfer with WinUSB must be contiguous in memory");
  2613. return LIBUSB_ERROR_INVALID_PARAM;
  2614. }
  2615. size_should_be_zero = (transfer->iso_packet_desc[idx].length == 0);
  2616. out_transfer_length += transfer->iso_packet_desc[idx].length;
  2617. }
  2618. }
  2619. if (transfer_priv->isoch_buffer_handle != NULL) {
  2620. if (WinUSBX[sub_api].UnregisterIsochBuffer(transfer_priv->isoch_buffer_handle)) {
  2621. transfer_priv->isoch_buffer_handle = NULL;
  2622. } else {
  2623. usbi_err(TRANSFER_CTX(transfer), "failed to unregister WinUSB isoch buffer: %s", windows_error_str(0));
  2624. return LIBUSB_ERROR_OTHER;
  2625. }
  2626. }
  2627. // Register the isoch buffer to the operating system.
  2628. ret = WinUSBX[sub_api].RegisterIsochBuffer(winusb_handle, transfer->endpoint, transfer->buffer, transfer->length, &buffer_handle);
  2629. if (!ret) {
  2630. usbi_err(TRANSFER_CTX(transfer), "failed to register WinUSB isoch buffer: %s", windows_error_str(0));
  2631. return LIBUSB_ERROR_NO_MEM;
  2632. }
  2633. // Important note: the WinUSB_Read/WriteIsochPipeAsap API requires a ContinueStream parameter that tells whether the isochronous
  2634. // stream must be continued or if the WinUSB driver can schedule the transfer at its convenience. Profiling subsequent transfers
  2635. // with ContinueStream = FALSE showed that 5 frames, i.e. about 5 milliseconds, were left empty between each transfer. This
  2636. // is critical as this greatly diminish the achievable isochronous bandwidth. We solved the problem using the following strategy:
  2637. // - Transfers are first scheduled with ContinueStream = TRUE and with winusbx_iso_transfer_continue_stream_callback as user callback.
  2638. // - If the transfer succeeds, winusbx_iso_transfer_continue_stream_callback restore the user callback and calls its.
  2639. // - If the transfer fails, winusbx_iso_transfer_continue_stream_callback reschedule the transfer and force ContinueStream = FALSE.
  2640. if (!transfer_priv->iso_break_stream) {
  2641. transfer_priv->iso_user_callback = transfer->callback;
  2642. transfer->callback = winusbx_native_iso_transfer_continue_stream_callback;
  2643. }
  2644. // Initiate the transfers.
  2645. if (IS_XFERIN(transfer))
  2646. ret = WinUSBX[sub_api].ReadIsochPipeAsap(buffer_handle, 0, transfer->length, !transfer_priv->iso_break_stream, transfer->num_iso_packets, (PUSBD_ISO_PACKET_DESCRIPTOR)transfer->iso_packet_desc, overlapped);
  2647. else
  2648. ret = WinUSBX[sub_api].WriteIsochPipeAsap(buffer_handle, 0, out_transfer_length, !transfer_priv->iso_break_stream, overlapped);
  2649. if (!ret && GetLastError() != ERROR_IO_PENDING) {
  2650. usbi_err(TRANSFER_CTX(transfer), "ReadIsochPipeAsap/WriteIsochPipeAsap failed: %s", windows_error_str(0));
  2651. if (!WinUSBX[sub_api].UnregisterIsochBuffer(buffer_handle))
  2652. usbi_warn(TRANSFER_CTX(transfer), "failed to unregister WinUSB isoch buffer: %s", windows_error_str(0));
  2653. return LIBUSB_ERROR_IO;
  2654. }
  2655. // Restore the ContinueStream parameter to TRUE.
  2656. transfer_priv->iso_break_stream = FALSE;
  2657. transfer_priv->isoch_buffer_handle = buffer_handle;
  2658. return LIBUSB_SUCCESS;
  2659. } else {
  2660. PRINT_UNSUPPORTED_API(winusbx_submit_iso_transfer);
  2661. return LIBUSB_ERROR_NOT_SUPPORTED;
  2662. }
  2663. }
  2664. static int winusbx_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
  2665. {
  2666. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  2667. struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
  2668. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(transfer->dev_handle);
  2669. struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
  2670. HANDLE winusb_handle;
  2671. OVERLAPPED *overlapped;
  2672. BOOL ret;
  2673. int current_interface;
  2674. CHECK_WINUSBX_AVAILABLE(sub_api);
  2675. current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
  2676. if (current_interface < 0) {
  2677. usbi_err(TRANSFER_CTX(transfer), "unable to match endpoint to an open interface - cancelling transfer");
  2678. return LIBUSB_ERROR_NOT_FOUND;
  2679. }
  2680. usbi_dbg(TRANSFER_CTX(transfer), "matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
  2681. transfer_priv->interface_number = (uint8_t)current_interface;
  2682. winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
  2683. set_transfer_priv_handle(itransfer, handle_priv->interface_handle[current_interface].dev_handle);
  2684. overlapped = get_transfer_priv_overlapped(itransfer);
  2685. if (IS_XFERIN(transfer)) {
  2686. usbi_dbg(TRANSFER_CTX(transfer), "reading %d bytes", transfer->length);
  2687. ret = WinUSBX[sub_api].ReadPipe(winusb_handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, overlapped);
  2688. } else {
  2689. // Set SHORT_PACKET_TERMINATE if ZLP requested.
  2690. // Changing this can be a problem with packets in flight, so only allow on the first transfer.
  2691. UCHAR policy = (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) != 0;
  2692. uint8_t* current_zlp = &handle_priv->interface_handle[current_interface].zlp[transfer->endpoint];
  2693. if (*current_zlp == WINUSB_ZLP_UNSET) {
  2694. if (policy &&
  2695. !WinUSBX[sub_api].SetPipePolicy(winusb_handle, transfer->endpoint,
  2696. SHORT_PACKET_TERMINATE, sizeof(UCHAR), &policy)) {
  2697. usbi_err(TRANSFER_CTX(transfer), "failed to set SHORT_PACKET_TERMINATE for endpoint %02X", transfer->endpoint);
  2698. return LIBUSB_ERROR_NOT_SUPPORTED;
  2699. }
  2700. *current_zlp = policy ? WINUSB_ZLP_ON : WINUSB_ZLP_OFF;
  2701. } else if (policy != (*current_zlp == WINUSB_ZLP_ON)) {
  2702. usbi_err(TRANSFER_CTX(transfer), "cannot change ZERO_PACKET for endpoint %02X on Windows", transfer->endpoint);
  2703. return LIBUSB_ERROR_NOT_SUPPORTED;
  2704. }
  2705. usbi_dbg(TRANSFER_CTX(transfer), "writing %d bytes", transfer->length);
  2706. ret = WinUSBX[sub_api].WritePipe(winusb_handle, transfer->endpoint, transfer->buffer, transfer->length, NULL, overlapped);
  2707. }
  2708. if (!ret && GetLastError() != ERROR_IO_PENDING) {
  2709. usbi_err(TRANSFER_CTX(transfer), "ReadPipe/WritePipe failed: %s", windows_error_str(0));
  2710. return LIBUSB_ERROR_IO;
  2711. }
  2712. return LIBUSB_SUCCESS;
  2713. }
  2714. static int winusbx_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
  2715. {
  2716. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  2717. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  2718. HANDLE winusb_handle;
  2719. int current_interface;
  2720. CHECK_WINUSBX_AVAILABLE(sub_api);
  2721. current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
  2722. if (current_interface < 0) {
  2723. usbi_err(HANDLE_CTX(dev_handle), "unable to match endpoint to an open interface - cannot clear");
  2724. return LIBUSB_ERROR_NOT_FOUND;
  2725. }
  2726. usbi_dbg(HANDLE_CTX(dev_handle), "matched endpoint %02X with interface %d", endpoint, current_interface);
  2727. winusb_handle = handle_priv->interface_handle[current_interface].api_handle;
  2728. if (!WinUSBX[sub_api].ResetPipe(winusb_handle, endpoint)) {
  2729. usbi_err(HANDLE_CTX(dev_handle), "ResetPipe failed: %s", windows_error_str(0));
  2730. return LIBUSB_ERROR_NO_DEVICE;
  2731. }
  2732. return LIBUSB_SUCCESS;
  2733. }
  2734. static int winusbx_cancel_transfer(int sub_api, struct usbi_transfer *itransfer)
  2735. {
  2736. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  2737. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(transfer->dev_handle);
  2738. struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
  2739. struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
  2740. int current_interface = transfer_priv->interface_number;
  2741. HANDLE handle;
  2742. CHECK_WINUSBX_AVAILABLE(sub_api);
  2743. usbi_dbg(TRANSFER_CTX(transfer), "will use interface %d", current_interface);
  2744. handle = handle_priv->interface_handle[current_interface].api_handle;
  2745. if (!WinUSBX[sub_api].AbortPipe(handle, transfer->endpoint)) {
  2746. usbi_err(TRANSFER_CTX(transfer), "AbortPipe failed: %s", windows_error_str(0));
  2747. return LIBUSB_ERROR_NO_DEVICE;
  2748. }
  2749. return LIBUSB_SUCCESS;
  2750. }
  2751. /*
  2752. * from the "How to Use WinUSB to Communicate with a USB Device" Microsoft white paper
  2753. * (http://www.microsoft.com/whdc/connect/usb/winusb_howto.mspx):
  2754. * "WinUSB does not support host-initiated reset port and cycle port operations" and
  2755. * IOCTL_INTERNAL_USB_CYCLE_PORT is only available in kernel mode and the
  2756. * IOCTL_USB_HUB_CYCLE_PORT ioctl was removed from Vista => the best we can do is
  2757. * cycle the pipes (and even then, the control pipe can not be reset using WinUSB)
  2758. */
  2759. // TODO: (post hotplug): see if we can force eject the device and redetect it (reuse hotplug?)
  2760. static int winusbx_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
  2761. {
  2762. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  2763. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  2764. HANDLE winusb_handle;
  2765. int i, j;
  2766. CHECK_WINUSBX_AVAILABLE(sub_api);
  2767. // Reset any available pipe (except control)
  2768. for (i = 0; i < USB_MAXINTERFACES; i++) {
  2769. winusb_handle = handle_priv->interface_handle[i].api_handle;
  2770. if (HANDLE_VALID(winusb_handle)) {
  2771. for (j = 0; j < priv->usb_interface[i].nb_endpoints; j++) {
  2772. usbi_dbg(HANDLE_CTX(dev_handle), "resetting ep %02X", priv->usb_interface[i].endpoint[j]);
  2773. if (!WinUSBX[sub_api].AbortPipe(winusb_handle, priv->usb_interface[i].endpoint[j]))
  2774. usbi_err(HANDLE_CTX(dev_handle), "AbortPipe (pipe address %02X) failed: %s",
  2775. priv->usb_interface[i].endpoint[j], windows_error_str(0));
  2776. // FlushPipe seems to fail on OUT pipes
  2777. if (IS_EPIN(priv->usb_interface[i].endpoint[j])
  2778. && (!WinUSBX[sub_api].FlushPipe(winusb_handle, priv->usb_interface[i].endpoint[j])))
  2779. usbi_err(HANDLE_CTX(dev_handle), "FlushPipe (pipe address %02X) failed: %s",
  2780. priv->usb_interface[i].endpoint[j], windows_error_str(0));
  2781. if (!WinUSBX[sub_api].ResetPipe(winusb_handle, priv->usb_interface[i].endpoint[j]))
  2782. usbi_err(HANDLE_CTX(dev_handle), "ResetPipe (pipe address %02X) failed: %s",
  2783. priv->usb_interface[i].endpoint[j], windows_error_str(0));
  2784. }
  2785. }
  2786. }
  2787. // libusbK & libusb0 have the ability to issue an actual device reset
  2788. if ((sub_api != SUB_API_WINUSB) && (WinUSBX[sub_api].ResetDevice != NULL)) {
  2789. winusb_handle = handle_priv->interface_handle[0].api_handle;
  2790. if (HANDLE_VALID(winusb_handle))
  2791. WinUSBX[sub_api].ResetDevice(winusb_handle);
  2792. }
  2793. return LIBUSB_SUCCESS;
  2794. }
  2795. static enum libusb_transfer_status winusbx_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, DWORD length)
  2796. {
  2797. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  2798. struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
  2799. int i;
  2800. if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS) {
  2801. struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
  2802. if (sub_api == SUB_API_NOTSET)
  2803. sub_api = priv->sub_api;
  2804. if (WinUSBX[sub_api].hDll == NULL)
  2805. return LIBUSB_TRANSFER_ERROR;
  2806. // for isochronous, need to copy the individual iso packet actual_lengths and statuses
  2807. if ((sub_api == SUB_API_LIBUSBK) || (sub_api == SUB_API_LIBUSB0)) {
  2808. // iso only supported on libusbk-based backends for now
  2809. PKISO_CONTEXT iso_context = transfer_priv->iso_context;
  2810. for (i = 0; i < transfer->num_iso_packets; i++) {
  2811. if (IS_XFERIN(transfer)) {
  2812. transfer->iso_packet_desc[i].actual_length = iso_context->IsoPackets[i].actual_length;
  2813. } else {
  2814. // On Windows the usbd Length field is not used for OUT transfers.
  2815. // Copy the requested value back for consistency with other platforms.
  2816. transfer->iso_packet_desc[i].actual_length = transfer->iso_packet_desc[i].length;
  2817. }
  2818. // TODO translate USDB_STATUS codes http://msdn.microsoft.com/en-us/library/ff539136(VS.85).aspx to libusb_transfer_status
  2819. //transfer->iso_packet_desc[i].status = transfer_priv->iso_context->IsoPackets[i].status;
  2820. }
  2821. } else if (sub_api == SUB_API_WINUSB) {
  2822. if (IS_XFERIN(transfer)) {
  2823. /* Convert isochronous packet descriptor between Windows and libusb representation.
  2824. * Both representation are guaranteed to have the same length in bytes.*/
  2825. PUSBD_ISO_PACKET_DESCRIPTOR usbd_iso_packet_desc = (PUSBD_ISO_PACKET_DESCRIPTOR)transfer->iso_packet_desc;
  2826. for (i = 0; i < transfer->num_iso_packets; i++) {
  2827. unsigned int packet_length = (i < transfer->num_iso_packets - 1) ? (usbd_iso_packet_desc[i + 1].Offset - usbd_iso_packet_desc[i].Offset) : usbd_iso_packet_desc[i].Length;
  2828. unsigned int actual_length = usbd_iso_packet_desc[i].Length;
  2829. USBD_STATUS status = usbd_iso_packet_desc[i].Status;
  2830. transfer->iso_packet_desc[i].length = packet_length;
  2831. transfer->iso_packet_desc[i].actual_length = actual_length;
  2832. transfer->iso_packet_desc[i].status = usbd_status_to_libusb_transfer_status(status);
  2833. }
  2834. } else {
  2835. for (i = 0; i < transfer->num_iso_packets; i++) {
  2836. transfer->iso_packet_desc[i].status = LIBUSB_TRANSFER_COMPLETED;
  2837. // On Windows the usbd Length field is not used for OUT transfers.
  2838. // Copy the requested value back for consistency with other platforms.
  2839. transfer->iso_packet_desc[i].actual_length = transfer->iso_packet_desc[i].length;
  2840. }
  2841. }
  2842. } else {
  2843. // This should only occur if backend is not set correctly or other backend isoc is partially implemented
  2844. PRINT_UNSUPPORTED_API(copy_transfer_data);
  2845. return LIBUSB_TRANSFER_ERROR;
  2846. }
  2847. }
  2848. itransfer->transferred += (int)length;
  2849. return LIBUSB_TRANSFER_COMPLETED;
  2850. }
  2851. /*
  2852. * Internal HID Support functions (from libusb-win32)
  2853. * Note that functions that complete data transfer synchronously must return
  2854. * LIBUSB_COMPLETED instead of LIBUSB_SUCCESS
  2855. */
  2856. static int _hid_get_hid_descriptor(struct hid_device_priv *dev, void *data, size_t *size);
  2857. static int _hid_get_report_descriptor(struct hid_device_priv *dev, void *data, size_t *size);
  2858. static int _hid_wcslen(WCHAR *str)
  2859. {
  2860. int i = 0;
  2861. while (str[i] && (str[i] != 0x409))
  2862. i++;
  2863. return i;
  2864. }
  2865. static int _hid_get_device_descriptor(struct hid_device_priv *hid_priv, void *data, size_t *size)
  2866. {
  2867. struct libusb_device_descriptor d;
  2868. d.bLength = LIBUSB_DT_DEVICE_SIZE;
  2869. d.bDescriptorType = LIBUSB_DT_DEVICE;
  2870. d.bcdUSB = 0x0200; /* 2.00 */
  2871. d.bDeviceClass = 0;
  2872. d.bDeviceSubClass = 0;
  2873. d.bDeviceProtocol = 0;
  2874. d.bMaxPacketSize0 = 64; /* fix this! */
  2875. d.idVendor = (uint16_t)hid_priv->vid;
  2876. d.idProduct = (uint16_t)hid_priv->pid;
  2877. d.bcdDevice = 0x0100;
  2878. d.iManufacturer = hid_priv->string_index[0];
  2879. d.iProduct = hid_priv->string_index[1];
  2880. d.iSerialNumber = hid_priv->string_index[2];
  2881. d.bNumConfigurations = 1;
  2882. if (*size > LIBUSB_DT_DEVICE_SIZE)
  2883. *size = LIBUSB_DT_DEVICE_SIZE;
  2884. memcpy(data, &d, *size);
  2885. return LIBUSB_COMPLETED;
  2886. }
  2887. static int _hid_get_config_descriptor(struct hid_device_priv *hid_priv, void *data, size_t *size)
  2888. {
  2889. char num_endpoints = 0;
  2890. size_t config_total_len = 0;
  2891. char tmp[HID_MAX_CONFIG_DESC_SIZE];
  2892. struct libusb_config_descriptor *cd;
  2893. struct libusb_interface_descriptor *id;
  2894. struct libusb_hid_descriptor *hd;
  2895. struct libusb_endpoint_descriptor *ed;
  2896. size_t tmp_size;
  2897. if (hid_priv->input_report_size)
  2898. num_endpoints++;
  2899. if (hid_priv->output_report_size)
  2900. num_endpoints++;
  2901. config_total_len = LIBUSB_DT_CONFIG_SIZE + LIBUSB_DT_INTERFACE_SIZE
  2902. + LIBUSB_DT_HID_SIZE + num_endpoints * LIBUSB_DT_ENDPOINT_SIZE;
  2903. cd = (struct libusb_config_descriptor *)tmp;
  2904. id = (struct libusb_interface_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE);
  2905. hd = (struct libusb_hid_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
  2906. + LIBUSB_DT_INTERFACE_SIZE);
  2907. ed = (struct libusb_endpoint_descriptor *)(tmp + LIBUSB_DT_CONFIG_SIZE
  2908. + LIBUSB_DT_INTERFACE_SIZE
  2909. + LIBUSB_DT_HID_SIZE);
  2910. cd->bLength = LIBUSB_DT_CONFIG_SIZE;
  2911. cd->bDescriptorType = LIBUSB_DT_CONFIG;
  2912. cd->wTotalLength = (uint16_t)config_total_len;
  2913. cd->bNumInterfaces = 1;
  2914. cd->bConfigurationValue = 1;
  2915. cd->iConfiguration = 0;
  2916. cd->bmAttributes = 1 << 7; /* bus powered */
  2917. cd->MaxPower = 50;
  2918. id->bLength = LIBUSB_DT_INTERFACE_SIZE;
  2919. id->bDescriptorType = LIBUSB_DT_INTERFACE;
  2920. id->bInterfaceNumber = 0;
  2921. id->bAlternateSetting = 0;
  2922. id->bNumEndpoints = num_endpoints;
  2923. id->bInterfaceClass = 3;
  2924. id->bInterfaceSubClass = 0;
  2925. id->bInterfaceProtocol = 0;
  2926. id->iInterface = 0;
  2927. tmp_size = LIBUSB_DT_HID_SIZE;
  2928. _hid_get_hid_descriptor(hid_priv, hd, &tmp_size);
  2929. if (hid_priv->input_report_size) {
  2930. ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
  2931. ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
  2932. ed->bEndpointAddress = HID_IN_EP;
  2933. ed->bmAttributes = 3;
  2934. ed->wMaxPacketSize = hid_priv->input_report_size - 1;
  2935. ed->bInterval = 10;
  2936. ed = (struct libusb_endpoint_descriptor *)((char *)ed + LIBUSB_DT_ENDPOINT_SIZE);
  2937. }
  2938. if (hid_priv->output_report_size) {
  2939. ed->bLength = LIBUSB_DT_ENDPOINT_SIZE;
  2940. ed->bDescriptorType = LIBUSB_DT_ENDPOINT;
  2941. ed->bEndpointAddress = HID_OUT_EP;
  2942. ed->bmAttributes = 3;
  2943. ed->wMaxPacketSize = hid_priv->output_report_size - 1;
  2944. ed->bInterval = 10;
  2945. }
  2946. if (*size > config_total_len)
  2947. *size = config_total_len;
  2948. memcpy(data, tmp, *size);
  2949. return LIBUSB_COMPLETED;
  2950. }
  2951. static int _hid_get_string_descriptor(struct hid_device_priv *hid_priv, int _index,
  2952. void *data, size_t *size, HANDLE hid_handle)
  2953. {
  2954. void *tmp = NULL;
  2955. WCHAR string[MAX_USB_STRING_LENGTH];
  2956. size_t tmp_size = 0;
  2957. int i;
  2958. /* language ID, EN-US */
  2959. char string_langid[] = {0x09, 0x04};
  2960. if (_index == 0) {
  2961. tmp = string_langid;
  2962. tmp_size = sizeof(string_langid) + 2;
  2963. } else {
  2964. for (i = 0; i < 3; i++) {
  2965. if (_index == (hid_priv->string_index[i])) {
  2966. tmp = hid_priv->string[i];
  2967. tmp_size = (_hid_wcslen(hid_priv->string[i]) + 1) * sizeof(WCHAR);
  2968. break;
  2969. }
  2970. }
  2971. if (i == 3) {
  2972. if (!HidD_GetIndexedString(hid_handle, _index, string, sizeof(string)))
  2973. return LIBUSB_ERROR_INVALID_PARAM;
  2974. tmp = string;
  2975. tmp_size = (_hid_wcslen(string) + 1) * sizeof(WCHAR);
  2976. }
  2977. }
  2978. if (!tmp_size)
  2979. return LIBUSB_ERROR_INVALID_PARAM;
  2980. if (tmp_size < *size)
  2981. *size = tmp_size;
  2982. // 2 byte header
  2983. ((uint8_t *)data)[0] = (uint8_t)*size;
  2984. ((uint8_t *)data)[1] = LIBUSB_DT_STRING;
  2985. memcpy((uint8_t *)data + 2, tmp, *size - 2);
  2986. return LIBUSB_COMPLETED;
  2987. }
  2988. static int _hid_get_hid_descriptor(struct hid_device_priv *hid_priv, void *data, size_t *size)
  2989. {
  2990. struct libusb_hid_descriptor d;
  2991. uint8_t tmp[MAX_HID_DESCRIPTOR_SIZE];
  2992. size_t report_len = MAX_HID_DESCRIPTOR_SIZE;
  2993. _hid_get_report_descriptor(hid_priv, tmp, &report_len);
  2994. d.bLength = LIBUSB_DT_HID_SIZE;
  2995. d.bDescriptorType = LIBUSB_DT_HID;
  2996. d.bcdHID = 0x0110; /* 1.10 */
  2997. d.bCountryCode = 0;
  2998. d.bNumDescriptors = 1;
  2999. d.bClassDescriptorType = LIBUSB_DT_REPORT;
  3000. d.wClassDescriptorLength = (uint16_t)report_len;
  3001. if (*size > LIBUSB_DT_HID_SIZE)
  3002. *size = LIBUSB_DT_HID_SIZE;
  3003. memcpy(data, &d, *size);
  3004. return LIBUSB_COMPLETED;
  3005. }
  3006. static int _hid_get_report_descriptor(struct hid_device_priv *hid_priv, void *data, size_t *size)
  3007. {
  3008. uint8_t d[MAX_HID_DESCRIPTOR_SIZE];
  3009. size_t i = 0;
  3010. /* usage page */
  3011. d[i++] = 0x06; d[i++] = hid_priv->usagePage & 0xFF; d[i++] = hid_priv->usagePage >> 8;
  3012. /* usage */
  3013. d[i++] = 0x09; d[i++] = (uint8_t)hid_priv->usage;
  3014. /* start collection (application) */
  3015. d[i++] = 0xA1; d[i++] = 0x01;
  3016. /* input report */
  3017. if (hid_priv->input_report_size) {
  3018. /* usage (vendor defined) */
  3019. d[i++] = 0x09; d[i++] = 0x01;
  3020. /* logical minimum (0) */
  3021. d[i++] = 0x15; d[i++] = 0x00;
  3022. /* logical maximum (255) */
  3023. d[i++] = 0x25; d[i++] = 0xFF;
  3024. /* report size (8 bits) */
  3025. d[i++] = 0x75; d[i++] = 0x08;
  3026. /* report count */
  3027. d[i++] = 0x95; d[i++] = (uint8_t)hid_priv->input_report_size - 1;
  3028. /* input (data, variable, absolute) */
  3029. d[i++] = 0x81; d[i++] = 0x00;
  3030. }
  3031. /* output report */
  3032. if (hid_priv->output_report_size) {
  3033. /* usage (vendor defined) */
  3034. d[i++] = 0x09; d[i++] = 0x02;
  3035. /* logical minimum (0) */
  3036. d[i++] = 0x15; d[i++] = 0x00;
  3037. /* logical maximum (255) */
  3038. d[i++] = 0x25; d[i++] = 0xFF;
  3039. /* report size (8 bits) */
  3040. d[i++] = 0x75; d[i++] = 0x08;
  3041. /* report count */
  3042. d[i++] = 0x95; d[i++] = (uint8_t)hid_priv->output_report_size - 1;
  3043. /* output (data, variable, absolute) */
  3044. d[i++] = 0x91; d[i++] = 0x00;
  3045. }
  3046. /* feature report */
  3047. if (hid_priv->feature_report_size) {
  3048. /* usage (vendor defined) */
  3049. d[i++] = 0x09; d[i++] = 0x03;
  3050. /* logical minimum (0) */
  3051. d[i++] = 0x15; d[i++] = 0x00;
  3052. /* logical maximum (255) */
  3053. d[i++] = 0x25; d[i++] = 0xFF;
  3054. /* report size (8 bits) */
  3055. d[i++] = 0x75; d[i++] = 0x08;
  3056. /* report count */
  3057. d[i++] = 0x95; d[i++] = (uint8_t)hid_priv->feature_report_size - 1;
  3058. /* feature (data, variable, absolute) */
  3059. d[i++] = 0xb2; d[i++] = 0x02; d[i++] = 0x01;
  3060. }
  3061. /* end collection */
  3062. d[i++] = 0xC0;
  3063. if (*size > i)
  3064. *size = i;
  3065. memcpy(data, d, *size);
  3066. return LIBUSB_COMPLETED;
  3067. }
  3068. static int _hid_get_descriptor(struct libusb_device *dev, HANDLE hid_handle, int recipient,
  3069. int type, int _index, void *data, size_t *size)
  3070. {
  3071. struct winusb_device_priv *priv = usbi_get_device_priv(dev);
  3072. UNUSED(recipient);
  3073. switch (type) {
  3074. case LIBUSB_DT_DEVICE:
  3075. usbi_dbg(DEVICE_CTX(dev), "LIBUSB_DT_DEVICE");
  3076. return _hid_get_device_descriptor(priv->hid, data, size);
  3077. case LIBUSB_DT_CONFIG:
  3078. usbi_dbg(DEVICE_CTX(dev), "LIBUSB_DT_CONFIG");
  3079. if (!_index)
  3080. return _hid_get_config_descriptor(priv->hid, data, size);
  3081. return LIBUSB_ERROR_INVALID_PARAM;
  3082. case LIBUSB_DT_STRING:
  3083. usbi_dbg(DEVICE_CTX(dev), "LIBUSB_DT_STRING");
  3084. return _hid_get_string_descriptor(priv->hid, _index, data, size, hid_handle);
  3085. case LIBUSB_DT_HID:
  3086. usbi_dbg(DEVICE_CTX(dev), "LIBUSB_DT_HID");
  3087. if (!_index)
  3088. return _hid_get_hid_descriptor(priv->hid, data, size);
  3089. return LIBUSB_ERROR_INVALID_PARAM;
  3090. case LIBUSB_DT_REPORT:
  3091. usbi_dbg(DEVICE_CTX(dev), "LIBUSB_DT_REPORT");
  3092. if (!_index)
  3093. return _hid_get_report_descriptor(priv->hid, data, size);
  3094. return LIBUSB_ERROR_INVALID_PARAM;
  3095. case LIBUSB_DT_PHYSICAL:
  3096. usbi_dbg(DEVICE_CTX(dev), "LIBUSB_DT_PHYSICAL");
  3097. if (HidD_GetPhysicalDescriptor(hid_handle, data, (ULONG)*size))
  3098. return LIBUSB_COMPLETED;
  3099. return LIBUSB_ERROR_OTHER;
  3100. }
  3101. usbi_warn(DEVICE_CTX(dev), "unsupported");
  3102. return LIBUSB_ERROR_NOT_SUPPORTED;
  3103. }
  3104. static int _hid_get_report(struct libusb_device *dev, HANDLE hid_handle, int id, void *data,
  3105. struct winusb_transfer_priv *tp, size_t size, OVERLAPPED *overlapped, int report_type)
  3106. {
  3107. DWORD ioctl_code, expected_size = (DWORD)size;
  3108. uint8_t *buf;
  3109. if (tp->hid_buffer != NULL)
  3110. usbi_err(DEVICE_CTX(dev), "program assertion failed - hid_buffer is not NULL");
  3111. if ((size == 0) || (size > MAX_HID_REPORT_SIZE)) {
  3112. usbi_warn(DEVICE_CTX(dev), "invalid size (%"PRIuPTR")", (uintptr_t)size);
  3113. return LIBUSB_ERROR_INVALID_PARAM;
  3114. }
  3115. switch (report_type) {
  3116. case HID_REPORT_TYPE_INPUT:
  3117. ioctl_code = IOCTL_HID_GET_INPUT_REPORT;
  3118. break;
  3119. case HID_REPORT_TYPE_FEATURE:
  3120. ioctl_code = IOCTL_HID_GET_FEATURE;
  3121. break;
  3122. default:
  3123. usbi_warn(DEVICE_CTX(dev), "unknown HID report type %d", report_type);
  3124. return LIBUSB_ERROR_INVALID_PARAM;
  3125. }
  3126. // Add a trailing byte to detect overflows
  3127. buf = calloc(1, expected_size + 1);
  3128. if (buf == NULL)
  3129. return LIBUSB_ERROR_NO_MEM;
  3130. buf[0] = (uint8_t)id; // Must be set always
  3131. usbi_dbg(DEVICE_CTX(dev), "report ID: 0x%02X", buf[0]);
  3132. // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
  3133. if (!DeviceIoControl(hid_handle, ioctl_code, buf, expected_size + 1,
  3134. buf, expected_size + 1, NULL, overlapped)) {
  3135. if (GetLastError() != ERROR_IO_PENDING) {
  3136. usbi_err(DEVICE_CTX(dev), "failed to read HID Report: %s", windows_error_str(0));
  3137. free(buf);
  3138. return LIBUSB_ERROR_IO;
  3139. }
  3140. }
  3141. // Asynchronous wait
  3142. tp->hid_buffer = buf;
  3143. tp->hid_dest = data; // copy dest, as not necessarily the start of the transfer buffer
  3144. tp->hid_expected_size = expected_size;
  3145. return LIBUSB_SUCCESS;
  3146. }
  3147. static int _hid_set_report(struct libusb_device *dev, HANDLE hid_handle, int id, void *data,
  3148. struct winusb_transfer_priv *tp, size_t size, OVERLAPPED *overlapped, int report_type)
  3149. {
  3150. DWORD ioctl_code, write_size = (DWORD)size;
  3151. // If an id is reported, we must allow MAX_HID_REPORT_SIZE + 1
  3152. size_t max_report_size = MAX_HID_REPORT_SIZE + (id ? 1 : 0);
  3153. uint8_t *buf;
  3154. if (tp->hid_buffer != NULL)
  3155. usbi_err(DEVICE_CTX(dev), "program assertion failed - hid_buffer is not NULL");
  3156. if ((size == 0) || (size > max_report_size)) {
  3157. usbi_warn(DEVICE_CTX(dev), "invalid size (%"PRIuPTR")", (uintptr_t)size);
  3158. return LIBUSB_ERROR_INVALID_PARAM;
  3159. }
  3160. switch (report_type) {
  3161. case HID_REPORT_TYPE_OUTPUT:
  3162. ioctl_code = IOCTL_HID_SET_OUTPUT_REPORT;
  3163. break;
  3164. case HID_REPORT_TYPE_FEATURE:
  3165. ioctl_code = IOCTL_HID_SET_FEATURE;
  3166. break;
  3167. default:
  3168. usbi_warn(DEVICE_CTX(dev), "unknown HID report type %d", report_type);
  3169. return LIBUSB_ERROR_INVALID_PARAM;
  3170. }
  3171. usbi_dbg(DEVICE_CTX(dev), "report ID: 0x%02X", id);
  3172. // When report IDs are not used (i.e. when id == 0), we must add
  3173. // a null report ID. Otherwise, we just use original data buffer
  3174. if (id == 0)
  3175. write_size++;
  3176. buf = malloc(write_size);
  3177. if (buf == NULL)
  3178. return LIBUSB_ERROR_NO_MEM;
  3179. if (id == 0) {
  3180. buf[0] = 0;
  3181. memcpy(buf + 1, data, size);
  3182. } else {
  3183. // This seems like a waste, but if we don't duplicate the
  3184. // data, we'll get issues when freeing hid_buffer
  3185. memcpy(buf, data, size);
  3186. if (buf[0] != id)
  3187. usbi_warn(DEVICE_CTX(dev), "mismatched report ID (data is %02X, parameter is %02X)", buf[0], id);
  3188. }
  3189. // NB: The size returned by DeviceIoControl doesn't include report IDs when not in use (0)
  3190. if (!DeviceIoControl(hid_handle, ioctl_code, buf, write_size,
  3191. buf, write_size, NULL, overlapped)) {
  3192. if (GetLastError() != ERROR_IO_PENDING) {
  3193. usbi_err(DEVICE_CTX(dev), "failed to write HID Output Report: %s", windows_error_str(0));
  3194. free(buf);
  3195. return LIBUSB_ERROR_IO;
  3196. }
  3197. }
  3198. tp->hid_buffer = buf;
  3199. tp->hid_dest = NULL;
  3200. return LIBUSB_SUCCESS;
  3201. }
  3202. static int _hid_class_request(struct libusb_device *dev, HANDLE hid_handle, int request_type,
  3203. int request, int value, int _index, void *data, struct winusb_transfer_priv *tp,
  3204. size_t size, OVERLAPPED *overlapped)
  3205. {
  3206. int report_type = (value >> 8) & 0xFF;
  3207. int report_id = value & 0xFF;
  3208. UNUSED(_index);
  3209. if ((LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_INTERFACE)
  3210. && (LIBUSB_REQ_RECIPIENT(request_type) != LIBUSB_RECIPIENT_DEVICE))
  3211. return LIBUSB_ERROR_INVALID_PARAM;
  3212. if (LIBUSB_REQ_OUT(request_type) && request == HID_REQ_SET_REPORT)
  3213. return _hid_set_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
  3214. if (LIBUSB_REQ_IN(request_type) && request == HID_REQ_GET_REPORT)
  3215. return _hid_get_report(dev, hid_handle, report_id, data, tp, size, overlapped, report_type);
  3216. return LIBUSB_ERROR_INVALID_PARAM;
  3217. }
  3218. /*
  3219. * HID API functions
  3220. */
  3221. static bool hid_init(struct libusb_context *ctx)
  3222. {
  3223. DLL_GET_HANDLE(ctx, hid);
  3224. DLL_LOAD_FUNC(hid, HidD_GetAttributes, true);
  3225. DLL_LOAD_FUNC(hid, HidD_GetHidGuid, true);
  3226. DLL_LOAD_FUNC(hid, HidD_GetPreparsedData, true);
  3227. DLL_LOAD_FUNC(hid, HidD_FreePreparsedData, true);
  3228. DLL_LOAD_FUNC(hid, HidD_GetManufacturerString, true);
  3229. DLL_LOAD_FUNC(hid, HidD_GetProductString, true);
  3230. DLL_LOAD_FUNC(hid, HidD_GetSerialNumberString, true);
  3231. DLL_LOAD_FUNC(hid, HidD_GetIndexedString, true);
  3232. DLL_LOAD_FUNC(hid, HidP_GetCaps, true);
  3233. DLL_LOAD_FUNC(hid, HidD_SetNumInputBuffers, true);
  3234. DLL_LOAD_FUNC(hid, HidD_GetPhysicalDescriptor, true);
  3235. DLL_LOAD_FUNC(hid, HidD_FlushQueue, true);
  3236. DLL_LOAD_FUNC(hid, HidP_GetValueCaps, true);
  3237. return true;
  3238. }
  3239. static void hid_exit(void)
  3240. {
  3241. DLL_FREE_HANDLE(hid);
  3242. }
  3243. // NB: open and close must ensure that they only handle interface of
  3244. // the right API type, as these functions can be called wholesale from
  3245. // composite_open(), with interfaces belonging to different APIs
  3246. static int hid_open(int sub_api, struct libusb_device_handle *dev_handle)
  3247. {
  3248. struct libusb_device *dev = dev_handle->dev;
  3249. struct winusb_device_priv *priv = usbi_get_device_priv(dev);
  3250. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  3251. HIDD_ATTRIBUTES hid_attributes;
  3252. PHIDP_PREPARSED_DATA preparsed_data = NULL;
  3253. HIDP_CAPS capabilities;
  3254. HIDP_VALUE_CAPS *value_caps;
  3255. HANDLE hid_handle = INVALID_HANDLE_VALUE;
  3256. int i, j;
  3257. // report IDs handling
  3258. ULONG size[3];
  3259. int nb_ids[2]; // zero and nonzero report IDs
  3260. #if defined(ENABLE_LOGGING)
  3261. const char * const type[3] = {"input", "output", "feature"};
  3262. #endif
  3263. UNUSED(sub_api);
  3264. CHECK_HID_AVAILABLE;
  3265. if (priv->hid == NULL) {
  3266. usbi_err(HANDLE_CTX(dev_handle), "program assertion failed - private HID structure is uninitialized");
  3267. return LIBUSB_ERROR_NOT_FOUND;
  3268. }
  3269. for (i = 0; i < USB_MAXINTERFACES; i++) {
  3270. if ((priv->usb_interface[i].path != NULL)
  3271. && (priv->usb_interface[i].apib->id == USB_API_HID)) {
  3272. hid_handle = windows_open(dev_handle, priv->usb_interface[i].path, GENERIC_READ | GENERIC_WRITE);
  3273. /*
  3274. * http://www.lvr.com/hidfaq.htm: Why do I receive "Access denied" when attempting to access my HID?
  3275. * "Windows 2000 and later have exclusive read/write access to HIDs that are configured as a system
  3276. * keyboards or mice. An application can obtain a handle to a system keyboard or mouse by not
  3277. * requesting READ or WRITE access with CreateFile. Applications can then use HidD_SetFeature and
  3278. * HidD_GetFeature (if the device supports Feature reports)."
  3279. */
  3280. if (hid_handle == INVALID_HANDLE_VALUE) {
  3281. usbi_warn(HANDLE_CTX(dev_handle), "could not open HID device in R/W mode (keyboard or mouse?) - trying without");
  3282. hid_handle = windows_open(dev_handle, priv->usb_interface[i].path, 0);
  3283. if (hid_handle == INVALID_HANDLE_VALUE) {
  3284. usbi_err(HANDLE_CTX(dev_handle), "could not open device %s (interface %d): %s", priv->path, i, windows_error_str(0));
  3285. switch (GetLastError()) {
  3286. case ERROR_FILE_NOT_FOUND: // The device was disconnected
  3287. return LIBUSB_ERROR_NO_DEVICE;
  3288. case ERROR_ACCESS_DENIED:
  3289. return LIBUSB_ERROR_ACCESS;
  3290. default:
  3291. return LIBUSB_ERROR_IO;
  3292. }
  3293. }
  3294. priv->usb_interface[i].restricted_functionality = true;
  3295. }
  3296. handle_priv->interface_handle[i].api_handle = hid_handle;
  3297. }
  3298. }
  3299. hid_attributes.Size = sizeof(hid_attributes);
  3300. do {
  3301. if (!HidD_GetAttributes(hid_handle, &hid_attributes)) {
  3302. usbi_err(HANDLE_CTX(dev_handle), "could not gain access to HID top collection (HidD_GetAttributes)");
  3303. break;
  3304. }
  3305. priv->hid->vid = hid_attributes.VendorID;
  3306. priv->hid->pid = hid_attributes.ProductID;
  3307. // Set the maximum available input buffer size
  3308. for (i = 32; HidD_SetNumInputBuffers(hid_handle, i); i *= 2);
  3309. usbi_dbg(HANDLE_CTX(dev_handle), "set maximum input buffer size to %d", i / 2);
  3310. // Get the maximum input and output report size
  3311. if (!HidD_GetPreparsedData(hid_handle, &preparsed_data) || !preparsed_data) {
  3312. usbi_err(HANDLE_CTX(dev_handle), "could not read HID preparsed data (HidD_GetPreparsedData)");
  3313. break;
  3314. }
  3315. if (HidP_GetCaps(preparsed_data, &capabilities) != HIDP_STATUS_SUCCESS) {
  3316. usbi_err(HANDLE_CTX(dev_handle), "could not parse HID capabilities (HidP_GetCaps)");
  3317. break;
  3318. }
  3319. // Find out if interrupt will need report IDs
  3320. size[0] = capabilities.NumberInputValueCaps;
  3321. size[1] = capabilities.NumberOutputValueCaps;
  3322. size[2] = capabilities.NumberFeatureValueCaps;
  3323. for (j = HidP_Input; j <= HidP_Feature; j++) {
  3324. usbi_dbg(HANDLE_CTX(dev_handle), "%lu HID %s report value(s) found", ULONG_CAST(size[j]), type[j]);
  3325. priv->hid->uses_report_ids[j] = false;
  3326. if (size[j] > 0) {
  3327. value_caps = calloc(size[j], sizeof(HIDP_VALUE_CAPS));
  3328. if ((value_caps != NULL)
  3329. && (HidP_GetValueCaps((HIDP_REPORT_TYPE)j, value_caps, &size[j], preparsed_data) == HIDP_STATUS_SUCCESS)
  3330. && (size[j] >= 1)) {
  3331. nb_ids[0] = 0;
  3332. nb_ids[1] = 0;
  3333. for (i = 0; i < (int)size[j]; i++) {
  3334. usbi_dbg(HANDLE_CTX(dev_handle), " Report ID: 0x%02X", value_caps[i].ReportID);
  3335. if (value_caps[i].ReportID != 0)
  3336. nb_ids[1]++;
  3337. else
  3338. nb_ids[0]++;
  3339. }
  3340. if (nb_ids[1] != 0) {
  3341. if (nb_ids[0] != 0)
  3342. usbi_warn(HANDLE_CTX(dev_handle), "program assertion failed - zero and nonzero report IDs used for %s",
  3343. type[j]);
  3344. priv->hid->uses_report_ids[j] = true;
  3345. }
  3346. } else {
  3347. usbi_warn(HANDLE_CTX(dev_handle), " could not process %s report IDs", type[j]);
  3348. }
  3349. free(value_caps);
  3350. }
  3351. }
  3352. // Set the report sizes
  3353. priv->hid->input_report_size = capabilities.InputReportByteLength;
  3354. priv->hid->output_report_size = capabilities.OutputReportByteLength;
  3355. priv->hid->feature_report_size = capabilities.FeatureReportByteLength;
  3356. // Store usage and usagePage values
  3357. priv->hid->usage = capabilities.Usage;
  3358. priv->hid->usagePage = capabilities.UsagePage;
  3359. // Fetch string descriptors
  3360. priv->hid->string_index[0] = dev->device_descriptor.iManufacturer;
  3361. if (priv->hid->string_index[0] != 0)
  3362. HidD_GetManufacturerString(hid_handle, priv->hid->string[0], sizeof(priv->hid->string[0]));
  3363. else
  3364. priv->hid->string[0][0] = 0;
  3365. priv->hid->string_index[1] = dev->device_descriptor.iProduct;
  3366. if (priv->hid->string_index[1] != 0)
  3367. // Using HidD_GetIndexedString() instead of HidD_GetProductString(), as the latter would otherwise return the name
  3368. // of the interface instead of the iProduct string whenever the iInterface member of the USB_INTERFACE_DESCRIPTOR
  3369. // structure for the interface is nonzero (see Remarks section in the documentation of the HID API routines)
  3370. HidD_GetIndexedString(hid_handle, priv->hid->string_index[1], priv->hid->string[1], sizeof(priv->hid->string[1]));
  3371. else
  3372. priv->hid->string[1][0] = 0;
  3373. priv->hid->string_index[2] = dev->device_descriptor.iSerialNumber;
  3374. if (priv->hid->string_index[2] != 0)
  3375. HidD_GetSerialNumberString(hid_handle, priv->hid->string[2], sizeof(priv->hid->string[2]));
  3376. else
  3377. priv->hid->string[2][0] = 0;
  3378. } while (0);
  3379. if (preparsed_data)
  3380. HidD_FreePreparsedData(preparsed_data);
  3381. return LIBUSB_SUCCESS;
  3382. }
  3383. static void hid_close(int sub_api, struct libusb_device_handle *dev_handle)
  3384. {
  3385. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  3386. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  3387. HANDLE file_handle;
  3388. int i;
  3389. UNUSED(sub_api);
  3390. if (DLL_HANDLE_NAME(hid) == NULL)
  3391. return;
  3392. for (i = 0; i < USB_MAXINTERFACES; i++) {
  3393. if (priv->usb_interface[i].apib->id == USB_API_HID) {
  3394. file_handle = handle_priv->interface_handle[i].api_handle;
  3395. if (HANDLE_VALID(file_handle))
  3396. CloseHandle(file_handle);
  3397. }
  3398. }
  3399. }
  3400. static int hid_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface)
  3401. {
  3402. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  3403. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  3404. UNUSED(sub_api);
  3405. CHECK_HID_AVAILABLE;
  3406. // NB: Disconnection detection is not possible in this function
  3407. if (priv->usb_interface[iface].path == NULL)
  3408. return LIBUSB_ERROR_NOT_FOUND; // invalid iface
  3409. // We use dev_handle as a flag for interface claimed
  3410. if (handle_priv->interface_handle[iface].dev_handle == INTERFACE_CLAIMED)
  3411. return LIBUSB_ERROR_BUSY; // already claimed
  3412. handle_priv->interface_handle[iface].dev_handle = INTERFACE_CLAIMED;
  3413. usbi_dbg(HANDLE_CTX(dev_handle), "claimed interface %u", iface);
  3414. handle_priv->active_interface = iface;
  3415. return LIBUSB_SUCCESS;
  3416. }
  3417. static int hid_release_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface)
  3418. {
  3419. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  3420. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  3421. UNUSED(sub_api);
  3422. CHECK_HID_AVAILABLE;
  3423. if (priv->usb_interface[iface].path == NULL)
  3424. return LIBUSB_ERROR_NOT_FOUND; // invalid iface
  3425. if (handle_priv->interface_handle[iface].dev_handle != INTERFACE_CLAIMED)
  3426. return LIBUSB_ERROR_NOT_FOUND; // invalid iface
  3427. handle_priv->interface_handle[iface].dev_handle = INVALID_HANDLE_VALUE;
  3428. return LIBUSB_SUCCESS;
  3429. }
  3430. static int hid_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting)
  3431. {
  3432. UNUSED(sub_api);
  3433. UNUSED(iface);
  3434. CHECK_HID_AVAILABLE;
  3435. if (altsetting != 0) {
  3436. usbi_err(HANDLE_CTX(dev_handle), "set interface altsetting not supported for altsetting >0");
  3437. return LIBUSB_ERROR_NOT_SUPPORTED;
  3438. }
  3439. return LIBUSB_SUCCESS;
  3440. }
  3441. static int hid_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
  3442. {
  3443. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  3444. struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
  3445. struct libusb_device_handle *dev_handle = transfer->dev_handle;
  3446. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  3447. struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
  3448. WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
  3449. HANDLE hid_handle;
  3450. OVERLAPPED *overlapped;
  3451. int current_interface;
  3452. uint8_t config;
  3453. size_t size;
  3454. int r;
  3455. UNUSED(sub_api);
  3456. CHECK_HID_AVAILABLE;
  3457. safe_free(transfer_priv->hid_buffer);
  3458. transfer_priv->hid_dest = NULL;
  3459. size = transfer->length - LIBUSB_CONTROL_SETUP_SIZE;
  3460. if (size > MAX_CTRL_BUFFER_LENGTH)
  3461. return LIBUSB_ERROR_INVALID_PARAM;
  3462. current_interface = get_valid_interface(dev_handle, USB_API_HID);
  3463. if (current_interface < 0) {
  3464. if (auto_claim(transfer, &current_interface, USB_API_HID) != LIBUSB_SUCCESS)
  3465. return LIBUSB_ERROR_NOT_FOUND;
  3466. }
  3467. usbi_dbg(ITRANSFER_CTX(itransfer), "will use interface %d", current_interface);
  3468. transfer_priv->interface_number = (uint8_t)current_interface;
  3469. hid_handle = handle_priv->interface_handle[current_interface].api_handle;
  3470. set_transfer_priv_handle(itransfer, hid_handle);
  3471. overlapped = get_transfer_priv_overlapped(itransfer);
  3472. switch (LIBUSB_REQ_TYPE(setup->RequestType)) {
  3473. case LIBUSB_REQUEST_TYPE_STANDARD:
  3474. switch (setup->Request) {
  3475. case LIBUSB_REQUEST_GET_DESCRIPTOR:
  3476. r = _hid_get_descriptor(dev_handle->dev, hid_handle, LIBUSB_REQ_RECIPIENT(setup->RequestType),
  3477. (setup->Value >> 8) & 0xFF, setup->Value & 0xFF, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, &size);
  3478. break;
  3479. case LIBUSB_REQUEST_GET_CONFIGURATION:
  3480. r = winusb_get_configuration(dev_handle, &config);
  3481. if (r == LIBUSB_SUCCESS) {
  3482. size = 1;
  3483. ((uint8_t *)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = config;
  3484. r = LIBUSB_COMPLETED;
  3485. }
  3486. break;
  3487. case LIBUSB_REQUEST_SET_CONFIGURATION:
  3488. if (setup->Value == priv->active_config) {
  3489. r = LIBUSB_COMPLETED;
  3490. } else {
  3491. usbi_warn(TRANSFER_CTX(transfer), "cannot set configuration other than the default one");
  3492. r = LIBUSB_ERROR_NOT_SUPPORTED;
  3493. }
  3494. break;
  3495. case LIBUSB_REQUEST_GET_INTERFACE:
  3496. size = 1;
  3497. ((uint8_t *)transfer->buffer)[LIBUSB_CONTROL_SETUP_SIZE] = 0;
  3498. r = LIBUSB_COMPLETED;
  3499. break;
  3500. case LIBUSB_REQUEST_SET_INTERFACE:
  3501. r = hid_set_interface_altsetting(0, dev_handle, (uint8_t)setup->Index, (uint8_t)setup->Value);
  3502. if (r == LIBUSB_SUCCESS)
  3503. r = LIBUSB_COMPLETED;
  3504. break;
  3505. default:
  3506. usbi_warn(TRANSFER_CTX(transfer), "unsupported HID control request");
  3507. return LIBUSB_ERROR_NOT_SUPPORTED;
  3508. }
  3509. break;
  3510. case LIBUSB_REQUEST_TYPE_CLASS:
  3511. r = _hid_class_request(dev_handle->dev, hid_handle, setup->RequestType, setup->Request, setup->Value,
  3512. setup->Index, transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE, transfer_priv,
  3513. size, overlapped);
  3514. break;
  3515. default:
  3516. usbi_warn(TRANSFER_CTX(transfer), "unsupported HID control request");
  3517. return LIBUSB_ERROR_NOT_SUPPORTED;
  3518. }
  3519. if (r < 0)
  3520. return r;
  3521. if (r == LIBUSB_COMPLETED) {
  3522. // Force request to be completed synchronously. Transferred size has been set by previous call
  3523. windows_force_sync_completion(itransfer, (ULONG)size);
  3524. r = LIBUSB_SUCCESS;
  3525. }
  3526. return LIBUSB_SUCCESS;
  3527. }
  3528. static int hid_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
  3529. {
  3530. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  3531. struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
  3532. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(transfer->dev_handle);
  3533. struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
  3534. HANDLE hid_handle;
  3535. OVERLAPPED *overlapped;
  3536. bool direction_in;
  3537. BOOL ret;
  3538. int current_interface, length;
  3539. UNUSED(sub_api);
  3540. CHECK_HID_AVAILABLE;
  3541. if (IS_XFEROUT(transfer) && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET))
  3542. return LIBUSB_ERROR_NOT_SUPPORTED;
  3543. transfer_priv->hid_dest = NULL;
  3544. safe_free(transfer_priv->hid_buffer);
  3545. current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
  3546. if (current_interface < 0) {
  3547. usbi_err(TRANSFER_CTX(transfer), "unable to match endpoint to an open interface - cancelling transfer");
  3548. return LIBUSB_ERROR_NOT_FOUND;
  3549. }
  3550. usbi_dbg(TRANSFER_CTX(transfer), "matched endpoint %02X with interface %d", transfer->endpoint, current_interface);
  3551. transfer_priv->interface_number = (uint8_t)current_interface;
  3552. hid_handle = handle_priv->interface_handle[current_interface].api_handle;
  3553. set_transfer_priv_handle(itransfer, hid_handle);
  3554. overlapped = get_transfer_priv_overlapped(itransfer);
  3555. direction_in = IS_XFERIN(transfer);
  3556. // If report IDs are not in use, an extra prefix byte must be added
  3557. if (((direction_in) && (!priv->hid->uses_report_ids[0]))
  3558. || ((!direction_in) && (!priv->hid->uses_report_ids[1])))
  3559. length = transfer->length + 1;
  3560. else
  3561. length = transfer->length;
  3562. // Add a trailing byte to detect overflows on input
  3563. transfer_priv->hid_buffer = calloc(1, length + 1);
  3564. if (transfer_priv->hid_buffer == NULL)
  3565. return LIBUSB_ERROR_NO_MEM;
  3566. transfer_priv->hid_expected_size = length;
  3567. if (direction_in) {
  3568. transfer_priv->hid_dest = transfer->buffer;
  3569. usbi_dbg(TRANSFER_CTX(transfer), "reading %d bytes (report ID: 0x00)", length);
  3570. ret = ReadFile(hid_handle, transfer_priv->hid_buffer, length + 1, NULL, overlapped);
  3571. } else {
  3572. if (!priv->hid->uses_report_ids[1])
  3573. memcpy(transfer_priv->hid_buffer + 1, transfer->buffer, transfer->length);
  3574. else
  3575. // We could actually do without the calloc and memcpy in this case
  3576. memcpy(transfer_priv->hid_buffer, transfer->buffer, transfer->length);
  3577. usbi_dbg(TRANSFER_CTX(transfer), "writing %d bytes (report ID: 0x%02X)", length, transfer_priv->hid_buffer[0]);
  3578. ret = WriteFile(hid_handle, transfer_priv->hid_buffer, length, NULL, overlapped);
  3579. }
  3580. if (!ret && GetLastError() != ERROR_IO_PENDING) {
  3581. usbi_err(TRANSFER_CTX(transfer), "HID transfer failed: %s", windows_error_str(0));
  3582. safe_free(transfer_priv->hid_buffer);
  3583. return LIBUSB_ERROR_IO;
  3584. }
  3585. return LIBUSB_SUCCESS;
  3586. }
  3587. static int hid_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
  3588. {
  3589. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  3590. HANDLE hid_handle;
  3591. int current_interface;
  3592. UNUSED(sub_api);
  3593. CHECK_HID_AVAILABLE;
  3594. // Flushing the queues on all interfaces is the best we can achieve
  3595. for (current_interface = 0; current_interface < USB_MAXINTERFACES; current_interface++) {
  3596. hid_handle = handle_priv->interface_handle[current_interface].api_handle;
  3597. if (HANDLE_VALID(hid_handle))
  3598. HidD_FlushQueue(hid_handle);
  3599. }
  3600. return LIBUSB_SUCCESS;
  3601. }
  3602. static int hid_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
  3603. {
  3604. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  3605. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  3606. HANDLE hid_handle;
  3607. int current_interface;
  3608. UNUSED(sub_api);
  3609. CHECK_HID_AVAILABLE;
  3610. current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
  3611. if (current_interface < 0) {
  3612. usbi_err(HANDLE_CTX(dev_handle), "unable to match endpoint to an open interface - cannot clear");
  3613. return LIBUSB_ERROR_NOT_FOUND;
  3614. }
  3615. usbi_dbg(HANDLE_CTX(dev_handle), "matched endpoint %02X with interface %d", endpoint, current_interface);
  3616. hid_handle = handle_priv->interface_handle[current_interface].api_handle;
  3617. // No endpoint selection with Microsoft's implementation, so we try to flush the
  3618. // whole interface. Should be OK for most case scenarios
  3619. if (!HidD_FlushQueue(hid_handle)) {
  3620. usbi_err(HANDLE_CTX(dev_handle), "Flushing of HID queue failed: %s", windows_error_str(0));
  3621. // Device was probably disconnected
  3622. return LIBUSB_ERROR_NO_DEVICE;
  3623. }
  3624. return LIBUSB_SUCCESS;
  3625. }
  3626. // This extra function is only needed for HID
  3627. static enum libusb_transfer_status hid_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, DWORD length)
  3628. {
  3629. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  3630. struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
  3631. enum libusb_transfer_status r = LIBUSB_TRANSFER_COMPLETED;
  3632. UNUSED(sub_api);
  3633. if (transfer_priv->hid_buffer != NULL) {
  3634. // If we have a valid hid_buffer, it means the transfer was async
  3635. if (transfer_priv->hid_dest != NULL) { // Data readout
  3636. if (length > 0) {
  3637. // First, check for overflow
  3638. if ((size_t)length > transfer_priv->hid_expected_size) {
  3639. usbi_err(TRANSFER_CTX(transfer), "OVERFLOW!");
  3640. length = (DWORD)transfer_priv->hid_expected_size;
  3641. r = LIBUSB_TRANSFER_OVERFLOW;
  3642. }
  3643. if (transfer_priv->hid_buffer[0] == 0) {
  3644. memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer + 1, length);
  3645. } else {
  3646. memcpy(transfer_priv->hid_dest, transfer_priv->hid_buffer, length);
  3647. }
  3648. }
  3649. transfer_priv->hid_dest = NULL;
  3650. }
  3651. // For write, we just need to free the hid buffer
  3652. safe_free(transfer_priv->hid_buffer);
  3653. }
  3654. itransfer->transferred += (int)length;
  3655. return r;
  3656. }
  3657. /*
  3658. * Composite API functions
  3659. */
  3660. static int composite_open(int sub_api, struct libusb_device_handle *dev_handle)
  3661. {
  3662. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  3663. int i, r = LIBUSB_ERROR_NOT_FOUND;
  3664. // SUB_API_MAX + 1 as the SUB_API_MAX pos is used to indicate availability of HID
  3665. bool available[SUB_API_MAX + 1];
  3666. UNUSED(sub_api);
  3667. for (i = 0; i < SUB_API_MAX + 1; i++)
  3668. available[i] = false;
  3669. for (i = 0; i < USB_MAXINTERFACES; i++) {
  3670. switch (priv->usb_interface[i].apib->id) {
  3671. case USB_API_WINUSBX:
  3672. if (priv->usb_interface[i].sub_api != SUB_API_NOTSET)
  3673. available[priv->usb_interface[i].sub_api] = true;
  3674. break;
  3675. case USB_API_HID:
  3676. available[SUB_API_MAX] = true;
  3677. break;
  3678. default:
  3679. break;
  3680. }
  3681. }
  3682. for (i = 0; i < SUB_API_MAX; i++) { // WinUSB-like drivers
  3683. if (available[i]) {
  3684. r = usb_api_backend[USB_API_WINUSBX].open(i, dev_handle);
  3685. if (r != LIBUSB_SUCCESS)
  3686. return r;
  3687. }
  3688. }
  3689. if (available[SUB_API_MAX]) { // HID driver
  3690. r = hid_open(SUB_API_NOTSET, dev_handle);
  3691. // On Windows 10 version 1903 (OS Build 18362) and later Windows blocks attempts to
  3692. // open HID devices with a U2F usage unless running as administrator. We ignore this
  3693. // failure and proceed without the HID device opened.
  3694. if (r == LIBUSB_ERROR_ACCESS) {
  3695. usbi_dbg(HANDLE_CTX(dev_handle), "ignoring access denied error while opening HID interface of composite device");
  3696. r = LIBUSB_SUCCESS;
  3697. }
  3698. }
  3699. return r;
  3700. }
  3701. static void composite_close(int sub_api, struct libusb_device_handle *dev_handle)
  3702. {
  3703. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  3704. int i;
  3705. // SUB_API_MAX + 1 as the SUB_API_MAX pos is used to indicate availability of HID
  3706. bool available[SUB_API_MAX + 1];
  3707. UNUSED(sub_api);
  3708. for (i = 0; i < SUB_API_MAX + 1; i++)
  3709. available[i] = false;
  3710. for (i = 0; i < USB_MAXINTERFACES; i++) {
  3711. switch (priv->usb_interface[i].apib->id) {
  3712. case USB_API_WINUSBX:
  3713. if (priv->usb_interface[i].sub_api != SUB_API_NOTSET)
  3714. available[priv->usb_interface[i].sub_api] = true;
  3715. break;
  3716. case USB_API_HID:
  3717. available[SUB_API_MAX] = true;
  3718. break;
  3719. default:
  3720. break;
  3721. }
  3722. }
  3723. for (i = 0; i < SUB_API_MAX; i++) { // WinUSB-like drivers
  3724. if (available[i])
  3725. usb_api_backend[USB_API_WINUSBX].close(i, dev_handle);
  3726. }
  3727. if (available[SUB_API_MAX]) // HID driver
  3728. hid_close(SUB_API_NOTSET, dev_handle);
  3729. }
  3730. static int composite_claim_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface)
  3731. {
  3732. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  3733. UNUSED(sub_api);
  3734. CHECK_SUPPORTED_API(priv->usb_interface[iface].apib, claim_interface);
  3735. return priv->usb_interface[iface].apib->
  3736. claim_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
  3737. }
  3738. static int composite_set_interface_altsetting(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting)
  3739. {
  3740. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  3741. UNUSED(sub_api);
  3742. CHECK_SUPPORTED_API(priv->usb_interface[iface].apib, set_interface_altsetting);
  3743. return priv->usb_interface[iface].apib->
  3744. set_interface_altsetting(priv->usb_interface[iface].sub_api, dev_handle, iface, altsetting);
  3745. }
  3746. static int composite_release_interface(int sub_api, struct libusb_device_handle *dev_handle, uint8_t iface)
  3747. {
  3748. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  3749. UNUSED(sub_api);
  3750. CHECK_SUPPORTED_API(priv->usb_interface[iface].apib, release_interface);
  3751. return priv->usb_interface[iface].apib->
  3752. release_interface(priv->usb_interface[iface].sub_api, dev_handle, iface);
  3753. }
  3754. static int composite_submit_control_transfer(int sub_api, struct usbi_transfer *itransfer)
  3755. {
  3756. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  3757. struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
  3758. struct libusb_config_descriptor *conf_desc;
  3759. WINUSB_SETUP_PACKET *setup = (WINUSB_SETUP_PACKET *)transfer->buffer;
  3760. int iface, pass, r;
  3761. UNUSED(sub_api);
  3762. // Interface shouldn't matter for control, but it does in practice, with Windows'
  3763. // restrictions with regards to accessing HID keyboards and mice. Try to target
  3764. // a specific interface first, if possible.
  3765. switch (LIBUSB_REQ_RECIPIENT(setup->RequestType)) {
  3766. case LIBUSB_RECIPIENT_INTERFACE:
  3767. iface = setup->Index & 0xFF;
  3768. break;
  3769. case LIBUSB_RECIPIENT_ENDPOINT:
  3770. r = libusb_get_active_config_descriptor(transfer->dev_handle->dev, &conf_desc);
  3771. if (r == LIBUSB_SUCCESS) {
  3772. iface = get_interface_by_endpoint(conf_desc, (setup->Index & 0xFF));
  3773. libusb_free_config_descriptor(conf_desc);
  3774. break;
  3775. }
  3776. // No break if not able to determine interface
  3777. // Fall through
  3778. default:
  3779. iface = -1;
  3780. break;
  3781. }
  3782. // Try and target a specific interface if the control setup indicates such
  3783. if ((iface >= 0) && (iface < USB_MAXINTERFACES)) {
  3784. usbi_dbg(TRANSFER_CTX(transfer), "attempting control transfer targeted to interface %d", iface);
  3785. if ((priv->usb_interface[iface].path != NULL)
  3786. && (priv->usb_interface[iface].apib->submit_control_transfer != NULL)) {
  3787. r = priv->usb_interface[iface].apib->submit_control_transfer(priv->usb_interface[iface].sub_api, itransfer);
  3788. if (r == LIBUSB_SUCCESS)
  3789. return r;
  3790. }
  3791. }
  3792. // Either not targeted to a specific interface or no luck in doing so.
  3793. // Try a 2 pass approach with all interfaces.
  3794. for (pass = 0; pass < 2; pass++) {
  3795. for (iface = 0; iface < USB_MAXINTERFACES; iface++) {
  3796. if ((priv->usb_interface[iface].path != NULL)
  3797. && (priv->usb_interface[iface].apib->submit_control_transfer != NULL)) {
  3798. if ((pass == 0) && (priv->usb_interface[iface].restricted_functionality)) {
  3799. usbi_dbg(TRANSFER_CTX(transfer), "trying to skip restricted interface #%d (HID keyboard or mouse?)", iface);
  3800. continue;
  3801. }
  3802. usbi_dbg(TRANSFER_CTX(transfer), "using interface %d", iface);
  3803. r = priv->usb_interface[iface].apib->submit_control_transfer(priv->usb_interface[iface].sub_api, itransfer);
  3804. // If not supported on this API, it may be supported on another, so don't give up yet!!
  3805. if (r == LIBUSB_ERROR_NOT_SUPPORTED)
  3806. continue;
  3807. return r;
  3808. }
  3809. }
  3810. }
  3811. usbi_err(TRANSFER_CTX(transfer), "no libusb supported interfaces to complete request");
  3812. return LIBUSB_ERROR_NOT_FOUND;
  3813. }
  3814. static int composite_submit_bulk_transfer(int sub_api, struct usbi_transfer *itransfer)
  3815. {
  3816. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  3817. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(transfer->dev_handle);
  3818. struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
  3819. int current_interface;
  3820. UNUSED(sub_api);
  3821. current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
  3822. if (current_interface < 0) {
  3823. usbi_err(TRANSFER_CTX(transfer), "unable to match endpoint to an open interface - cancelling transfer");
  3824. return LIBUSB_ERROR_NOT_FOUND;
  3825. }
  3826. CHECK_SUPPORTED_API(priv->usb_interface[current_interface].apib, submit_bulk_transfer);
  3827. return priv->usb_interface[current_interface].apib->
  3828. submit_bulk_transfer(priv->usb_interface[current_interface].sub_api, itransfer);
  3829. }
  3830. static int composite_submit_iso_transfer(int sub_api, struct usbi_transfer *itransfer)
  3831. {
  3832. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  3833. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(transfer->dev_handle);
  3834. struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
  3835. int current_interface;
  3836. UNUSED(sub_api);
  3837. current_interface = interface_by_endpoint(priv, handle_priv, transfer->endpoint);
  3838. if (current_interface < 0) {
  3839. usbi_err(TRANSFER_CTX(transfer), "unable to match endpoint to an open interface - cancelling transfer");
  3840. return LIBUSB_ERROR_NOT_FOUND;
  3841. }
  3842. CHECK_SUPPORTED_API(priv->usb_interface[current_interface].apib, submit_iso_transfer);
  3843. return priv->usb_interface[current_interface].apib->
  3844. submit_iso_transfer(priv->usb_interface[current_interface].sub_api, itransfer);
  3845. }
  3846. static int composite_clear_halt(int sub_api, struct libusb_device_handle *dev_handle, unsigned char endpoint)
  3847. {
  3848. struct winusb_device_handle_priv *handle_priv = get_winusb_device_handle_priv(dev_handle);
  3849. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  3850. int current_interface;
  3851. UNUSED(sub_api);
  3852. current_interface = interface_by_endpoint(priv, handle_priv, endpoint);
  3853. if (current_interface < 0) {
  3854. usbi_err(HANDLE_CTX(dev_handle), "unable to match endpoint to an open interface - cannot clear");
  3855. return LIBUSB_ERROR_NOT_FOUND;
  3856. }
  3857. CHECK_SUPPORTED_API(priv->usb_interface[current_interface].apib, clear_halt);
  3858. return priv->usb_interface[current_interface].apib->
  3859. clear_halt(priv->usb_interface[current_interface].sub_api, dev_handle, endpoint);
  3860. }
  3861. static int composite_cancel_transfer(int sub_api, struct usbi_transfer *itransfer)
  3862. {
  3863. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  3864. struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
  3865. struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
  3866. int current_interface = transfer_priv->interface_number;
  3867. UNUSED(sub_api);
  3868. if ((current_interface < 0) || (current_interface >= USB_MAXINTERFACES)) {
  3869. usbi_err(TRANSFER_CTX(transfer), "program assertion failed - invalid interface_number");
  3870. return LIBUSB_ERROR_NOT_FOUND;
  3871. }
  3872. CHECK_SUPPORTED_API(priv->usb_interface[current_interface].apib, cancel_transfer);
  3873. return priv->usb_interface[current_interface].apib->
  3874. cancel_transfer(priv->usb_interface[current_interface].sub_api, itransfer);
  3875. }
  3876. static int composite_reset_device(int sub_api, struct libusb_device_handle *dev_handle)
  3877. {
  3878. struct winusb_device_priv *priv = usbi_get_device_priv(dev_handle->dev);
  3879. int i, r;
  3880. bool available[SUB_API_MAX];
  3881. UNUSED(sub_api);
  3882. for (i = 0; i < SUB_API_MAX; i++)
  3883. available[i] = false;
  3884. for (i = 0; i < USB_MAXINTERFACES; i++) {
  3885. if ((priv->usb_interface[i].apib->id == USB_API_WINUSBX)
  3886. && (priv->usb_interface[i].sub_api != SUB_API_NOTSET))
  3887. available[priv->usb_interface[i].sub_api] = true;
  3888. }
  3889. for (i = 0; i < SUB_API_MAX; i++) {
  3890. if (available[i]) {
  3891. r = usb_api_backend[USB_API_WINUSBX].reset_device(i, dev_handle);
  3892. if (r != LIBUSB_SUCCESS)
  3893. return r;
  3894. }
  3895. }
  3896. return LIBUSB_SUCCESS;
  3897. }
  3898. static enum libusb_transfer_status composite_copy_transfer_data(int sub_api, struct usbi_transfer *itransfer, DWORD length)
  3899. {
  3900. struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
  3901. struct winusb_transfer_priv *transfer_priv = get_winusb_transfer_priv(itransfer);
  3902. struct winusb_device_priv *priv = usbi_get_device_priv(transfer->dev_handle->dev);
  3903. int current_interface = transfer_priv->interface_number;
  3904. UNUSED(sub_api);
  3905. if (priv->usb_interface[current_interface].apib->copy_transfer_data == NULL) {
  3906. usbi_err(TRANSFER_CTX(transfer), "program assertion failed - no function to copy transfer data");
  3907. return LIBUSB_TRANSFER_ERROR;
  3908. }
  3909. return priv->usb_interface[current_interface].apib->
  3910. copy_transfer_data(priv->usb_interface[current_interface].sub_api, itransfer, length);
  3911. }