test_dbus.py 232 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697
  1. # wpa_supplicant D-Bus interface tests
  2. # Copyright (c) 2014-2015, Jouni Malinen <j@w1.fi>
  3. #
  4. # This software may be distributed under the terms of the BSD license.
  5. # See README for more details.
  6. import binascii
  7. import logging
  8. logger = logging.getLogger()
  9. import subprocess
  10. import time
  11. try:
  12. import gobject
  13. import dbus
  14. dbus_imported = True
  15. except ImportError:
  16. dbus_imported = False
  17. import hostapd
  18. from wpasupplicant import WpaSupplicant
  19. from utils import HwsimSkip, alloc_fail, fail_test
  20. from p2p_utils import *
  21. from test_ap_tdls import connect_2sta_open
  22. from test_ap_eap import check_altsubject_match_support
  23. from test_nfc_p2p import set_ip_addr_info
  24. from test_wpas_mesh import check_mesh_support, add_open_mesh_network
  25. WPAS_DBUS_SERVICE = "fi.w1.wpa_supplicant1"
  26. WPAS_DBUS_PATH = "/fi/w1/wpa_supplicant1"
  27. WPAS_DBUS_IFACE = "fi.w1.wpa_supplicant1.Interface"
  28. WPAS_DBUS_IFACE_WPS = WPAS_DBUS_IFACE + ".WPS"
  29. WPAS_DBUS_NETWORK = "fi.w1.wpa_supplicant1.Network"
  30. WPAS_DBUS_BSS = "fi.w1.wpa_supplicant1.BSS"
  31. WPAS_DBUS_IFACE_P2PDEVICE = WPAS_DBUS_IFACE + ".P2PDevice"
  32. WPAS_DBUS_P2P_PEER = "fi.w1.wpa_supplicant1.Peer"
  33. WPAS_DBUS_GROUP = "fi.w1.wpa_supplicant1.Group"
  34. WPAS_DBUS_PERSISTENT_GROUP = "fi.w1.wpa_supplicant1.PersistentGroup"
  35. WPAS_DBUS_IFACE_MESH = WPAS_DBUS_IFACE + ".Mesh"
  36. def prepare_dbus(dev):
  37. if not dbus_imported:
  38. logger.info("No dbus module available")
  39. raise HwsimSkip("No dbus module available")
  40. try:
  41. from dbus.mainloop.glib import DBusGMainLoop
  42. dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
  43. bus = dbus.SystemBus()
  44. wpas_obj = bus.get_object(WPAS_DBUS_SERVICE, WPAS_DBUS_PATH)
  45. wpas = dbus.Interface(wpas_obj, WPAS_DBUS_SERVICE)
  46. path = wpas.GetInterface(dev.ifname)
  47. if_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  48. return (bus,wpas_obj,path,if_obj)
  49. except Exception, e:
  50. raise HwsimSkip("Could not connect to D-Bus: %s" % e)
  51. class TestDbus(object):
  52. def __init__(self, bus):
  53. self.loop = gobject.MainLoop()
  54. self.signals = []
  55. self.bus = bus
  56. def __exit__(self, type, value, traceback):
  57. for s in self.signals:
  58. s.remove()
  59. def add_signal(self, handler, interface, name, byte_arrays=False):
  60. s = self.bus.add_signal_receiver(handler, dbus_interface=interface,
  61. signal_name=name,
  62. byte_arrays=byte_arrays)
  63. self.signals.append(s)
  64. def timeout(self, *args):
  65. logger.debug("timeout")
  66. self.loop.quit()
  67. return False
  68. class alloc_fail_dbus(object):
  69. def __init__(self, dev, count, funcs, operation="Operation",
  70. expected="NoMemory"):
  71. self._dev = dev
  72. self._count = count
  73. self._funcs = funcs
  74. self._operation = operation
  75. self._expected = expected
  76. def __enter__(self):
  77. cmd = "TEST_ALLOC_FAIL %d:%s" % (self._count, self._funcs)
  78. if "OK" not in self._dev.request(cmd):
  79. raise HwsimSkip("TEST_ALLOC_FAIL not supported")
  80. def __exit__(self, type, value, traceback):
  81. if type is None:
  82. raise Exception("%s succeeded during out-of-memory" % self._operation)
  83. if type == dbus.exceptions.DBusException and self._expected in str(value):
  84. return True
  85. if self._dev.request("GET_ALLOC_FAIL") != "0:%s" % self._funcs:
  86. raise Exception("%s did not trigger allocation failure" % self._operation)
  87. return False
  88. def start_ap(ap, ssid="test-wps",
  89. ap_uuid="27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"):
  90. params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
  91. "wpa_passphrase": "12345678", "wpa": "2",
  92. "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
  93. "ap_pin": "12345670", "uuid": ap_uuid}
  94. return hostapd.add_ap(ap, params)
  95. def test_dbus_getall(dev, apdev):
  96. """D-Bus GetAll"""
  97. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  98. props = wpas_obj.GetAll(WPAS_DBUS_SERVICE,
  99. dbus_interface=dbus.PROPERTIES_IFACE)
  100. logger.debug("GetAll(fi.w1.wpa.supplicant1, /fi/w1/wpa_supplicant1) ==> " + str(props))
  101. props = if_obj.GetAll(WPAS_DBUS_IFACE,
  102. dbus_interface=dbus.PROPERTIES_IFACE)
  103. logger.debug("GetAll(%s, %s): %s" % (WPAS_DBUS_IFACE, path, str(props)))
  104. props = if_obj.GetAll(WPAS_DBUS_IFACE_WPS,
  105. dbus_interface=dbus.PROPERTIES_IFACE)
  106. logger.debug("GetAll(%s, %s): %s" % (WPAS_DBUS_IFACE_WPS, path, str(props)))
  107. res = if_obj.Get(WPAS_DBUS_IFACE, 'BSSs',
  108. dbus_interface=dbus.PROPERTIES_IFACE)
  109. if len(res) != 0:
  110. raise Exception("Unexpected BSSs entry: " + str(res))
  111. res = if_obj.Get(WPAS_DBUS_IFACE, 'Networks',
  112. dbus_interface=dbus.PROPERTIES_IFACE)
  113. if len(res) != 0:
  114. raise Exception("Unexpected Networks entry: " + str(res))
  115. hapd = hostapd.add_ap(apdev[0], { "ssid": "open" })
  116. bssid = apdev[0]['bssid']
  117. dev[0].scan_for_bss(bssid, freq=2412)
  118. id = dev[0].add_network()
  119. dev[0].set_network(id, "disabled", "0")
  120. dev[0].set_network_quoted(id, "ssid", "test")
  121. res = if_obj.Get(WPAS_DBUS_IFACE, 'BSSs',
  122. dbus_interface=dbus.PROPERTIES_IFACE)
  123. if len(res) != 1:
  124. raise Exception("Missing BSSs entry: " + str(res))
  125. bss_obj = bus.get_object(WPAS_DBUS_SERVICE, res[0])
  126. props = bss_obj.GetAll(WPAS_DBUS_BSS, dbus_interface=dbus.PROPERTIES_IFACE)
  127. logger.debug("GetAll(%s, %s): %s" % (WPAS_DBUS_BSS, res[0], str(props)))
  128. bssid_str = ''
  129. for item in props['BSSID']:
  130. if len(bssid_str) > 0:
  131. bssid_str += ':'
  132. bssid_str += '%02x' % item
  133. if bssid_str != bssid:
  134. raise Exception("Unexpected BSSID in BSSs entry")
  135. res = if_obj.Get(WPAS_DBUS_IFACE, 'Networks',
  136. dbus_interface=dbus.PROPERTIES_IFACE)
  137. if len(res) != 1:
  138. raise Exception("Missing Networks entry: " + str(res))
  139. net_obj = bus.get_object(WPAS_DBUS_SERVICE, res[0])
  140. props = net_obj.GetAll(WPAS_DBUS_NETWORK,
  141. dbus_interface=dbus.PROPERTIES_IFACE)
  142. logger.debug("GetAll(%s, %s): %s" % (WPAS_DBUS_NETWORK, res[0], str(props)))
  143. ssid = props['Properties']['ssid']
  144. if ssid != '"test"':
  145. raise Exception("Unexpected SSID in network entry")
  146. def test_dbus_getall_oom(dev, apdev):
  147. """D-Bus GetAll wpa_config_get_all() OOM"""
  148. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  149. id = dev[0].add_network()
  150. dev[0].set_network(id, "disabled", "0")
  151. dev[0].set_network_quoted(id, "ssid", "test")
  152. res = if_obj.Get(WPAS_DBUS_IFACE, 'Networks',
  153. dbus_interface=dbus.PROPERTIES_IFACE)
  154. if len(res) != 1:
  155. raise Exception("Missing Networks entry: " + str(res))
  156. net_obj = bus.get_object(WPAS_DBUS_SERVICE, res[0])
  157. for i in range(1, 50):
  158. with alloc_fail(dev[0], i, "wpa_config_get_all"):
  159. try:
  160. props = net_obj.GetAll(WPAS_DBUS_NETWORK,
  161. dbus_interface=dbus.PROPERTIES_IFACE)
  162. except dbus.exceptions.DBusException, e:
  163. pass
  164. def dbus_get(dbus, wpas_obj, prop, expect=None, byte_arrays=False):
  165. val = wpas_obj.Get(WPAS_DBUS_SERVICE, prop,
  166. dbus_interface=dbus.PROPERTIES_IFACE,
  167. byte_arrays=byte_arrays)
  168. if expect is not None and val != expect:
  169. raise Exception("Unexpected %s: %s (expected: %s)" %
  170. (prop, str(val), str(expect)))
  171. return val
  172. def dbus_set(dbus, wpas_obj, prop, val):
  173. wpas_obj.Set(WPAS_DBUS_SERVICE, prop, val,
  174. dbus_interface=dbus.PROPERTIES_IFACE)
  175. def test_dbus_properties(dev, apdev):
  176. """D-Bus Get/Set fi.w1.wpa_supplicant1 properties"""
  177. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  178. dbus_get(dbus, wpas_obj, "DebugLevel", expect="msgdump")
  179. dbus_set(dbus, wpas_obj, "DebugLevel", "debug")
  180. dbus_get(dbus, wpas_obj, "DebugLevel", expect="debug")
  181. for (val,err) in [ (3, "Error.Failed: wrong property type"),
  182. ("foo", "Error.Failed: wrong debug level value") ]:
  183. try:
  184. dbus_set(dbus, wpas_obj, "DebugLevel", val)
  185. raise Exception("Invalid DebugLevel value accepted: " + str(val))
  186. except dbus.exceptions.DBusException, e:
  187. if err not in str(e):
  188. raise Exception("Unexpected error message: " + str(e))
  189. dbus_set(dbus, wpas_obj, "DebugLevel", "msgdump")
  190. dbus_get(dbus, wpas_obj, "DebugLevel", expect="msgdump")
  191. dbus_get(dbus, wpas_obj, "DebugTimestamp", expect=True)
  192. dbus_set(dbus, wpas_obj, "DebugTimestamp", False)
  193. dbus_get(dbus, wpas_obj, "DebugTimestamp", expect=False)
  194. try:
  195. dbus_set(dbus, wpas_obj, "DebugTimestamp", "foo")
  196. raise Exception("Invalid DebugTimestamp value accepted")
  197. except dbus.exceptions.DBusException, e:
  198. if "Error.Failed: wrong property type" not in str(e):
  199. raise Exception("Unexpected error message: " + str(e))
  200. dbus_set(dbus, wpas_obj, "DebugTimestamp", True)
  201. dbus_get(dbus, wpas_obj, "DebugTimestamp", expect=True)
  202. dbus_get(dbus, wpas_obj, "DebugShowKeys", expect=True)
  203. dbus_set(dbus, wpas_obj, "DebugShowKeys", False)
  204. dbus_get(dbus, wpas_obj, "DebugShowKeys", expect=False)
  205. try:
  206. dbus_set(dbus, wpas_obj, "DebugShowKeys", "foo")
  207. raise Exception("Invalid DebugShowKeys value accepted")
  208. except dbus.exceptions.DBusException, e:
  209. if "Error.Failed: wrong property type" not in str(e):
  210. raise Exception("Unexpected error message: " + str(e))
  211. dbus_set(dbus, wpas_obj, "DebugShowKeys", True)
  212. dbus_get(dbus, wpas_obj, "DebugShowKeys", expect=True)
  213. res = dbus_get(dbus, wpas_obj, "Interfaces")
  214. if len(res) != 1:
  215. raise Exception("Unexpected Interfaces value: " + str(res))
  216. res = dbus_get(dbus, wpas_obj, "EapMethods")
  217. if len(res) < 5 or "TTLS" not in res:
  218. raise Exception("Unexpected EapMethods value: " + str(res))
  219. res = dbus_get(dbus, wpas_obj, "Capabilities")
  220. if len(res) < 2 or "p2p" not in res:
  221. raise Exception("Unexpected Capabilities value: " + str(res))
  222. dbus_get(dbus, wpas_obj, "WFDIEs", byte_arrays=True)
  223. val = binascii.unhexlify("010006020304050608")
  224. dbus_set(dbus, wpas_obj, "WFDIEs", dbus.ByteArray(val))
  225. res = dbus_get(dbus, wpas_obj, "WFDIEs", byte_arrays=True)
  226. if val != res:
  227. raise Exception("WFDIEs value changed")
  228. try:
  229. dbus_set(dbus, wpas_obj, "WFDIEs", dbus.ByteArray('\x00'))
  230. raise Exception("Invalid WFDIEs value accepted")
  231. except dbus.exceptions.DBusException, e:
  232. if "InvalidArgs" not in str(e):
  233. raise Exception("Unexpected error message: " + str(e))
  234. dbus_set(dbus, wpas_obj, "WFDIEs", dbus.ByteArray(''))
  235. dbus_set(dbus, wpas_obj, "WFDIEs", dbus.ByteArray(val))
  236. dbus_set(dbus, wpas_obj, "WFDIEs", dbus.ByteArray(''))
  237. res = dbus_get(dbus, wpas_obj, "WFDIEs", byte_arrays=True)
  238. if len(res) != 0:
  239. raise Exception("WFDIEs not cleared properly")
  240. res = dbus_get(dbus, wpas_obj, "EapMethods")
  241. try:
  242. dbus_set(dbus, wpas_obj, "EapMethods", res)
  243. raise Exception("Invalid Set accepted")
  244. except dbus.exceptions.DBusException, e:
  245. if "InvalidArgs: Property is read-only" not in str(e):
  246. raise Exception("Unexpected error message: " + str(e))
  247. try:
  248. wpas_obj.SetFoo(WPAS_DBUS_SERVICE, "DebugShowKeys", True,
  249. dbus_interface=dbus.PROPERTIES_IFACE)
  250. raise Exception("Unknown method accepted")
  251. except dbus.exceptions.DBusException, e:
  252. if "UnknownMethod" not in str(e):
  253. raise Exception("Unexpected error message: " + str(e))
  254. try:
  255. wpas_obj.Get("foo", "DebugShowKeys",
  256. dbus_interface=dbus.PROPERTIES_IFACE)
  257. raise Exception("Invalid Get accepted")
  258. except dbus.exceptions.DBusException, e:
  259. if "InvalidArgs: No such property" not in str(e):
  260. raise Exception("Unexpected error message: " + str(e))
  261. test_obj = bus.get_object(WPAS_DBUS_SERVICE, WPAS_DBUS_PATH,
  262. introspect=False)
  263. try:
  264. test_obj.Get(123, "DebugShowKeys",
  265. dbus_interface=dbus.PROPERTIES_IFACE)
  266. raise Exception("Invalid Get accepted")
  267. except dbus.exceptions.DBusException, e:
  268. if "InvalidArgs: Invalid arguments" not in str(e):
  269. raise Exception("Unexpected error message: " + str(e))
  270. try:
  271. test_obj.Get(WPAS_DBUS_SERVICE, 123,
  272. dbus_interface=dbus.PROPERTIES_IFACE)
  273. raise Exception("Invalid Get accepted")
  274. except dbus.exceptions.DBusException, e:
  275. if "InvalidArgs: Invalid arguments" not in str(e):
  276. raise Exception("Unexpected error message: " + str(e))
  277. try:
  278. wpas_obj.Set(WPAS_DBUS_SERVICE, "WFDIEs",
  279. dbus.ByteArray('', variant_level=2),
  280. dbus_interface=dbus.PROPERTIES_IFACE)
  281. raise Exception("Invalid Set accepted")
  282. except dbus.exceptions.DBusException, e:
  283. if "InvalidArgs: invalid message format" not in str(e):
  284. raise Exception("Unexpected error message: " + str(e))
  285. def test_dbus_set_global_properties(dev, apdev):
  286. """D-Bus Get/Set fi.w1.wpa_supplicant1 interface global properties"""
  287. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  288. dev[0].set("model_name", "")
  289. props = [ ('Okc', '0', '1'), ('ModelName', '', 'blahblahblah') ]
  290. for p in props:
  291. res = if_obj.Get(WPAS_DBUS_IFACE, p[0],
  292. dbus_interface=dbus.PROPERTIES_IFACE)
  293. if res != p[1]:
  294. raise Exception("Unexpected " + p[0] + " value: " + str(res))
  295. if_obj.Set(WPAS_DBUS_IFACE, p[0], p[2],
  296. dbus_interface=dbus.PROPERTIES_IFACE)
  297. res = if_obj.Get(WPAS_DBUS_IFACE, p[0],
  298. dbus_interface=dbus.PROPERTIES_IFACE)
  299. if res != p[2]:
  300. raise Exception("Unexpected " + p[0] + " value after set: " + str(res))
  301. dev[0].set("model_name", "")
  302. def test_dbus_invalid_method(dev, apdev):
  303. """D-Bus invalid method"""
  304. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  305. wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
  306. try:
  307. wps.Foo()
  308. raise Exception("Unknown method accepted")
  309. except dbus.exceptions.DBusException, e:
  310. if "UnknownMethod" not in str(e):
  311. raise Exception("Unexpected error message: " + str(e))
  312. test_obj = bus.get_object(WPAS_DBUS_SERVICE, path, introspect=False)
  313. test_wps = dbus.Interface(test_obj, WPAS_DBUS_IFACE_WPS)
  314. try:
  315. test_wps.Start(123)
  316. raise Exception("WPS.Start with incorrect signature accepted")
  317. except dbus.exceptions.DBusException, e:
  318. if "InvalidArgs: Invalid arg" not in str(e):
  319. raise Exception("Unexpected error message: " + str(e))
  320. def test_dbus_get_set_wps(dev, apdev):
  321. """D-Bus Get/Set for WPS properties"""
  322. try:
  323. _test_dbus_get_set_wps(dev, apdev)
  324. finally:
  325. dev[0].request("SET wps_cred_processing 0")
  326. dev[0].request("SET config_methods display keypad virtual_display nfc_interface p2ps")
  327. dev[0].set("device_name", "Device A")
  328. dev[0].set("manufacturer", "")
  329. dev[0].set("model_name", "")
  330. dev[0].set("model_number", "")
  331. dev[0].set("serial_number", "")
  332. dev[0].set("device_type", "0-00000000-0")
  333. def _test_dbus_get_set_wps(dev, apdev):
  334. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  335. if_obj.Get(WPAS_DBUS_IFACE_WPS, "ConfigMethods",
  336. dbus_interface=dbus.PROPERTIES_IFACE)
  337. val = "display keypad virtual_display nfc_interface"
  338. dev[0].request("SET config_methods " + val)
  339. config = if_obj.Get(WPAS_DBUS_IFACE_WPS, "ConfigMethods",
  340. dbus_interface=dbus.PROPERTIES_IFACE)
  341. if config != val:
  342. raise Exception("Unexpected Get(ConfigMethods) result: " + config)
  343. val2 = "push_button display"
  344. if_obj.Set(WPAS_DBUS_IFACE_WPS, "ConfigMethods", val2,
  345. dbus_interface=dbus.PROPERTIES_IFACE)
  346. config = if_obj.Get(WPAS_DBUS_IFACE_WPS, "ConfigMethods",
  347. dbus_interface=dbus.PROPERTIES_IFACE)
  348. if config != val2:
  349. raise Exception("Unexpected Get(ConfigMethods) result after Set: " + config)
  350. dev[0].request("SET config_methods " + val)
  351. for i in range(3):
  352. dev[0].request("SET wps_cred_processing " + str(i))
  353. val = if_obj.Get(WPAS_DBUS_IFACE_WPS, "ProcessCredentials",
  354. dbus_interface=dbus.PROPERTIES_IFACE)
  355. expected_val = False if i == 1 else True
  356. if val != expected_val:
  357. raise Exception("Unexpected Get(ProcessCredentials) result({}): {}".format(i, val))
  358. tests = [ ("device_name", "DeviceName"),
  359. ("manufacturer", "Manufacturer"),
  360. ("model_name", "ModelName"),
  361. ("model_number", "ModelNumber"),
  362. ("serial_number", "SerialNumber") ]
  363. for f1,f2 in tests:
  364. val2 = "test-value-test"
  365. dev[0].set(f1, val2)
  366. val = if_obj.Get(WPAS_DBUS_IFACE_WPS, f2,
  367. dbus_interface=dbus.PROPERTIES_IFACE)
  368. if val != val2:
  369. raise Exception("Get(%s) returned unexpected value" % f2)
  370. val2 = "TEST-value"
  371. if_obj.Set(WPAS_DBUS_IFACE_WPS, f2, val2,
  372. dbus_interface=dbus.PROPERTIES_IFACE)
  373. val = if_obj.Get(WPAS_DBUS_IFACE_WPS, f2,
  374. dbus_interface=dbus.PROPERTIES_IFACE)
  375. if val != val2:
  376. raise Exception("Get(%s) returned unexpected value after Set" % f2)
  377. dev[0].set("device_type", "5-0050F204-1")
  378. val = if_obj.Get(WPAS_DBUS_IFACE_WPS, "DeviceType",
  379. dbus_interface=dbus.PROPERTIES_IFACE)
  380. if val[0] != 0x00 or val[1] != 0x05 != val[2] != 0x00 or val[3] != 0x50 or val[4] != 0xf2 or val[5] != 0x04 or val[6] != 0x00 or val[7] != 0x01:
  381. raise Exception("DeviceType mismatch")
  382. if_obj.Set(WPAS_DBUS_IFACE_WPS, "DeviceType", val,
  383. dbus_interface=dbus.PROPERTIES_IFACE)
  384. val = if_obj.Get(WPAS_DBUS_IFACE_WPS, "DeviceType",
  385. dbus_interface=dbus.PROPERTIES_IFACE)
  386. if val[0] != 0x00 or val[1] != 0x05 != val[2] != 0x00 or val[3] != 0x50 or val[4] != 0xf2 or val[5] != 0x04 or val[6] != 0x00 or val[7] != 0x01:
  387. raise Exception("DeviceType mismatch after Set")
  388. val2 = '\x01\x02\x03\x04\x05\x06\x07\x08'
  389. if_obj.Set(WPAS_DBUS_IFACE_WPS, "DeviceType", dbus.ByteArray(val2),
  390. dbus_interface=dbus.PROPERTIES_IFACE)
  391. val = if_obj.Get(WPAS_DBUS_IFACE_WPS, "DeviceType",
  392. dbus_interface=dbus.PROPERTIES_IFACE,
  393. byte_arrays=True)
  394. if val != val2:
  395. raise Exception("DeviceType mismatch after Set (2)")
  396. class TestDbusGetSet(TestDbus):
  397. def __init__(self, bus):
  398. TestDbus.__init__(self, bus)
  399. self.signal_received = False
  400. self.signal_received_deprecated = False
  401. self.sets_done = False
  402. def __enter__(self):
  403. gobject.timeout_add(1, self.run_sets)
  404. gobject.timeout_add(1000, self.timeout)
  405. self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE_WPS,
  406. "PropertiesChanged")
  407. self.add_signal(self.propertiesChanged2, dbus.PROPERTIES_IFACE,
  408. "PropertiesChanged")
  409. self.loop.run()
  410. return self
  411. def propertiesChanged(self, properties):
  412. logger.debug("PropertiesChanged: " + str(properties))
  413. if properties.has_key("ProcessCredentials"):
  414. self.signal_received_deprecated = True
  415. if self.sets_done and self.signal_received:
  416. self.loop.quit()
  417. def propertiesChanged2(self, interface_name, changed_properties,
  418. invalidated_properties):
  419. logger.debug("propertiesChanged2: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
  420. if interface_name != WPAS_DBUS_IFACE_WPS:
  421. return
  422. if changed_properties.has_key("ProcessCredentials"):
  423. self.signal_received = True
  424. if self.sets_done and self.signal_received_deprecated:
  425. self.loop.quit()
  426. def run_sets(self, *args):
  427. logger.debug("run_sets")
  428. if_obj.Set(WPAS_DBUS_IFACE_WPS, "ProcessCredentials",
  429. dbus.Boolean(1),
  430. dbus_interface=dbus.PROPERTIES_IFACE)
  431. if if_obj.Get(WPAS_DBUS_IFACE_WPS, "ProcessCredentials",
  432. dbus_interface=dbus.PROPERTIES_IFACE) != True:
  433. raise Exception("Unexpected Get(ProcessCredentials) result after Set")
  434. if_obj.Set(WPAS_DBUS_IFACE_WPS, "ProcessCredentials",
  435. dbus.Boolean(0),
  436. dbus_interface=dbus.PROPERTIES_IFACE)
  437. if if_obj.Get(WPAS_DBUS_IFACE_WPS, "ProcessCredentials",
  438. dbus_interface=dbus.PROPERTIES_IFACE) != False:
  439. raise Exception("Unexpected Get(ProcessCredentials) result after Set")
  440. self.dbus_sets_done = True
  441. return False
  442. def success(self):
  443. return self.signal_received and self.signal_received_deprecated
  444. with TestDbusGetSet(bus) as t:
  445. if not t.success():
  446. raise Exception("No signal received for ProcessCredentials change")
  447. def test_dbus_wps_invalid(dev, apdev):
  448. """D-Bus invaldi WPS operation"""
  449. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  450. wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
  451. failures = [ {'Role': 'foo', 'Type': 'pbc'},
  452. {'Role': 123, 'Type': 'pbc'},
  453. {'Type': 'pbc'},
  454. {'Role': 'enrollee'},
  455. {'Role': 'registrar'},
  456. {'Role': 'enrollee', 'Type': 123},
  457. {'Role': 'enrollee', 'Type': 'foo'},
  458. {'Role': 'enrollee', 'Type': 'pbc',
  459. 'Bssid': '02:33:44:55:66:77'},
  460. {'Role': 'enrollee', 'Type': 'pin', 'Pin': 123},
  461. {'Role': 'enrollee', 'Type': 'pbc',
  462. 'Bssid': dbus.ByteArray('12345')},
  463. {'Role': 'enrollee', 'Type': 'pbc',
  464. 'P2PDeviceAddress': 12345},
  465. {'Role': 'enrollee', 'Type': 'pbc',
  466. 'P2PDeviceAddress': dbus.ByteArray('12345')},
  467. {'Role': 'enrollee', 'Type': 'pbc', 'Foo': 'bar'} ]
  468. for args in failures:
  469. try:
  470. wps.Start(args)
  471. raise Exception("Invalid WPS.Start() arguments accepted: " + str(args))
  472. except dbus.exceptions.DBusException, e:
  473. if not str(e).startswith("fi.w1.wpa_supplicant1.InvalidArgs"):
  474. raise Exception("Unexpected error message: " + str(e))
  475. def test_dbus_wps_oom(dev, apdev):
  476. """D-Bus WPS operation (OOM)"""
  477. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  478. wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
  479. with alloc_fail_dbus(dev[0], 1, "=wpas_dbus_getter_state", "Get"):
  480. if_obj.Get(WPAS_DBUS_IFACE, "State",
  481. dbus_interface=dbus.PROPERTIES_IFACE)
  482. hapd = hostapd.add_ap(apdev[0], { "ssid": "open" })
  483. bssid = apdev[0]['bssid']
  484. dev[0].scan_for_bss(bssid, freq=2412)
  485. time.sleep(0.05)
  486. for i in range(1, 3):
  487. with alloc_fail_dbus(dev[0], i, "=wpas_dbus_getter_bsss", "Get"):
  488. if_obj.Get(WPAS_DBUS_IFACE, "BSSs",
  489. dbus_interface=dbus.PROPERTIES_IFACE)
  490. res = if_obj.Get(WPAS_DBUS_IFACE, 'BSSs',
  491. dbus_interface=dbus.PROPERTIES_IFACE)
  492. bss_obj = bus.get_object(WPAS_DBUS_SERVICE, res[0])
  493. with alloc_fail_dbus(dev[0], 1, "=wpas_dbus_getter_bss_rates", "Get"):
  494. bss_obj.Get(WPAS_DBUS_BSS, "Rates",
  495. dbus_interface=dbus.PROPERTIES_IFACE)
  496. with alloc_fail(dev[0], 1,
  497. "wpa_bss_get_bit_rates;wpas_dbus_getter_bss_rates"):
  498. try:
  499. bss_obj.Get(WPAS_DBUS_BSS, "Rates",
  500. dbus_interface=dbus.PROPERTIES_IFACE)
  501. except dbus.exceptions.DBusException, e:
  502. pass
  503. id = dev[0].add_network()
  504. dev[0].set_network(id, "disabled", "0")
  505. dev[0].set_network_quoted(id, "ssid", "test")
  506. for i in range(1, 3):
  507. with alloc_fail_dbus(dev[0], i, "=wpas_dbus_getter_networks", "Get"):
  508. if_obj.Get(WPAS_DBUS_IFACE, "Networks",
  509. dbus_interface=dbus.PROPERTIES_IFACE)
  510. with alloc_fail_dbus(dev[0], 1, "wpas_dbus_getter_interfaces", "Get"):
  511. dbus_get(dbus, wpas_obj, "Interfaces")
  512. for i in range(1, 6):
  513. with alloc_fail_dbus(dev[0], i, "=eap_get_names_as_string_array;wpas_dbus_getter_eap_methods", "Get"):
  514. dbus_get(dbus, wpas_obj, "EapMethods")
  515. with alloc_fail_dbus(dev[0], 1, "wpas_dbus_setter_config_methods", "Set",
  516. expected="Error.Failed: Failed to set property"):
  517. val2 = "push_button display"
  518. if_obj.Set(WPAS_DBUS_IFACE_WPS, "ConfigMethods", val2,
  519. dbus_interface=dbus.PROPERTIES_IFACE)
  520. with alloc_fail_dbus(dev[0], 1, "=wpa_config_add_network;wpas_dbus_handler_wps_start",
  521. "WPS.Start",
  522. expected="UnknownError: WPS start failed"):
  523. wps.Start({'Role': 'enrollee', 'Type': 'pin', 'Pin': '12345670'})
  524. def test_dbus_wps_pbc(dev, apdev):
  525. """D-Bus WPS/PBC operation and signals"""
  526. try:
  527. _test_dbus_wps_pbc(dev, apdev)
  528. finally:
  529. dev[0].request("SET wps_cred_processing 0")
  530. def _test_dbus_wps_pbc(dev, apdev):
  531. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  532. wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
  533. hapd = start_ap(apdev[0])
  534. hapd.request("WPS_PBC")
  535. bssid = apdev[0]['bssid']
  536. dev[0].scan_for_bss(bssid, freq="2412")
  537. dev[0].request("SET wps_cred_processing 2")
  538. res = if_obj.Get(WPAS_DBUS_IFACE, 'BSSs',
  539. dbus_interface=dbus.PROPERTIES_IFACE)
  540. if len(res) != 1:
  541. raise Exception("Missing BSSs entry: " + str(res))
  542. bss_obj = bus.get_object(WPAS_DBUS_SERVICE, res[0])
  543. props = bss_obj.GetAll(WPAS_DBUS_BSS, dbus_interface=dbus.PROPERTIES_IFACE)
  544. logger.debug("GetAll(%s, %s): %s" % (WPAS_DBUS_BSS, res[0], str(props)))
  545. if 'WPS' not in props:
  546. raise Exception("No WPS information in the BSS entry")
  547. if 'Type' not in props['WPS']:
  548. raise Exception("No Type field in the WPS dictionary")
  549. if props['WPS']['Type'] != 'pbc':
  550. raise Exception("Unexpected WPS Type: " + props['WPS']['Type'])
  551. class TestDbusWps(TestDbus):
  552. def __init__(self, bus, wps):
  553. TestDbus.__init__(self, bus)
  554. self.success_seen = False
  555. self.credentials_received = False
  556. self.wps = wps
  557. def __enter__(self):
  558. gobject.timeout_add(1, self.start_pbc)
  559. gobject.timeout_add(15000, self.timeout)
  560. self.add_signal(self.wpsEvent, WPAS_DBUS_IFACE_WPS, "Event")
  561. self.add_signal(self.credentials, WPAS_DBUS_IFACE_WPS,
  562. "Credentials")
  563. self.loop.run()
  564. return self
  565. def wpsEvent(self, name, args):
  566. logger.debug("wpsEvent: %s args='%s'" % (name, str(args)))
  567. if name == "success":
  568. self.success_seen = True
  569. if self.credentials_received:
  570. self.loop.quit()
  571. def credentials(self, args):
  572. logger.debug("credentials: " + str(args))
  573. self.credentials_received = True
  574. if self.success_seen:
  575. self.loop.quit()
  576. def start_pbc(self, *args):
  577. logger.debug("start_pbc")
  578. self.wps.Start({'Role': 'enrollee', 'Type': 'pbc'})
  579. return False
  580. def success(self):
  581. return self.success_seen and self.credentials_received
  582. with TestDbusWps(bus, wps) as t:
  583. if not t.success():
  584. raise Exception("Failure in D-Bus operations")
  585. dev[0].wait_connected(timeout=10)
  586. dev[0].request("DISCONNECT")
  587. hapd.disable()
  588. dev[0].flush_scan_cache()
  589. def test_dbus_wps_pbc_overlap(dev, apdev):
  590. """D-Bus WPS/PBC operation and signal for PBC overlap"""
  591. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  592. wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
  593. hapd = start_ap(apdev[0])
  594. hapd2 = start_ap(apdev[1], ssid="test-wps2",
  595. ap_uuid="27ea801a-9e5c-4e73-bd82-f89cbcd10d7f")
  596. hapd.request("WPS_PBC")
  597. hapd2.request("WPS_PBC")
  598. bssid = apdev[0]['bssid']
  599. dev[0].scan_for_bss(bssid, freq="2412")
  600. bssid2 = apdev[1]['bssid']
  601. dev[0].scan_for_bss(bssid2, freq="2412")
  602. class TestDbusWps(TestDbus):
  603. def __init__(self, bus, wps):
  604. TestDbus.__init__(self, bus)
  605. self.overlap_seen = False
  606. self.wps = wps
  607. def __enter__(self):
  608. gobject.timeout_add(1, self.start_pbc)
  609. gobject.timeout_add(15000, self.timeout)
  610. self.add_signal(self.wpsEvent, WPAS_DBUS_IFACE_WPS, "Event")
  611. self.loop.run()
  612. return self
  613. def wpsEvent(self, name, args):
  614. logger.debug("wpsEvent: %s args='%s'" % (name, str(args)))
  615. if name == "pbc-overlap":
  616. self.overlap_seen = True
  617. self.loop.quit()
  618. def start_pbc(self, *args):
  619. logger.debug("start_pbc")
  620. self.wps.Start({'Role': 'enrollee', 'Type': 'pbc'})
  621. return False
  622. def success(self):
  623. return self.overlap_seen
  624. with TestDbusWps(bus, wps) as t:
  625. if not t.success():
  626. raise Exception("Failure in D-Bus operations")
  627. dev[0].request("WPS_CANCEL")
  628. dev[0].request("DISCONNECT")
  629. hapd.disable()
  630. dev[0].flush_scan_cache()
  631. def test_dbus_wps_pin(dev, apdev):
  632. """D-Bus WPS/PIN operation and signals"""
  633. try:
  634. _test_dbus_wps_pin(dev, apdev)
  635. finally:
  636. dev[0].request("SET wps_cred_processing 0")
  637. def _test_dbus_wps_pin(dev, apdev):
  638. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  639. wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
  640. hapd = start_ap(apdev[0])
  641. hapd.request("WPS_PIN any 12345670")
  642. bssid = apdev[0]['bssid']
  643. dev[0].scan_for_bss(bssid, freq="2412")
  644. dev[0].request("SET wps_cred_processing 2")
  645. class TestDbusWps(TestDbus):
  646. def __init__(self, bus):
  647. TestDbus.__init__(self, bus)
  648. self.success_seen = False
  649. self.credentials_received = False
  650. def __enter__(self):
  651. gobject.timeout_add(1, self.start_pin)
  652. gobject.timeout_add(15000, self.timeout)
  653. self.add_signal(self.wpsEvent, WPAS_DBUS_IFACE_WPS, "Event")
  654. self.add_signal(self.credentials, WPAS_DBUS_IFACE_WPS,
  655. "Credentials")
  656. self.loop.run()
  657. return self
  658. def wpsEvent(self, name, args):
  659. logger.debug("wpsEvent: %s args='%s'" % (name, str(args)))
  660. if name == "success":
  661. self.success_seen = True
  662. if self.credentials_received:
  663. self.loop.quit()
  664. def credentials(self, args):
  665. logger.debug("credentials: " + str(args))
  666. self.credentials_received = True
  667. if self.success_seen:
  668. self.loop.quit()
  669. def start_pin(self, *args):
  670. logger.debug("start_pin")
  671. bssid_ay = dbus.ByteArray(bssid.replace(':','').decode('hex'))
  672. wps.Start({'Role': 'enrollee', 'Type': 'pin', 'Pin': '12345670',
  673. 'Bssid': bssid_ay})
  674. return False
  675. def success(self):
  676. return self.success_seen and self.credentials_received
  677. with TestDbusWps(bus) as t:
  678. if not t.success():
  679. raise Exception("Failure in D-Bus operations")
  680. dev[0].wait_connected(timeout=10)
  681. def test_dbus_wps_pin2(dev, apdev):
  682. """D-Bus WPS/PIN operation and signals (PIN from wpa_supplicant)"""
  683. try:
  684. _test_dbus_wps_pin2(dev, apdev)
  685. finally:
  686. dev[0].request("SET wps_cred_processing 0")
  687. def _test_dbus_wps_pin2(dev, apdev):
  688. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  689. wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
  690. hapd = start_ap(apdev[0])
  691. bssid = apdev[0]['bssid']
  692. dev[0].scan_for_bss(bssid, freq="2412")
  693. dev[0].request("SET wps_cred_processing 2")
  694. class TestDbusWps(TestDbus):
  695. def __init__(self, bus):
  696. TestDbus.__init__(self, bus)
  697. self.success_seen = False
  698. self.failed = False
  699. def __enter__(self):
  700. gobject.timeout_add(1, self.start_pin)
  701. gobject.timeout_add(15000, self.timeout)
  702. self.add_signal(self.wpsEvent, WPAS_DBUS_IFACE_WPS, "Event")
  703. self.add_signal(self.credentials, WPAS_DBUS_IFACE_WPS,
  704. "Credentials")
  705. self.loop.run()
  706. return self
  707. def wpsEvent(self, name, args):
  708. logger.debug("wpsEvent: %s args='%s'" % (name, str(args)))
  709. if name == "success":
  710. self.success_seen = True
  711. if self.credentials_received:
  712. self.loop.quit()
  713. def credentials(self, args):
  714. logger.debug("credentials: " + str(args))
  715. self.credentials_received = True
  716. if self.success_seen:
  717. self.loop.quit()
  718. def start_pin(self, *args):
  719. logger.debug("start_pin")
  720. bssid_ay = dbus.ByteArray(bssid.replace(':','').decode('hex'))
  721. res = wps.Start({'Role': 'enrollee', 'Type': 'pin',
  722. 'Bssid': bssid_ay})
  723. pin = res['Pin']
  724. h = hostapd.Hostapd(apdev[0]['ifname'])
  725. h.request("WPS_PIN any " + pin)
  726. return False
  727. def success(self):
  728. return self.success_seen and self.credentials_received
  729. with TestDbusWps(bus) as t:
  730. if not t.success():
  731. raise Exception("Failure in D-Bus operations")
  732. dev[0].wait_connected(timeout=10)
  733. def test_dbus_wps_pin_m2d(dev, apdev):
  734. """D-Bus WPS/PIN operation and signals with M2D"""
  735. try:
  736. _test_dbus_wps_pin_m2d(dev, apdev)
  737. finally:
  738. dev[0].request("SET wps_cred_processing 0")
  739. def _test_dbus_wps_pin_m2d(dev, apdev):
  740. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  741. wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
  742. hapd = start_ap(apdev[0])
  743. bssid = apdev[0]['bssid']
  744. dev[0].scan_for_bss(bssid, freq="2412")
  745. dev[0].request("SET wps_cred_processing 2")
  746. class TestDbusWps(TestDbus):
  747. def __init__(self, bus):
  748. TestDbus.__init__(self, bus)
  749. self.success_seen = False
  750. self.credentials_received = False
  751. def __enter__(self):
  752. gobject.timeout_add(1, self.start_pin)
  753. gobject.timeout_add(15000, self.timeout)
  754. self.add_signal(self.wpsEvent, WPAS_DBUS_IFACE_WPS, "Event")
  755. self.add_signal(self.credentials, WPAS_DBUS_IFACE_WPS,
  756. "Credentials")
  757. self.loop.run()
  758. return self
  759. def wpsEvent(self, name, args):
  760. logger.debug("wpsEvent: %s args='%s'" % (name, str(args)))
  761. if name == "success":
  762. self.success_seen = True
  763. if self.credentials_received:
  764. self.loop.quit()
  765. elif name == "m2d":
  766. h = hostapd.Hostapd(apdev[0]['ifname'])
  767. h.request("WPS_PIN any 12345670")
  768. def credentials(self, args):
  769. logger.debug("credentials: " + str(args))
  770. self.credentials_received = True
  771. if self.success_seen:
  772. self.loop.quit()
  773. def start_pin(self, *args):
  774. logger.debug("start_pin")
  775. bssid_ay = dbus.ByteArray(bssid.replace(':','').decode('hex'))
  776. wps.Start({'Role': 'enrollee', 'Type': 'pin', 'Pin': '12345670',
  777. 'Bssid': bssid_ay})
  778. return False
  779. def success(self):
  780. return self.success_seen and self.credentials_received
  781. with TestDbusWps(bus) as t:
  782. if not t.success():
  783. raise Exception("Failure in D-Bus operations")
  784. dev[0].wait_connected(timeout=10)
  785. def test_dbus_wps_reg(dev, apdev):
  786. """D-Bus WPS/Registrar operation and signals"""
  787. try:
  788. _test_dbus_wps_reg(dev, apdev)
  789. finally:
  790. dev[0].request("SET wps_cred_processing 0")
  791. def _test_dbus_wps_reg(dev, apdev):
  792. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  793. wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
  794. hapd = start_ap(apdev[0])
  795. hapd.request("WPS_PIN any 12345670")
  796. bssid = apdev[0]['bssid']
  797. dev[0].scan_for_bss(bssid, freq="2412")
  798. dev[0].request("SET wps_cred_processing 2")
  799. class TestDbusWps(TestDbus):
  800. def __init__(self, bus):
  801. TestDbus.__init__(self, bus)
  802. self.credentials_received = False
  803. def __enter__(self):
  804. gobject.timeout_add(100, self.start_reg)
  805. gobject.timeout_add(15000, self.timeout)
  806. self.add_signal(self.wpsEvent, WPAS_DBUS_IFACE_WPS, "Event")
  807. self.add_signal(self.credentials, WPAS_DBUS_IFACE_WPS,
  808. "Credentials")
  809. self.loop.run()
  810. return self
  811. def wpsEvent(self, name, args):
  812. logger.debug("wpsEvent: %s args='%s'" % (name, str(args)))
  813. def credentials(self, args):
  814. logger.debug("credentials: " + str(args))
  815. self.credentials_received = True
  816. self.loop.quit()
  817. def start_reg(self, *args):
  818. logger.debug("start_reg")
  819. bssid_ay = dbus.ByteArray(bssid.replace(':','').decode('hex'))
  820. wps.Start({'Role': 'registrar', 'Type': 'pin',
  821. 'Pin': '12345670', 'Bssid': bssid_ay})
  822. return False
  823. def success(self):
  824. return self.credentials_received
  825. with TestDbusWps(bus) as t:
  826. if not t.success():
  827. raise Exception("Failure in D-Bus operations")
  828. dev[0].wait_connected(timeout=10)
  829. def test_dbus_wps_cancel(dev, apdev):
  830. """D-Bus WPS Cancel operation"""
  831. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  832. wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
  833. hapd = start_ap(apdev[0])
  834. bssid = apdev[0]['bssid']
  835. wps.Cancel()
  836. dev[0].scan_for_bss(bssid, freq="2412")
  837. bssid_ay = dbus.ByteArray(bssid.replace(':','').decode('hex'))
  838. wps.Start({'Role': 'enrollee', 'Type': 'pin', 'Pin': '12345670',
  839. 'Bssid': bssid_ay})
  840. wps.Cancel()
  841. dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 1)
  842. def test_dbus_scan_invalid(dev, apdev):
  843. """D-Bus invalid scan method"""
  844. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  845. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  846. tests = [ ({}, "InvalidArgs"),
  847. ({'Type': 123}, "InvalidArgs"),
  848. ({'Type': 'foo'}, "InvalidArgs"),
  849. ({'Type': 'active', 'Foo': 'bar'}, "InvalidArgs"),
  850. ({'Type': 'active', 'SSIDs': 'foo'}, "InvalidArgs"),
  851. ({'Type': 'active', 'SSIDs': ['foo']}, "InvalidArgs"),
  852. ({'Type': 'active',
  853. 'SSIDs': [ dbus.ByteArray("1"), dbus.ByteArray("2"),
  854. dbus.ByteArray("3"), dbus.ByteArray("4"),
  855. dbus.ByteArray("5"), dbus.ByteArray("6"),
  856. dbus.ByteArray("7"), dbus.ByteArray("8"),
  857. dbus.ByteArray("9"), dbus.ByteArray("10"),
  858. dbus.ByteArray("11"), dbus.ByteArray("12"),
  859. dbus.ByteArray("13"), dbus.ByteArray("14"),
  860. dbus.ByteArray("15"), dbus.ByteArray("16"),
  861. dbus.ByteArray("17") ]},
  862. "InvalidArgs"),
  863. ({'Type': 'active',
  864. 'SSIDs': [ dbus.ByteArray("1234567890abcdef1234567890abcdef1") ]},
  865. "InvalidArgs"),
  866. ({'Type': 'active', 'IEs': 'foo'}, "InvalidArgs"),
  867. ({'Type': 'active', 'IEs': ['foo']}, "InvalidArgs"),
  868. ({'Type': 'active', 'Channels': 2412 }, "InvalidArgs"),
  869. ({'Type': 'active', 'Channels': [ 2412 ] }, "InvalidArgs"),
  870. ({'Type': 'active',
  871. 'Channels': [ (dbus.Int32(2412), dbus.UInt32(20)) ] },
  872. "InvalidArgs"),
  873. ({'Type': 'active',
  874. 'Channels': [ (dbus.UInt32(2412), dbus.Int32(20)) ] },
  875. "InvalidArgs"),
  876. ({'Type': 'active', 'AllowRoam': "yes" }, "InvalidArgs"),
  877. ({'Type': 'passive', 'IEs': [ dbus.ByteArray("\xdd\x00") ]},
  878. "InvalidArgs"),
  879. ({'Type': 'passive', 'SSIDs': [ dbus.ByteArray("foo") ]},
  880. "InvalidArgs")]
  881. for (t,err) in tests:
  882. try:
  883. iface.Scan(t)
  884. raise Exception("Invalid Scan() arguments accepted: " + str(t))
  885. except dbus.exceptions.DBusException, e:
  886. if err not in str(e):
  887. raise Exception("Unexpected error message for invalid Scan(%s): %s" % (str(t), str(e)))
  888. def test_dbus_scan_oom(dev, apdev):
  889. """D-Bus scan method and OOM"""
  890. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  891. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  892. with alloc_fail_dbus(dev[0], 1,
  893. "wpa_scan_clone_params;wpas_dbus_handler_scan",
  894. "Scan", expected="ScanError: Scan request rejected"):
  895. iface.Scan({ 'Type': 'passive',
  896. 'Channels': [ (dbus.UInt32(2412), dbus.UInt32(20)) ] })
  897. with alloc_fail_dbus(dev[0], 1,
  898. "=wpas_dbus_get_scan_channels;wpas_dbus_handler_scan",
  899. "Scan"):
  900. iface.Scan({ 'Type': 'passive',
  901. 'Channels': [ (dbus.UInt32(2412), dbus.UInt32(20)) ] })
  902. with alloc_fail_dbus(dev[0], 1,
  903. "=wpas_dbus_get_scan_ies;wpas_dbus_handler_scan",
  904. "Scan"):
  905. iface.Scan({ 'Type': 'active',
  906. 'IEs': [ dbus.ByteArray("\xdd\x00") ],
  907. 'Channels': [ (dbus.UInt32(2412), dbus.UInt32(20)) ] })
  908. with alloc_fail_dbus(dev[0], 1,
  909. "=wpas_dbus_get_scan_ssids;wpas_dbus_handler_scan",
  910. "Scan"):
  911. iface.Scan({ 'Type': 'active',
  912. 'SSIDs': [ dbus.ByteArray("open"),
  913. dbus.ByteArray() ],
  914. 'Channels': [ (dbus.UInt32(2412), dbus.UInt32(20)) ] })
  915. def test_dbus_scan(dev, apdev):
  916. """D-Bus scan and related signals"""
  917. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  918. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  919. hapd = hostapd.add_ap(apdev[0], { "ssid": "open" })
  920. class TestDbusScan(TestDbus):
  921. def __init__(self, bus):
  922. TestDbus.__init__(self, bus)
  923. self.scan_completed = 0
  924. self.bss_added = False
  925. self.fail_reason = None
  926. def __enter__(self):
  927. gobject.timeout_add(1, self.run_scan)
  928. gobject.timeout_add(15000, self.timeout)
  929. self.add_signal(self.scanDone, WPAS_DBUS_IFACE, "ScanDone")
  930. self.add_signal(self.bssAdded, WPAS_DBUS_IFACE, "BSSAdded")
  931. self.add_signal(self.bssRemoved, WPAS_DBUS_IFACE, "BSSRemoved")
  932. self.loop.run()
  933. return self
  934. def scanDone(self, success):
  935. logger.debug("scanDone: success=%s" % success)
  936. self.scan_completed += 1
  937. if self.scan_completed == 1:
  938. iface.Scan({'Type': 'passive',
  939. 'AllowRoam': True,
  940. 'Channels': [(dbus.UInt32(2412), dbus.UInt32(20))]})
  941. elif self.scan_completed == 2:
  942. iface.Scan({'Type': 'passive',
  943. 'AllowRoam': False})
  944. elif self.bss_added and self.scan_completed == 3:
  945. self.loop.quit()
  946. def bssAdded(self, bss, properties):
  947. logger.debug("bssAdded: %s" % bss)
  948. logger.debug(str(properties))
  949. if 'WPS' in properties:
  950. if 'Type' in properties['WPS']:
  951. self.fail_reason = "Unexpected WPS dictionary entry in non-WPS BSS"
  952. self.loop.quit()
  953. self.bss_added = True
  954. if self.scan_completed == 3:
  955. self.loop.quit()
  956. def bssRemoved(self, bss):
  957. logger.debug("bssRemoved: %s" % bss)
  958. def run_scan(self, *args):
  959. logger.debug("run_scan")
  960. iface.Scan({'Type': 'active',
  961. 'SSIDs': [ dbus.ByteArray("open"),
  962. dbus.ByteArray() ],
  963. 'IEs': [ dbus.ByteArray("\xdd\x00"),
  964. dbus.ByteArray() ],
  965. 'AllowRoam': False,
  966. 'Channels': [(dbus.UInt32(2412), dbus.UInt32(20))]})
  967. return False
  968. def success(self):
  969. return self.scan_completed == 3 and self.bss_added
  970. with TestDbusScan(bus) as t:
  971. if t.fail_reason:
  972. raise Exception(t.fail_reason)
  973. if not t.success():
  974. raise Exception("Expected signals not seen")
  975. res = if_obj.Get(WPAS_DBUS_IFACE, "BSSs",
  976. dbus_interface=dbus.PROPERTIES_IFACE)
  977. if len(res) < 1:
  978. raise Exception("Scan result not in BSSs property")
  979. iface.FlushBSS(0)
  980. res = if_obj.Get(WPAS_DBUS_IFACE, "BSSs",
  981. dbus_interface=dbus.PROPERTIES_IFACE)
  982. if len(res) != 0:
  983. raise Exception("FlushBSS() did not remove scan results from BSSs property")
  984. iface.FlushBSS(1)
  985. def test_dbus_scan_busy(dev, apdev):
  986. """D-Bus scan trigger rejection when busy with previous scan"""
  987. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  988. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  989. if "OK" not in dev[0].request("SCAN freq=2412-2462"):
  990. raise Exception("Failed to start scan")
  991. ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], 15)
  992. if ev is None:
  993. raise Exception("Scan start timed out")
  994. try:
  995. iface.Scan({'Type': 'active', 'AllowRoam': False})
  996. raise Exception("Scan() accepted when busy")
  997. except dbus.exceptions.DBusException, e:
  998. if "ScanError: Scan request reject" not in str(e):
  999. raise Exception("Unexpected error message: " + str(e))
  1000. ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  1001. if ev is None:
  1002. raise Exception("Scan timed out")
  1003. def test_dbus_scan_abort(dev, apdev):
  1004. """D-Bus scan trigger and abort"""
  1005. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1006. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1007. iface.Scan({'Type': 'active', 'AllowRoam': False})
  1008. ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], 15)
  1009. if ev is None:
  1010. raise Exception("Scan start timed out")
  1011. iface.AbortScan()
  1012. ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  1013. if ev is None:
  1014. raise Exception("Scan abort result timed out")
  1015. dev[0].dump_monitor()
  1016. iface.Scan({'Type': 'active', 'AllowRoam': False})
  1017. iface.AbortScan()
  1018. ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
  1019. if ev is None:
  1020. raise Exception("Scan timed out")
  1021. def test_dbus_connect(dev, apdev):
  1022. """D-Bus AddNetwork and connect"""
  1023. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1024. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1025. ssid = "test-wpa2-psk"
  1026. passphrase = 'qwertyuiop'
  1027. params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
  1028. hapd = hostapd.add_ap(apdev[0], params)
  1029. class TestDbusConnect(TestDbus):
  1030. def __init__(self, bus):
  1031. TestDbus.__init__(self, bus)
  1032. self.network_added = False
  1033. self.network_selected = False
  1034. self.network_removed = False
  1035. self.state = 0
  1036. def __enter__(self):
  1037. gobject.timeout_add(1, self.run_connect)
  1038. gobject.timeout_add(15000, self.timeout)
  1039. self.add_signal(self.networkAdded, WPAS_DBUS_IFACE, "NetworkAdded")
  1040. self.add_signal(self.networkRemoved, WPAS_DBUS_IFACE,
  1041. "NetworkRemoved")
  1042. self.add_signal(self.networkSelected, WPAS_DBUS_IFACE,
  1043. "NetworkSelected")
  1044. self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
  1045. "PropertiesChanged")
  1046. self.loop.run()
  1047. return self
  1048. def networkAdded(self, network, properties):
  1049. logger.debug("networkAdded: %s" % str(network))
  1050. logger.debug(str(properties))
  1051. self.network_added = True
  1052. def networkRemoved(self, network):
  1053. logger.debug("networkRemoved: %s" % str(network))
  1054. self.network_removed = True
  1055. def networkSelected(self, network):
  1056. logger.debug("networkSelected: %s" % str(network))
  1057. self.network_selected = True
  1058. def propertiesChanged(self, properties):
  1059. logger.debug("propertiesChanged: %s" % str(properties))
  1060. if 'State' in properties and properties['State'] == "completed":
  1061. if self.state == 0:
  1062. self.state = 1
  1063. iface.Disconnect()
  1064. elif self.state == 2:
  1065. self.state = 3
  1066. iface.Disconnect()
  1067. elif self.state == 4:
  1068. self.state = 5
  1069. iface.Reattach()
  1070. elif self.state == 5:
  1071. self.state = 6
  1072. iface.Disconnect()
  1073. elif self.state == 7:
  1074. self.state = 8
  1075. res = iface.SignalPoll()
  1076. logger.debug("SignalPoll: " + str(res))
  1077. if 'frequency' not in res or res['frequency'] != 2412:
  1078. self.state = -1
  1079. logger.info("Unexpected SignalPoll result")
  1080. iface.RemoveNetwork(self.netw)
  1081. if 'State' in properties and properties['State'] == "disconnected":
  1082. if self.state == 1:
  1083. self.state = 2
  1084. iface.SelectNetwork(self.netw)
  1085. elif self.state == 3:
  1086. self.state = 4
  1087. iface.Reassociate()
  1088. elif self.state == 6:
  1089. self.state = 7
  1090. iface.Reconnect()
  1091. elif self.state == 8:
  1092. self.state = 9
  1093. self.loop.quit()
  1094. def run_connect(self, *args):
  1095. logger.debug("run_connect")
  1096. args = dbus.Dictionary({ 'ssid': ssid,
  1097. 'key_mgmt': 'WPA-PSK',
  1098. 'psk': passphrase,
  1099. 'scan_freq': 2412 },
  1100. signature='sv')
  1101. self.netw = iface.AddNetwork(args)
  1102. iface.SelectNetwork(self.netw)
  1103. return False
  1104. def success(self):
  1105. if not self.network_added or \
  1106. not self.network_removed or \
  1107. not self.network_selected:
  1108. return False
  1109. return self.state == 9
  1110. with TestDbusConnect(bus) as t:
  1111. if not t.success():
  1112. raise Exception("Expected signals not seen")
  1113. def test_dbus_connect_psk_mem(dev, apdev):
  1114. """D-Bus AddNetwork and connect with memory-only PSK"""
  1115. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1116. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1117. ssid = "test-wpa2-psk"
  1118. passphrase = 'qwertyuiop'
  1119. params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
  1120. hapd = hostapd.add_ap(apdev[0], params)
  1121. class TestDbusConnect(TestDbus):
  1122. def __init__(self, bus):
  1123. TestDbus.__init__(self, bus)
  1124. self.connected = False
  1125. def __enter__(self):
  1126. gobject.timeout_add(1, self.run_connect)
  1127. gobject.timeout_add(15000, self.timeout)
  1128. self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
  1129. "PropertiesChanged")
  1130. self.add_signal(self.networkRequest, WPAS_DBUS_IFACE,
  1131. "NetworkRequest")
  1132. self.loop.run()
  1133. return self
  1134. def propertiesChanged(self, properties):
  1135. logger.debug("propertiesChanged: %s" % str(properties))
  1136. if 'State' in properties and properties['State'] == "completed":
  1137. self.connected = True
  1138. self.loop.quit()
  1139. def networkRequest(self, path, field, txt):
  1140. logger.debug("networkRequest: %s %s %s" % (path, field, txt))
  1141. if field == "PSK_PASSPHRASE":
  1142. iface.NetworkReply(path, field, '"' + passphrase + '"')
  1143. def run_connect(self, *args):
  1144. logger.debug("run_connect")
  1145. args = dbus.Dictionary({ 'ssid': ssid,
  1146. 'key_mgmt': 'WPA-PSK',
  1147. 'mem_only_psk': 1,
  1148. 'scan_freq': 2412 },
  1149. signature='sv')
  1150. self.netw = iface.AddNetwork(args)
  1151. iface.SelectNetwork(self.netw)
  1152. return False
  1153. def success(self):
  1154. return self.connected
  1155. with TestDbusConnect(bus) as t:
  1156. if not t.success():
  1157. raise Exception("Expected signals not seen")
  1158. def test_dbus_connect_oom(dev, apdev):
  1159. """D-Bus AddNetwork and connect when out-of-memory"""
  1160. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1161. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1162. if "OK" not in dev[0].request("TEST_ALLOC_FAIL 0:"):
  1163. raise HwsimSkip("TEST_ALLOC_FAIL not supported in the build")
  1164. ssid = "test-wpa2-psk"
  1165. passphrase = 'qwertyuiop'
  1166. params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
  1167. hapd = hostapd.add_ap(apdev[0], params)
  1168. class TestDbusConnect(TestDbus):
  1169. def __init__(self, bus):
  1170. TestDbus.__init__(self, bus)
  1171. self.network_added = False
  1172. self.network_selected = False
  1173. self.network_removed = False
  1174. self.state = 0
  1175. def __enter__(self):
  1176. gobject.timeout_add(1, self.run_connect)
  1177. gobject.timeout_add(1500, self.timeout)
  1178. self.add_signal(self.networkAdded, WPAS_DBUS_IFACE, "NetworkAdded")
  1179. self.add_signal(self.networkRemoved, WPAS_DBUS_IFACE,
  1180. "NetworkRemoved")
  1181. self.add_signal(self.networkSelected, WPAS_DBUS_IFACE,
  1182. "NetworkSelected")
  1183. self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
  1184. "PropertiesChanged")
  1185. self.loop.run()
  1186. return self
  1187. def networkAdded(self, network, properties):
  1188. logger.debug("networkAdded: %s" % str(network))
  1189. logger.debug(str(properties))
  1190. self.network_added = True
  1191. def networkRemoved(self, network):
  1192. logger.debug("networkRemoved: %s" % str(network))
  1193. self.network_removed = True
  1194. def networkSelected(self, network):
  1195. logger.debug("networkSelected: %s" % str(network))
  1196. self.network_selected = True
  1197. def propertiesChanged(self, properties):
  1198. logger.debug("propertiesChanged: %s" % str(properties))
  1199. if 'State' in properties and properties['State'] == "completed":
  1200. if self.state == 0:
  1201. self.state = 1
  1202. iface.Disconnect()
  1203. elif self.state == 2:
  1204. self.state = 3
  1205. iface.Disconnect()
  1206. elif self.state == 4:
  1207. self.state = 5
  1208. iface.Reattach()
  1209. elif self.state == 5:
  1210. self.state = 6
  1211. res = iface.SignalPoll()
  1212. logger.debug("SignalPoll: " + str(res))
  1213. if 'frequency' not in res or res['frequency'] != 2412:
  1214. self.state = -1
  1215. logger.info("Unexpected SignalPoll result")
  1216. iface.RemoveNetwork(self.netw)
  1217. if 'State' in properties and properties['State'] == "disconnected":
  1218. if self.state == 1:
  1219. self.state = 2
  1220. iface.SelectNetwork(self.netw)
  1221. elif self.state == 3:
  1222. self.state = 4
  1223. iface.Reassociate()
  1224. elif self.state == 6:
  1225. self.state = 7
  1226. self.loop.quit()
  1227. def run_connect(self, *args):
  1228. logger.debug("run_connect")
  1229. args = dbus.Dictionary({ 'ssid': ssid,
  1230. 'key_mgmt': 'WPA-PSK',
  1231. 'psk': passphrase,
  1232. 'scan_freq': 2412 },
  1233. signature='sv')
  1234. try:
  1235. self.netw = iface.AddNetwork(args)
  1236. except Exception, e:
  1237. logger.info("Exception on AddNetwork: " + str(e))
  1238. self.loop.quit()
  1239. return False
  1240. try:
  1241. iface.SelectNetwork(self.netw)
  1242. except Exception, e:
  1243. logger.info("Exception on SelectNetwork: " + str(e))
  1244. self.loop.quit()
  1245. return False
  1246. def success(self):
  1247. if not self.network_added or \
  1248. not self.network_removed or \
  1249. not self.network_selected:
  1250. return False
  1251. return self.state == 7
  1252. count = 0
  1253. for i in range(1, 1000):
  1254. for j in range(3):
  1255. dev[j].dump_monitor()
  1256. dev[0].request("TEST_ALLOC_FAIL %d:main" % i)
  1257. try:
  1258. with TestDbusConnect(bus) as t:
  1259. if not t.success():
  1260. logger.info("Iteration %d - Expected signals not seen" % i)
  1261. else:
  1262. logger.info("Iteration %d - success" % i)
  1263. state = dev[0].request('GET_ALLOC_FAIL')
  1264. logger.info("GET_ALLOC_FAIL: " + state)
  1265. dev[0].dump_monitor()
  1266. dev[0].request("TEST_ALLOC_FAIL 0:")
  1267. if i < 3:
  1268. raise Exception("Connection succeeded during out-of-memory")
  1269. if not state.startswith('0:'):
  1270. count += 1
  1271. if count == 5:
  1272. break
  1273. except:
  1274. pass
  1275. # Force regulatory update to re-fetch hw capabilities for the following
  1276. # test cases.
  1277. try:
  1278. dev[0].dump_monitor()
  1279. subprocess.call(['iw', 'reg', 'set', 'US'])
  1280. ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
  1281. finally:
  1282. dev[0].dump_monitor()
  1283. subprocess.call(['iw', 'reg', 'set', '00'])
  1284. ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
  1285. def test_dbus_while_not_connected(dev, apdev):
  1286. """D-Bus invalid operations while not connected"""
  1287. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1288. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1289. try:
  1290. iface.Disconnect()
  1291. raise Exception("Disconnect() accepted when not connected")
  1292. except dbus.exceptions.DBusException, e:
  1293. if "NotConnected" not in str(e):
  1294. raise Exception("Unexpected error message for invalid Disconnect: " + str(e))
  1295. try:
  1296. iface.Reattach()
  1297. raise Exception("Reattach() accepted when not connected")
  1298. except dbus.exceptions.DBusException, e:
  1299. if "NotConnected" not in str(e):
  1300. raise Exception("Unexpected error message for invalid Reattach: " + str(e))
  1301. def test_dbus_connect_eap(dev, apdev):
  1302. """D-Bus AddNetwork and connect to EAP network"""
  1303. check_altsubject_match_support(dev[0])
  1304. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1305. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1306. ssid = "ieee8021x-open"
  1307. params = hostapd.radius_params()
  1308. params["ssid"] = ssid
  1309. params["ieee8021x"] = "1"
  1310. hapd = hostapd.add_ap(apdev[0], params)
  1311. class TestDbusConnect(TestDbus):
  1312. def __init__(self, bus):
  1313. TestDbus.__init__(self, bus)
  1314. self.certification_received = False
  1315. self.eap_status = False
  1316. self.state = 0
  1317. def __enter__(self):
  1318. gobject.timeout_add(1, self.run_connect)
  1319. gobject.timeout_add(15000, self.timeout)
  1320. self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
  1321. "PropertiesChanged")
  1322. self.add_signal(self.certification, WPAS_DBUS_IFACE,
  1323. "Certification", byte_arrays=True)
  1324. self.add_signal(self.networkRequest, WPAS_DBUS_IFACE,
  1325. "NetworkRequest")
  1326. self.add_signal(self.eap, WPAS_DBUS_IFACE, "EAP")
  1327. self.loop.run()
  1328. return self
  1329. def propertiesChanged(self, properties):
  1330. logger.debug("propertiesChanged: %s" % str(properties))
  1331. if 'State' in properties and properties['State'] == "completed":
  1332. if self.state == 0:
  1333. self.state = 1
  1334. iface.EAPLogoff()
  1335. logger.info("Set dNSName constraint")
  1336. net_obj = bus.get_object(WPAS_DBUS_SERVICE, self.netw)
  1337. args = dbus.Dictionary({ 'altsubject_match':
  1338. self.server_dnsname },
  1339. signature='sv')
  1340. net_obj.Set(WPAS_DBUS_NETWORK, "Properties", args,
  1341. dbus_interface=dbus.PROPERTIES_IFACE)
  1342. elif self.state == 2:
  1343. self.state = 3
  1344. iface.Disconnect()
  1345. logger.info("Set non-matching dNSName constraint")
  1346. net_obj = bus.get_object(WPAS_DBUS_SERVICE, self.netw)
  1347. args = dbus.Dictionary({ 'altsubject_match':
  1348. self.server_dnsname + "FOO" },
  1349. signature='sv')
  1350. net_obj.Set(WPAS_DBUS_NETWORK, "Properties", args,
  1351. dbus_interface=dbus.PROPERTIES_IFACE)
  1352. if 'State' in properties and properties['State'] == "disconnected":
  1353. if self.state == 1:
  1354. self.state = 2
  1355. iface.EAPLogon()
  1356. iface.SelectNetwork(self.netw)
  1357. if self.state == 3:
  1358. self.state = 4
  1359. iface.SelectNetwork(self.netw)
  1360. def certification(self, args):
  1361. logger.debug("certification: %s" % str(args))
  1362. self.certification_received = True
  1363. if args['depth'] == 0:
  1364. # The test server certificate is supposed to have dNSName
  1365. if len(args['altsubject']) < 1:
  1366. raise Exception("Missing dNSName")
  1367. dnsname = args['altsubject'][0]
  1368. if not dnsname.startswith("DNS:"):
  1369. raise Exception("Expected dNSName not found: " + dnsname)
  1370. logger.info("altsubject: " + dnsname)
  1371. self.server_dnsname = dnsname
  1372. def eap(self, status, parameter):
  1373. logger.debug("EAP: status=%s parameter=%s" % (status, parameter))
  1374. if status == 'completion' and parameter == 'success':
  1375. self.eap_status = True
  1376. if self.state == 4 and status == 'remote certificate verification' and parameter == 'AltSubject mismatch':
  1377. self.state = 5
  1378. self.loop.quit()
  1379. def networkRequest(self, path, field, txt):
  1380. logger.debug("networkRequest: %s %s %s" % (path, field, txt))
  1381. if field == "PASSWORD":
  1382. iface.NetworkReply(path, field, "password")
  1383. def run_connect(self, *args):
  1384. logger.debug("run_connect")
  1385. args = dbus.Dictionary({ 'ssid': ssid,
  1386. 'key_mgmt': 'IEEE8021X',
  1387. 'eapol_flags': 0,
  1388. 'eap': 'TTLS',
  1389. 'anonymous_identity': 'ttls',
  1390. 'identity': 'pap user',
  1391. 'ca_cert': 'auth_serv/ca.pem',
  1392. 'phase2': 'auth=PAP',
  1393. 'scan_freq': 2412 },
  1394. signature='sv')
  1395. self.netw = iface.AddNetwork(args)
  1396. iface.SelectNetwork(self.netw)
  1397. return False
  1398. def success(self):
  1399. if not self.eap_status or not self.certification_received:
  1400. return False
  1401. return self.state == 5
  1402. with TestDbusConnect(bus) as t:
  1403. if not t.success():
  1404. raise Exception("Expected signals not seen")
  1405. def test_dbus_network(dev, apdev):
  1406. """D-Bus AddNetwork/RemoveNetwork parameters and error cases"""
  1407. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1408. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1409. args = dbus.Dictionary({ 'ssid': "foo",
  1410. 'key_mgmt': 'WPA-PSK',
  1411. 'psk': "12345678",
  1412. 'identity': dbus.ByteArray([ 1, 2 ]),
  1413. 'priority': dbus.Int32(0),
  1414. 'scan_freq': dbus.UInt32(2412) },
  1415. signature='sv')
  1416. netw = iface.AddNetwork(args)
  1417. id = int(dev[0].list_networks()[0]['id'])
  1418. val = dev[0].get_network(id, "scan_freq")
  1419. if val != "2412":
  1420. raise Exception("Invalid scan_freq value: " + str(val))
  1421. iface.RemoveNetwork(netw)
  1422. args = dbus.Dictionary({ 'ssid': "foo",
  1423. 'key_mgmt': 'NONE',
  1424. 'scan_freq': "2412 2432",
  1425. 'freq_list': "2412 2417 2432" },
  1426. signature='sv')
  1427. netw = iface.AddNetwork(args)
  1428. id = int(dev[0].list_networks()[0]['id'])
  1429. val = dev[0].get_network(id, "scan_freq")
  1430. if val != "2412 2432":
  1431. raise Exception("Invalid scan_freq value (2): " + str(val))
  1432. val = dev[0].get_network(id, "freq_list")
  1433. if val != "2412 2417 2432":
  1434. raise Exception("Invalid freq_list value: " + str(val))
  1435. iface.RemoveNetwork(netw)
  1436. try:
  1437. iface.RemoveNetwork(netw)
  1438. raise Exception("Invalid RemoveNetwork() accepted")
  1439. except dbus.exceptions.DBusException, e:
  1440. if "NetworkUnknown" not in str(e):
  1441. raise Exception("Unexpected error message for invalid RemoveNetwork: " + str(e))
  1442. try:
  1443. iface.SelectNetwork(netw)
  1444. raise Exception("Invalid SelectNetwork() accepted")
  1445. except dbus.exceptions.DBusException, e:
  1446. if "NetworkUnknown" not in str(e):
  1447. raise Exception("Unexpected error message for invalid RemoveNetwork: " + str(e))
  1448. args = dbus.Dictionary({ 'ssid': "foo1", 'key_mgmt': 'NONE',
  1449. 'identity': "testuser", 'scan_freq': '2412' },
  1450. signature='sv')
  1451. netw1 = iface.AddNetwork(args)
  1452. args = dbus.Dictionary({ 'ssid': "foo2", 'key_mgmt': 'NONE' },
  1453. signature='sv')
  1454. netw2 = iface.AddNetwork(args)
  1455. res = if_obj.Get(WPAS_DBUS_IFACE, "Networks",
  1456. dbus_interface=dbus.PROPERTIES_IFACE)
  1457. if len(res) != 2:
  1458. raise Exception("Unexpected number of networks")
  1459. net_obj = bus.get_object(WPAS_DBUS_SERVICE, netw1)
  1460. res = net_obj.Get(WPAS_DBUS_NETWORK, "Enabled",
  1461. dbus_interface=dbus.PROPERTIES_IFACE)
  1462. if res != False:
  1463. raise Exception("Added network was unexpectedly enabled by default")
  1464. net_obj.Set(WPAS_DBUS_NETWORK, "Enabled", dbus.Boolean(True),
  1465. dbus_interface=dbus.PROPERTIES_IFACE)
  1466. res = net_obj.Get(WPAS_DBUS_NETWORK, "Enabled",
  1467. dbus_interface=dbus.PROPERTIES_IFACE)
  1468. if res != True:
  1469. raise Exception("Set(Enabled,True) did not seem to change property value")
  1470. net_obj.Set(WPAS_DBUS_NETWORK, "Enabled", dbus.Boolean(False),
  1471. dbus_interface=dbus.PROPERTIES_IFACE)
  1472. res = net_obj.Get(WPAS_DBUS_NETWORK, "Enabled",
  1473. dbus_interface=dbus.PROPERTIES_IFACE)
  1474. if res != False:
  1475. raise Exception("Set(Enabled,False) did not seem to change property value")
  1476. try:
  1477. net_obj.Set(WPAS_DBUS_NETWORK, "Enabled", dbus.UInt32(1),
  1478. dbus_interface=dbus.PROPERTIES_IFACE)
  1479. raise Exception("Invalid Set(Enabled,1) accepted")
  1480. except dbus.exceptions.DBusException, e:
  1481. if "Error.Failed: wrong property type" not in str(e):
  1482. raise Exception("Unexpected error message for invalid Set(Enabled,1): " + str(e))
  1483. args = dbus.Dictionary({ 'ssid': "foo1new" }, signature='sv')
  1484. net_obj.Set(WPAS_DBUS_NETWORK, "Properties", args,
  1485. dbus_interface=dbus.PROPERTIES_IFACE)
  1486. res = net_obj.Get(WPAS_DBUS_NETWORK, "Properties",
  1487. dbus_interface=dbus.PROPERTIES_IFACE)
  1488. if res['ssid'] != '"foo1new"':
  1489. raise Exception("Set(Properties) failed to update ssid")
  1490. if res['identity'] != '"testuser"':
  1491. raise Exception("Set(Properties) unexpectedly changed unrelated parameter")
  1492. iface.RemoveAllNetworks()
  1493. res = if_obj.Get(WPAS_DBUS_IFACE, "Networks",
  1494. dbus_interface=dbus.PROPERTIES_IFACE)
  1495. if len(res) != 0:
  1496. raise Exception("Unexpected number of networks")
  1497. iface.RemoveAllNetworks()
  1498. tests = [ dbus.Dictionary({ 'psk': "1234567" }, signature='sv'),
  1499. dbus.Dictionary({ 'identity': dbus.ByteArray() },
  1500. signature='sv'),
  1501. dbus.Dictionary({ 'identity': dbus.Byte(1) }, signature='sv'),
  1502. dbus.Dictionary({ 'identity': "" }, signature='sv') ]
  1503. for args in tests:
  1504. try:
  1505. iface.AddNetwork(args)
  1506. raise Exception("Invalid AddNetwork args accepted: " + str(args))
  1507. except dbus.exceptions.DBusException, e:
  1508. if "InvalidArgs" not in str(e):
  1509. raise Exception("Unexpected error message for invalid AddNetwork: " + str(e))
  1510. def test_dbus_network_oom(dev, apdev):
  1511. """D-Bus AddNetwork/RemoveNetwork parameters and OOM error cases"""
  1512. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1513. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1514. args = dbus.Dictionary({ 'ssid': "foo1", 'key_mgmt': 'NONE',
  1515. 'identity': "testuser", 'scan_freq': '2412' },
  1516. signature='sv')
  1517. netw1 = iface.AddNetwork(args)
  1518. net_obj = bus.get_object(WPAS_DBUS_SERVICE, netw1)
  1519. with alloc_fail_dbus(dev[0], 1,
  1520. "wpa_config_get_all;wpas_dbus_getter_network_properties",
  1521. "Get"):
  1522. net_obj.Get(WPAS_DBUS_NETWORK, "Properties",
  1523. dbus_interface=dbus.PROPERTIES_IFACE)
  1524. iface.RemoveAllNetworks()
  1525. with alloc_fail_dbus(dev[0], 1,
  1526. "wpas_dbus_new_decompose_object_path;wpas_dbus_handler_remove_network",
  1527. "RemoveNetwork", "InvalidArgs"):
  1528. iface.RemoveNetwork(dbus.ObjectPath("/fi/w1/wpa_supplicant1/Interfaces/1234/Networks/1234"))
  1529. with alloc_fail(dev[0], 1, "wpa_dbus_register_object_per_iface;wpas_dbus_register_network"):
  1530. args = dbus.Dictionary({ 'ssid': "foo2", 'key_mgmt': 'NONE' },
  1531. signature='sv')
  1532. try:
  1533. netw = iface.AddNetwork(args)
  1534. # Currently, AddNetwork() succeeds even if os_strdup() for path
  1535. # fails, so remove the network if that occurs.
  1536. iface.RemoveNetwork(netw)
  1537. except dbus.exceptions.DBusException, e:
  1538. pass
  1539. for i in range(1, 3):
  1540. with alloc_fail(dev[0], i, "=wpas_dbus_register_network"):
  1541. try:
  1542. netw = iface.AddNetwork(args)
  1543. # Currently, AddNetwork() succeeds even if network registration
  1544. # fails, so remove the network if that occurs.
  1545. iface.RemoveNetwork(netw)
  1546. except dbus.exceptions.DBusException, e:
  1547. pass
  1548. with alloc_fail_dbus(dev[0], 1,
  1549. "=wpa_config_add_network;wpas_dbus_handler_add_network",
  1550. "AddNetwork",
  1551. "UnknownError: wpa_supplicant could not add a network"):
  1552. args = dbus.Dictionary({ 'ssid': "foo2", 'key_mgmt': 'NONE' },
  1553. signature='sv')
  1554. netw = iface.AddNetwork(args)
  1555. tests = [ (1,
  1556. 'wpa_dbus_dict_get_entry;set_network_properties;wpas_dbus_handler_add_network',
  1557. dbus.Dictionary({ 'ssid': dbus.ByteArray(' ') },
  1558. signature='sv')),
  1559. (1, '=set_network_properties;wpas_dbus_handler_add_network',
  1560. dbus.Dictionary({ 'ssid': 'foo' }, signature='sv')),
  1561. (1, '=set_network_properties;wpas_dbus_handler_add_network',
  1562. dbus.Dictionary({ 'eap': 'foo' }, signature='sv')),
  1563. (1, '=set_network_properties;wpas_dbus_handler_add_network',
  1564. dbus.Dictionary({ 'priority': dbus.UInt32(1) },
  1565. signature='sv')),
  1566. (1, '=set_network_properties;wpas_dbus_handler_add_network',
  1567. dbus.Dictionary({ 'priority': dbus.Int32(1) },
  1568. signature='sv')),
  1569. (1, '=set_network_properties;wpas_dbus_handler_add_network',
  1570. dbus.Dictionary({ 'ssid': dbus.ByteArray(' ') },
  1571. signature='sv')) ]
  1572. for (count,funcs,args) in tests:
  1573. with alloc_fail_dbus(dev[0], count, funcs, "AddNetwork", "InvalidArgs"):
  1574. netw = iface.AddNetwork(args)
  1575. if len(if_obj.Get(WPAS_DBUS_IFACE, 'Networks',
  1576. dbus_interface=dbus.PROPERTIES_IFACE)) > 0:
  1577. raise Exception("Unexpected network block added")
  1578. if len(dev[0].list_networks()) > 0:
  1579. raise Exception("Unexpected network block visible")
  1580. def test_dbus_interface(dev, apdev):
  1581. """D-Bus CreateInterface/GetInterface/RemoveInterface parameters and error cases"""
  1582. try:
  1583. _test_dbus_interface(dev, apdev)
  1584. finally:
  1585. # Need to force P2P channel list update since the 'lo' interface
  1586. # with driver=none ends up configuring default dualband channels.
  1587. dev[0].request("SET country US")
  1588. ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
  1589. if ev is None:
  1590. ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"],
  1591. timeout=1)
  1592. dev[0].request("SET country 00")
  1593. ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
  1594. if ev is None:
  1595. ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"],
  1596. timeout=1)
  1597. subprocess.call(['iw', 'reg', 'set', '00'])
  1598. def _test_dbus_interface(dev, apdev):
  1599. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1600. wpas = dbus.Interface(wpas_obj, WPAS_DBUS_SERVICE)
  1601. params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none' },
  1602. signature='sv')
  1603. path = wpas.CreateInterface(params)
  1604. logger.debug("New interface path: " + str(path))
  1605. path2 = wpas.GetInterface("lo")
  1606. if path != path2:
  1607. raise Exception("Interface object mismatch")
  1608. params = dbus.Dictionary({ 'Ifname': 'lo',
  1609. 'Driver': 'none',
  1610. 'ConfigFile': 'foo',
  1611. 'BridgeIfname': 'foo', },
  1612. signature='sv')
  1613. try:
  1614. wpas.CreateInterface(params)
  1615. raise Exception("Invalid CreateInterface() accepted")
  1616. except dbus.exceptions.DBusException, e:
  1617. if "InterfaceExists" not in str(e):
  1618. raise Exception("Unexpected error message for invalid CreateInterface: " + str(e))
  1619. wpas.RemoveInterface(path)
  1620. try:
  1621. wpas.RemoveInterface(path)
  1622. raise Exception("Invalid RemoveInterface() accepted")
  1623. except dbus.exceptions.DBusException, e:
  1624. if "InterfaceUnknown" not in str(e):
  1625. raise Exception("Unexpected error message for invalid RemoveInterface: " + str(e))
  1626. params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none',
  1627. 'Foo': 123 },
  1628. signature='sv')
  1629. try:
  1630. wpas.CreateInterface(params)
  1631. raise Exception("Invalid CreateInterface() accepted")
  1632. except dbus.exceptions.DBusException, e:
  1633. if "InvalidArgs" not in str(e):
  1634. raise Exception("Unexpected error message for invalid CreateInterface: " + str(e))
  1635. params = dbus.Dictionary({ 'Driver': 'none' }, signature='sv')
  1636. try:
  1637. wpas.CreateInterface(params)
  1638. raise Exception("Invalid CreateInterface() accepted")
  1639. except dbus.exceptions.DBusException, e:
  1640. if "InvalidArgs" not in str(e):
  1641. raise Exception("Unexpected error message for invalid CreateInterface: " + str(e))
  1642. try:
  1643. wpas.GetInterface("lo")
  1644. raise Exception("Invalid GetInterface() accepted")
  1645. except dbus.exceptions.DBusException, e:
  1646. if "InterfaceUnknown" not in str(e):
  1647. raise Exception("Unexpected error message for invalid RemoveInterface: " + str(e))
  1648. def test_dbus_interface_oom(dev, apdev):
  1649. """D-Bus CreateInterface/GetInterface/RemoveInterface OOM error cases"""
  1650. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1651. wpas = dbus.Interface(wpas_obj, WPAS_DBUS_SERVICE)
  1652. with alloc_fail_dbus(dev[0], 1, "wpa_dbus_dict_get_entry;wpas_dbus_handler_create_interface", "CreateInterface", "InvalidArgs"):
  1653. params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none' },
  1654. signature='sv')
  1655. wpas.CreateInterface(params)
  1656. for i in range(1, 1000):
  1657. dev[0].request("TEST_ALLOC_FAIL %d:wpa_supplicant_add_iface;wpas_dbus_handler_create_interface" % i)
  1658. params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none' },
  1659. signature='sv')
  1660. try:
  1661. npath = wpas.CreateInterface(params)
  1662. wpas.RemoveInterface(npath)
  1663. logger.info("CreateInterface succeeds after %d allocation failures" % i)
  1664. state = dev[0].request('GET_ALLOC_FAIL')
  1665. logger.info("GET_ALLOC_FAIL: " + state)
  1666. dev[0].dump_monitor()
  1667. dev[0].request("TEST_ALLOC_FAIL 0:")
  1668. if i < 5:
  1669. raise Exception("CreateInterface succeeded during out-of-memory")
  1670. if not state.startswith('0:'):
  1671. break
  1672. except dbus.exceptions.DBusException, e:
  1673. pass
  1674. for arg in [ 'Driver', 'Ifname', 'ConfigFile', 'BridgeIfname' ]:
  1675. with alloc_fail_dbus(dev[0], 1, "=wpas_dbus_handler_create_interface",
  1676. "CreateInterface"):
  1677. params = dbus.Dictionary({ arg: 'foo' }, signature='sv')
  1678. wpas.CreateInterface(params)
  1679. def test_dbus_blob(dev, apdev):
  1680. """D-Bus AddNetwork/RemoveNetwork parameters and error cases"""
  1681. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1682. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1683. blob = dbus.ByteArray("\x01\x02\x03")
  1684. iface.AddBlob('blob1', blob)
  1685. try:
  1686. iface.AddBlob('blob1', dbus.ByteArray("\x01\x02\x04"))
  1687. raise Exception("Invalid AddBlob() accepted")
  1688. except dbus.exceptions.DBusException, e:
  1689. if "BlobExists" not in str(e):
  1690. raise Exception("Unexpected error message for invalid AddBlob: " + str(e))
  1691. res = iface.GetBlob('blob1')
  1692. if len(res) != len(blob):
  1693. raise Exception("Unexpected blob data length")
  1694. for i in range(len(res)):
  1695. if res[i] != dbus.Byte(blob[i]):
  1696. raise Exception("Unexpected blob data")
  1697. res = if_obj.Get(WPAS_DBUS_IFACE, "Blobs",
  1698. dbus_interface=dbus.PROPERTIES_IFACE)
  1699. if 'blob1' not in res:
  1700. raise Exception("Added blob missing from Blobs property")
  1701. iface.RemoveBlob('blob1')
  1702. try:
  1703. iface.RemoveBlob('blob1')
  1704. raise Exception("Invalid RemoveBlob() accepted")
  1705. except dbus.exceptions.DBusException, e:
  1706. if "BlobUnknown" not in str(e):
  1707. raise Exception("Unexpected error message for invalid RemoveBlob: " + str(e))
  1708. try:
  1709. iface.GetBlob('blob1')
  1710. raise Exception("Invalid GetBlob() accepted")
  1711. except dbus.exceptions.DBusException, e:
  1712. if "BlobUnknown" not in str(e):
  1713. raise Exception("Unexpected error message for invalid GetBlob: " + str(e))
  1714. class TestDbusBlob(TestDbus):
  1715. def __init__(self, bus):
  1716. TestDbus.__init__(self, bus)
  1717. self.blob_added = False
  1718. self.blob_removed = False
  1719. def __enter__(self):
  1720. gobject.timeout_add(1, self.run_blob)
  1721. gobject.timeout_add(15000, self.timeout)
  1722. self.add_signal(self.blobAdded, WPAS_DBUS_IFACE, "BlobAdded")
  1723. self.add_signal(self.blobRemoved, WPAS_DBUS_IFACE, "BlobRemoved")
  1724. self.loop.run()
  1725. return self
  1726. def blobAdded(self, blobName):
  1727. logger.debug("blobAdded: %s" % blobName)
  1728. if blobName == 'blob2':
  1729. self.blob_added = True
  1730. def blobRemoved(self, blobName):
  1731. logger.debug("blobRemoved: %s" % blobName)
  1732. if blobName == 'blob2':
  1733. self.blob_removed = True
  1734. self.loop.quit()
  1735. def run_blob(self, *args):
  1736. logger.debug("run_blob")
  1737. iface.AddBlob('blob2', dbus.ByteArray("\x01\x02\x04"))
  1738. iface.RemoveBlob('blob2')
  1739. return False
  1740. def success(self):
  1741. return self.blob_added and self.blob_removed
  1742. with TestDbusBlob(bus) as t:
  1743. if not t.success():
  1744. raise Exception("Expected signals not seen")
  1745. def test_dbus_blob_oom(dev, apdev):
  1746. """D-Bus AddNetwork/RemoveNetwork OOM error cases"""
  1747. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1748. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1749. for i in range(1, 4):
  1750. with alloc_fail_dbus(dev[0], i, "wpas_dbus_handler_add_blob",
  1751. "AddBlob"):
  1752. iface.AddBlob('blob_no_mem', dbus.ByteArray("\x01\x02\x03\x04"))
  1753. def test_dbus_autoscan(dev, apdev):
  1754. """D-Bus Autoscan()"""
  1755. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1756. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1757. iface.AutoScan("foo")
  1758. iface.AutoScan("periodic:1")
  1759. iface.AutoScan("")
  1760. dev[0].request("AUTOSCAN ")
  1761. def test_dbus_autoscan_oom(dev, apdev):
  1762. """D-Bus Autoscan() OOM"""
  1763. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1764. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1765. with alloc_fail_dbus(dev[0], 1, "wpas_dbus_handler_autoscan", "AutoScan"):
  1766. iface.AutoScan("foo")
  1767. dev[0].request("AUTOSCAN ")
  1768. def test_dbus_tdls_invalid(dev, apdev):
  1769. """D-Bus invalid TDLS operations"""
  1770. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1771. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1772. hapd = hostapd.add_ap(apdev[0], { "ssid": "test-open" })
  1773. connect_2sta_open(dev, hapd)
  1774. addr1 = dev[1].p2p_interface_addr()
  1775. try:
  1776. iface.TDLSDiscover("foo")
  1777. raise Exception("Invalid TDLSDiscover() accepted")
  1778. except dbus.exceptions.DBusException, e:
  1779. if "InvalidArgs" not in str(e):
  1780. raise Exception("Unexpected error message for invalid TDLSDiscover: " + str(e))
  1781. try:
  1782. iface.TDLSStatus("foo")
  1783. raise Exception("Invalid TDLSStatus() accepted")
  1784. except dbus.exceptions.DBusException, e:
  1785. if "InvalidArgs" not in str(e):
  1786. raise Exception("Unexpected error message for invalid TDLSStatus: " + str(e))
  1787. res = iface.TDLSStatus(addr1)
  1788. if res != "peer does not exist":
  1789. raise Exception("Unexpected TDLSStatus response")
  1790. try:
  1791. iface.TDLSSetup("foo")
  1792. raise Exception("Invalid TDLSSetup() accepted")
  1793. except dbus.exceptions.DBusException, e:
  1794. if "InvalidArgs" not in str(e):
  1795. raise Exception("Unexpected error message for invalid TDLSSetup: " + str(e))
  1796. try:
  1797. iface.TDLSTeardown("foo")
  1798. raise Exception("Invalid TDLSTeardown() accepted")
  1799. except dbus.exceptions.DBusException, e:
  1800. if "InvalidArgs" not in str(e):
  1801. raise Exception("Unexpected error message for invalid TDLSTeardown: " + str(e))
  1802. try:
  1803. iface.TDLSTeardown("00:11:22:33:44:55")
  1804. raise Exception("TDLSTeardown accepted for unknown peer")
  1805. except dbus.exceptions.DBusException, e:
  1806. if "UnknownError: error performing TDLS teardown" not in str(e):
  1807. raise Exception("Unexpected error message: " + str(e))
  1808. try:
  1809. iface.TDLSChannelSwitch({})
  1810. raise Exception("Invalid TDLSChannelSwitch() accepted")
  1811. except dbus.exceptions.DBusException, e:
  1812. if "InvalidArgs" not in str(e):
  1813. raise Exception("Unexpected error message for invalid TDLSChannelSwitch: " + str(e))
  1814. try:
  1815. iface.TDLSCancelChannelSwitch("foo")
  1816. raise Exception("Invalid TDLSCancelChannelSwitch() accepted")
  1817. except dbus.exceptions.DBusException, e:
  1818. if "InvalidArgs" not in str(e):
  1819. raise Exception("Unexpected error message for invalid TDLSCancelChannelSwitch: " + str(e))
  1820. def test_dbus_tdls_oom(dev, apdev):
  1821. """D-Bus TDLS operations during OOM"""
  1822. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1823. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1824. with alloc_fail_dbus(dev[0], 1, "wpa_tdls_add_peer", "TDLSSetup",
  1825. "UnknownError: error performing TDLS setup"):
  1826. iface.TDLSSetup("00:11:22:33:44:55")
  1827. def test_dbus_tdls(dev, apdev):
  1828. """D-Bus TDLS"""
  1829. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1830. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1831. hapd = hostapd.add_ap(apdev[0], { "ssid": "test-open" })
  1832. connect_2sta_open(dev, hapd)
  1833. addr1 = dev[1].p2p_interface_addr()
  1834. class TestDbusTdls(TestDbus):
  1835. def __init__(self, bus):
  1836. TestDbus.__init__(self, bus)
  1837. self.tdls_setup = False
  1838. self.tdls_teardown = False
  1839. def __enter__(self):
  1840. gobject.timeout_add(1, self.run_tdls)
  1841. gobject.timeout_add(15000, self.timeout)
  1842. self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
  1843. "PropertiesChanged")
  1844. self.loop.run()
  1845. return self
  1846. def propertiesChanged(self, properties):
  1847. logger.debug("propertiesChanged: %s" % str(properties))
  1848. def run_tdls(self, *args):
  1849. logger.debug("run_tdls")
  1850. iface.TDLSDiscover(addr1)
  1851. gobject.timeout_add(100, self.run_tdls2)
  1852. return False
  1853. def run_tdls2(self, *args):
  1854. logger.debug("run_tdls2")
  1855. iface.TDLSSetup(addr1)
  1856. gobject.timeout_add(500, self.run_tdls3)
  1857. return False
  1858. def run_tdls3(self, *args):
  1859. logger.debug("run_tdls3")
  1860. res = iface.TDLSStatus(addr1)
  1861. if res == "connected":
  1862. self.tdls_setup = True
  1863. else:
  1864. logger.info("Unexpected TDLSStatus: " + res)
  1865. iface.TDLSTeardown(addr1)
  1866. gobject.timeout_add(200, self.run_tdls4)
  1867. return False
  1868. def run_tdls4(self, *args):
  1869. logger.debug("run_tdls4")
  1870. res = iface.TDLSStatus(addr1)
  1871. if res == "peer does not exist":
  1872. self.tdls_teardown = True
  1873. else:
  1874. logger.info("Unexpected TDLSStatus: " + res)
  1875. self.loop.quit()
  1876. return False
  1877. def success(self):
  1878. return self.tdls_setup and self.tdls_teardown
  1879. with TestDbusTdls(bus) as t:
  1880. if not t.success():
  1881. raise Exception("Expected signals not seen")
  1882. def test_dbus_tdls_channel_switch(dev, apdev):
  1883. """D-Bus TDLS channel switch configuration"""
  1884. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1885. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1886. hapd = hostapd.add_ap(apdev[0], { "ssid": "test-open" })
  1887. connect_2sta_open(dev, hapd)
  1888. addr1 = dev[1].p2p_interface_addr()
  1889. class TestDbusTdls(TestDbus):
  1890. def __init__(self, bus):
  1891. TestDbus.__init__(self, bus)
  1892. self.tdls_setup = False
  1893. self.tdls_done = False
  1894. def __enter__(self):
  1895. gobject.timeout_add(1, self.run_tdls)
  1896. gobject.timeout_add(15000, self.timeout)
  1897. self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
  1898. "PropertiesChanged")
  1899. self.loop.run()
  1900. return self
  1901. def propertiesChanged(self, properties):
  1902. logger.debug("propertiesChanged: %s" % str(properties))
  1903. def run_tdls(self, *args):
  1904. logger.debug("run_tdls")
  1905. iface.TDLSDiscover(addr1)
  1906. gobject.timeout_add(100, self.run_tdls2)
  1907. return False
  1908. def run_tdls2(self, *args):
  1909. logger.debug("run_tdls2")
  1910. iface.TDLSSetup(addr1)
  1911. gobject.timeout_add(500, self.run_tdls3)
  1912. return False
  1913. def run_tdls3(self, *args):
  1914. logger.debug("run_tdls3")
  1915. res = iface.TDLSStatus(addr1)
  1916. if res == "connected":
  1917. self.tdls_setup = True
  1918. else:
  1919. logger.info("Unexpected TDLSStatus: " + res)
  1920. # Unknown dict entry
  1921. args = dbus.Dictionary({ 'Foobar': dbus.Byte(1) },
  1922. signature='sv')
  1923. try:
  1924. iface.TDLSChannelSwitch(args)
  1925. except Exception, e:
  1926. if "InvalidArgs" not in str(e):
  1927. raise Exception("Unexpected exception")
  1928. # Missing OperClass
  1929. args = dbus.Dictionary({}, signature='sv')
  1930. try:
  1931. iface.TDLSChannelSwitch(args)
  1932. except Exception, e:
  1933. if "InvalidArgs" not in str(e):
  1934. raise Exception("Unexpected exception")
  1935. # Missing Frequency
  1936. args = dbus.Dictionary({ 'OperClass': dbus.Byte(1) },
  1937. signature='sv')
  1938. try:
  1939. iface.TDLSChannelSwitch(args)
  1940. except Exception, e:
  1941. if "InvalidArgs" not in str(e):
  1942. raise Exception("Unexpected exception")
  1943. # Missing PeerAddress
  1944. args = dbus.Dictionary({ 'OperClass': dbus.Byte(1),
  1945. 'Frequency': dbus.UInt32(2417) },
  1946. signature='sv')
  1947. try:
  1948. iface.TDLSChannelSwitch(args)
  1949. except Exception, e:
  1950. if "InvalidArgs" not in str(e):
  1951. raise Exception("Unexpected exception")
  1952. # Valid parameters
  1953. args = dbus.Dictionary({ 'OperClass': dbus.Byte(1),
  1954. 'Frequency': dbus.UInt32(2417),
  1955. 'PeerAddress': addr1,
  1956. 'SecChannelOffset': dbus.UInt32(0),
  1957. 'CenterFrequency1': dbus.UInt32(0),
  1958. 'CenterFrequency2': dbus.UInt32(0),
  1959. 'Bandwidth': dbus.UInt32(20),
  1960. 'HT': dbus.Boolean(False),
  1961. 'VHT': dbus.Boolean(False) },
  1962. signature='sv')
  1963. iface.TDLSChannelSwitch(args)
  1964. gobject.timeout_add(200, self.run_tdls4)
  1965. return False
  1966. def run_tdls4(self, *args):
  1967. logger.debug("run_tdls4")
  1968. iface.TDLSCancelChannelSwitch(addr1)
  1969. self.tdls_done = True
  1970. self.loop.quit()
  1971. return False
  1972. def success(self):
  1973. return self.tdls_setup and self.tdls_done
  1974. with TestDbusTdls(bus) as t:
  1975. if not t.success():
  1976. raise Exception("Expected signals not seen")
  1977. def test_dbus_pkcs11(dev, apdev):
  1978. """D-Bus SetPKCS11EngineAndModulePath()"""
  1979. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1980. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1981. try:
  1982. iface.SetPKCS11EngineAndModulePath("foo", "bar")
  1983. except dbus.exceptions.DBusException, e:
  1984. if "Error.Failed: Reinit of the EAPOL" not in str(e):
  1985. raise Exception("Unexpected error message for invalid SetPKCS11EngineAndModulePath: " + str(e))
  1986. try:
  1987. iface.SetPKCS11EngineAndModulePath("foo", "")
  1988. except dbus.exceptions.DBusException, e:
  1989. if "Error.Failed: Reinit of the EAPOL" not in str(e):
  1990. raise Exception("Unexpected error message for invalid SetPKCS11EngineAndModulePath: " + str(e))
  1991. iface.SetPKCS11EngineAndModulePath("", "bar")
  1992. res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11EnginePath",
  1993. dbus_interface=dbus.PROPERTIES_IFACE)
  1994. if res != "":
  1995. raise Exception("Unexpected PKCS11EnginePath value: " + res)
  1996. res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11ModulePath",
  1997. dbus_interface=dbus.PROPERTIES_IFACE)
  1998. if res != "bar":
  1999. raise Exception("Unexpected PKCS11ModulePath value: " + res)
  2000. iface.SetPKCS11EngineAndModulePath("", "")
  2001. res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11EnginePath",
  2002. dbus_interface=dbus.PROPERTIES_IFACE)
  2003. if res != "":
  2004. raise Exception("Unexpected PKCS11EnginePath value: " + res)
  2005. res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11ModulePath",
  2006. dbus_interface=dbus.PROPERTIES_IFACE)
  2007. if res != "":
  2008. raise Exception("Unexpected PKCS11ModulePath value: " + res)
  2009. def test_dbus_apscan(dev, apdev):
  2010. """D-Bus Get/Set ApScan"""
  2011. try:
  2012. _test_dbus_apscan(dev, apdev)
  2013. finally:
  2014. dev[0].request("AP_SCAN 1")
  2015. def _test_dbus_apscan(dev, apdev):
  2016. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2017. res = if_obj.Get(WPAS_DBUS_IFACE, "ApScan",
  2018. dbus_interface=dbus.PROPERTIES_IFACE)
  2019. if res != 1:
  2020. raise Exception("Unexpected initial ApScan value: %d" % res)
  2021. for i in range(3):
  2022. if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.UInt32(i),
  2023. dbus_interface=dbus.PROPERTIES_IFACE)
  2024. res = if_obj.Get(WPAS_DBUS_IFACE, "ApScan",
  2025. dbus_interface=dbus.PROPERTIES_IFACE)
  2026. if res != i:
  2027. raise Exception("Unexpected ApScan value %d (expected %d)" % (res, i))
  2028. try:
  2029. if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.Int16(-1),
  2030. dbus_interface=dbus.PROPERTIES_IFACE)
  2031. raise Exception("Invalid Set(ApScan,-1) accepted")
  2032. except dbus.exceptions.DBusException, e:
  2033. if "Error.Failed: wrong property type" not in str(e):
  2034. raise Exception("Unexpected error message for invalid Set(ApScan,-1): " + str(e))
  2035. try:
  2036. if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.UInt32(123),
  2037. dbus_interface=dbus.PROPERTIES_IFACE)
  2038. raise Exception("Invalid Set(ApScan,123) accepted")
  2039. except dbus.exceptions.DBusException, e:
  2040. if "Error.Failed: ap_scan must be 0, 1, or 2" not in str(e):
  2041. raise Exception("Unexpected error message for invalid Set(ApScan,123): " + str(e))
  2042. if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.UInt32(1),
  2043. dbus_interface=dbus.PROPERTIES_IFACE)
  2044. def test_dbus_pmf(dev, apdev):
  2045. """D-Bus Get/Set Pmf"""
  2046. try:
  2047. _test_dbus_pmf(dev, apdev)
  2048. finally:
  2049. dev[0].request("SET pmf 0")
  2050. def _test_dbus_pmf(dev, apdev):
  2051. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2052. dev[0].set("pmf", "0")
  2053. res = if_obj.Get(WPAS_DBUS_IFACE, "Pmf",
  2054. dbus_interface=dbus.PROPERTIES_IFACE)
  2055. if res != 0:
  2056. raise Exception("Unexpected initial Pmf value: %d" % res)
  2057. for i in range(3):
  2058. if_obj.Set(WPAS_DBUS_IFACE, "Pmf", dbus.UInt32(i),
  2059. dbus_interface=dbus.PROPERTIES_IFACE)
  2060. res = if_obj.Get(WPAS_DBUS_IFACE, "Pmf",
  2061. dbus_interface=dbus.PROPERTIES_IFACE)
  2062. if res != i:
  2063. raise Exception("Unexpected Pmf value %d (expected %d)" % (res, i))
  2064. try:
  2065. if_obj.Set(WPAS_DBUS_IFACE, "Pmf", dbus.Int16(-1),
  2066. dbus_interface=dbus.PROPERTIES_IFACE)
  2067. raise Exception("Invalid Set(Pmf,-1) accepted")
  2068. except dbus.exceptions.DBusException, e:
  2069. if "Error.Failed: wrong property type" not in str(e):
  2070. raise Exception("Unexpected error message for invalid Set(Pmf,-1): " + str(e))
  2071. try:
  2072. if_obj.Set(WPAS_DBUS_IFACE, "Pmf", dbus.UInt32(123),
  2073. dbus_interface=dbus.PROPERTIES_IFACE)
  2074. raise Exception("Invalid Set(Pmf,123) accepted")
  2075. except dbus.exceptions.DBusException, e:
  2076. if "Error.Failed: Pmf must be 0, 1, or 2" not in str(e):
  2077. raise Exception("Unexpected error message for invalid Set(Pmf,123): " + str(e))
  2078. if_obj.Set(WPAS_DBUS_IFACE, "Pmf", dbus.UInt32(1),
  2079. dbus_interface=dbus.PROPERTIES_IFACE)
  2080. def test_dbus_fastreauth(dev, apdev):
  2081. """D-Bus Get/Set FastReauth"""
  2082. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2083. res = if_obj.Get(WPAS_DBUS_IFACE, "FastReauth",
  2084. dbus_interface=dbus.PROPERTIES_IFACE)
  2085. if res != True:
  2086. raise Exception("Unexpected initial FastReauth value: " + str(res))
  2087. for i in [ False, True ]:
  2088. if_obj.Set(WPAS_DBUS_IFACE, "FastReauth", dbus.Boolean(i),
  2089. dbus_interface=dbus.PROPERTIES_IFACE)
  2090. res = if_obj.Get(WPAS_DBUS_IFACE, "FastReauth",
  2091. dbus_interface=dbus.PROPERTIES_IFACE)
  2092. if res != i:
  2093. raise Exception("Unexpected FastReauth value %d (expected %d)" % (res, i))
  2094. try:
  2095. if_obj.Set(WPAS_DBUS_IFACE, "FastReauth", dbus.Int16(-1),
  2096. dbus_interface=dbus.PROPERTIES_IFACE)
  2097. raise Exception("Invalid Set(FastReauth,-1) accepted")
  2098. except dbus.exceptions.DBusException, e:
  2099. if "Error.Failed: wrong property type" not in str(e):
  2100. raise Exception("Unexpected error message for invalid Set(ApScan,-1): " + str(e))
  2101. if_obj.Set(WPAS_DBUS_IFACE, "FastReauth", dbus.Boolean(True),
  2102. dbus_interface=dbus.PROPERTIES_IFACE)
  2103. def test_dbus_bss_expire(dev, apdev):
  2104. """D-Bus Get/Set BSSExpireAge and BSSExpireCount"""
  2105. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2106. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.UInt32(179),
  2107. dbus_interface=dbus.PROPERTIES_IFACE)
  2108. res = if_obj.Get(WPAS_DBUS_IFACE, "BSSExpireAge",
  2109. dbus_interface=dbus.PROPERTIES_IFACE)
  2110. if res != 179:
  2111. raise Exception("Unexpected BSSExpireAge value %d (expected %d)" % (res, i))
  2112. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.UInt32(3),
  2113. dbus_interface=dbus.PROPERTIES_IFACE)
  2114. res = if_obj.Get(WPAS_DBUS_IFACE, "BSSExpireCount",
  2115. dbus_interface=dbus.PROPERTIES_IFACE)
  2116. if res != 3:
  2117. raise Exception("Unexpected BSSExpireCount value %d (expected %d)" % (res, i))
  2118. try:
  2119. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.Int16(-1),
  2120. dbus_interface=dbus.PROPERTIES_IFACE)
  2121. raise Exception("Invalid Set(BSSExpireAge,-1) accepted")
  2122. except dbus.exceptions.DBusException, e:
  2123. if "Error.Failed: wrong property type" not in str(e):
  2124. raise Exception("Unexpected error message for invalid Set(BSSExpireAge,-1): " + str(e))
  2125. try:
  2126. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.UInt32(9),
  2127. dbus_interface=dbus.PROPERTIES_IFACE)
  2128. raise Exception("Invalid Set(BSSExpireAge,9) accepted")
  2129. except dbus.exceptions.DBusException, e:
  2130. if "Error.Failed: BSSExpireAge must be >= 10" not in str(e):
  2131. raise Exception("Unexpected error message for invalid Set(BSSExpireAge,9): " + str(e))
  2132. try:
  2133. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.Int16(-1),
  2134. dbus_interface=dbus.PROPERTIES_IFACE)
  2135. raise Exception("Invalid Set(BSSExpireCount,-1) accepted")
  2136. except dbus.exceptions.DBusException, e:
  2137. if "Error.Failed: wrong property type" not in str(e):
  2138. raise Exception("Unexpected error message for invalid Set(BSSExpireCount,-1): " + str(e))
  2139. try:
  2140. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.UInt32(0),
  2141. dbus_interface=dbus.PROPERTIES_IFACE)
  2142. raise Exception("Invalid Set(BSSExpireCount,0) accepted")
  2143. except dbus.exceptions.DBusException, e:
  2144. if "Error.Failed: BSSExpireCount must be > 0" not in str(e):
  2145. raise Exception("Unexpected error message for invalid Set(BSSExpireCount,0): " + str(e))
  2146. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.UInt32(180),
  2147. dbus_interface=dbus.PROPERTIES_IFACE)
  2148. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.UInt32(2),
  2149. dbus_interface=dbus.PROPERTIES_IFACE)
  2150. def test_dbus_country(dev, apdev):
  2151. """D-Bus Get/Set Country"""
  2152. try:
  2153. _test_dbus_country(dev, apdev)
  2154. finally:
  2155. dev[0].request("SET country 00")
  2156. subprocess.call(['iw', 'reg', 'set', '00'])
  2157. def _test_dbus_country(dev, apdev):
  2158. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2159. # work around issues with possible pending regdom event from the end of
  2160. # the previous test case
  2161. time.sleep(0.2)
  2162. dev[0].dump_monitor()
  2163. if_obj.Set(WPAS_DBUS_IFACE, "Country", "FI",
  2164. dbus_interface=dbus.PROPERTIES_IFACE)
  2165. res = if_obj.Get(WPAS_DBUS_IFACE, "Country",
  2166. dbus_interface=dbus.PROPERTIES_IFACE)
  2167. if res != "FI":
  2168. raise Exception("Unexpected Country value %s (expected FI)" % res)
  2169. ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"])
  2170. if ev is None:
  2171. # For now, work around separate P2P Device interface event delivery
  2172. ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
  2173. if ev is None:
  2174. raise Exception("regdom change event not seen")
  2175. if "init=USER type=COUNTRY alpha2=FI" not in ev:
  2176. raise Exception("Unexpected event contents: " + ev)
  2177. try:
  2178. if_obj.Set(WPAS_DBUS_IFACE, "Country", dbus.Int16(-1),
  2179. dbus_interface=dbus.PROPERTIES_IFACE)
  2180. raise Exception("Invalid Set(Country,-1) accepted")
  2181. except dbus.exceptions.DBusException, e:
  2182. if "Error.Failed: wrong property type" not in str(e):
  2183. raise Exception("Unexpected error message for invalid Set(Country,-1): " + str(e))
  2184. try:
  2185. if_obj.Set(WPAS_DBUS_IFACE, "Country", "F",
  2186. dbus_interface=dbus.PROPERTIES_IFACE)
  2187. raise Exception("Invalid Set(Country,F) accepted")
  2188. except dbus.exceptions.DBusException, e:
  2189. if "Error.Failed: invalid country code" not in str(e):
  2190. raise Exception("Unexpected error message for invalid Set(Country,F): " + str(e))
  2191. if_obj.Set(WPAS_DBUS_IFACE, "Country", "00",
  2192. dbus_interface=dbus.PROPERTIES_IFACE)
  2193. ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"])
  2194. if ev is None:
  2195. # For now, work around separate P2P Device interface event delivery
  2196. ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
  2197. if ev is None:
  2198. raise Exception("regdom change event not seen")
  2199. # init=CORE was previously used due to invalid db.txt data for 00. For
  2200. # now, allow both it and the new init=USER after fixed db.txt.
  2201. if "init=CORE type=WORLD" not in ev and "init=USER type=WORLD" not in ev:
  2202. raise Exception("Unexpected event contents: " + ev)
  2203. def test_dbus_scan_interval(dev, apdev):
  2204. """D-Bus Get/Set ScanInterval"""
  2205. try:
  2206. _test_dbus_scan_interval(dev, apdev)
  2207. finally:
  2208. dev[0].request("SCAN_INTERVAL 5")
  2209. def _test_dbus_scan_interval(dev, apdev):
  2210. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2211. if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.Int32(3),
  2212. dbus_interface=dbus.PROPERTIES_IFACE)
  2213. res = if_obj.Get(WPAS_DBUS_IFACE, "ScanInterval",
  2214. dbus_interface=dbus.PROPERTIES_IFACE)
  2215. if res != 3:
  2216. raise Exception("Unexpected ScanInterval value %d (expected %d)" % (res, i))
  2217. try:
  2218. if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.UInt16(100),
  2219. dbus_interface=dbus.PROPERTIES_IFACE)
  2220. raise Exception("Invalid Set(ScanInterval,100) accepted")
  2221. except dbus.exceptions.DBusException, e:
  2222. if "Error.Failed: wrong property type" not in str(e):
  2223. raise Exception("Unexpected error message for invalid Set(ScanInterval,100): " + str(e))
  2224. try:
  2225. if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.Int32(-1),
  2226. dbus_interface=dbus.PROPERTIES_IFACE)
  2227. raise Exception("Invalid Set(ScanInterval,-1) accepted")
  2228. except dbus.exceptions.DBusException, e:
  2229. if "Error.Failed: scan_interval must be >= 0" not in str(e):
  2230. raise Exception("Unexpected error message for invalid Set(ScanInterval,-1): " + str(e))
  2231. if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.Int32(5),
  2232. dbus_interface=dbus.PROPERTIES_IFACE)
  2233. def test_dbus_probe_req_reporting(dev, apdev):
  2234. """D-Bus Probe Request reporting"""
  2235. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2236. dev[1].p2p_find(social=True)
  2237. class TestDbusProbe(TestDbus):
  2238. def __init__(self, bus):
  2239. TestDbus.__init__(self, bus)
  2240. self.reported = False
  2241. def __enter__(self):
  2242. gobject.timeout_add(1, self.run_test)
  2243. gobject.timeout_add(15000, self.timeout)
  2244. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2245. "GroupStarted")
  2246. self.add_signal(self.probeRequest, WPAS_DBUS_IFACE, "ProbeRequest",
  2247. byte_arrays=True)
  2248. self.loop.run()
  2249. return self
  2250. def groupStarted(self, properties):
  2251. logger.debug("groupStarted: " + str(properties))
  2252. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  2253. properties['interface_object'])
  2254. self.iface = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE)
  2255. self.iface.SubscribeProbeReq()
  2256. self.group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2257. def probeRequest(self, args):
  2258. logger.debug("probeRequest: args=%s" % str(args))
  2259. self.reported = True
  2260. self.loop.quit()
  2261. def run_test(self, *args):
  2262. logger.debug("run_test")
  2263. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2264. params = dbus.Dictionary({ 'frequency': 2412 })
  2265. p2p.GroupAdd(params)
  2266. return False
  2267. def success(self):
  2268. return self.reported
  2269. with TestDbusProbe(bus) as t:
  2270. if not t.success():
  2271. raise Exception("Expected signals not seen")
  2272. t.iface.UnsubscribeProbeReq()
  2273. try:
  2274. t.iface.UnsubscribeProbeReq()
  2275. raise Exception("Invalid UnsubscribeProbeReq() accepted")
  2276. except dbus.exceptions.DBusException, e:
  2277. if "NoSubscription" not in str(e):
  2278. raise Exception("Unexpected error message for invalid UnsubscribeProbeReq(): " + str(e))
  2279. t.group_p2p.Disconnect()
  2280. with TestDbusProbe(bus) as t:
  2281. if not t.success():
  2282. raise Exception("Expected signals not seen")
  2283. # On purpose, leave ProbeReq subscription in place to test automatic
  2284. # cleanup.
  2285. dev[1].p2p_stop_find()
  2286. def test_dbus_probe_req_reporting_oom(dev, apdev):
  2287. """D-Bus Probe Request reporting (OOM)"""
  2288. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2289. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  2290. # Need to make sure this process has not already subscribed to avoid false
  2291. # failures due to the operation succeeding due to os_strdup() not even
  2292. # getting called.
  2293. try:
  2294. iface.UnsubscribeProbeReq()
  2295. was_subscribed = True
  2296. except dbus.exceptions.DBusException, e:
  2297. was_subscribed = False
  2298. pass
  2299. with alloc_fail_dbus(dev[0], 1, "wpas_dbus_handler_subscribe_preq",
  2300. "SubscribeProbeReq"):
  2301. iface.SubscribeProbeReq()
  2302. if was_subscribed:
  2303. # On purpose, leave ProbeReq subscription in place to test automatic
  2304. # cleanup.
  2305. iface.SubscribeProbeReq()
  2306. def test_dbus_p2p_invalid(dev, apdev):
  2307. """D-Bus invalid P2P operations"""
  2308. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2309. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2310. try:
  2311. p2p.RejectPeer(path + "/Peers/00112233445566")
  2312. raise Exception("Invalid RejectPeer accepted")
  2313. except dbus.exceptions.DBusException, e:
  2314. if "UnknownError: Failed to call wpas_p2p_reject" not in str(e):
  2315. raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
  2316. try:
  2317. p2p.RejectPeer("/foo")
  2318. raise Exception("Invalid RejectPeer accepted")
  2319. except dbus.exceptions.DBusException, e:
  2320. if "InvalidArgs" not in str(e):
  2321. raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
  2322. tests = [ { },
  2323. { 'peer': 'foo' },
  2324. { 'foo': "bar" },
  2325. { 'iface': "abc" },
  2326. { 'iface': 123 } ]
  2327. for t in tests:
  2328. try:
  2329. p2p.RemoveClient(t)
  2330. raise Exception("Invalid RemoveClient accepted")
  2331. except dbus.exceptions.DBusException, e:
  2332. if "InvalidArgs" not in str(e):
  2333. raise Exception("Unexpected error message for invalid RemoveClient(): " + str(e))
  2334. tests = [ {'DiscoveryType': 'foo'},
  2335. {'RequestedDeviceTypes': 'foo'},
  2336. {'RequestedDeviceTypes': ['foo']},
  2337. {'RequestedDeviceTypes': ['1','2','3','4','5','6','7','8','9',
  2338. '10','11','12','13','14','15','16',
  2339. '17']},
  2340. {'RequestedDeviceTypes': dbus.Array([], signature="s")},
  2341. {'RequestedDeviceTypes': dbus.Array([['foo']], signature="as")},
  2342. {'RequestedDeviceTypes': dbus.Array([], signature="i")},
  2343. {'RequestedDeviceTypes': [dbus.ByteArray('12345678'),
  2344. dbus.ByteArray('1234567')]},
  2345. {'Foo': dbus.Int16(1)},
  2346. {'Foo': dbus.UInt16(1)},
  2347. {'Foo': dbus.Int64(1)},
  2348. {'Foo': dbus.UInt64(1)},
  2349. {'Foo': dbus.Double(1.23)},
  2350. {'Foo': dbus.Signature('s')},
  2351. {'Foo': 'bar'}]
  2352. for t in tests:
  2353. try:
  2354. p2p.Find(dbus.Dictionary(t))
  2355. raise Exception("Invalid Find accepted")
  2356. except dbus.exceptions.DBusException, e:
  2357. if "InvalidArgs" not in str(e):
  2358. raise Exception("Unexpected error message for invalid Find(): " + str(e))
  2359. for p in [ "/foo",
  2360. "/fi/w1/wpa_supplicant1/Interfaces/1234",
  2361. "/fi/w1/wpa_supplicant1/Interfaces/1234/Networks/1234" ]:
  2362. try:
  2363. p2p.RemovePersistentGroup(dbus.ObjectPath(p))
  2364. raise Exception("Invalid RemovePersistentGroup accepted")
  2365. except dbus.exceptions.DBusException, e:
  2366. if "InvalidArgs" not in str(e):
  2367. raise Exception("Unexpected error message for invalid RemovePersistentGroup: " + str(e))
  2368. try:
  2369. dev[0].request("P2P_SET disabled 1")
  2370. p2p.Listen(5)
  2371. raise Exception("Invalid Listen accepted")
  2372. except dbus.exceptions.DBusException, e:
  2373. if "UnknownError: Could not start P2P listen" not in str(e):
  2374. raise Exception("Unexpected error message for invalid Listen: " + str(e))
  2375. finally:
  2376. dev[0].request("P2P_SET disabled 0")
  2377. test_obj = bus.get_object(WPAS_DBUS_SERVICE, path, introspect=False)
  2378. test_p2p = dbus.Interface(test_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2379. try:
  2380. test_p2p.Listen("foo")
  2381. raise Exception("Invalid Listen accepted")
  2382. except dbus.exceptions.DBusException, e:
  2383. if "InvalidArgs" not in str(e):
  2384. raise Exception("Unexpected error message for invalid Listen: " + str(e))
  2385. try:
  2386. dev[0].request("P2P_SET disabled 1")
  2387. p2p.ExtendedListen(dbus.Dictionary({}))
  2388. raise Exception("Invalid ExtendedListen accepted")
  2389. except dbus.exceptions.DBusException, e:
  2390. if "UnknownError: failed to initiate a p2p_ext_listen" not in str(e):
  2391. raise Exception("Unexpected error message for invalid ExtendedListen: " + str(e))
  2392. finally:
  2393. dev[0].request("P2P_SET disabled 0")
  2394. try:
  2395. dev[0].request("P2P_SET disabled 1")
  2396. args = { 'duration1': 30000, 'interval1': 102400,
  2397. 'duration2': 20000, 'interval2': 102400 }
  2398. p2p.PresenceRequest(args)
  2399. raise Exception("Invalid PresenceRequest accepted")
  2400. except dbus.exceptions.DBusException, e:
  2401. if "UnknownError: Failed to invoke presence request" not in str(e):
  2402. raise Exception("Unexpected error message for invalid PresenceRequest: " + str(e))
  2403. finally:
  2404. dev[0].request("P2P_SET disabled 0")
  2405. try:
  2406. params = dbus.Dictionary({'frequency': dbus.Int32(-1)})
  2407. p2p.GroupAdd(params)
  2408. raise Exception("Invalid GroupAdd accepted")
  2409. except dbus.exceptions.DBusException, e:
  2410. if "InvalidArgs" not in str(e):
  2411. raise Exception("Unexpected error message for invalid GroupAdd: " + str(e))
  2412. try:
  2413. params = dbus.Dictionary({'persistent_group_object':
  2414. dbus.ObjectPath(path),
  2415. 'frequency': 2412})
  2416. p2p.GroupAdd(params)
  2417. raise Exception("Invalid GroupAdd accepted")
  2418. except dbus.exceptions.DBusException, e:
  2419. if "InvalidArgs" not in str(e):
  2420. raise Exception("Unexpected error message for invalid GroupAdd: " + str(e))
  2421. try:
  2422. p2p.Disconnect()
  2423. raise Exception("Invalid Disconnect accepted")
  2424. except dbus.exceptions.DBusException, e:
  2425. if "UnknownError: failed to disconnect" not in str(e):
  2426. raise Exception("Unexpected error message for invalid Disconnect: " + str(e))
  2427. try:
  2428. dev[0].request("P2P_SET disabled 1")
  2429. p2p.Flush()
  2430. raise Exception("Invalid Flush accepted")
  2431. except dbus.exceptions.DBusException, e:
  2432. if "Error.Failed: P2P is not available for this interface" not in str(e):
  2433. raise Exception("Unexpected error message for invalid Flush: " + str(e))
  2434. finally:
  2435. dev[0].request("P2P_SET disabled 0")
  2436. try:
  2437. dev[0].request("P2P_SET disabled 1")
  2438. args = { 'peer': path,
  2439. 'join': True,
  2440. 'wps_method': 'pbc',
  2441. 'frequency': 2412 }
  2442. pin = p2p.Connect(args)
  2443. raise Exception("Invalid Connect accepted")
  2444. except dbus.exceptions.DBusException, e:
  2445. if "Error.Failed: P2P is not available for this interface" not in str(e):
  2446. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  2447. finally:
  2448. dev[0].request("P2P_SET disabled 0")
  2449. tests = [ { 'frequency': dbus.Int32(-1) },
  2450. { 'wps_method': 'pbc' },
  2451. { 'wps_method': 'foo' } ]
  2452. for args in tests:
  2453. try:
  2454. pin = p2p.Connect(args)
  2455. raise Exception("Invalid Connect accepted")
  2456. except dbus.exceptions.DBusException, e:
  2457. if "InvalidArgs" not in str(e):
  2458. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  2459. try:
  2460. dev[0].request("P2P_SET disabled 1")
  2461. args = { 'peer': path }
  2462. pin = p2p.Invite(args)
  2463. raise Exception("Invalid Invite accepted")
  2464. except dbus.exceptions.DBusException, e:
  2465. if "Error.Failed: P2P is not available for this interface" not in str(e):
  2466. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  2467. finally:
  2468. dev[0].request("P2P_SET disabled 0")
  2469. try:
  2470. args = { 'foo': 'bar' }
  2471. pin = p2p.Invite(args)
  2472. raise Exception("Invalid Invite accepted")
  2473. except dbus.exceptions.DBusException, e:
  2474. if "InvalidArgs" not in str(e):
  2475. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  2476. tests = [ (path, 'display', "InvalidArgs"),
  2477. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2478. 'display',
  2479. "UnknownError: Failed to send provision discovery request"),
  2480. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2481. 'keypad',
  2482. "UnknownError: Failed to send provision discovery request"),
  2483. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2484. 'pbc',
  2485. "UnknownError: Failed to send provision discovery request"),
  2486. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2487. 'pushbutton',
  2488. "UnknownError: Failed to send provision discovery request"),
  2489. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2490. 'foo', "InvalidArgs") ]
  2491. for (p,method,err) in tests:
  2492. try:
  2493. p2p.ProvisionDiscoveryRequest(p, method)
  2494. raise Exception("Invalid ProvisionDiscoveryRequest accepted")
  2495. except dbus.exceptions.DBusException, e:
  2496. if err not in str(e):
  2497. raise Exception("Unexpected error message for invalid ProvisionDiscoveryRequest: " + str(e))
  2498. try:
  2499. dev[0].request("P2P_SET disabled 1")
  2500. if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Peers",
  2501. dbus_interface=dbus.PROPERTIES_IFACE)
  2502. raise Exception("Invalid Get(Peers) accepted")
  2503. except dbus.exceptions.DBusException, e:
  2504. if "Error.Failed: P2P is not available for this interface" not in str(e):
  2505. raise Exception("Unexpected error message for invalid Get(Peers): " + str(e))
  2506. finally:
  2507. dev[0].request("P2P_SET disabled 0")
  2508. def test_dbus_p2p_oom(dev, apdev):
  2509. """D-Bus P2P operations and OOM"""
  2510. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2511. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2512. with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_entry_get_string_array",
  2513. "Find", "InvalidArgs"):
  2514. p2p.Find(dbus.Dictionary({ 'Foo': [ 'bar' ] }))
  2515. with alloc_fail_dbus(dev[0], 2, "_wpa_dbus_dict_entry_get_string_array",
  2516. "Find", "InvalidArgs"):
  2517. p2p.Find(dbus.Dictionary({ 'Foo': [ 'bar' ] }))
  2518. with alloc_fail_dbus(dev[0], 10, "_wpa_dbus_dict_entry_get_string_array",
  2519. "Find", "InvalidArgs"):
  2520. p2p.Find(dbus.Dictionary({ 'Foo': [ '1','2','3','4','5','6','7','8','9' ] }))
  2521. with alloc_fail_dbus(dev[0], 1, ":=_wpa_dbus_dict_entry_get_binarray",
  2522. "Find", "InvalidArgs"):
  2523. p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123') ] }))
  2524. with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_entry_get_byte_array;_wpa_dbus_dict_entry_get_binarray",
  2525. "Find", "InvalidArgs"):
  2526. p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123') ] }))
  2527. with alloc_fail_dbus(dev[0], 2, "=_wpa_dbus_dict_entry_get_binarray",
  2528. "Find", "InvalidArgs"):
  2529. p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123'),
  2530. dbus.ByteArray('123'),
  2531. dbus.ByteArray('123'),
  2532. dbus.ByteArray('123'),
  2533. dbus.ByteArray('123'),
  2534. dbus.ByteArray('123'),
  2535. dbus.ByteArray('123'),
  2536. dbus.ByteArray('123'),
  2537. dbus.ByteArray('123'),
  2538. dbus.ByteArray('123'),
  2539. dbus.ByteArray('123') ] }))
  2540. with alloc_fail_dbus(dev[0], 1, "wpabuf_alloc_ext_data;_wpa_dbus_dict_entry_get_binarray",
  2541. "Find", "InvalidArgs"):
  2542. p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123') ] }))
  2543. with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_fill_value_from_variant;wpas_dbus_handler_p2p_find",
  2544. "Find", "InvalidArgs"):
  2545. p2p.Find(dbus.Dictionary({ 'Foo': path }))
  2546. with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_entry_get_byte_array",
  2547. "AddService", "InvalidArgs"):
  2548. args = { 'service_type': 'bonjour',
  2549. 'response': dbus.ByteArray(500*'b') }
  2550. p2p.AddService(args)
  2551. with alloc_fail_dbus(dev[0], 2, "_wpa_dbus_dict_entry_get_byte_array",
  2552. "AddService", "InvalidArgs"):
  2553. p2p.AddService(args)
  2554. def test_dbus_p2p_discovery(dev, apdev):
  2555. """D-Bus P2P discovery"""
  2556. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2557. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2558. addr0 = dev[0].p2p_dev_addr()
  2559. dev[1].request("SET sec_device_type 1-0050F204-2")
  2560. dev[1].request("VENDOR_ELEM_ADD 1 dd0c0050f2041049000411223344")
  2561. dev[1].p2p_listen()
  2562. addr1 = dev[1].p2p_dev_addr()
  2563. a1 = binascii.unhexlify(addr1.replace(':',''))
  2564. wfd_devinfo = "00001c440028"
  2565. dev[2].request("SET wifi_display 1")
  2566. dev[2].request("WFD_SUBELEM_SET 0 0006" + wfd_devinfo)
  2567. wfd = binascii.unhexlify('000006' + wfd_devinfo)
  2568. dev[2].p2p_listen()
  2569. addr2 = dev[2].p2p_dev_addr()
  2570. a2 = binascii.unhexlify(addr2.replace(':',''))
  2571. res = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
  2572. dbus_interface=dbus.PROPERTIES_IFACE)
  2573. if 'Peers' not in res:
  2574. raise Exception("GetAll result missing Peers")
  2575. if len(res['Peers']) != 0:
  2576. raise Exception("Unexpected peer(s) in the list")
  2577. args = {'DiscoveryType': 'social',
  2578. 'RequestedDeviceTypes': [dbus.ByteArray('12345678')],
  2579. 'Timeout': dbus.Int32(1) }
  2580. p2p.Find(dbus.Dictionary(args))
  2581. p2p.StopFind()
  2582. class TestDbusP2p(TestDbus):
  2583. def __init__(self, bus):
  2584. TestDbus.__init__(self, bus)
  2585. self.found = False
  2586. self.found2 = False
  2587. self.found_prop = False
  2588. self.lost = False
  2589. self.find_stopped = False
  2590. def __enter__(self):
  2591. gobject.timeout_add(1, self.run_test)
  2592. gobject.timeout_add(15000, self.timeout)
  2593. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2594. "DeviceFound")
  2595. self.add_signal(self.deviceFoundProperties,
  2596. WPAS_DBUS_IFACE_P2PDEVICE, "DeviceFoundProperties")
  2597. self.add_signal(self.deviceLost, WPAS_DBUS_IFACE_P2PDEVICE,
  2598. "DeviceLost")
  2599. self.add_signal(self.provisionDiscoveryResponseEnterPin,
  2600. WPAS_DBUS_IFACE_P2PDEVICE,
  2601. "ProvisionDiscoveryResponseEnterPin")
  2602. self.add_signal(self.findStopped, WPAS_DBUS_IFACE_P2PDEVICE,
  2603. "FindStopped")
  2604. self.loop.run()
  2605. return self
  2606. def deviceFound(self, path):
  2607. logger.debug("deviceFound: path=%s" % path)
  2608. res = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Peers",
  2609. dbus_interface=dbus.PROPERTIES_IFACE)
  2610. if len(res) < 1:
  2611. raise Exception("Unexpected number of peers")
  2612. if path not in res:
  2613. raise Exception("Mismatch in peer object path")
  2614. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  2615. res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2616. dbus_interface=dbus.PROPERTIES_IFACE,
  2617. byte_arrays=True)
  2618. logger.debug("peer properties: " + str(res))
  2619. if res['DeviceAddress'] == a1:
  2620. if 'SecondaryDeviceTypes' not in res:
  2621. raise Exception("Missing SecondaryDeviceTypes")
  2622. sec = res['SecondaryDeviceTypes']
  2623. if len(sec) < 1:
  2624. raise Exception("Secondary device type missing")
  2625. if "\x00\x01\x00\x50\xF2\x04\x00\x02" not in sec:
  2626. raise Exception("Secondary device type mismatch")
  2627. if 'VendorExtension' not in res:
  2628. raise Exception("Missing VendorExtension")
  2629. vendor = res['VendorExtension']
  2630. if len(vendor) < 1:
  2631. raise Exception("Vendor extension missing")
  2632. if "\x11\x22\x33\x44" not in vendor:
  2633. raise Exception("Secondary device type mismatch")
  2634. self.found = True
  2635. elif res['DeviceAddress'] == a2:
  2636. if 'IEs' not in res:
  2637. raise Exception("IEs missing")
  2638. if res['IEs'] != wfd:
  2639. raise Exception("IEs mismatch")
  2640. self.found2 = True
  2641. else:
  2642. raise Exception("Unexpected peer device address")
  2643. if self.found and self.found2:
  2644. p2p.StopFind()
  2645. p2p.RejectPeer(path)
  2646. p2p.ProvisionDiscoveryRequest(path, 'display')
  2647. def deviceLost(self, path):
  2648. logger.debug("deviceLost: path=%s" % path)
  2649. if not self.found or not self.found2:
  2650. # This may happen if a previous test case ended up scheduling
  2651. # deviceLost event and that event did not get delivered before
  2652. # starting the next test execution.
  2653. logger.debug("Ignore deviceLost before the deviceFound events")
  2654. return
  2655. self.lost = True
  2656. try:
  2657. p2p.RejectPeer(path)
  2658. raise Exception("Invalid RejectPeer accepted")
  2659. except dbus.exceptions.DBusException, e:
  2660. if "UnknownError: Failed to call wpas_p2p_reject" not in str(e):
  2661. raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
  2662. self.loop.quit()
  2663. def deviceFoundProperties(self, path, properties):
  2664. logger.debug("deviceFoundProperties: path=%s" % path)
  2665. logger.debug("peer properties: " + str(properties))
  2666. if properties['DeviceAddress'] == a1:
  2667. self.found_prop = True
  2668. def provisionDiscoveryResponseEnterPin(self, peer_object):
  2669. logger.debug("provisionDiscoveryResponseEnterPin - peer=%s" % peer_object)
  2670. p2p.Flush()
  2671. def findStopped(self):
  2672. logger.debug("findStopped")
  2673. self.find_stopped = True
  2674. def run_test(self, *args):
  2675. logger.debug("run_test")
  2676. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social',
  2677. 'Timeout': dbus.Int32(10)}))
  2678. return False
  2679. def success(self):
  2680. return self.found and self.lost and self.found2 and self.find_stopped
  2681. with TestDbusP2p(bus) as t:
  2682. if not t.success():
  2683. raise Exception("Expected signals not seen")
  2684. dev[1].request("VENDOR_ELEM_REMOVE 1 *")
  2685. dev[1].p2p_stop_find()
  2686. p2p.Listen(1)
  2687. dev[2].p2p_stop_find()
  2688. dev[2].request("P2P_FLUSH")
  2689. if not dev[2].discover_peer(addr0):
  2690. raise Exception("Peer not found")
  2691. p2p.StopFind()
  2692. dev[2].p2p_stop_find()
  2693. try:
  2694. p2p.ExtendedListen(dbus.Dictionary({'foo': 100}))
  2695. raise Exception("Invalid ExtendedListen accepted")
  2696. except dbus.exceptions.DBusException, e:
  2697. if "InvalidArgs" not in str(e):
  2698. raise Exception("Unexpected error message for invalid ExtendedListen(): " + str(e))
  2699. p2p.ExtendedListen(dbus.Dictionary({'period': 100, 'interval': 1000}))
  2700. p2p.ExtendedListen(dbus.Dictionary({}))
  2701. dev[0].global_request("P2P_EXT_LISTEN")
  2702. def test_dbus_p2p_discovery_freq(dev, apdev):
  2703. """D-Bus P2P discovery on a specific non-social channel"""
  2704. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2705. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2706. addr1 = dev[1].p2p_dev_addr()
  2707. autogo(dev[1], freq=2422)
  2708. class TestDbusP2p(TestDbus):
  2709. def __init__(self, bus):
  2710. TestDbus.__init__(self, bus)
  2711. self.found = False
  2712. def __enter__(self):
  2713. gobject.timeout_add(1, self.run_test)
  2714. gobject.timeout_add(5000, self.timeout)
  2715. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2716. "DeviceFound")
  2717. self.loop.run()
  2718. return self
  2719. def deviceFound(self, path):
  2720. logger.debug("deviceFound: path=%s" % path)
  2721. self.found = True
  2722. self.loop.quit()
  2723. def run_test(self, *args):
  2724. logger.debug("run_test")
  2725. p2p.Find(dbus.Dictionary({'freq': 2422}))
  2726. return False
  2727. def success(self):
  2728. return self.found
  2729. with TestDbusP2p(bus) as t:
  2730. if not t.success():
  2731. raise Exception("Expected signals not seen")
  2732. dev[1].remove_group()
  2733. p2p.StopFind()
  2734. def test_dbus_p2p_service_discovery(dev, apdev):
  2735. """D-Bus P2P service discovery"""
  2736. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2737. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2738. addr0 = dev[0].p2p_dev_addr()
  2739. addr1 = dev[1].p2p_dev_addr()
  2740. bonjour_query = dbus.ByteArray(binascii.unhexlify('0b5f6166706f766572746370c00c000c01'))
  2741. bonjour_response = dbus.ByteArray(binascii.unhexlify('074578616d706c65c027'))
  2742. args = { 'service_type': 'bonjour',
  2743. 'query': bonjour_query,
  2744. 'response': bonjour_response }
  2745. p2p.AddService(args)
  2746. p2p.FlushService()
  2747. p2p.AddService(args)
  2748. try:
  2749. p2p.DeleteService(args)
  2750. raise Exception("Invalid DeleteService() accepted")
  2751. except dbus.exceptions.DBusException, e:
  2752. if "InvalidArgs" not in str(e):
  2753. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  2754. args = { 'service_type': 'bonjour',
  2755. 'query': bonjour_query }
  2756. p2p.DeleteService(args)
  2757. try:
  2758. p2p.DeleteService(args)
  2759. raise Exception("Invalid DeleteService() accepted")
  2760. except dbus.exceptions.DBusException, e:
  2761. if "InvalidArgs" not in str(e):
  2762. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  2763. args = { 'service_type': 'upnp',
  2764. 'version': 0x10,
  2765. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' }
  2766. p2p.AddService(args)
  2767. p2p.DeleteService(args)
  2768. try:
  2769. p2p.DeleteService(args)
  2770. raise Exception("Invalid DeleteService() accepted")
  2771. except dbus.exceptions.DBusException, e:
  2772. if "InvalidArgs" not in str(e):
  2773. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  2774. tests = [ { 'service_type': 'foo' },
  2775. { 'service_type': 'foo', 'query': bonjour_query },
  2776. { 'service_type': 'upnp' },
  2777. { 'service_type': 'upnp', 'version': 0x10 },
  2778. { 'service_type': 'upnp',
  2779. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
  2780. { 'version': 0x10,
  2781. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
  2782. { 'service_type': 'upnp', 'foo': 'bar' },
  2783. { 'service_type': 'bonjour' },
  2784. { 'service_type': 'bonjour', 'query': 'foo' },
  2785. { 'service_type': 'bonjour', 'foo': 'bar' } ]
  2786. for args in tests:
  2787. try:
  2788. p2p.DeleteService(args)
  2789. raise Exception("Invalid DeleteService() accepted")
  2790. except dbus.exceptions.DBusException, e:
  2791. if "InvalidArgs" not in str(e):
  2792. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  2793. tests = [ { 'service_type': 'foo' },
  2794. { 'service_type': 'upnp' },
  2795. { 'service_type': 'upnp', 'version': 0x10 },
  2796. { 'service_type': 'upnp',
  2797. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
  2798. { 'version': 0x10,
  2799. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
  2800. { 'service_type': 'upnp', 'foo': 'bar' },
  2801. { 'service_type': 'bonjour' },
  2802. { 'service_type': 'bonjour', 'query': 'foo' },
  2803. { 'service_type': 'bonjour', 'response': 'foo' },
  2804. { 'service_type': 'bonjour', 'query': bonjour_query },
  2805. { 'service_type': 'bonjour', 'response': bonjour_response },
  2806. { 'service_type': 'bonjour', 'query': dbus.ByteArray(500*'a') },
  2807. { 'service_type': 'bonjour', 'foo': 'bar' } ]
  2808. for args in tests:
  2809. try:
  2810. p2p.AddService(args)
  2811. raise Exception("Invalid AddService() accepted")
  2812. except dbus.exceptions.DBusException, e:
  2813. if "InvalidArgs" not in str(e):
  2814. raise Exception("Unexpected error message for invalid AddService(): " + str(e))
  2815. args = { 'tlv': dbus.ByteArray("\x02\x00\x00\x01") }
  2816. ref = p2p.ServiceDiscoveryRequest(args)
  2817. p2p.ServiceDiscoveryCancelRequest(ref)
  2818. try:
  2819. p2p.ServiceDiscoveryCancelRequest(ref)
  2820. raise Exception("Invalid ServiceDiscoveryCancelRequest() accepted")
  2821. except dbus.exceptions.DBusException, e:
  2822. if "InvalidArgs" not in str(e):
  2823. raise Exception("Unexpected error message for invalid AddService(): " + str(e))
  2824. try:
  2825. p2p.ServiceDiscoveryCancelRequest(dbus.UInt64(0))
  2826. raise Exception("Invalid ServiceDiscoveryCancelRequest() accepted")
  2827. except dbus.exceptions.DBusException, e:
  2828. if "InvalidArgs" not in str(e):
  2829. raise Exception("Unexpected error message for invalid AddService(): " + str(e))
  2830. args = { 'service_type': 'upnp',
  2831. 'version': 0x10,
  2832. 'service': 'ssdp:foo' }
  2833. ref = p2p.ServiceDiscoveryRequest(args)
  2834. p2p.ServiceDiscoveryCancelRequest(ref)
  2835. tests = [ { 'service_type': 'foo' },
  2836. { 'foo': 'bar' },
  2837. { 'tlv': 'foo' },
  2838. { },
  2839. { 'version': 0 },
  2840. { 'service_type': 'upnp',
  2841. 'service': 'ssdp:foo' },
  2842. { 'service_type': 'upnp',
  2843. 'version': 0x10 },
  2844. { 'service_type': 'upnp',
  2845. 'version': 0x10,
  2846. 'service': 'ssdp:foo',
  2847. 'peer_object': dbus.ObjectPath(path + "/Peers") },
  2848. { 'service_type': 'upnp',
  2849. 'version': 0x10,
  2850. 'service': 'ssdp:foo',
  2851. 'peer_object': path + "/Peers" },
  2852. { 'service_type': 'upnp',
  2853. 'version': 0x10,
  2854. 'service': 'ssdp:foo',
  2855. 'peer_object': dbus.ObjectPath(path + "/Peers/00112233445566") } ]
  2856. for args in tests:
  2857. try:
  2858. p2p.ServiceDiscoveryRequest(args)
  2859. raise Exception("Invalid ServiceDiscoveryRequest accepted")
  2860. except dbus.exceptions.DBusException, e:
  2861. if "InvalidArgs" not in str(e):
  2862. raise Exception("Unexpected error message for invalid ServiceDiscoveryRequest(): " + str(e))
  2863. args = { 'foo': 'bar' }
  2864. try:
  2865. p2p.ServiceDiscoveryResponse(dbus.Dictionary(args, signature='sv'))
  2866. raise Exception("Invalid ServiceDiscoveryResponse accepted")
  2867. except dbus.exceptions.DBusException, e:
  2868. if "InvalidArgs" not in str(e):
  2869. raise Exception("Unexpected error message for invalid ServiceDiscoveryResponse(): " + str(e))
  2870. def test_dbus_p2p_service_discovery_query(dev, apdev):
  2871. """D-Bus P2P service discovery query"""
  2872. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2873. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2874. addr0 = dev[0].p2p_dev_addr()
  2875. dev[1].request("P2P_SERVICE_ADD bonjour 0b5f6166706f766572746370c00c000c01 074578616d706c65c027")
  2876. dev[1].p2p_listen()
  2877. addr1 = dev[1].p2p_dev_addr()
  2878. class TestDbusP2p(TestDbus):
  2879. def __init__(self, bus):
  2880. TestDbus.__init__(self, bus)
  2881. self.done = False
  2882. def __enter__(self):
  2883. gobject.timeout_add(1, self.run_test)
  2884. gobject.timeout_add(15000, self.timeout)
  2885. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2886. "DeviceFound")
  2887. self.add_signal(self.serviceDiscoveryResponse,
  2888. WPAS_DBUS_IFACE_P2PDEVICE,
  2889. "ServiceDiscoveryResponse", byte_arrays=True)
  2890. self.loop.run()
  2891. return self
  2892. def deviceFound(self, path):
  2893. logger.debug("deviceFound: path=%s" % path)
  2894. args = { 'peer_object': path,
  2895. 'tlv': dbus.ByteArray("\x02\x00\x00\x01") }
  2896. p2p.ServiceDiscoveryRequest(args)
  2897. def serviceDiscoveryResponse(self, sd_request):
  2898. logger.debug("serviceDiscoveryResponse: sd_request=%s" % str(sd_request))
  2899. self.done = True
  2900. self.loop.quit()
  2901. def run_test(self, *args):
  2902. logger.debug("run_test")
  2903. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social',
  2904. 'Timeout': dbus.Int32(10)}))
  2905. return False
  2906. def success(self):
  2907. return self.done
  2908. with TestDbusP2p(bus) as t:
  2909. if not t.success():
  2910. raise Exception("Expected signals not seen")
  2911. dev[1].p2p_stop_find()
  2912. def test_dbus_p2p_service_discovery_external(dev, apdev):
  2913. """D-Bus P2P service discovery with external response"""
  2914. try:
  2915. _test_dbus_p2p_service_discovery_external(dev, apdev)
  2916. finally:
  2917. dev[0].request("P2P_SERV_DISC_EXTERNAL 0")
  2918. def _test_dbus_p2p_service_discovery_external(dev, apdev):
  2919. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2920. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2921. addr0 = dev[0].p2p_dev_addr()
  2922. addr1 = dev[1].p2p_dev_addr()
  2923. resp = "0300000101"
  2924. dev[1].request("P2P_FLUSH")
  2925. dev[1].request("P2P_SERV_DISC_REQ " + addr0 + " 02000001")
  2926. dev[1].p2p_find(social=True)
  2927. class TestDbusP2p(TestDbus):
  2928. def __init__(self, bus):
  2929. TestDbus.__init__(self, bus)
  2930. self.sd = False
  2931. def __enter__(self):
  2932. gobject.timeout_add(1, self.run_test)
  2933. gobject.timeout_add(15000, self.timeout)
  2934. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2935. "DeviceFound")
  2936. self.add_signal(self.serviceDiscoveryRequest,
  2937. WPAS_DBUS_IFACE_P2PDEVICE,
  2938. "ServiceDiscoveryRequest")
  2939. self.loop.run()
  2940. return self
  2941. def deviceFound(self, path):
  2942. logger.debug("deviceFound: path=%s" % path)
  2943. def serviceDiscoveryRequest(self, sd_request):
  2944. logger.debug("serviceDiscoveryRequest: sd_request=%s" % str(sd_request))
  2945. self.sd = True
  2946. args = { 'peer_object': sd_request['peer_object'],
  2947. 'frequency': sd_request['frequency'],
  2948. 'dialog_token': sd_request['dialog_token'],
  2949. 'tlvs': dbus.ByteArray(binascii.unhexlify(resp)) }
  2950. p2p.ServiceDiscoveryResponse(dbus.Dictionary(args, signature='sv'))
  2951. self.loop.quit()
  2952. def run_test(self, *args):
  2953. logger.debug("run_test")
  2954. p2p.ServiceDiscoveryExternal(1)
  2955. p2p.ServiceUpdate()
  2956. p2p.Listen(15)
  2957. return False
  2958. def success(self):
  2959. return self.sd
  2960. with TestDbusP2p(bus) as t:
  2961. if not t.success():
  2962. raise Exception("Expected signals not seen")
  2963. ev = dev[1].wait_global_event(["P2P-SERV-DISC-RESP"], timeout=5)
  2964. if ev is None:
  2965. raise Exception("Service discovery timed out")
  2966. if addr0 not in ev:
  2967. raise Exception("Unexpected address in SD Response: " + ev)
  2968. if ev.split(' ')[4] != resp:
  2969. raise Exception("Unexpected response data SD Response: " + ev)
  2970. dev[1].p2p_stop_find()
  2971. p2p.StopFind()
  2972. p2p.ServiceDiscoveryExternal(0)
  2973. def test_dbus_p2p_autogo(dev, apdev):
  2974. """D-Bus P2P autonomous GO"""
  2975. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2976. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2977. addr0 = dev[0].p2p_dev_addr()
  2978. class TestDbusP2p(TestDbus):
  2979. def __init__(self, bus):
  2980. TestDbus.__init__(self, bus)
  2981. self.first = True
  2982. self.waiting_end = False
  2983. self.exceptions = False
  2984. self.deauthorized = False
  2985. self.done = False
  2986. def __enter__(self):
  2987. gobject.timeout_add(1, self.run_test)
  2988. gobject.timeout_add(15000, self.timeout)
  2989. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2990. "DeviceFound")
  2991. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2992. "GroupStarted")
  2993. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2994. "GroupFinished")
  2995. self.add_signal(self.persistentGroupAdded,
  2996. WPAS_DBUS_IFACE_P2PDEVICE,
  2997. "PersistentGroupAdded")
  2998. self.add_signal(self.persistentGroupRemoved,
  2999. WPAS_DBUS_IFACE_P2PDEVICE,
  3000. "PersistentGroupRemoved")
  3001. self.add_signal(self.provisionDiscoveryRequestDisplayPin,
  3002. WPAS_DBUS_IFACE_P2PDEVICE,
  3003. "ProvisionDiscoveryRequestDisplayPin")
  3004. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  3005. "StaAuthorized")
  3006. self.add_signal(self.staDeauthorized, WPAS_DBUS_IFACE,
  3007. "StaDeauthorized")
  3008. self.loop.run()
  3009. return self
  3010. def groupStarted(self, properties):
  3011. logger.debug("groupStarted: " + str(properties))
  3012. self.group = properties['group_object']
  3013. self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3014. properties['interface_object'])
  3015. role = self.g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Role",
  3016. dbus_interface=dbus.PROPERTIES_IFACE)
  3017. if role != "GO":
  3018. self.exceptions = True
  3019. raise Exception("Unexpected role reported: " + role)
  3020. group = self.g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Group",
  3021. dbus_interface=dbus.PROPERTIES_IFACE)
  3022. if group != properties['group_object']:
  3023. self.exceptions = True
  3024. raise Exception("Unexpected Group reported: " + str(group))
  3025. go = self.g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PeerGO",
  3026. dbus_interface=dbus.PROPERTIES_IFACE)
  3027. if go != '/':
  3028. self.exceptions = True
  3029. raise Exception("Unexpected PeerGO value: " + str(go))
  3030. if self.first:
  3031. self.first = False
  3032. logger.info("Remove persistent group instance")
  3033. group_p2p = dbus.Interface(self.g_if_obj,
  3034. WPAS_DBUS_IFACE_P2PDEVICE)
  3035. group_p2p.Disconnect()
  3036. else:
  3037. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3038. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 join")
  3039. def groupFinished(self, properties):
  3040. logger.debug("groupFinished: " + str(properties))
  3041. if self.waiting_end:
  3042. logger.info("Remove persistent group")
  3043. p2p.RemovePersistentGroup(self.persistent)
  3044. else:
  3045. logger.info("Re-start persistent group")
  3046. params = dbus.Dictionary({'persistent_group_object':
  3047. self.persistent,
  3048. 'frequency': 2412})
  3049. p2p.GroupAdd(params)
  3050. def persistentGroupAdded(self, path, properties):
  3051. logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
  3052. self.persistent = path
  3053. def persistentGroupRemoved(self, path):
  3054. logger.debug("persistentGroupRemoved: %s" % path)
  3055. self.done = True
  3056. self.loop.quit()
  3057. def deviceFound(self, path):
  3058. logger.debug("deviceFound: path=%s" % path)
  3059. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  3060. self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  3061. dbus_interface=dbus.PROPERTIES_IFACE,
  3062. byte_arrays=True)
  3063. logger.debug('peer properties: ' + str(self.peer))
  3064. def provisionDiscoveryRequestDisplayPin(self, peer_object, pin):
  3065. logger.debug("provisionDiscoveryRequestDisplayPin - peer=%s pin=%s" % (peer_object, pin))
  3066. self.peer_path = peer_object
  3067. peer = binascii.unhexlify(peer_object.split('/')[-1])
  3068. addr = ""
  3069. for p in peer:
  3070. if len(addr) > 0:
  3071. addr += ':'
  3072. addr += '%02x' % ord(p)
  3073. params = { 'Role': 'registrar',
  3074. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  3075. 'Bssid': self.peer['DeviceAddress'],
  3076. 'Type': 'pin' }
  3077. wps = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_WPS)
  3078. try:
  3079. wps.Start(params)
  3080. self.exceptions = True
  3081. raise Exception("Invalid WPS.Start() accepted")
  3082. except dbus.exceptions.DBusException, e:
  3083. if "InvalidArgs" not in str(e):
  3084. self.exceptions = True
  3085. raise Exception("Unexpected error message: " + str(e))
  3086. params = { 'Role': 'registrar',
  3087. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  3088. 'Type': 'pin',
  3089. 'Pin': '12345670' }
  3090. logger.info("Authorize peer to connect to the group")
  3091. wps.Start(params)
  3092. def staAuthorized(self, name):
  3093. logger.debug("staAuthorized: " + name)
  3094. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, self.peer_path)
  3095. res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  3096. dbus_interface=dbus.PROPERTIES_IFACE,
  3097. byte_arrays=True)
  3098. logger.debug("Peer properties: " + str(res))
  3099. if 'Groups' not in res or len(res['Groups']) != 1:
  3100. self.exceptions = True
  3101. raise Exception("Unexpected number of peer Groups entries")
  3102. if res['Groups'][0] != self.group:
  3103. self.exceptions = True
  3104. raise Exception("Unexpected peer Groups[0] value")
  3105. g_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group)
  3106. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  3107. dbus_interface=dbus.PROPERTIES_IFACE,
  3108. byte_arrays=True)
  3109. logger.debug("Group properties: " + str(res))
  3110. if 'Members' not in res or len(res['Members']) != 1:
  3111. self.exceptions = True
  3112. raise Exception("Unexpected number of group members")
  3113. ext = dbus.ByteArray("\x11\x22\x33\x44")
  3114. # Earlier implementation of this interface was a bit strange. The
  3115. # property is defined to have aay signature and that is what the
  3116. # getter returned. However, the setter expected there to be a
  3117. # dictionary with 'WPSVendorExtensions' as the key surrounding these
  3118. # values.. The current implementations maintains support for that
  3119. # for backwards compability reasons. Verify that encoding first.
  3120. vals = dbus.Dictionary({ 'WPSVendorExtensions': [ ext ]},
  3121. signature='sv')
  3122. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
  3123. dbus_interface=dbus.PROPERTIES_IFACE)
  3124. res = g_obj.Get(WPAS_DBUS_GROUP, 'WPSVendorExtensions',
  3125. dbus_interface=dbus.PROPERTIES_IFACE,
  3126. byte_arrays=True)
  3127. if len(res) != 1:
  3128. self.exceptions = True
  3129. raise Exception("Unexpected number of vendor extensions")
  3130. if res[0] != ext:
  3131. self.exceptions = True
  3132. raise Exception("Vendor extension value changed")
  3133. # And now verify that the more appropriate encoding is accepted as
  3134. # well.
  3135. res.append(dbus.ByteArray('\xaa\xbb\xcc\xdd\xee\xff'))
  3136. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
  3137. dbus_interface=dbus.PROPERTIES_IFACE)
  3138. res2 = g_obj.Get(WPAS_DBUS_GROUP, 'WPSVendorExtensions',
  3139. dbus_interface=dbus.PROPERTIES_IFACE,
  3140. byte_arrays=True)
  3141. if len(res) != 2:
  3142. self.exceptions = True
  3143. raise Exception("Unexpected number of vendor extensions")
  3144. if res[0] != res2[0] or res[1] != res2[1]:
  3145. self.exceptions = True
  3146. raise Exception("Vendor extension value changed")
  3147. for i in range(10):
  3148. res.append(dbus.ByteArray('\xaa\xbb'))
  3149. try:
  3150. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
  3151. dbus_interface=dbus.PROPERTIES_IFACE)
  3152. self.exceptions = True
  3153. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  3154. except dbus.exceptions.DBusException, e:
  3155. if "Error.Failed" not in str(e):
  3156. self.exceptions = True
  3157. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  3158. vals = dbus.Dictionary({ 'Foo': [ ext ]}, signature='sv')
  3159. try:
  3160. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
  3161. dbus_interface=dbus.PROPERTIES_IFACE)
  3162. self.exceptions = True
  3163. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  3164. except dbus.exceptions.DBusException, e:
  3165. if "InvalidArgs" not in str(e):
  3166. self.exceptions = True
  3167. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  3168. vals = [ "foo" ]
  3169. try:
  3170. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
  3171. dbus_interface=dbus.PROPERTIES_IFACE)
  3172. self.exceptions = True
  3173. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  3174. except dbus.exceptions.DBusException, e:
  3175. if "Error.Failed" not in str(e):
  3176. self.exceptions = True
  3177. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  3178. vals = [ [ "foo" ] ]
  3179. try:
  3180. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
  3181. dbus_interface=dbus.PROPERTIES_IFACE)
  3182. self.exceptions = True
  3183. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  3184. except dbus.exceptions.DBusException, e:
  3185. if "Error.Failed" not in str(e):
  3186. self.exceptions = True
  3187. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  3188. p2p.RemoveClient({ 'peer': self.peer_path })
  3189. self.waiting_end = True
  3190. group_p2p = dbus.Interface(self.g_if_obj,
  3191. WPAS_DBUS_IFACE_P2PDEVICE)
  3192. group_p2p.Disconnect()
  3193. def staDeauthorized(self, name):
  3194. logger.debug("staDeauthorized: " + name)
  3195. self.deauthorized = True
  3196. def run_test(self, *args):
  3197. logger.debug("run_test")
  3198. params = dbus.Dictionary({'persistent': True,
  3199. 'frequency': 2412})
  3200. logger.info("Add a persistent group")
  3201. p2p.GroupAdd(params)
  3202. return False
  3203. def success(self):
  3204. return self.done and self.deauthorized and not self.exceptions
  3205. with TestDbusP2p(bus) as t:
  3206. if not t.success():
  3207. raise Exception("Expected signals not seen")
  3208. dev[1].wait_go_ending_session()
  3209. def test_dbus_p2p_autogo_pbc(dev, apdev):
  3210. """D-Bus P2P autonomous GO and PBC"""
  3211. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3212. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3213. addr0 = dev[0].p2p_dev_addr()
  3214. class TestDbusP2p(TestDbus):
  3215. def __init__(self, bus):
  3216. TestDbus.__init__(self, bus)
  3217. self.first = True
  3218. self.waiting_end = False
  3219. self.done = False
  3220. def __enter__(self):
  3221. gobject.timeout_add(1, self.run_test)
  3222. gobject.timeout_add(15000, self.timeout)
  3223. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3224. "DeviceFound")
  3225. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3226. "GroupStarted")
  3227. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3228. "GroupFinished")
  3229. self.add_signal(self.provisionDiscoveryPBCRequest,
  3230. WPAS_DBUS_IFACE_P2PDEVICE,
  3231. "ProvisionDiscoveryPBCRequest")
  3232. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  3233. "StaAuthorized")
  3234. self.loop.run()
  3235. return self
  3236. def groupStarted(self, properties):
  3237. logger.debug("groupStarted: " + str(properties))
  3238. self.group = properties['group_object']
  3239. self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3240. properties['interface_object'])
  3241. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3242. dev1.global_request("P2P_CONNECT " + addr0 + " pbc join")
  3243. def groupFinished(self, properties):
  3244. logger.debug("groupFinished: " + str(properties))
  3245. self.done = True
  3246. self.loop.quit()
  3247. def deviceFound(self, path):
  3248. logger.debug("deviceFound: path=%s" % path)
  3249. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  3250. self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  3251. dbus_interface=dbus.PROPERTIES_IFACE,
  3252. byte_arrays=True)
  3253. logger.debug('peer properties: ' + str(self.peer))
  3254. def provisionDiscoveryPBCRequest(self, peer_object):
  3255. logger.debug("provisionDiscoveryPBCRequest - peer=%s" % peer_object)
  3256. self.peer_path = peer_object
  3257. peer = binascii.unhexlify(peer_object.split('/')[-1])
  3258. addr = ""
  3259. for p in peer:
  3260. if len(addr) > 0:
  3261. addr += ':'
  3262. addr += '%02x' % ord(p)
  3263. params = { 'Role': 'registrar',
  3264. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  3265. 'Type': 'pbc' }
  3266. logger.info("Authorize peer to connect to the group")
  3267. wps = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_WPS)
  3268. wps.Start(params)
  3269. def staAuthorized(self, name):
  3270. logger.debug("staAuthorized: " + name)
  3271. group_p2p = dbus.Interface(self.g_if_obj,
  3272. WPAS_DBUS_IFACE_P2PDEVICE)
  3273. group_p2p.Disconnect()
  3274. def run_test(self, *args):
  3275. logger.debug("run_test")
  3276. params = dbus.Dictionary({'frequency': 2412})
  3277. p2p.GroupAdd(params)
  3278. return False
  3279. def success(self):
  3280. return self.done
  3281. with TestDbusP2p(bus) as t:
  3282. if not t.success():
  3283. raise Exception("Expected signals not seen")
  3284. dev[1].wait_go_ending_session()
  3285. dev[1].flush_scan_cache()
  3286. def test_dbus_p2p_autogo_legacy(dev, apdev):
  3287. """D-Bus P2P autonomous GO and legacy STA"""
  3288. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3289. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3290. addr0 = dev[0].p2p_dev_addr()
  3291. class TestDbusP2p(TestDbus):
  3292. def __init__(self, bus):
  3293. TestDbus.__init__(self, bus)
  3294. self.done = False
  3295. def __enter__(self):
  3296. gobject.timeout_add(1, self.run_test)
  3297. gobject.timeout_add(15000, self.timeout)
  3298. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3299. "GroupStarted")
  3300. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3301. "GroupFinished")
  3302. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  3303. "StaAuthorized")
  3304. self.loop.run()
  3305. return self
  3306. def groupStarted(self, properties):
  3307. logger.debug("groupStarted: " + str(properties))
  3308. g_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3309. properties['group_object'])
  3310. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  3311. dbus_interface=dbus.PROPERTIES_IFACE,
  3312. byte_arrays=True)
  3313. bssid = ':'.join([binascii.hexlify(l) for l in res['BSSID']])
  3314. pin = '12345670'
  3315. params = { 'Role': 'enrollee',
  3316. 'Type': 'pin',
  3317. 'Pin': pin }
  3318. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3319. properties['interface_object'])
  3320. wps = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_WPS)
  3321. wps.Start(params)
  3322. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3323. dev1.scan_for_bss(bssid, freq=2412)
  3324. dev1.request("WPS_PIN " + bssid + " " + pin)
  3325. self.group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3326. def groupFinished(self, properties):
  3327. logger.debug("groupFinished: " + str(properties))
  3328. self.done = True
  3329. self.loop.quit()
  3330. def staAuthorized(self, name):
  3331. logger.debug("staAuthorized: " + name)
  3332. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3333. dev1.request("DISCONNECT")
  3334. self.group_p2p.Disconnect()
  3335. def run_test(self, *args):
  3336. logger.debug("run_test")
  3337. params = dbus.Dictionary({'frequency': 2412})
  3338. p2p.GroupAdd(params)
  3339. return False
  3340. def success(self):
  3341. return self.done
  3342. with TestDbusP2p(bus) as t:
  3343. if not t.success():
  3344. raise Exception("Expected signals not seen")
  3345. def test_dbus_p2p_join(dev, apdev):
  3346. """D-Bus P2P join an autonomous GO"""
  3347. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3348. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3349. addr1 = dev[1].p2p_dev_addr()
  3350. addr2 = dev[2].p2p_dev_addr()
  3351. dev[1].p2p_start_go(freq=2412)
  3352. dev1_group_ifname = dev[1].group_ifname
  3353. dev[2].p2p_listen()
  3354. class TestDbusP2p(TestDbus):
  3355. def __init__(self, bus):
  3356. TestDbus.__init__(self, bus)
  3357. self.done = False
  3358. self.peer = None
  3359. self.go = None
  3360. def __enter__(self):
  3361. gobject.timeout_add(1, self.run_test)
  3362. gobject.timeout_add(15000, self.timeout)
  3363. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3364. "DeviceFound")
  3365. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3366. "GroupStarted")
  3367. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3368. "GroupFinished")
  3369. self.add_signal(self.invitationResult, WPAS_DBUS_IFACE_P2PDEVICE,
  3370. "InvitationResult")
  3371. self.loop.run()
  3372. return self
  3373. def deviceFound(self, path):
  3374. logger.debug("deviceFound: path=%s" % path)
  3375. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  3376. res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  3377. dbus_interface=dbus.PROPERTIES_IFACE,
  3378. byte_arrays=True)
  3379. logger.debug('peer properties: ' + str(res))
  3380. if addr2.replace(':','') in path:
  3381. self.peer = path
  3382. elif addr1.replace(':','') in path:
  3383. self.go = path
  3384. if self.peer and self.go:
  3385. logger.info("Join the group")
  3386. p2p.StopFind()
  3387. args = { 'peer': self.go,
  3388. 'join': True,
  3389. 'wps_method': 'pin',
  3390. 'frequency': 2412 }
  3391. pin = p2p.Connect(args)
  3392. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3393. dev1.group_ifname = dev1_group_ifname
  3394. dev1.group_request("WPS_PIN any " + pin)
  3395. def groupStarted(self, properties):
  3396. logger.debug("groupStarted: " + str(properties))
  3397. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3398. properties['interface_object'])
  3399. role = g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Role",
  3400. dbus_interface=dbus.PROPERTIES_IFACE)
  3401. if role != "client":
  3402. raise Exception("Unexpected role reported: " + role)
  3403. group = g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Group",
  3404. dbus_interface=dbus.PROPERTIES_IFACE)
  3405. if group != properties['group_object']:
  3406. raise Exception("Unexpected Group reported: " + str(group))
  3407. go = g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PeerGO",
  3408. dbus_interface=dbus.PROPERTIES_IFACE)
  3409. if go != self.go:
  3410. raise Exception("Unexpected PeerGO value: " + str(go))
  3411. g_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3412. properties['group_object'])
  3413. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  3414. dbus_interface=dbus.PROPERTIES_IFACE,
  3415. byte_arrays=True)
  3416. logger.debug("Group properties: " + str(res))
  3417. ext = dbus.ByteArray("\x11\x22\x33\x44")
  3418. try:
  3419. # Set(WPSVendorExtensions) not allowed for P2P Client
  3420. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
  3421. dbus_interface=dbus.PROPERTIES_IFACE)
  3422. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  3423. except dbus.exceptions.DBusException, e:
  3424. if "Error.Failed: Failed to set property" not in str(e):
  3425. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  3426. group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3427. args = { 'duration1': 30000, 'interval1': 102400,
  3428. 'duration2': 20000, 'interval2': 102400 }
  3429. group_p2p.PresenceRequest(args)
  3430. args = { 'peer': self.peer }
  3431. group_p2p.Invite(args)
  3432. def groupFinished(self, properties):
  3433. logger.debug("groupFinished: " + str(properties))
  3434. self.done = True
  3435. self.loop.quit()
  3436. def invitationResult(self, result):
  3437. logger.debug("invitationResult: " + str(result))
  3438. if result['status'] != 1:
  3439. raise Exception("Unexpected invitation result: " + str(result))
  3440. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3441. dev1.group_ifname = dev1_group_ifname
  3442. dev1.remove_group()
  3443. def run_test(self, *args):
  3444. logger.debug("run_test")
  3445. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  3446. return False
  3447. def success(self):
  3448. return self.done
  3449. with TestDbusP2p(bus) as t:
  3450. if not t.success():
  3451. raise Exception("Expected signals not seen")
  3452. dev[2].p2p_stop_find()
  3453. def test_dbus_p2p_invitation_received(dev, apdev):
  3454. """D-Bus P2P and InvitationReceived"""
  3455. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3456. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3457. form(dev[0], dev[1])
  3458. addr0 = dev[0].p2p_dev_addr()
  3459. dev[0].p2p_listen()
  3460. dev[0].global_request("SET persistent_reconnect 0")
  3461. if not dev[1].discover_peer(addr0, social=True):
  3462. raise Exception("Peer " + addr0 + " not found")
  3463. peer = dev[1].get_peer(addr0)
  3464. class TestDbusP2p(TestDbus):
  3465. def __init__(self, bus):
  3466. TestDbus.__init__(self, bus)
  3467. self.done = False
  3468. def __enter__(self):
  3469. gobject.timeout_add(1, self.run_test)
  3470. gobject.timeout_add(15000, self.timeout)
  3471. self.add_signal(self.invitationReceived, WPAS_DBUS_IFACE_P2PDEVICE,
  3472. "InvitationReceived")
  3473. self.loop.run()
  3474. return self
  3475. def invitationReceived(self, result):
  3476. logger.debug("invitationReceived: " + str(result))
  3477. self.done = True
  3478. self.loop.quit()
  3479. def run_test(self, *args):
  3480. logger.debug("run_test")
  3481. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3482. cmd = "P2P_INVITE persistent=" + peer['persistent'] + " peer=" + addr0
  3483. dev1.global_request(cmd)
  3484. return False
  3485. def success(self):
  3486. return self.done
  3487. with TestDbusP2p(bus) as t:
  3488. if not t.success():
  3489. raise Exception("Expected signals not seen")
  3490. dev[0].p2p_stop_find()
  3491. dev[1].p2p_stop_find()
  3492. def test_dbus_p2p_config(dev, apdev):
  3493. """D-Bus Get/Set P2PDeviceConfig"""
  3494. try:
  3495. _test_dbus_p2p_config(dev, apdev)
  3496. finally:
  3497. dev[0].request("P2P_SET ssid_postfix ")
  3498. def _test_dbus_p2p_config(dev, apdev):
  3499. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3500. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3501. res = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3502. dbus_interface=dbus.PROPERTIES_IFACE,
  3503. byte_arrays=True)
  3504. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig", res,
  3505. dbus_interface=dbus.PROPERTIES_IFACE)
  3506. res2 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3507. dbus_interface=dbus.PROPERTIES_IFACE,
  3508. byte_arrays=True)
  3509. if len(res) != len(res2):
  3510. raise Exception("Different number of parameters")
  3511. for k in res:
  3512. if res[k] != res2[k]:
  3513. raise Exception("Parameter %s value changes" % k)
  3514. changes = { 'SsidPostfix': 'foo',
  3515. 'VendorExtension': [ dbus.ByteArray('\x11\x22\x33\x44') ],
  3516. 'SecondaryDeviceTypes': [ dbus.ByteArray('\x11\x22\x33\x44\x55\x66\x77\x88') ]}
  3517. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3518. dbus.Dictionary(changes, signature='sv'),
  3519. dbus_interface=dbus.PROPERTIES_IFACE)
  3520. res2 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3521. dbus_interface=dbus.PROPERTIES_IFACE,
  3522. byte_arrays=True)
  3523. logger.debug("P2PDeviceConfig: " + str(res2))
  3524. if 'VendorExtension' not in res2 or len(res2['VendorExtension']) != 1:
  3525. raise Exception("VendorExtension does not match")
  3526. if 'SecondaryDeviceTypes' not in res2 or len(res2['SecondaryDeviceTypes']) != 1:
  3527. raise Exception("SecondaryDeviceType does not match")
  3528. changes = { 'SsidPostfix': '',
  3529. 'VendorExtension': dbus.Array([], signature="ay"),
  3530. 'SecondaryDeviceTypes': dbus.Array([], signature="ay") }
  3531. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3532. dbus.Dictionary(changes, signature='sv'),
  3533. dbus_interface=dbus.PROPERTIES_IFACE)
  3534. res3 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3535. dbus_interface=dbus.PROPERTIES_IFACE,
  3536. byte_arrays=True)
  3537. logger.debug("P2PDeviceConfig: " + str(res3))
  3538. if 'VendorExtension' in res3:
  3539. raise Exception("VendorExtension not removed")
  3540. if 'SecondaryDeviceTypes' in res3:
  3541. raise Exception("SecondaryDeviceType not removed")
  3542. try:
  3543. dev[0].request("P2P_SET disabled 1")
  3544. if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3545. dbus_interface=dbus.PROPERTIES_IFACE,
  3546. byte_arrays=True)
  3547. raise Exception("Invalid Get(P2PDeviceConfig) accepted")
  3548. except dbus.exceptions.DBusException, e:
  3549. if "Error.Failed: P2P is not available for this interface" not in str(e):
  3550. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  3551. finally:
  3552. dev[0].request("P2P_SET disabled 0")
  3553. try:
  3554. dev[0].request("P2P_SET disabled 1")
  3555. changes = { 'SsidPostfix': 'foo' }
  3556. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3557. dbus.Dictionary(changes, signature='sv'),
  3558. dbus_interface=dbus.PROPERTIES_IFACE)
  3559. raise Exception("Invalid Set(P2PDeviceConfig) accepted")
  3560. except dbus.exceptions.DBusException, e:
  3561. if "Error.Failed: P2P is not available for this interface" not in str(e):
  3562. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  3563. finally:
  3564. dev[0].request("P2P_SET disabled 0")
  3565. tests = [ { 'DeviceName': 123 },
  3566. { 'SsidPostfix': 123 },
  3567. { 'Foo': 'Bar' } ]
  3568. for changes in tests:
  3569. try:
  3570. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3571. dbus.Dictionary(changes, signature='sv'),
  3572. dbus_interface=dbus.PROPERTIES_IFACE)
  3573. raise Exception("Invalid Set(P2PDeviceConfig) accepted")
  3574. except dbus.exceptions.DBusException, e:
  3575. if "InvalidArgs" not in str(e):
  3576. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  3577. def test_dbus_p2p_persistent(dev, apdev):
  3578. """D-Bus P2P persistent group"""
  3579. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3580. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3581. class TestDbusP2p(TestDbus):
  3582. def __init__(self, bus):
  3583. TestDbus.__init__(self, bus)
  3584. def __enter__(self):
  3585. gobject.timeout_add(1, self.run_test)
  3586. gobject.timeout_add(15000, self.timeout)
  3587. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3588. "GroupStarted")
  3589. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3590. "GroupFinished")
  3591. self.add_signal(self.persistentGroupAdded,
  3592. WPAS_DBUS_IFACE_P2PDEVICE,
  3593. "PersistentGroupAdded")
  3594. self.loop.run()
  3595. return self
  3596. def groupStarted(self, properties):
  3597. logger.debug("groupStarted: " + str(properties))
  3598. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3599. properties['interface_object'])
  3600. group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3601. group_p2p.Disconnect()
  3602. def groupFinished(self, properties):
  3603. logger.debug("groupFinished: " + str(properties))
  3604. self.loop.quit()
  3605. def persistentGroupAdded(self, path, properties):
  3606. logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
  3607. self.persistent = path
  3608. def run_test(self, *args):
  3609. logger.debug("run_test")
  3610. params = dbus.Dictionary({'persistent': True,
  3611. 'frequency': 2412})
  3612. logger.info("Add a persistent group")
  3613. p2p.GroupAdd(params)
  3614. return False
  3615. def success(self):
  3616. return True
  3617. with TestDbusP2p(bus) as t:
  3618. if not t.success():
  3619. raise Exception("Expected signals not seen")
  3620. persistent = t.persistent
  3621. p_obj = bus.get_object(WPAS_DBUS_SERVICE, persistent)
  3622. res = p_obj.Get(WPAS_DBUS_PERSISTENT_GROUP, "Properties",
  3623. dbus_interface=dbus.PROPERTIES_IFACE, byte_arrays=True)
  3624. logger.info("Persistent group Properties: " + str(res))
  3625. vals = dbus.Dictionary({ 'ssid': 'DIRECT-foo' }, signature='sv')
  3626. p_obj.Set(WPAS_DBUS_PERSISTENT_GROUP, "Properties", vals,
  3627. dbus_interface=dbus.PROPERTIES_IFACE)
  3628. res2 = p_obj.Get(WPAS_DBUS_PERSISTENT_GROUP, "Properties",
  3629. dbus_interface=dbus.PROPERTIES_IFACE)
  3630. if len(res) != len(res2):
  3631. raise Exception("Different number of parameters")
  3632. for k in res:
  3633. if k != 'ssid' and res[k] != res2[k]:
  3634. raise Exception("Parameter %s value changes" % k)
  3635. if res2['ssid'] != '"DIRECT-foo"':
  3636. raise Exception("Unexpected ssid")
  3637. args = dbus.Dictionary({ 'ssid': 'DIRECT-testing',
  3638. 'psk': '1234567890' }, signature='sv')
  3639. group = p2p.AddPersistentGroup(args)
  3640. groups = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PersistentGroups",
  3641. dbus_interface=dbus.PROPERTIES_IFACE)
  3642. if len(groups) != 2:
  3643. raise Exception("Unexpected number of persistent groups: " + str(groups))
  3644. p2p.RemoveAllPersistentGroups()
  3645. groups = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PersistentGroups",
  3646. dbus_interface=dbus.PROPERTIES_IFACE)
  3647. if len(groups) != 0:
  3648. raise Exception("Unexpected number of persistent groups: " + str(groups))
  3649. try:
  3650. p2p.RemovePersistentGroup(persistent)
  3651. raise Exception("Invalid RemovePersistentGroup accepted")
  3652. except dbus.exceptions.DBusException, e:
  3653. if "NetworkUnknown: There is no such persistent group" not in str(e):
  3654. raise Exception("Unexpected error message for invalid RemovePersistentGroup: " + str(e))
  3655. def test_dbus_p2p_reinvoke_persistent(dev, apdev):
  3656. """D-Bus P2P reinvoke persistent group"""
  3657. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3658. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3659. addr0 = dev[0].p2p_dev_addr()
  3660. class TestDbusP2p(TestDbus):
  3661. def __init__(self, bus):
  3662. TestDbus.__init__(self, bus)
  3663. self.first = True
  3664. self.waiting_end = False
  3665. self.done = False
  3666. self.invited = False
  3667. def __enter__(self):
  3668. gobject.timeout_add(1, self.run_test)
  3669. gobject.timeout_add(15000, self.timeout)
  3670. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3671. "DeviceFound")
  3672. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3673. "GroupStarted")
  3674. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3675. "GroupFinished")
  3676. self.add_signal(self.persistentGroupAdded,
  3677. WPAS_DBUS_IFACE_P2PDEVICE,
  3678. "PersistentGroupAdded")
  3679. self.add_signal(self.provisionDiscoveryRequestDisplayPin,
  3680. WPAS_DBUS_IFACE_P2PDEVICE,
  3681. "ProvisionDiscoveryRequestDisplayPin")
  3682. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  3683. "StaAuthorized")
  3684. self.loop.run()
  3685. return self
  3686. def groupStarted(self, properties):
  3687. logger.debug("groupStarted: " + str(properties))
  3688. self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3689. properties['interface_object'])
  3690. if not self.invited:
  3691. g_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3692. properties['group_object'])
  3693. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  3694. dbus_interface=dbus.PROPERTIES_IFACE,
  3695. byte_arrays=True)
  3696. bssid = ':'.join([binascii.hexlify(l) for l in res['BSSID']])
  3697. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3698. dev1.scan_for_bss(bssid, freq=2412)
  3699. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 join")
  3700. def groupFinished(self, properties):
  3701. logger.debug("groupFinished: " + str(properties))
  3702. if self.invited:
  3703. self.done = True
  3704. self.loop.quit()
  3705. else:
  3706. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3707. dev1.global_request("SET persistent_reconnect 1")
  3708. dev1.p2p_listen()
  3709. args = { 'persistent_group_object': dbus.ObjectPath(path),
  3710. 'peer': self.peer_path }
  3711. try:
  3712. pin = p2p.Invite(args)
  3713. raise Exception("Invalid Invite accepted")
  3714. except dbus.exceptions.DBusException, e:
  3715. if "InvalidArgs" not in str(e):
  3716. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  3717. args = { 'persistent_group_object': self.persistent,
  3718. 'peer': self.peer_path }
  3719. pin = p2p.Invite(args)
  3720. self.invited = True
  3721. self.sta_group_ev = dev1.wait_global_event(["P2P-GROUP-STARTED"],
  3722. timeout=15)
  3723. if self.sta_group_ev is None:
  3724. raise Exception("P2P-GROUP-STARTED event not seen")
  3725. def persistentGroupAdded(self, path, properties):
  3726. logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
  3727. self.persistent = path
  3728. def deviceFound(self, path):
  3729. logger.debug("deviceFound: path=%s" % path)
  3730. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  3731. self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  3732. dbus_interface=dbus.PROPERTIES_IFACE,
  3733. byte_arrays=True)
  3734. def provisionDiscoveryRequestDisplayPin(self, peer_object, pin):
  3735. logger.debug("provisionDiscoveryRequestDisplayPin - peer=%s pin=%s" % (peer_object, pin))
  3736. self.peer_path = peer_object
  3737. peer = binascii.unhexlify(peer_object.split('/')[-1])
  3738. addr = ""
  3739. for p in peer:
  3740. if len(addr) > 0:
  3741. addr += ':'
  3742. addr += '%02x' % ord(p)
  3743. params = { 'Role': 'registrar',
  3744. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  3745. 'Bssid': self.peer['DeviceAddress'],
  3746. 'Type': 'pin',
  3747. 'Pin': '12345670' }
  3748. logger.info("Authorize peer to connect to the group")
  3749. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3750. wps = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_WPS)
  3751. wps.Start(params)
  3752. self.sta_group_ev = dev1.wait_global_event(["P2P-GROUP-STARTED"],
  3753. timeout=15)
  3754. if self.sta_group_ev is None:
  3755. raise Exception("P2P-GROUP-STARTED event not seen")
  3756. def staAuthorized(self, name):
  3757. logger.debug("staAuthorized: " + name)
  3758. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3759. dev1.group_form_result(self.sta_group_ev)
  3760. dev1.remove_group()
  3761. ev = dev1.wait_global_event(["P2P-GROUP-REMOVED"], timeout=10)
  3762. if ev is None:
  3763. raise Exception("Group removal timed out")
  3764. group_p2p = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3765. group_p2p.Disconnect()
  3766. def run_test(self, *args):
  3767. logger.debug("run_test")
  3768. params = dbus.Dictionary({'persistent': True,
  3769. 'frequency': 2412})
  3770. logger.info("Add a persistent group")
  3771. p2p.GroupAdd(params)
  3772. return False
  3773. def success(self):
  3774. return self.done
  3775. with TestDbusP2p(bus) as t:
  3776. if not t.success():
  3777. raise Exception("Expected signals not seen")
  3778. def test_dbus_p2p_go_neg_rx(dev, apdev):
  3779. """D-Bus P2P GO Negotiation receive"""
  3780. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3781. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3782. addr0 = dev[0].p2p_dev_addr()
  3783. class TestDbusP2p(TestDbus):
  3784. def __init__(self, bus):
  3785. TestDbus.__init__(self, bus)
  3786. self.done = False
  3787. def __enter__(self):
  3788. gobject.timeout_add(1, self.run_test)
  3789. gobject.timeout_add(15000, self.timeout)
  3790. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3791. "DeviceFound")
  3792. self.add_signal(self.goNegotiationRequest,
  3793. WPAS_DBUS_IFACE_P2PDEVICE,
  3794. "GONegotiationRequest",
  3795. byte_arrays=True)
  3796. self.add_signal(self.goNegotiationSuccess,
  3797. WPAS_DBUS_IFACE_P2PDEVICE,
  3798. "GONegotiationSuccess",
  3799. byte_arrays=True)
  3800. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3801. "GroupStarted")
  3802. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3803. "GroupFinished")
  3804. self.loop.run()
  3805. return self
  3806. def deviceFound(self, path):
  3807. logger.debug("deviceFound: path=%s" % path)
  3808. def goNegotiationRequest(self, path, dev_passwd_id, go_intent=0):
  3809. logger.debug("goNegotiationRequest: path=%s dev_passwd_id=%d go_intent=%d" % (path, dev_passwd_id, go_intent))
  3810. if dev_passwd_id != 1:
  3811. raise Exception("Unexpected dev_passwd_id=%d" % dev_passwd_id)
  3812. args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
  3813. 'go_intent': 15, 'persistent': False, 'frequency': 5175 }
  3814. try:
  3815. p2p.Connect(args)
  3816. raise Exception("Invalid Connect accepted")
  3817. except dbus.exceptions.DBusException, e:
  3818. if "ConnectChannelUnsupported" not in str(e):
  3819. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  3820. args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
  3821. 'go_intent': 15, 'persistent': False }
  3822. p2p.Connect(args)
  3823. def goNegotiationSuccess(self, properties):
  3824. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3825. def groupStarted(self, properties):
  3826. logger.debug("groupStarted: " + str(properties))
  3827. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3828. properties['interface_object'])
  3829. group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3830. group_p2p.Disconnect()
  3831. def groupFinished(self, properties):
  3832. logger.debug("groupFinished: " + str(properties))
  3833. self.done = True
  3834. self.loop.quit()
  3835. def run_test(self, *args):
  3836. logger.debug("run_test")
  3837. p2p.Listen(10)
  3838. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3839. if not dev1.discover_peer(addr0):
  3840. raise Exception("Peer not found")
  3841. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 enter")
  3842. return False
  3843. def success(self):
  3844. return self.done
  3845. with TestDbusP2p(bus) as t:
  3846. if not t.success():
  3847. raise Exception("Expected signals not seen")
  3848. def test_dbus_p2p_go_neg_auth(dev, apdev):
  3849. """D-Bus P2P GO Negotiation authorized"""
  3850. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3851. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3852. addr0 = dev[0].p2p_dev_addr()
  3853. dev[1].p2p_listen()
  3854. class TestDbusP2p(TestDbus):
  3855. def __init__(self, bus):
  3856. TestDbus.__init__(self, bus)
  3857. self.done = False
  3858. self.peer_joined = False
  3859. self.peer_disconnected = False
  3860. def __enter__(self):
  3861. gobject.timeout_add(1, self.run_test)
  3862. gobject.timeout_add(15000, self.timeout)
  3863. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3864. "DeviceFound")
  3865. self.add_signal(self.goNegotiationSuccess,
  3866. WPAS_DBUS_IFACE_P2PDEVICE,
  3867. "GONegotiationSuccess",
  3868. byte_arrays=True)
  3869. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3870. "GroupStarted")
  3871. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3872. "GroupFinished")
  3873. self.add_signal(self.staDeauthorized, WPAS_DBUS_IFACE,
  3874. "StaDeauthorized")
  3875. self.add_signal(self.peerJoined, WPAS_DBUS_GROUP,
  3876. "PeerJoined")
  3877. self.add_signal(self.peerDisconnected, WPAS_DBUS_GROUP,
  3878. "PeerDisconnected")
  3879. self.loop.run()
  3880. return self
  3881. def deviceFound(self, path):
  3882. logger.debug("deviceFound: path=%s" % path)
  3883. args = { 'peer': path, 'wps_method': 'keypad',
  3884. 'go_intent': 15, 'authorize_only': True }
  3885. try:
  3886. p2p.Connect(args)
  3887. raise Exception("Invalid Connect accepted")
  3888. except dbus.exceptions.DBusException, e:
  3889. if "InvalidArgs" not in str(e):
  3890. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  3891. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  3892. 'go_intent': 15, 'authorize_only': True }
  3893. p2p.Connect(args)
  3894. p2p.Listen(10)
  3895. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3896. if not dev1.discover_peer(addr0):
  3897. raise Exception("Peer not found")
  3898. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=0")
  3899. ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
  3900. if ev is None:
  3901. raise Exception("Group formation timed out")
  3902. self.sta_group_ev = ev
  3903. def goNegotiationSuccess(self, properties):
  3904. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3905. def groupStarted(self, properties):
  3906. logger.debug("groupStarted: " + str(properties))
  3907. self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3908. properties['interface_object'])
  3909. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3910. dev1.group_form_result(self.sta_group_ev)
  3911. dev1.remove_group()
  3912. def staDeauthorized(self, name):
  3913. logger.debug("staDeuthorized: " + name)
  3914. group_p2p = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3915. group_p2p.Disconnect()
  3916. def peerJoined(self, peer):
  3917. logger.debug("peerJoined: " + peer)
  3918. self.peer_joined = True
  3919. def peerDisconnected(self, peer):
  3920. logger.debug("peerDisconnected: " + peer)
  3921. self.peer_disconnected = True
  3922. def groupFinished(self, properties):
  3923. logger.debug("groupFinished: " + str(properties))
  3924. self.done = True
  3925. self.loop.quit()
  3926. def run_test(self, *args):
  3927. logger.debug("run_test")
  3928. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  3929. return False
  3930. def success(self):
  3931. return self.done and self.peer_joined and self.peer_disconnected
  3932. with TestDbusP2p(bus) as t:
  3933. if not t.success():
  3934. raise Exception("Expected signals not seen")
  3935. def test_dbus_p2p_go_neg_init(dev, apdev):
  3936. """D-Bus P2P GO Negotiation initiation"""
  3937. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3938. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3939. addr0 = dev[0].p2p_dev_addr()
  3940. dev[1].p2p_listen()
  3941. class TestDbusP2p(TestDbus):
  3942. def __init__(self, bus):
  3943. TestDbus.__init__(self, bus)
  3944. self.done = False
  3945. self.peer_group_added = False
  3946. self.peer_group_removed = False
  3947. def __enter__(self):
  3948. gobject.timeout_add(1, self.run_test)
  3949. gobject.timeout_add(15000, self.timeout)
  3950. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3951. "DeviceFound")
  3952. self.add_signal(self.goNegotiationSuccess,
  3953. WPAS_DBUS_IFACE_P2PDEVICE,
  3954. "GONegotiationSuccess",
  3955. byte_arrays=True)
  3956. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3957. "GroupStarted")
  3958. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3959. "GroupFinished")
  3960. self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
  3961. "PropertiesChanged")
  3962. self.loop.run()
  3963. return self
  3964. def deviceFound(self, path):
  3965. logger.debug("deviceFound: path=%s" % path)
  3966. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3967. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  3968. 'go_intent': 0 }
  3969. p2p.Connect(args)
  3970. ev = dev1.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
  3971. if ev is None:
  3972. raise Exception("Timeout while waiting for GO Neg Request")
  3973. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=15")
  3974. ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
  3975. if ev is None:
  3976. raise Exception("Group formation timed out")
  3977. self.sta_group_ev = ev
  3978. def goNegotiationSuccess(self, properties):
  3979. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3980. def groupStarted(self, properties):
  3981. logger.debug("groupStarted: " + str(properties))
  3982. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3983. properties['interface_object'])
  3984. group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3985. group_p2p.Disconnect()
  3986. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3987. dev1.group_form_result(self.sta_group_ev)
  3988. dev1.remove_group()
  3989. def groupFinished(self, properties):
  3990. logger.debug("groupFinished: " + str(properties))
  3991. self.done = True
  3992. def propertiesChanged(self, interface_name, changed_properties,
  3993. invalidated_properties):
  3994. logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
  3995. if interface_name != WPAS_DBUS_P2P_PEER:
  3996. return
  3997. if "Groups" not in changed_properties:
  3998. return
  3999. if len(changed_properties["Groups"]) > 0:
  4000. self.peer_group_added = True
  4001. if len(changed_properties["Groups"]) == 0:
  4002. if not self.peer_group_added:
  4003. # This is likely a leftover event from an earlier test case,
  4004. # ignore it to allow this test case to go through its steps.
  4005. logger.info("Ignore propertiesChanged indicating group removal before group has been added")
  4006. return
  4007. self.peer_group_removed = True
  4008. self.loop.quit()
  4009. def run_test(self, *args):
  4010. logger.debug("run_test")
  4011. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  4012. return False
  4013. def success(self):
  4014. return self.done and self.peer_group_added and self.peer_group_removed
  4015. with TestDbusP2p(bus) as t:
  4016. if not t.success():
  4017. raise Exception("Expected signals not seen")
  4018. def test_dbus_p2p_group_termination_by_go(dev, apdev):
  4019. """D-Bus P2P group removal on GO terminating the group"""
  4020. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4021. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  4022. addr0 = dev[0].p2p_dev_addr()
  4023. dev[1].p2p_listen()
  4024. class TestDbusP2p(TestDbus):
  4025. def __init__(self, bus):
  4026. TestDbus.__init__(self, bus)
  4027. self.done = False
  4028. self.peer_group_added = False
  4029. self.peer_group_removed = False
  4030. def __enter__(self):
  4031. gobject.timeout_add(1, self.run_test)
  4032. gobject.timeout_add(15000, self.timeout)
  4033. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  4034. "DeviceFound")
  4035. self.add_signal(self.goNegotiationSuccess,
  4036. WPAS_DBUS_IFACE_P2PDEVICE,
  4037. "GONegotiationSuccess",
  4038. byte_arrays=True)
  4039. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  4040. "GroupStarted")
  4041. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  4042. "GroupFinished")
  4043. self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
  4044. "PropertiesChanged")
  4045. self.loop.run()
  4046. return self
  4047. def deviceFound(self, path):
  4048. logger.debug("deviceFound: path=%s" % path)
  4049. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  4050. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  4051. 'go_intent': 0 }
  4052. p2p.Connect(args)
  4053. ev = dev1.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
  4054. if ev is None:
  4055. raise Exception("Timeout while waiting for GO Neg Request")
  4056. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=15")
  4057. ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
  4058. if ev is None:
  4059. raise Exception("Group formation timed out")
  4060. self.sta_group_ev = ev
  4061. def goNegotiationSuccess(self, properties):
  4062. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  4063. def groupStarted(self, properties):
  4064. logger.debug("groupStarted: " + str(properties))
  4065. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  4066. properties['interface_object'])
  4067. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  4068. dev1.group_form_result(self.sta_group_ev)
  4069. dev1.remove_group()
  4070. def groupFinished(self, properties):
  4071. logger.debug("groupFinished: " + str(properties))
  4072. self.done = True
  4073. def propertiesChanged(self, interface_name, changed_properties,
  4074. invalidated_properties):
  4075. logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
  4076. if interface_name != WPAS_DBUS_P2P_PEER:
  4077. return
  4078. if "Groups" not in changed_properties:
  4079. return
  4080. if len(changed_properties["Groups"]) > 0:
  4081. self.peer_group_added = True
  4082. if len(changed_properties["Groups"]) == 0 and self.peer_group_added:
  4083. self.peer_group_removed = True
  4084. self.loop.quit()
  4085. def run_test(self, *args):
  4086. logger.debug("run_test")
  4087. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  4088. return False
  4089. def success(self):
  4090. return self.done and self.peer_group_added and self.peer_group_removed
  4091. with TestDbusP2p(bus) as t:
  4092. if not t.success():
  4093. raise Exception("Expected signals not seen")
  4094. def test_dbus_p2p_group_idle_timeout(dev, apdev):
  4095. """D-Bus P2P group removal on idle timeout"""
  4096. try:
  4097. dev[0].global_request("SET p2p_group_idle 1")
  4098. _test_dbus_p2p_group_idle_timeout(dev, apdev)
  4099. finally:
  4100. dev[0].global_request("SET p2p_group_idle 0")
  4101. def _test_dbus_p2p_group_idle_timeout(dev, apdev):
  4102. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4103. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  4104. addr0 = dev[0].p2p_dev_addr()
  4105. dev[1].p2p_listen()
  4106. class TestDbusP2p(TestDbus):
  4107. def __init__(self, bus):
  4108. TestDbus.__init__(self, bus)
  4109. self.done = False
  4110. self.group_started = False
  4111. self.peer_group_added = False
  4112. self.peer_group_removed = False
  4113. def __enter__(self):
  4114. gobject.timeout_add(1, self.run_test)
  4115. gobject.timeout_add(15000, self.timeout)
  4116. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  4117. "DeviceFound")
  4118. self.add_signal(self.goNegotiationSuccess,
  4119. WPAS_DBUS_IFACE_P2PDEVICE,
  4120. "GONegotiationSuccess",
  4121. byte_arrays=True)
  4122. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  4123. "GroupStarted")
  4124. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  4125. "GroupFinished")
  4126. self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
  4127. "PropertiesChanged")
  4128. self.loop.run()
  4129. return self
  4130. def deviceFound(self, path):
  4131. logger.debug("deviceFound: path=%s" % path)
  4132. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  4133. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  4134. 'go_intent': 0 }
  4135. p2p.Connect(args)
  4136. ev = dev1.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
  4137. if ev is None:
  4138. raise Exception("Timeout while waiting for GO Neg Request")
  4139. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=15")
  4140. ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
  4141. if ev is None:
  4142. raise Exception("Group formation timed out")
  4143. self.sta_group_ev = ev
  4144. def goNegotiationSuccess(self, properties):
  4145. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  4146. def groupStarted(self, properties):
  4147. logger.debug("groupStarted: " + str(properties))
  4148. self.group_started = True
  4149. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  4150. properties['interface_object'])
  4151. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  4152. dev1.group_form_result(self.sta_group_ev)
  4153. ifaddr = dev1.group_request("STA-FIRST").splitlines()[0]
  4154. # Force disassociation with different reason code so that the
  4155. # P2P Client using D-Bus does not get normal group termination event
  4156. # from the GO.
  4157. dev1.group_request("DEAUTHENTICATE " + ifaddr + " reason=0 test=0")
  4158. dev1.remove_group()
  4159. def groupFinished(self, properties):
  4160. logger.debug("groupFinished: " + str(properties))
  4161. self.done = True
  4162. def propertiesChanged(self, interface_name, changed_properties,
  4163. invalidated_properties):
  4164. logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
  4165. if interface_name != WPAS_DBUS_P2P_PEER:
  4166. return
  4167. if not self.group_started:
  4168. return
  4169. if "Groups" not in changed_properties:
  4170. return
  4171. if len(changed_properties["Groups"]) > 0:
  4172. self.peer_group_added = True
  4173. if len(changed_properties["Groups"]) == 0:
  4174. self.peer_group_removed = True
  4175. self.loop.quit()
  4176. def run_test(self, *args):
  4177. logger.debug("run_test")
  4178. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  4179. return False
  4180. def success(self):
  4181. return self.done and self.peer_group_added and self.peer_group_removed
  4182. with TestDbusP2p(bus) as t:
  4183. if not t.success():
  4184. raise Exception("Expected signals not seen")
  4185. def test_dbus_p2p_wps_failure(dev, apdev):
  4186. """D-Bus P2P WPS failure"""
  4187. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4188. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  4189. addr0 = dev[0].p2p_dev_addr()
  4190. class TestDbusP2p(TestDbus):
  4191. def __init__(self, bus):
  4192. TestDbus.__init__(self, bus)
  4193. self.wps_failed = False
  4194. self.formation_failure = False
  4195. def __enter__(self):
  4196. gobject.timeout_add(1, self.run_test)
  4197. gobject.timeout_add(15000, self.timeout)
  4198. self.add_signal(self.goNegotiationRequest,
  4199. WPAS_DBUS_IFACE_P2PDEVICE,
  4200. "GONegotiationRequest",
  4201. byte_arrays=True)
  4202. self.add_signal(self.goNegotiationSuccess,
  4203. WPAS_DBUS_IFACE_P2PDEVICE,
  4204. "GONegotiationSuccess",
  4205. byte_arrays=True)
  4206. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  4207. "GroupStarted")
  4208. self.add_signal(self.wpsFailed, WPAS_DBUS_IFACE_P2PDEVICE,
  4209. "WpsFailed")
  4210. self.add_signal(self.groupFormationFailure,
  4211. WPAS_DBUS_IFACE_P2PDEVICE,
  4212. "GroupFormationFailure")
  4213. self.loop.run()
  4214. return self
  4215. def goNegotiationRequest(self, path, dev_passwd_id, go_intent=0):
  4216. logger.debug("goNegotiationRequest: path=%s dev_passwd_id=%d go_intent=%d" % (path, dev_passwd_id, go_intent))
  4217. if dev_passwd_id != 1:
  4218. raise Exception("Unexpected dev_passwd_id=%d" % dev_passwd_id)
  4219. args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
  4220. 'go_intent': 15 }
  4221. p2p.Connect(args)
  4222. def goNegotiationSuccess(self, properties):
  4223. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  4224. def groupStarted(self, properties):
  4225. logger.debug("groupStarted: " + str(properties))
  4226. raise Exception("Unexpected GroupStarted")
  4227. def wpsFailed(self, name, args):
  4228. logger.debug("wpsFailed - name=%s args=%s" % (name, str(args)))
  4229. self.wps_failed = True
  4230. if self.formation_failure:
  4231. self.loop.quit()
  4232. def groupFormationFailure(self, reason):
  4233. logger.debug("groupFormationFailure - reason=%s" % reason)
  4234. self.formation_failure = True
  4235. if self.wps_failed:
  4236. self.loop.quit()
  4237. def run_test(self, *args):
  4238. logger.debug("run_test")
  4239. p2p.Listen(10)
  4240. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  4241. if not dev1.discover_peer(addr0):
  4242. raise Exception("Peer not found")
  4243. dev1.global_request("P2P_CONNECT " + addr0 + " 87654321 enter")
  4244. return False
  4245. def success(self):
  4246. return self.wps_failed and self.formation_failure
  4247. with TestDbusP2p(bus) as t:
  4248. if not t.success():
  4249. raise Exception("Expected signals not seen")
  4250. def test_dbus_p2p_two_groups(dev, apdev):
  4251. """D-Bus P2P with two concurrent groups"""
  4252. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4253. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  4254. dev[0].request("SET p2p_no_group_iface 0")
  4255. addr0 = dev[0].p2p_dev_addr()
  4256. addr1 = dev[1].p2p_dev_addr()
  4257. addr2 = dev[2].p2p_dev_addr()
  4258. dev[1].p2p_start_go(freq=2412)
  4259. dev1_group_ifname = dev[1].group_ifname
  4260. class TestDbusP2p(TestDbus):
  4261. def __init__(self, bus):
  4262. TestDbus.__init__(self, bus)
  4263. self.done = False
  4264. self.peer = None
  4265. self.go = None
  4266. self.group1 = None
  4267. self.group2 = None
  4268. self.groups_removed = False
  4269. def __enter__(self):
  4270. gobject.timeout_add(1, self.run_test)
  4271. gobject.timeout_add(15000, self.timeout)
  4272. self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
  4273. "PropertiesChanged", byte_arrays=True)
  4274. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  4275. "DeviceFound")
  4276. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  4277. "GroupStarted")
  4278. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  4279. "GroupFinished")
  4280. self.add_signal(self.peerJoined, WPAS_DBUS_GROUP,
  4281. "PeerJoined")
  4282. self.loop.run()
  4283. return self
  4284. def propertiesChanged(self, interface_name, changed_properties,
  4285. invalidated_properties):
  4286. logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
  4287. def deviceFound(self, path):
  4288. logger.debug("deviceFound: path=%s" % path)
  4289. if addr2.replace(':','') in path:
  4290. self.peer = path
  4291. elif addr1.replace(':','') in path:
  4292. self.go = path
  4293. if self.go and not self.group1:
  4294. logger.info("Join the group")
  4295. p2p.StopFind()
  4296. pin = '12345670'
  4297. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  4298. dev1.group_ifname = dev1_group_ifname
  4299. dev1.group_request("WPS_PIN any " + pin)
  4300. args = { 'peer': self.go,
  4301. 'join': True,
  4302. 'wps_method': 'pin',
  4303. 'pin': pin,
  4304. 'frequency': 2412 }
  4305. p2p.Connect(args)
  4306. def groupStarted(self, properties):
  4307. logger.debug("groupStarted: " + str(properties))
  4308. prop = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
  4309. dbus_interface=dbus.PROPERTIES_IFACE)
  4310. logger.debug("p2pdevice properties: " + str(prop))
  4311. g_obj = bus.get_object(WPAS_DBUS_SERVICE,
  4312. properties['group_object'])
  4313. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  4314. dbus_interface=dbus.PROPERTIES_IFACE,
  4315. byte_arrays=True)
  4316. logger.debug("Group properties: " + str(res))
  4317. if not self.group1:
  4318. self.group1 = properties['group_object']
  4319. self.group1iface = properties['interface_object']
  4320. self.g1_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  4321. self.group1iface)
  4322. logger.info("Start autonomous GO")
  4323. params = dbus.Dictionary({ 'frequency': 2412 })
  4324. p2p.GroupAdd(params)
  4325. elif not self.group2:
  4326. self.group2 = properties['group_object']
  4327. self.group2iface = properties['interface_object']
  4328. self.g2_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  4329. self.group2iface)
  4330. self.g2_bssid = res['BSSID']
  4331. if self.group1 and self.group2:
  4332. logger.info("Authorize peer to join the group")
  4333. a2 = binascii.unhexlify(addr2.replace(':',''))
  4334. params = { 'Role': 'enrollee',
  4335. 'P2PDeviceAddress': dbus.ByteArray(a2),
  4336. 'Bssid': dbus.ByteArray(a2),
  4337. 'Type': 'pin',
  4338. 'Pin': '12345670' }
  4339. g_wps = dbus.Interface(self.g2_if_obj, WPAS_DBUS_IFACE_WPS)
  4340. g_wps.Start(params)
  4341. bssid = ':'.join([binascii.hexlify(l) for l in self.g2_bssid])
  4342. dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2')
  4343. dev2.scan_for_bss(bssid, freq=2412)
  4344. dev2.global_request("P2P_CONNECT " + bssid + " 12345670 join freq=2412")
  4345. ev = dev2.wait_global_event(["P2P-GROUP-STARTED"], timeout=15)
  4346. if ev is None:
  4347. raise Exception("Group join timed out")
  4348. self.dev2_group_ev = ev
  4349. def groupFinished(self, properties):
  4350. logger.debug("groupFinished: " + str(properties))
  4351. if self.group1 == properties['group_object']:
  4352. self.group1 = None
  4353. elif self.group2 == properties['group_object']:
  4354. self.group2 = None
  4355. if not self.group1 and not self.group2:
  4356. self.done = True
  4357. self.loop.quit()
  4358. def peerJoined(self, peer):
  4359. logger.debug("peerJoined: " + peer)
  4360. if self.groups_removed:
  4361. return
  4362. self.check_results()
  4363. dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2')
  4364. dev2.group_form_result(self.dev2_group_ev)
  4365. dev2.remove_group()
  4366. logger.info("Disconnect group2")
  4367. group_p2p = dbus.Interface(self.g2_if_obj,
  4368. WPAS_DBUS_IFACE_P2PDEVICE)
  4369. group_p2p.Disconnect()
  4370. logger.info("Disconnect group1")
  4371. group_p2p = dbus.Interface(self.g1_if_obj,
  4372. WPAS_DBUS_IFACE_P2PDEVICE)
  4373. group_p2p.Disconnect()
  4374. self.groups_removed = True
  4375. def check_results(self):
  4376. logger.info("Check results with two concurrent groups in operation")
  4377. g1_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group1)
  4378. res1 = g1_obj.GetAll(WPAS_DBUS_GROUP,
  4379. dbus_interface=dbus.PROPERTIES_IFACE,
  4380. byte_arrays=True)
  4381. g2_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group2)
  4382. res2 = g2_obj.GetAll(WPAS_DBUS_GROUP,
  4383. dbus_interface=dbus.PROPERTIES_IFACE,
  4384. byte_arrays=True)
  4385. logger.info("group1 = " + self.group1)
  4386. logger.debug("Group properties: " + str(res1))
  4387. logger.info("group2 = " + self.group2)
  4388. logger.debug("Group properties: " + str(res2))
  4389. prop = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
  4390. dbus_interface=dbus.PROPERTIES_IFACE)
  4391. logger.debug("p2pdevice properties: " + str(prop))
  4392. if res1['Role'] != 'client':
  4393. raise Exception("Group1 role reported incorrectly: " + res1['Role'])
  4394. if res2['Role'] != 'GO':
  4395. raise Exception("Group2 role reported incorrectly: " + res2['Role'])
  4396. if prop['Role'] != 'device':
  4397. raise Exception("p2pdevice role reported incorrectly: " + prop['Role'])
  4398. if len(res2['Members']) != 1:
  4399. raise Exception("Unexpected Members value for group 2")
  4400. def run_test(self, *args):
  4401. logger.debug("run_test")
  4402. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  4403. return False
  4404. def success(self):
  4405. return self.done
  4406. with TestDbusP2p(bus) as t:
  4407. if not t.success():
  4408. raise Exception("Expected signals not seen")
  4409. dev[1].remove_group()
  4410. def test_dbus_p2p_cancel(dev, apdev):
  4411. """D-Bus P2P Cancel"""
  4412. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4413. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  4414. try:
  4415. p2p.Cancel()
  4416. raise Exception("Unexpected p2p.Cancel() success")
  4417. except dbus.exceptions.DBusException, e:
  4418. pass
  4419. addr0 = dev[0].p2p_dev_addr()
  4420. dev[1].p2p_listen()
  4421. class TestDbusP2p(TestDbus):
  4422. def __init__(self, bus):
  4423. TestDbus.__init__(self, bus)
  4424. self.done = False
  4425. def __enter__(self):
  4426. gobject.timeout_add(1, self.run_test)
  4427. gobject.timeout_add(15000, self.timeout)
  4428. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  4429. "DeviceFound")
  4430. self.loop.run()
  4431. return self
  4432. def deviceFound(self, path):
  4433. logger.debug("deviceFound: path=%s" % path)
  4434. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  4435. 'go_intent': 0 }
  4436. p2p.Connect(args)
  4437. p2p.Cancel()
  4438. self.done = True
  4439. self.loop.quit()
  4440. def run_test(self, *args):
  4441. logger.debug("run_test")
  4442. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  4443. return False
  4444. def success(self):
  4445. return self.done
  4446. with TestDbusP2p(bus) as t:
  4447. if not t.success():
  4448. raise Exception("Expected signals not seen")
  4449. def test_dbus_p2p_ip_addr(dev, apdev):
  4450. """D-Bus P2P and IP address parameters"""
  4451. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4452. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  4453. vals = [ ("IpAddrGo", "192.168.43.1"),
  4454. ("IpAddrMask", "255.255.255.0"),
  4455. ("IpAddrStart", "192.168.43.100"),
  4456. ("IpAddrEnd", "192.168.43.199") ]
  4457. for field, value in vals:
  4458. if_obj.Set(WPAS_DBUS_IFACE, field, value,
  4459. dbus_interface=dbus.PROPERTIES_IFACE)
  4460. val = if_obj.Get(WPAS_DBUS_IFACE, field,
  4461. dbus_interface=dbus.PROPERTIES_IFACE)
  4462. if val != value:
  4463. raise Exception("Unexpected %s value: %s" % (field, val))
  4464. set_ip_addr_info(dev[1])
  4465. dev[0].global_request("SET p2p_go_intent 0")
  4466. req = dev[0].global_request("NFC_GET_HANDOVER_REQ NDEF P2P-CR").rstrip()
  4467. if "FAIL" in req:
  4468. raise Exception("Failed to generate NFC connection handover request")
  4469. sel = dev[1].global_request("NFC_GET_HANDOVER_SEL NDEF P2P-CR").rstrip()
  4470. if "FAIL" in sel:
  4471. raise Exception("Failed to generate NFC connection handover select")
  4472. dev[0].dump_monitor()
  4473. dev[1].dump_monitor()
  4474. res = dev[1].global_request("NFC_REPORT_HANDOVER RESP P2P " + req + " " + sel)
  4475. if "FAIL" in res:
  4476. raise Exception("Failed to report NFC connection handover to wpa_supplicant(resp)")
  4477. res = dev[0].global_request("NFC_REPORT_HANDOVER INIT P2P " + req + " " + sel)
  4478. if "FAIL" in res:
  4479. raise Exception("Failed to report NFC connection handover to wpa_supplicant(init)")
  4480. class TestDbusP2p(TestDbus):
  4481. def __init__(self, bus):
  4482. TestDbus.__init__(self, bus)
  4483. self.done = False
  4484. def __enter__(self):
  4485. gobject.timeout_add(1, self.run_test)
  4486. gobject.timeout_add(15000, self.timeout)
  4487. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  4488. "GroupStarted")
  4489. self.loop.run()
  4490. return self
  4491. def groupStarted(self, properties):
  4492. logger.debug("groupStarted: " + str(properties))
  4493. self.loop.quit()
  4494. if 'IpAddrGo' not in properties:
  4495. logger.info("IpAddrGo missing from GroupStarted")
  4496. ip_addr_go = properties['IpAddrGo']
  4497. addr = "%d.%d.%d.%d" % (ip_addr_go[0], ip_addr_go[1], ip_addr_go[2], ip_addr_go[3])
  4498. if addr != "192.168.42.1":
  4499. logger.info("Unexpected IpAddrGo value: " + addr)
  4500. self.done = True
  4501. def run_test(self, *args):
  4502. logger.debug("run_test")
  4503. return False
  4504. def success(self):
  4505. return self.done
  4506. with TestDbusP2p(bus) as t:
  4507. if not t.success():
  4508. raise Exception("Expected signals not seen")
  4509. def test_dbus_introspect(dev, apdev):
  4510. """D-Bus introspection"""
  4511. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4512. res = if_obj.Introspect(WPAS_DBUS_IFACE,
  4513. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  4514. logger.info("Initial Introspect: " + str(res))
  4515. if res is None or "Introspectable" not in res or "GroupStarted" not in res:
  4516. raise Exception("Unexpected initial Introspect response: " + str(res))
  4517. if "FastReauth" not in res or "PassiveScan" not in res:
  4518. raise Exception("Unexpected initial Introspect response: " + str(res))
  4519. with alloc_fail(dev[0], 1, "wpa_dbus_introspect"):
  4520. res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
  4521. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  4522. logger.info("Introspect: " + str(res2))
  4523. if res2 is not None:
  4524. raise Exception("Unexpected Introspect response")
  4525. with alloc_fail(dev[0], 1, "=add_interface;wpa_dbus_introspect"):
  4526. res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
  4527. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  4528. logger.info("Introspect: " + str(res2))
  4529. if res2 is None:
  4530. raise Exception("No Introspect response")
  4531. if len(res2) >= len(res):
  4532. raise Exception("Unexpected Introspect response")
  4533. with alloc_fail(dev[0], 1, "wpabuf_alloc;add_interface;wpa_dbus_introspect"):
  4534. res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
  4535. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  4536. logger.info("Introspect: " + str(res2))
  4537. if res2 is None:
  4538. raise Exception("No Introspect response")
  4539. if len(res2) >= len(res):
  4540. raise Exception("Unexpected Introspect response")
  4541. with alloc_fail(dev[0], 2, "=add_interface;wpa_dbus_introspect"):
  4542. res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
  4543. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  4544. logger.info("Introspect: " + str(res2))
  4545. if res2 is None:
  4546. raise Exception("No Introspect response")
  4547. if len(res2) >= len(res):
  4548. raise Exception("Unexpected Introspect response")
  4549. def test_dbus_ap(dev, apdev):
  4550. """D-Bus AddNetwork for AP mode"""
  4551. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4552. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  4553. ssid = "test-wpa2-psk"
  4554. passphrase = 'qwertyuiop'
  4555. class TestDbusConnect(TestDbus):
  4556. def __init__(self, bus):
  4557. TestDbus.__init__(self, bus)
  4558. self.started = False
  4559. def __enter__(self):
  4560. gobject.timeout_add(1, self.run_connect)
  4561. gobject.timeout_add(15000, self.timeout)
  4562. self.add_signal(self.networkAdded, WPAS_DBUS_IFACE, "NetworkAdded")
  4563. self.add_signal(self.networkSelected, WPAS_DBUS_IFACE,
  4564. "NetworkSelected")
  4565. self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
  4566. "PropertiesChanged")
  4567. self.loop.run()
  4568. return self
  4569. def networkAdded(self, network, properties):
  4570. logger.debug("networkAdded: %s" % str(network))
  4571. logger.debug(str(properties))
  4572. def networkSelected(self, network):
  4573. logger.debug("networkSelected: %s" % str(network))
  4574. self.network_selected = True
  4575. def propertiesChanged(self, properties):
  4576. logger.debug("propertiesChanged: %s" % str(properties))
  4577. if 'State' in properties and properties['State'] == "completed":
  4578. self.started = True
  4579. self.loop.quit()
  4580. def run_connect(self, *args):
  4581. logger.debug("run_connect")
  4582. args = dbus.Dictionary({ 'ssid': ssid,
  4583. 'key_mgmt': 'WPA-PSK',
  4584. 'psk': passphrase,
  4585. 'mode': 2,
  4586. 'frequency': 2412 },
  4587. signature='sv')
  4588. self.netw = iface.AddNetwork(args)
  4589. iface.SelectNetwork(self.netw)
  4590. return False
  4591. def success(self):
  4592. return self.started
  4593. with TestDbusConnect(bus) as t:
  4594. if not t.success():
  4595. raise Exception("Expected signals not seen")
  4596. dev[1].connect(ssid, psk=passphrase, scan_freq="2412")
  4597. def test_dbus_connect_wpa_eap(dev, apdev):
  4598. """D-Bus AddNetwork and connection with WPA+WPA2-Enterprise AP"""
  4599. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4600. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  4601. ssid = "test-wpa-eap"
  4602. params = hostapd.wpa_eap_params(ssid=ssid)
  4603. params["wpa"] = "3"
  4604. params["rsn_pairwise"] = "CCMP"
  4605. hapd = hostapd.add_ap(apdev[0], params)
  4606. class TestDbusConnect(TestDbus):
  4607. def __init__(self, bus):
  4608. TestDbus.__init__(self, bus)
  4609. self.done = False
  4610. def __enter__(self):
  4611. gobject.timeout_add(1, self.run_connect)
  4612. gobject.timeout_add(15000, self.timeout)
  4613. self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
  4614. "PropertiesChanged")
  4615. self.add_signal(self.eap, WPAS_DBUS_IFACE, "EAP")
  4616. self.loop.run()
  4617. return self
  4618. def propertiesChanged(self, properties):
  4619. logger.debug("propertiesChanged: %s" % str(properties))
  4620. if 'State' in properties and properties['State'] == "completed":
  4621. self.done = True
  4622. self.loop.quit()
  4623. def eap(self, status, parameter):
  4624. logger.debug("EAP: status=%s parameter=%s" % (status, parameter))
  4625. def run_connect(self, *args):
  4626. logger.debug("run_connect")
  4627. args = dbus.Dictionary({ 'ssid': ssid,
  4628. 'key_mgmt': 'WPA-EAP',
  4629. 'eap': 'PEAP',
  4630. 'identity': 'user',
  4631. 'password': 'password',
  4632. 'ca_cert': 'auth_serv/ca.pem',
  4633. 'phase2': 'auth=MSCHAPV2',
  4634. 'scan_freq': 2412 },
  4635. signature='sv')
  4636. self.netw = iface.AddNetwork(args)
  4637. iface.SelectNetwork(self.netw)
  4638. return False
  4639. def success(self):
  4640. return self.done
  4641. with TestDbusConnect(bus) as t:
  4642. if not t.success():
  4643. raise Exception("Expected signals not seen")
  4644. def test_dbus_ap_scan_2_ap_mode_scan(dev, apdev):
  4645. """AP_SCAN 2 AP mode and D-Bus Scan()"""
  4646. try:
  4647. _test_dbus_ap_scan_2_ap_mode_scan(dev, apdev)
  4648. finally:
  4649. dev[0].request("AP_SCAN 1")
  4650. def _test_dbus_ap_scan_2_ap_mode_scan(dev, apdev):
  4651. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4652. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  4653. if "OK" not in dev[0].request("AP_SCAN 2"):
  4654. raise Exception("Failed to set AP_SCAN 2")
  4655. id = dev[0].add_network()
  4656. dev[0].set_network(id, "mode", "2")
  4657. dev[0].set_network_quoted(id, "ssid", "wpas-ap-open")
  4658. dev[0].set_network(id, "key_mgmt", "NONE")
  4659. dev[0].set_network(id, "frequency", "2412")
  4660. dev[0].set_network(id, "scan_freq", "2412")
  4661. dev[0].set_network(id, "disabled", "0")
  4662. dev[0].select_network(id)
  4663. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=5)
  4664. if ev is None:
  4665. raise Exception("AP failed to start")
  4666. with fail_test(dev[0], 1, "wpa_driver_nl80211_scan"):
  4667. iface.Scan({'Type': 'active',
  4668. 'AllowRoam': True,
  4669. 'Channels': [(dbus.UInt32(2412), dbus.UInt32(20))]})
  4670. ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED",
  4671. "AP-DISABLED"], timeout=5)
  4672. if ev is None:
  4673. raise Exception("CTRL-EVENT-SCAN-FAILED not seen")
  4674. if "AP-DISABLED" in ev:
  4675. raise Exception("Unexpected AP-DISABLED event")
  4676. if "retry=1" in ev:
  4677. # Wait for the retry to scan happen
  4678. ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED",
  4679. "AP-DISABLED"], timeout=5)
  4680. if ev is None:
  4681. raise Exception("CTRL-EVENT-SCAN-FAILED not seen - retry")
  4682. if "AP-DISABLED" in ev:
  4683. raise Exception("Unexpected AP-DISABLED event - retry")
  4684. dev[1].connect("wpas-ap-open", key_mgmt="NONE", scan_freq="2412")
  4685. dev[1].request("DISCONNECT")
  4686. dev[1].wait_disconnected()
  4687. dev[0].request("DISCONNECT")
  4688. dev[0].wait_disconnected()
  4689. def test_dbus_expectdisconnect(dev, apdev):
  4690. """D-Bus ExpectDisconnect"""
  4691. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4692. wpas = dbus.Interface(wpas_obj, WPAS_DBUS_SERVICE)
  4693. params = { "ssid": "test-open" }
  4694. hapd = hostapd.add_ap(apdev[0], params)
  4695. dev[0].connect("test-open", key_mgmt="NONE", scan_freq="2412")
  4696. # This does not really verify the behavior other than by going through the
  4697. # code path for additional coverage.
  4698. wpas.ExpectDisconnect()
  4699. dev[0].request("DISCONNECT")
  4700. dev[0].wait_disconnected()
  4701. def test_dbus_save_config(dev, apdev):
  4702. """D-Bus SaveConfig"""
  4703. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4704. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  4705. try:
  4706. iface.SaveConfig()
  4707. raise Exception("SaveConfig() accepted unexpectedly")
  4708. except dbus.exceptions.DBusException, e:
  4709. if not str(e).startswith("fi.w1.wpa_supplicant1.UnknownError: Not allowed to update configuration"):
  4710. raise Exception("Unexpected error message for SaveConfig(): " + str(e))
  4711. def test_dbus_vendor_elem(dev, apdev):
  4712. """D-Bus vendor element operations"""
  4713. try:
  4714. _test_dbus_vendor_elem(dev, apdev)
  4715. finally:
  4716. dev[0].request("VENDOR_ELEM_REMOVE 1 *")
  4717. def _test_dbus_vendor_elem(dev, apdev):
  4718. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4719. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  4720. dev[0].request("VENDOR_ELEM_REMOVE 1 *")
  4721. try:
  4722. ie = dbus.ByteArray("\x00\x00")
  4723. iface.VendorElemAdd(-1, ie)
  4724. raise Exception("Invalid VendorElemAdd() accepted")
  4725. except dbus.exceptions.DBusException, e:
  4726. if "InvalidArgs" not in str(e) or "Invalid ID" not in str(e):
  4727. raise Exception("Unexpected error message for invalid VendorElemAdd[1]: " + str(e))
  4728. try:
  4729. ie = dbus.ByteArray("")
  4730. iface.VendorElemAdd(1, ie)
  4731. raise Exception("Invalid VendorElemAdd() accepted")
  4732. except dbus.exceptions.DBusException, e:
  4733. if "InvalidArgs" not in str(e) or "Invalid value" not in str(e):
  4734. raise Exception("Unexpected error message for invalid VendorElemAdd[2]: " + str(e))
  4735. try:
  4736. ie = dbus.ByteArray("\x00\x01")
  4737. iface.VendorElemAdd(1, ie)
  4738. raise Exception("Invalid VendorElemAdd() accepted")
  4739. except dbus.exceptions.DBusException, e:
  4740. if "InvalidArgs" not in str(e) or "Parse error" not in str(e):
  4741. raise Exception("Unexpected error message for invalid VendorElemAdd[3]: " + str(e))
  4742. try:
  4743. iface.VendorElemGet(-1)
  4744. raise Exception("Invalid VendorElemGet() accepted")
  4745. except dbus.exceptions.DBusException, e:
  4746. if "InvalidArgs" not in str(e) or "Invalid ID" not in str(e):
  4747. raise Exception("Unexpected error message for invalid VendorElemGet[1]: " + str(e))
  4748. try:
  4749. iface.VendorElemGet(1)
  4750. raise Exception("Invalid VendorElemGet() accepted")
  4751. except dbus.exceptions.DBusException, e:
  4752. if "InvalidArgs" not in str(e) or "ID value does not exist" not in str(e):
  4753. raise Exception("Unexpected error message for invalid VendorElemGet[2]: " + str(e))
  4754. try:
  4755. ie = dbus.ByteArray("\x00\x00")
  4756. iface.VendorElemRem(-1, ie)
  4757. raise Exception("Invalid VendorElemRemove() accepted")
  4758. except dbus.exceptions.DBusException, e:
  4759. if "InvalidArgs" not in str(e) or "Invalid ID" not in str(e):
  4760. raise Exception("Unexpected error message for invalid VendorElemRemove[1]: " + str(e))
  4761. try:
  4762. ie = dbus.ByteArray("")
  4763. iface.VendorElemRem(1, ie)
  4764. raise Exception("Invalid VendorElemRemove() accepted")
  4765. except dbus.exceptions.DBusException, e:
  4766. if "InvalidArgs" not in str(e) or "Invalid value" not in str(e):
  4767. raise Exception("Unexpected error message for invalid VendorElemRemove[1]: " + str(e))
  4768. iface.VendorElemRem(1, "*")
  4769. ie = dbus.ByteArray("\x00\x01\x00")
  4770. iface.VendorElemAdd(1, ie)
  4771. val = iface.VendorElemGet(1)
  4772. if len(val) != len(ie):
  4773. raise Exception("Unexpected VendorElemGet length")
  4774. for i in range(len(val)):
  4775. if val[i] != dbus.Byte(ie[i]):
  4776. raise Exception("Unexpected VendorElemGet data")
  4777. ie2 = dbus.ByteArray("\xe0\x00")
  4778. iface.VendorElemAdd(1, ie2)
  4779. ies = ie + ie2
  4780. val = iface.VendorElemGet(1)
  4781. if len(val) != len(ies):
  4782. raise Exception("Unexpected VendorElemGet length[2]")
  4783. for i in range(len(val)):
  4784. if val[i] != dbus.Byte(ies[i]):
  4785. raise Exception("Unexpected VendorElemGet data[2]")
  4786. try:
  4787. test_ie = dbus.ByteArray("\x01\x01")
  4788. iface.VendorElemRem(1, test_ie)
  4789. raise Exception("Invalid VendorElemRemove() accepted")
  4790. except dbus.exceptions.DBusException, e:
  4791. if "InvalidArgs" not in str(e) or "Parse error" not in str(e):
  4792. raise Exception("Unexpected error message for invalid VendorElemRemove[1]: " + str(e))
  4793. iface.VendorElemRem(1, ie)
  4794. val = iface.VendorElemGet(1)
  4795. if len(val) != len(ie2):
  4796. raise Exception("Unexpected VendorElemGet length[3]")
  4797. iface.VendorElemRem(1, "*")
  4798. try:
  4799. iface.VendorElemGet(1)
  4800. raise Exception("Invalid VendorElemGet() accepted after removal")
  4801. except dbus.exceptions.DBusException, e:
  4802. if "InvalidArgs" not in str(e) or "ID value does not exist" not in str(e):
  4803. raise Exception("Unexpected error message for invalid VendorElemGet after removal: " + str(e))
  4804. def test_dbus_assoc_reject(dev, apdev):
  4805. """D-Bus AssocStatusCode"""
  4806. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4807. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  4808. ssid = "test-open"
  4809. params = { "ssid": ssid,
  4810. "max_listen_interval": "1" }
  4811. hapd = hostapd.add_ap(apdev[0], params)
  4812. class TestDbusConnect(TestDbus):
  4813. def __init__(self, bus):
  4814. TestDbus.__init__(self, bus)
  4815. self.assoc_status_seen = False
  4816. self.state = 0
  4817. def __enter__(self):
  4818. gobject.timeout_add(1, self.run_connect)
  4819. gobject.timeout_add(15000, self.timeout)
  4820. self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
  4821. "PropertiesChanged")
  4822. self.loop.run()
  4823. return self
  4824. def propertiesChanged(self, properties):
  4825. logger.debug("propertiesChanged: %s" % str(properties))
  4826. if 'AssocStatusCode' in properties:
  4827. status = properties['AssocStatusCode']
  4828. if status != 51:
  4829. logger.info("Unexpected status code: " + str(status))
  4830. else:
  4831. self.assoc_status_seen = True
  4832. iface.Disconnect()
  4833. self.loop.quit()
  4834. def run_connect(self, *args):
  4835. args = dbus.Dictionary({ 'ssid': ssid,
  4836. 'key_mgmt': 'NONE',
  4837. 'scan_freq': 2412 },
  4838. signature='sv')
  4839. self.netw = iface.AddNetwork(args)
  4840. iface.SelectNetwork(self.netw)
  4841. return False
  4842. def success(self):
  4843. return self.assoc_status_seen
  4844. with TestDbusConnect(bus) as t:
  4845. if not t.success():
  4846. raise Exception("Expected signals not seen")
  4847. def test_dbus_mesh(dev, apdev):
  4848. """D-Bus mesh"""
  4849. check_mesh_support(dev[0])
  4850. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4851. mesh = dbus.Interface(if_obj, WPAS_DBUS_IFACE_MESH)
  4852. add_open_mesh_network(dev[1])
  4853. addr1 = dev[1].own_addr()
  4854. class TestDbusMesh(TestDbus):
  4855. def __init__(self, bus):
  4856. TestDbus.__init__(self, bus)
  4857. self.done = False
  4858. def __enter__(self):
  4859. gobject.timeout_add(1, self.run_test)
  4860. gobject.timeout_add(15000, self.timeout)
  4861. self.add_signal(self.meshGroupStarted, WPAS_DBUS_IFACE_MESH,
  4862. "MeshGroupStarted")
  4863. self.add_signal(self.meshGroupRemoved, WPAS_DBUS_IFACE_MESH,
  4864. "MeshGroupRemoved")
  4865. self.add_signal(self.meshPeerConnected, WPAS_DBUS_IFACE_MESH,
  4866. "MeshPeerConnected")
  4867. self.add_signal(self.meshPeerDisconnected, WPAS_DBUS_IFACE_MESH,
  4868. "MeshPeerDisconnected")
  4869. self.loop.run()
  4870. return self
  4871. def meshGroupStarted(self, args):
  4872. logger.debug("MeshGroupStarted: " + str(args))
  4873. def meshGroupRemoved(self, args):
  4874. logger.debug("MeshGroupRemoved: " + str(args))
  4875. self.done = True
  4876. self.loop.quit()
  4877. def meshPeerConnected(self, args):
  4878. logger.debug("MeshPeerConnected: " + str(args))
  4879. res = if_obj.Get(WPAS_DBUS_IFACE_MESH, 'MeshPeers',
  4880. dbus_interface=dbus.PROPERTIES_IFACE,
  4881. byte_arrays=True)
  4882. logger.debug("MeshPeers: " + str(res))
  4883. if len(res) != 1:
  4884. raise Exception("Unexpected number of MeshPeer values")
  4885. if binascii.hexlify(res[0]) != addr1.replace(':', ''):
  4886. raise Exception("Unexpected peer address")
  4887. res = if_obj.Get(WPAS_DBUS_IFACE_MESH, 'MeshGroup',
  4888. dbus_interface=dbus.PROPERTIES_IFACE,
  4889. byte_arrays=True)
  4890. logger.debug("MeshGroup: " + str(res))
  4891. if res != "wpas-mesh-open":
  4892. raise Exception("Unexpected MeshGroup")
  4893. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  4894. dev1.mesh_group_remove()
  4895. def meshPeerDisconnected(self, args):
  4896. logger.debug("MeshPeerDisconnected: " + str(args))
  4897. dev0 = WpaSupplicant('wlan0', '/tmp/wpas-wlan0')
  4898. dev0.mesh_group_remove()
  4899. def run_test(self, *args):
  4900. logger.debug("run_test")
  4901. dev0 = WpaSupplicant('wlan0', '/tmp/wpas-wlan0')
  4902. add_open_mesh_network(dev0)
  4903. return False
  4904. def success(self):
  4905. return self.done
  4906. with TestDbusMesh(bus) as t:
  4907. if not t.success():
  4908. raise Exception("Expected signals not seen")