test_dbus.py 232 KB

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