test_dbus.py 207 KB

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