test_dbus.py 224 KB

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