test_dbus.py 212 KB

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