windows_usb.c 151 KB

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