test_dbus.py 208 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049
  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. # Force regulatory update to re-fetch hw capabilities for the following
  1182. # test cases.
  1183. try:
  1184. dev[0].dump_monitor()
  1185. subprocess.call(['iw', 'reg', 'set', 'US'])
  1186. ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
  1187. finally:
  1188. dev[0].dump_monitor()
  1189. subprocess.call(['iw', 'reg', 'set', '00'])
  1190. ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
  1191. def test_dbus_while_not_connected(dev, apdev):
  1192. """D-Bus invalid operations while not connected"""
  1193. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1194. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1195. try:
  1196. iface.Disconnect()
  1197. raise Exception("Disconnect() accepted when not connected")
  1198. except dbus.exceptions.DBusException, e:
  1199. if "NotConnected" not in str(e):
  1200. raise Exception("Unexpected error message for invalid Disconnect: " + str(e))
  1201. try:
  1202. iface.Reattach()
  1203. raise Exception("Reattach() accepted when not connected")
  1204. except dbus.exceptions.DBusException, e:
  1205. if "NotConnected" not in str(e):
  1206. raise Exception("Unexpected error message for invalid Reattach: " + str(e))
  1207. def test_dbus_connect_eap(dev, apdev):
  1208. """D-Bus AddNetwork and connect to EAP network"""
  1209. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1210. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1211. ssid = "ieee8021x-open"
  1212. params = hostapd.radius_params()
  1213. params["ssid"] = ssid
  1214. params["ieee8021x"] = "1"
  1215. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  1216. class TestDbusConnect(TestDbus):
  1217. def __init__(self, bus):
  1218. TestDbus.__init__(self, bus)
  1219. self.certification_received = False
  1220. self.eap_status = False
  1221. self.state = 0
  1222. def __enter__(self):
  1223. gobject.timeout_add(1, self.run_connect)
  1224. gobject.timeout_add(15000, self.timeout)
  1225. self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
  1226. "PropertiesChanged")
  1227. self.add_signal(self.certification, WPAS_DBUS_IFACE,
  1228. "Certification", byte_arrays=True)
  1229. self.add_signal(self.networkRequest, WPAS_DBUS_IFACE,
  1230. "NetworkRequest")
  1231. self.add_signal(self.eap, WPAS_DBUS_IFACE, "EAP")
  1232. self.loop.run()
  1233. return self
  1234. def propertiesChanged(self, properties):
  1235. logger.debug("propertiesChanged: %s" % str(properties))
  1236. if 'State' in properties and properties['State'] == "completed":
  1237. if self.state == 0:
  1238. self.state = 1
  1239. iface.EAPLogoff()
  1240. logger.info("Set dNSName constraint")
  1241. net_obj = bus.get_object(WPAS_DBUS_SERVICE, self.netw)
  1242. args = dbus.Dictionary({ 'altsubject_match':
  1243. self.server_dnsname },
  1244. signature='sv')
  1245. net_obj.Set(WPAS_DBUS_NETWORK, "Properties", args,
  1246. dbus_interface=dbus.PROPERTIES_IFACE)
  1247. elif self.state == 2:
  1248. self.state = 3
  1249. iface.Disconnect()
  1250. logger.info("Set non-matching dNSName constraint")
  1251. net_obj = bus.get_object(WPAS_DBUS_SERVICE, self.netw)
  1252. args = dbus.Dictionary({ 'altsubject_match':
  1253. self.server_dnsname + "FOO" },
  1254. signature='sv')
  1255. net_obj.Set(WPAS_DBUS_NETWORK, "Properties", args,
  1256. dbus_interface=dbus.PROPERTIES_IFACE)
  1257. if 'State' in properties and properties['State'] == "disconnected":
  1258. if self.state == 1:
  1259. self.state = 2
  1260. iface.EAPLogon()
  1261. iface.SelectNetwork(self.netw)
  1262. if self.state == 3:
  1263. self.state = 4
  1264. iface.SelectNetwork(self.netw)
  1265. def certification(self, args):
  1266. logger.debug("certification: %s" % str(args))
  1267. self.certification_received = True
  1268. if args['depth'] == 0:
  1269. # The test server certificate is supposed to have dNSName
  1270. if len(args['altsubject']) < 1:
  1271. raise Exception("Missing dNSName")
  1272. dnsname = args['altsubject'][0]
  1273. if not dnsname.startswith("DNS:"):
  1274. raise Exception("Expected dNSName not found: " + dnsname)
  1275. logger.info("altsubject: " + dnsname)
  1276. self.server_dnsname = dnsname
  1277. def eap(self, status, parameter):
  1278. logger.debug("EAP: status=%s parameter=%s" % (status, parameter))
  1279. if status == 'completion' and parameter == 'success':
  1280. self.eap_status = True
  1281. if self.state == 4 and status == 'remote certificate verification' and parameter == 'AltSubject mismatch':
  1282. self.state = 5
  1283. self.loop.quit()
  1284. def networkRequest(self, path, field, txt):
  1285. logger.debug("networkRequest: %s %s %s" % (path, field, txt))
  1286. if field == "PASSWORD":
  1287. iface.NetworkReply(path, field, "password")
  1288. def run_connect(self, *args):
  1289. logger.debug("run_connect")
  1290. args = dbus.Dictionary({ 'ssid': ssid,
  1291. 'key_mgmt': 'IEEE8021X',
  1292. 'eapol_flags': 0,
  1293. 'eap': 'TTLS',
  1294. 'anonymous_identity': 'ttls',
  1295. 'identity': 'pap user',
  1296. 'ca_cert': 'auth_serv/ca.pem',
  1297. 'phase2': 'auth=PAP',
  1298. 'scan_freq': 2412 },
  1299. signature='sv')
  1300. self.netw = iface.AddNetwork(args)
  1301. iface.SelectNetwork(self.netw)
  1302. return False
  1303. def success(self):
  1304. if not self.eap_status or not self.certification_received:
  1305. return False
  1306. return self.state == 5
  1307. with TestDbusConnect(bus) as t:
  1308. if not t.success():
  1309. raise Exception("Expected signals not seen")
  1310. def test_dbus_network(dev, apdev):
  1311. """D-Bus AddNetwork/RemoveNetwork parameters and error cases"""
  1312. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1313. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1314. args = dbus.Dictionary({ 'ssid': "foo",
  1315. 'key_mgmt': 'WPA-PSK',
  1316. 'psk': "12345678",
  1317. 'identity': dbus.ByteArray([ 1, 2 ]),
  1318. 'priority': dbus.Int32(0),
  1319. 'scan_freq': dbus.UInt32(2412) },
  1320. signature='sv')
  1321. netw = iface.AddNetwork(args)
  1322. id = int(dev[0].list_networks()[0]['id'])
  1323. val = dev[0].get_network(id, "scan_freq")
  1324. if val != "2412":
  1325. raise Exception("Invalid scan_freq value: " + str(val))
  1326. iface.RemoveNetwork(netw)
  1327. args = dbus.Dictionary({ 'ssid': "foo",
  1328. 'key_mgmt': 'NONE',
  1329. 'scan_freq': "2412 2432",
  1330. 'freq_list': "2412 2417 2432" },
  1331. signature='sv')
  1332. netw = iface.AddNetwork(args)
  1333. id = int(dev[0].list_networks()[0]['id'])
  1334. val = dev[0].get_network(id, "scan_freq")
  1335. if val != "2412 2432":
  1336. raise Exception("Invalid scan_freq value (2): " + str(val))
  1337. val = dev[0].get_network(id, "freq_list")
  1338. if val != "2412 2417 2432":
  1339. raise Exception("Invalid freq_list value: " + str(val))
  1340. iface.RemoveNetwork(netw)
  1341. try:
  1342. iface.RemoveNetwork(netw)
  1343. raise Exception("Invalid RemoveNetwork() accepted")
  1344. except dbus.exceptions.DBusException, e:
  1345. if "NetworkUnknown" not in str(e):
  1346. raise Exception("Unexpected error message for invalid RemoveNetwork: " + str(e))
  1347. try:
  1348. iface.SelectNetwork(netw)
  1349. raise Exception("Invalid SelectNetwork() accepted")
  1350. except dbus.exceptions.DBusException, e:
  1351. if "NetworkUnknown" not in str(e):
  1352. raise Exception("Unexpected error message for invalid RemoveNetwork: " + str(e))
  1353. args = dbus.Dictionary({ 'ssid': "foo1", 'key_mgmt': 'NONE',
  1354. 'identity': "testuser", 'scan_freq': '2412' },
  1355. signature='sv')
  1356. netw1 = iface.AddNetwork(args)
  1357. args = dbus.Dictionary({ 'ssid': "foo2", 'key_mgmt': 'NONE' },
  1358. signature='sv')
  1359. netw2 = iface.AddNetwork(args)
  1360. res = if_obj.Get(WPAS_DBUS_IFACE, "Networks",
  1361. dbus_interface=dbus.PROPERTIES_IFACE)
  1362. if len(res) != 2:
  1363. raise Exception("Unexpected number of networks")
  1364. net_obj = bus.get_object(WPAS_DBUS_SERVICE, netw1)
  1365. res = net_obj.Get(WPAS_DBUS_NETWORK, "Enabled",
  1366. dbus_interface=dbus.PROPERTIES_IFACE)
  1367. if res != False:
  1368. raise Exception("Added network was unexpectedly enabled by default")
  1369. net_obj.Set(WPAS_DBUS_NETWORK, "Enabled", dbus.Boolean(True),
  1370. dbus_interface=dbus.PROPERTIES_IFACE)
  1371. res = net_obj.Get(WPAS_DBUS_NETWORK, "Enabled",
  1372. dbus_interface=dbus.PROPERTIES_IFACE)
  1373. if res != True:
  1374. raise Exception("Set(Enabled,True) did not seem to change property value")
  1375. net_obj.Set(WPAS_DBUS_NETWORK, "Enabled", dbus.Boolean(False),
  1376. dbus_interface=dbus.PROPERTIES_IFACE)
  1377. res = net_obj.Get(WPAS_DBUS_NETWORK, "Enabled",
  1378. dbus_interface=dbus.PROPERTIES_IFACE)
  1379. if res != False:
  1380. raise Exception("Set(Enabled,False) did not seem to change property value")
  1381. try:
  1382. net_obj.Set(WPAS_DBUS_NETWORK, "Enabled", dbus.UInt32(1),
  1383. dbus_interface=dbus.PROPERTIES_IFACE)
  1384. raise Exception("Invalid Set(Enabled,1) accepted")
  1385. except dbus.exceptions.DBusException, e:
  1386. if "Error.Failed: wrong property type" not in str(e):
  1387. raise Exception("Unexpected error message for invalid Set(Enabled,1): " + str(e))
  1388. args = dbus.Dictionary({ 'ssid': "foo1new" }, signature='sv')
  1389. net_obj.Set(WPAS_DBUS_NETWORK, "Properties", args,
  1390. dbus_interface=dbus.PROPERTIES_IFACE)
  1391. res = net_obj.Get(WPAS_DBUS_NETWORK, "Properties",
  1392. dbus_interface=dbus.PROPERTIES_IFACE)
  1393. if res['ssid'] != '"foo1new"':
  1394. raise Exception("Set(Properties) failed to update ssid")
  1395. if res['identity'] != '"testuser"':
  1396. raise Exception("Set(Properties) unexpectedly changed unrelated parameter")
  1397. iface.RemoveAllNetworks()
  1398. res = if_obj.Get(WPAS_DBUS_IFACE, "Networks",
  1399. dbus_interface=dbus.PROPERTIES_IFACE)
  1400. if len(res) != 0:
  1401. raise Exception("Unexpected number of networks")
  1402. iface.RemoveAllNetworks()
  1403. tests = [ dbus.Dictionary({ 'psk': "1234567" }, signature='sv'),
  1404. dbus.Dictionary({ 'identity': dbus.ByteArray() },
  1405. signature='sv'),
  1406. dbus.Dictionary({ 'identity': dbus.Byte(1) }, signature='sv'),
  1407. dbus.Dictionary({ 'identity': "" }, signature='sv') ]
  1408. for args in tests:
  1409. try:
  1410. iface.AddNetwork(args)
  1411. raise Exception("Invalid AddNetwork args accepted: " + str(args))
  1412. except dbus.exceptions.DBusException, e:
  1413. if "InvalidArgs" not in str(e):
  1414. raise Exception("Unexpected error message for invalid AddNetwork: " + str(e))
  1415. def test_dbus_network_oom(dev, apdev):
  1416. """D-Bus AddNetwork/RemoveNetwork parameters and OOM error cases"""
  1417. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1418. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1419. args = dbus.Dictionary({ 'ssid': "foo1", 'key_mgmt': 'NONE',
  1420. 'identity': "testuser", 'scan_freq': '2412' },
  1421. signature='sv')
  1422. netw1 = iface.AddNetwork(args)
  1423. net_obj = bus.get_object(WPAS_DBUS_SERVICE, netw1)
  1424. with alloc_fail_dbus(dev[0], 1,
  1425. "wpa_config_get_all;wpas_dbus_getter_network_properties",
  1426. "Get"):
  1427. net_obj.Get(WPAS_DBUS_NETWORK, "Properties",
  1428. dbus_interface=dbus.PROPERTIES_IFACE)
  1429. iface.RemoveAllNetworks()
  1430. with alloc_fail_dbus(dev[0], 1,
  1431. "wpas_dbus_new_decompose_object_path;wpas_dbus_handler_remove_network",
  1432. "RemoveNetwork", "InvalidArgs"):
  1433. iface.RemoveNetwork(dbus.ObjectPath("/fi/w1/wpa_supplicant1/Interfaces/1234/Networks/1234"))
  1434. with alloc_fail(dev[0], 1, "wpa_dbus_register_object_per_iface;wpas_dbus_register_network"):
  1435. args = dbus.Dictionary({ 'ssid': "foo2", 'key_mgmt': 'NONE' },
  1436. signature='sv')
  1437. try:
  1438. netw = iface.AddNetwork(args)
  1439. # Currently, AddNetwork() succeeds even if os_strdup() for path
  1440. # fails, so remove the network if that occurs.
  1441. iface.RemoveNetwork(netw)
  1442. except dbus.exceptions.DBusException, e:
  1443. pass
  1444. for i in range(1, 3):
  1445. with alloc_fail(dev[0], i, "=wpas_dbus_register_network"):
  1446. try:
  1447. netw = iface.AddNetwork(args)
  1448. # Currently, AddNetwork() succeeds even if network registration
  1449. # fails, so remove the network if that occurs.
  1450. iface.RemoveNetwork(netw)
  1451. except dbus.exceptions.DBusException, e:
  1452. pass
  1453. with alloc_fail_dbus(dev[0], 1,
  1454. "=wpa_config_add_network;wpas_dbus_handler_add_network",
  1455. "AddNetwork",
  1456. "UnknownError: wpa_supplicant could not add a network"):
  1457. args = dbus.Dictionary({ 'ssid': "foo2", 'key_mgmt': 'NONE' },
  1458. signature='sv')
  1459. netw = iface.AddNetwork(args)
  1460. tests = [ (1,
  1461. 'wpa_dbus_dict_get_entry;set_network_properties;wpas_dbus_handler_add_network',
  1462. dbus.Dictionary({ 'ssid': dbus.ByteArray(' ') },
  1463. signature='sv')),
  1464. (1, '=set_network_properties;wpas_dbus_handler_add_network',
  1465. dbus.Dictionary({ 'ssid': 'foo' }, signature='sv')),
  1466. (1, '=set_network_properties;wpas_dbus_handler_add_network',
  1467. dbus.Dictionary({ 'eap': 'foo' }, signature='sv')),
  1468. (1, '=set_network_properties;wpas_dbus_handler_add_network',
  1469. dbus.Dictionary({ 'priority': dbus.UInt32(1) },
  1470. signature='sv')),
  1471. (1, '=set_network_properties;wpas_dbus_handler_add_network',
  1472. dbus.Dictionary({ 'priority': dbus.Int32(1) },
  1473. signature='sv')),
  1474. (1, '=set_network_properties;wpas_dbus_handler_add_network',
  1475. dbus.Dictionary({ 'ssid': dbus.ByteArray(' ') },
  1476. signature='sv')) ]
  1477. for (count,funcs,args) in tests:
  1478. with alloc_fail_dbus(dev[0], count, funcs, "AddNetwork", "InvalidArgs"):
  1479. netw = iface.AddNetwork(args)
  1480. if len(if_obj.Get(WPAS_DBUS_IFACE, 'Networks',
  1481. dbus_interface=dbus.PROPERTIES_IFACE)) > 0:
  1482. raise Exception("Unexpected network block added")
  1483. if len(dev[0].list_networks()) > 0:
  1484. raise Exception("Unexpected network block visible")
  1485. def test_dbus_interface(dev, apdev):
  1486. """D-Bus CreateInterface/GetInterface/RemoveInterface parameters and error cases"""
  1487. try:
  1488. _test_dbus_interface(dev, apdev)
  1489. finally:
  1490. # Need to force P2P channel list update since the 'lo' interface
  1491. # with driver=none ends up configuring default dualband channels.
  1492. dev[0].request("SET country US")
  1493. ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
  1494. if ev is None:
  1495. ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"],
  1496. timeout=1)
  1497. dev[0].request("SET country 00")
  1498. ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
  1499. if ev is None:
  1500. ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"],
  1501. timeout=1)
  1502. subprocess.call(['iw', 'reg', 'set', '00'])
  1503. def _test_dbus_interface(dev, apdev):
  1504. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1505. wpas = dbus.Interface(wpas_obj, WPAS_DBUS_SERVICE)
  1506. params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none' },
  1507. signature='sv')
  1508. path = wpas.CreateInterface(params)
  1509. logger.debug("New interface path: " + str(path))
  1510. path2 = wpas.GetInterface("lo")
  1511. if path != path2:
  1512. raise Exception("Interface object mismatch")
  1513. params = dbus.Dictionary({ 'Ifname': 'lo',
  1514. 'Driver': 'none',
  1515. 'ConfigFile': 'foo',
  1516. 'BridgeIfname': 'foo', },
  1517. signature='sv')
  1518. try:
  1519. wpas.CreateInterface(params)
  1520. raise Exception("Invalid CreateInterface() accepted")
  1521. except dbus.exceptions.DBusException, e:
  1522. if "InterfaceExists" not in str(e):
  1523. raise Exception("Unexpected error message for invalid CreateInterface: " + str(e))
  1524. wpas.RemoveInterface(path)
  1525. try:
  1526. wpas.RemoveInterface(path)
  1527. raise Exception("Invalid RemoveInterface() accepted")
  1528. except dbus.exceptions.DBusException, e:
  1529. if "InterfaceUnknown" not in str(e):
  1530. raise Exception("Unexpected error message for invalid RemoveInterface: " + str(e))
  1531. params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none',
  1532. 'Foo': 123 },
  1533. signature='sv')
  1534. try:
  1535. wpas.CreateInterface(params)
  1536. raise Exception("Invalid CreateInterface() accepted")
  1537. except dbus.exceptions.DBusException, e:
  1538. if "InvalidArgs" not in str(e):
  1539. raise Exception("Unexpected error message for invalid CreateInterface: " + str(e))
  1540. params = dbus.Dictionary({ 'Driver': 'none' }, signature='sv')
  1541. try:
  1542. wpas.CreateInterface(params)
  1543. raise Exception("Invalid CreateInterface() accepted")
  1544. except dbus.exceptions.DBusException, e:
  1545. if "InvalidArgs" not in str(e):
  1546. raise Exception("Unexpected error message for invalid CreateInterface: " + str(e))
  1547. try:
  1548. wpas.GetInterface("lo")
  1549. raise Exception("Invalid GetInterface() accepted")
  1550. except dbus.exceptions.DBusException, e:
  1551. if "InterfaceUnknown" not in str(e):
  1552. raise Exception("Unexpected error message for invalid RemoveInterface: " + str(e))
  1553. def test_dbus_interface_oom(dev, apdev):
  1554. """D-Bus CreateInterface/GetInterface/RemoveInterface OOM error cases"""
  1555. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1556. wpas = dbus.Interface(wpas_obj, WPAS_DBUS_SERVICE)
  1557. with alloc_fail_dbus(dev[0], 1, "wpa_dbus_dict_get_entry;wpas_dbus_handler_create_interface", "CreateInterface", "InvalidArgs"):
  1558. params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none' },
  1559. signature='sv')
  1560. wpas.CreateInterface(params)
  1561. for i in range(1, 1000):
  1562. dev[0].request("TEST_ALLOC_FAIL %d:wpa_supplicant_add_iface;wpas_dbus_handler_create_interface" % i)
  1563. params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none' },
  1564. signature='sv')
  1565. try:
  1566. npath = wpas.CreateInterface(params)
  1567. wpas.RemoveInterface(npath)
  1568. logger.info("CreateInterface succeeds after %d allocation failures" % i)
  1569. state = dev[0].request('GET_ALLOC_FAIL')
  1570. logger.info("GET_ALLOC_FAIL: " + state)
  1571. dev[0].dump_monitor()
  1572. dev[0].request("TEST_ALLOC_FAIL 0:")
  1573. if i < 5:
  1574. raise Exception("CreateInterface succeeded during out-of-memory")
  1575. if not state.startswith('0:'):
  1576. break
  1577. except dbus.exceptions.DBusException, e:
  1578. pass
  1579. for arg in [ 'Driver', 'Ifname', 'ConfigFile', 'BridgeIfname' ]:
  1580. with alloc_fail_dbus(dev[0], 1, "=wpas_dbus_handler_create_interface",
  1581. "CreateInterface"):
  1582. params = dbus.Dictionary({ arg: 'foo' }, signature='sv')
  1583. wpas.CreateInterface(params)
  1584. def test_dbus_blob(dev, apdev):
  1585. """D-Bus AddNetwork/RemoveNetwork parameters and error cases"""
  1586. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1587. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1588. blob = dbus.ByteArray("\x01\x02\x03")
  1589. iface.AddBlob('blob1', blob)
  1590. try:
  1591. iface.AddBlob('blob1', dbus.ByteArray("\x01\x02\x04"))
  1592. raise Exception("Invalid AddBlob() accepted")
  1593. except dbus.exceptions.DBusException, e:
  1594. if "BlobExists" not in str(e):
  1595. raise Exception("Unexpected error message for invalid AddBlob: " + str(e))
  1596. res = iface.GetBlob('blob1')
  1597. if len(res) != len(blob):
  1598. raise Exception("Unexpected blob data length")
  1599. for i in range(len(res)):
  1600. if res[i] != dbus.Byte(blob[i]):
  1601. raise Exception("Unexpected blob data")
  1602. res = if_obj.Get(WPAS_DBUS_IFACE, "Blobs",
  1603. dbus_interface=dbus.PROPERTIES_IFACE)
  1604. if 'blob1' not in res:
  1605. raise Exception("Added blob missing from Blobs property")
  1606. iface.RemoveBlob('blob1')
  1607. try:
  1608. iface.RemoveBlob('blob1')
  1609. raise Exception("Invalid RemoveBlob() accepted")
  1610. except dbus.exceptions.DBusException, e:
  1611. if "BlobUnknown" not in str(e):
  1612. raise Exception("Unexpected error message for invalid RemoveBlob: " + str(e))
  1613. try:
  1614. iface.GetBlob('blob1')
  1615. raise Exception("Invalid GetBlob() accepted")
  1616. except dbus.exceptions.DBusException, e:
  1617. if "BlobUnknown" not in str(e):
  1618. raise Exception("Unexpected error message for invalid GetBlob: " + str(e))
  1619. class TestDbusBlob(TestDbus):
  1620. def __init__(self, bus):
  1621. TestDbus.__init__(self, bus)
  1622. self.blob_added = False
  1623. self.blob_removed = False
  1624. def __enter__(self):
  1625. gobject.timeout_add(1, self.run_blob)
  1626. gobject.timeout_add(15000, self.timeout)
  1627. self.add_signal(self.blobAdded, WPAS_DBUS_IFACE, "BlobAdded")
  1628. self.add_signal(self.blobRemoved, WPAS_DBUS_IFACE, "BlobRemoved")
  1629. self.loop.run()
  1630. return self
  1631. def blobAdded(self, blobName):
  1632. logger.debug("blobAdded: %s" % blobName)
  1633. if blobName == 'blob2':
  1634. self.blob_added = True
  1635. def blobRemoved(self, blobName):
  1636. logger.debug("blobRemoved: %s" % blobName)
  1637. if blobName == 'blob2':
  1638. self.blob_removed = True
  1639. self.loop.quit()
  1640. def run_blob(self, *args):
  1641. logger.debug("run_blob")
  1642. iface.AddBlob('blob2', dbus.ByteArray("\x01\x02\x04"))
  1643. iface.RemoveBlob('blob2')
  1644. return False
  1645. def success(self):
  1646. return self.blob_added and self.blob_removed
  1647. with TestDbusBlob(bus) as t:
  1648. if not t.success():
  1649. raise Exception("Expected signals not seen")
  1650. def test_dbus_blob_oom(dev, apdev):
  1651. """D-Bus AddNetwork/RemoveNetwork OOM error cases"""
  1652. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1653. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1654. for i in range(1, 4):
  1655. with alloc_fail_dbus(dev[0], i, "wpas_dbus_handler_add_blob",
  1656. "AddBlob"):
  1657. iface.AddBlob('blob_no_mem', dbus.ByteArray("\x01\x02\x03\x04"))
  1658. def test_dbus_autoscan(dev, apdev):
  1659. """D-Bus Autoscan()"""
  1660. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1661. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1662. iface.AutoScan("foo")
  1663. iface.AutoScan("periodic:1")
  1664. iface.AutoScan("")
  1665. dev[0].request("AUTOSCAN ")
  1666. def test_dbus_autoscan_oom(dev, apdev):
  1667. """D-Bus Autoscan() OOM"""
  1668. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1669. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1670. with alloc_fail_dbus(dev[0], 1, "wpas_dbus_handler_autoscan", "AutoScan"):
  1671. iface.AutoScan("foo")
  1672. dev[0].request("AUTOSCAN ")
  1673. def test_dbus_tdls_invalid(dev, apdev):
  1674. """D-Bus invalid TDLS operations"""
  1675. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1676. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1677. hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "test-open" })
  1678. connect_2sta_open(dev, hapd)
  1679. addr1 = dev[1].p2p_interface_addr()
  1680. try:
  1681. iface.TDLSDiscover("foo")
  1682. raise Exception("Invalid TDLSDiscover() accepted")
  1683. except dbus.exceptions.DBusException, e:
  1684. if "InvalidArgs" not in str(e):
  1685. raise Exception("Unexpected error message for invalid TDLSDiscover: " + str(e))
  1686. try:
  1687. iface.TDLSStatus("foo")
  1688. raise Exception("Invalid TDLSStatus() accepted")
  1689. except dbus.exceptions.DBusException, e:
  1690. if "InvalidArgs" not in str(e):
  1691. raise Exception("Unexpected error message for invalid TDLSStatus: " + str(e))
  1692. res = iface.TDLSStatus(addr1)
  1693. if res != "peer does not exist":
  1694. raise Exception("Unexpected TDLSStatus response")
  1695. try:
  1696. iface.TDLSSetup("foo")
  1697. raise Exception("Invalid TDLSSetup() accepted")
  1698. except dbus.exceptions.DBusException, e:
  1699. if "InvalidArgs" not in str(e):
  1700. raise Exception("Unexpected error message for invalid TDLSSetup: " + str(e))
  1701. try:
  1702. iface.TDLSTeardown("foo")
  1703. raise Exception("Invalid TDLSTeardown() accepted")
  1704. except dbus.exceptions.DBusException, e:
  1705. if "InvalidArgs" not in str(e):
  1706. raise Exception("Unexpected error message for invalid TDLSTeardown: " + str(e))
  1707. try:
  1708. iface.TDLSTeardown("00:11:22:33:44:55")
  1709. raise Exception("TDLSTeardown accepted for unknown peer")
  1710. except dbus.exceptions.DBusException, e:
  1711. if "UnknownError: error performing TDLS teardown" not in str(e):
  1712. raise Exception("Unexpected error message: " + str(e))
  1713. def test_dbus_tdls_oom(dev, apdev):
  1714. """D-Bus TDLS operations during OOM"""
  1715. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1716. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1717. with alloc_fail_dbus(dev[0], 1, "wpa_tdls_add_peer", "TDLSSetup",
  1718. "UnknownError: error performing TDLS setup"):
  1719. iface.TDLSSetup("00:11:22:33:44:55")
  1720. def test_dbus_tdls(dev, apdev):
  1721. """D-Bus TDLS"""
  1722. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1723. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1724. hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "test-open" })
  1725. connect_2sta_open(dev, hapd)
  1726. addr1 = dev[1].p2p_interface_addr()
  1727. class TestDbusTdls(TestDbus):
  1728. def __init__(self, bus):
  1729. TestDbus.__init__(self, bus)
  1730. self.tdls_setup = False
  1731. self.tdls_teardown = False
  1732. def __enter__(self):
  1733. gobject.timeout_add(1, self.run_tdls)
  1734. gobject.timeout_add(15000, self.timeout)
  1735. self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
  1736. "PropertiesChanged")
  1737. self.loop.run()
  1738. return self
  1739. def propertiesChanged(self, properties):
  1740. logger.debug("propertiesChanged: %s" % str(properties))
  1741. def run_tdls(self, *args):
  1742. logger.debug("run_tdls")
  1743. iface.TDLSDiscover(addr1)
  1744. gobject.timeout_add(100, self.run_tdls2)
  1745. return False
  1746. def run_tdls2(self, *args):
  1747. logger.debug("run_tdls2")
  1748. iface.TDLSSetup(addr1)
  1749. gobject.timeout_add(500, self.run_tdls3)
  1750. return False
  1751. def run_tdls3(self, *args):
  1752. logger.debug("run_tdls3")
  1753. res = iface.TDLSStatus(addr1)
  1754. if res == "connected":
  1755. self.tdls_setup = True
  1756. else:
  1757. logger.info("Unexpected TDLSStatus: " + res)
  1758. iface.TDLSTeardown(addr1)
  1759. gobject.timeout_add(200, self.run_tdls4)
  1760. return False
  1761. def run_tdls4(self, *args):
  1762. logger.debug("run_tdls4")
  1763. res = iface.TDLSStatus(addr1)
  1764. if res == "peer does not exist":
  1765. self.tdls_teardown = True
  1766. else:
  1767. logger.info("Unexpected TDLSStatus: " + res)
  1768. self.loop.quit()
  1769. return False
  1770. def success(self):
  1771. return self.tdls_setup and self.tdls_teardown
  1772. with TestDbusTdls(bus) as t:
  1773. if not t.success():
  1774. raise Exception("Expected signals not seen")
  1775. def test_dbus_pkcs11(dev, apdev):
  1776. """D-Bus SetPKCS11EngineAndModulePath()"""
  1777. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1778. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1779. try:
  1780. iface.SetPKCS11EngineAndModulePath("foo", "bar")
  1781. except dbus.exceptions.DBusException, e:
  1782. if "Error.Failed: Reinit of the EAPOL" not in str(e):
  1783. raise Exception("Unexpected error message for invalid SetPKCS11EngineAndModulePath: " + str(e))
  1784. try:
  1785. iface.SetPKCS11EngineAndModulePath("foo", "")
  1786. except dbus.exceptions.DBusException, e:
  1787. if "Error.Failed: Reinit of the EAPOL" not in str(e):
  1788. raise Exception("Unexpected error message for invalid SetPKCS11EngineAndModulePath: " + str(e))
  1789. iface.SetPKCS11EngineAndModulePath("", "bar")
  1790. res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11EnginePath",
  1791. dbus_interface=dbus.PROPERTIES_IFACE)
  1792. if res != "":
  1793. raise Exception("Unexpected PKCS11EnginePath value: " + res)
  1794. res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11ModulePath",
  1795. dbus_interface=dbus.PROPERTIES_IFACE)
  1796. if res != "bar":
  1797. raise Exception("Unexpected PKCS11ModulePath value: " + res)
  1798. iface.SetPKCS11EngineAndModulePath("", "")
  1799. res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11EnginePath",
  1800. dbus_interface=dbus.PROPERTIES_IFACE)
  1801. if res != "":
  1802. raise Exception("Unexpected PKCS11EnginePath value: " + res)
  1803. res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11ModulePath",
  1804. dbus_interface=dbus.PROPERTIES_IFACE)
  1805. if res != "":
  1806. raise Exception("Unexpected PKCS11ModulePath value: " + res)
  1807. def test_dbus_apscan(dev, apdev):
  1808. """D-Bus Get/Set ApScan"""
  1809. try:
  1810. _test_dbus_apscan(dev, apdev)
  1811. finally:
  1812. dev[0].request("AP_SCAN 1")
  1813. def _test_dbus_apscan(dev, apdev):
  1814. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1815. res = if_obj.Get(WPAS_DBUS_IFACE, "ApScan",
  1816. dbus_interface=dbus.PROPERTIES_IFACE)
  1817. if res != 1:
  1818. raise Exception("Unexpected initial ApScan value: %d" % res)
  1819. for i in range(3):
  1820. if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.UInt32(i),
  1821. dbus_interface=dbus.PROPERTIES_IFACE)
  1822. res = if_obj.Get(WPAS_DBUS_IFACE, "ApScan",
  1823. dbus_interface=dbus.PROPERTIES_IFACE)
  1824. if res != i:
  1825. raise Exception("Unexpected ApScan value %d (expected %d)" % (res, i))
  1826. try:
  1827. if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.Int16(-1),
  1828. dbus_interface=dbus.PROPERTIES_IFACE)
  1829. raise Exception("Invalid Set(ApScan,-1) accepted")
  1830. except dbus.exceptions.DBusException, e:
  1831. if "Error.Failed: wrong property type" not in str(e):
  1832. raise Exception("Unexpected error message for invalid Set(ApScan,-1): " + str(e))
  1833. try:
  1834. if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.UInt32(123),
  1835. dbus_interface=dbus.PROPERTIES_IFACE)
  1836. raise Exception("Invalid Set(ApScan,123) accepted")
  1837. except dbus.exceptions.DBusException, e:
  1838. if "Error.Failed: ap_scan must be 0, 1, or 2" not in str(e):
  1839. raise Exception("Unexpected error message for invalid Set(ApScan,123): " + str(e))
  1840. if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.UInt32(1),
  1841. dbus_interface=dbus.PROPERTIES_IFACE)
  1842. def test_dbus_fastreauth(dev, apdev):
  1843. """D-Bus Get/Set FastReauth"""
  1844. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1845. res = if_obj.Get(WPAS_DBUS_IFACE, "FastReauth",
  1846. dbus_interface=dbus.PROPERTIES_IFACE)
  1847. if res != True:
  1848. raise Exception("Unexpected initial FastReauth value: " + str(res))
  1849. for i in [ False, True ]:
  1850. if_obj.Set(WPAS_DBUS_IFACE, "FastReauth", dbus.Boolean(i),
  1851. dbus_interface=dbus.PROPERTIES_IFACE)
  1852. res = if_obj.Get(WPAS_DBUS_IFACE, "FastReauth",
  1853. dbus_interface=dbus.PROPERTIES_IFACE)
  1854. if res != i:
  1855. raise Exception("Unexpected FastReauth value %d (expected %d)" % (res, i))
  1856. try:
  1857. if_obj.Set(WPAS_DBUS_IFACE, "FastReauth", dbus.Int16(-1),
  1858. dbus_interface=dbus.PROPERTIES_IFACE)
  1859. raise Exception("Invalid Set(FastReauth,-1) accepted")
  1860. except dbus.exceptions.DBusException, e:
  1861. if "Error.Failed: wrong property type" not in str(e):
  1862. raise Exception("Unexpected error message for invalid Set(ApScan,-1): " + str(e))
  1863. if_obj.Set(WPAS_DBUS_IFACE, "FastReauth", dbus.Boolean(True),
  1864. dbus_interface=dbus.PROPERTIES_IFACE)
  1865. def test_dbus_bss_expire(dev, apdev):
  1866. """D-Bus Get/Set BSSExpireAge and BSSExpireCount"""
  1867. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1868. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.UInt32(179),
  1869. dbus_interface=dbus.PROPERTIES_IFACE)
  1870. res = if_obj.Get(WPAS_DBUS_IFACE, "BSSExpireAge",
  1871. dbus_interface=dbus.PROPERTIES_IFACE)
  1872. if res != 179:
  1873. raise Exception("Unexpected BSSExpireAge value %d (expected %d)" % (res, i))
  1874. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.UInt32(3),
  1875. dbus_interface=dbus.PROPERTIES_IFACE)
  1876. res = if_obj.Get(WPAS_DBUS_IFACE, "BSSExpireCount",
  1877. dbus_interface=dbus.PROPERTIES_IFACE)
  1878. if res != 3:
  1879. raise Exception("Unexpected BSSExpireCount value %d (expected %d)" % (res, i))
  1880. try:
  1881. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.Int16(-1),
  1882. dbus_interface=dbus.PROPERTIES_IFACE)
  1883. raise Exception("Invalid Set(BSSExpireAge,-1) accepted")
  1884. except dbus.exceptions.DBusException, e:
  1885. if "Error.Failed: wrong property type" not in str(e):
  1886. raise Exception("Unexpected error message for invalid Set(BSSExpireAge,-1): " + str(e))
  1887. try:
  1888. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.UInt32(9),
  1889. dbus_interface=dbus.PROPERTIES_IFACE)
  1890. raise Exception("Invalid Set(BSSExpireAge,9) accepted")
  1891. except dbus.exceptions.DBusException, e:
  1892. if "Error.Failed: BSSExpireAge must be >= 10" not in str(e):
  1893. raise Exception("Unexpected error message for invalid Set(BSSExpireAge,9): " + str(e))
  1894. try:
  1895. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.Int16(-1),
  1896. dbus_interface=dbus.PROPERTIES_IFACE)
  1897. raise Exception("Invalid Set(BSSExpireCount,-1) accepted")
  1898. except dbus.exceptions.DBusException, e:
  1899. if "Error.Failed: wrong property type" not in str(e):
  1900. raise Exception("Unexpected error message for invalid Set(BSSExpireCount,-1): " + str(e))
  1901. try:
  1902. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.UInt32(0),
  1903. dbus_interface=dbus.PROPERTIES_IFACE)
  1904. raise Exception("Invalid Set(BSSExpireCount,0) accepted")
  1905. except dbus.exceptions.DBusException, e:
  1906. if "Error.Failed: BSSExpireCount must be > 0" not in str(e):
  1907. raise Exception("Unexpected error message for invalid Set(BSSExpireCount,0): " + str(e))
  1908. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.UInt32(180),
  1909. dbus_interface=dbus.PROPERTIES_IFACE)
  1910. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.UInt32(2),
  1911. dbus_interface=dbus.PROPERTIES_IFACE)
  1912. def test_dbus_country(dev, apdev):
  1913. """D-Bus Get/Set Country"""
  1914. try:
  1915. _test_dbus_country(dev, apdev)
  1916. finally:
  1917. dev[0].request("SET country 00")
  1918. subprocess.call(['iw', 'reg', 'set', '00'])
  1919. def _test_dbus_country(dev, apdev):
  1920. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1921. # work around issues with possible pending regdom event from the end of
  1922. # the previous test case
  1923. time.sleep(0.2)
  1924. dev[0].dump_monitor()
  1925. if_obj.Set(WPAS_DBUS_IFACE, "Country", "FI",
  1926. dbus_interface=dbus.PROPERTIES_IFACE)
  1927. res = if_obj.Get(WPAS_DBUS_IFACE, "Country",
  1928. dbus_interface=dbus.PROPERTIES_IFACE)
  1929. if res != "FI":
  1930. raise Exception("Unexpected Country value %s (expected FI)" % res)
  1931. ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"])
  1932. if ev is None:
  1933. # For now, work around separate P2P Device interface event delivery
  1934. ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
  1935. if ev is None:
  1936. raise Exception("regdom change event not seen")
  1937. if "init=USER type=COUNTRY alpha2=FI" not in ev:
  1938. raise Exception("Unexpected event contents: " + ev)
  1939. try:
  1940. if_obj.Set(WPAS_DBUS_IFACE, "Country", dbus.Int16(-1),
  1941. dbus_interface=dbus.PROPERTIES_IFACE)
  1942. raise Exception("Invalid Set(Country,-1) accepted")
  1943. except dbus.exceptions.DBusException, e:
  1944. if "Error.Failed: wrong property type" not in str(e):
  1945. raise Exception("Unexpected error message for invalid Set(Country,-1): " + str(e))
  1946. try:
  1947. if_obj.Set(WPAS_DBUS_IFACE, "Country", "F",
  1948. dbus_interface=dbus.PROPERTIES_IFACE)
  1949. raise Exception("Invalid Set(Country,F) accepted")
  1950. except dbus.exceptions.DBusException, e:
  1951. if "Error.Failed: invalid country code" not in str(e):
  1952. raise Exception("Unexpected error message for invalid Set(Country,F): " + str(e))
  1953. if_obj.Set(WPAS_DBUS_IFACE, "Country", "00",
  1954. dbus_interface=dbus.PROPERTIES_IFACE)
  1955. ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"])
  1956. if ev is None:
  1957. # For now, work around separate P2P Device interface event delivery
  1958. ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
  1959. if ev is None:
  1960. raise Exception("regdom change event not seen")
  1961. if "init=CORE type=WORLD" not in ev:
  1962. raise Exception("Unexpected event contents: " + ev)
  1963. def test_dbus_scan_interval(dev, apdev):
  1964. """D-Bus Get/Set ScanInterval"""
  1965. try:
  1966. _test_dbus_scan_interval(dev, apdev)
  1967. finally:
  1968. dev[0].request("SCAN_INTERVAL 5")
  1969. def _test_dbus_scan_interval(dev, apdev):
  1970. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1971. if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.Int32(3),
  1972. dbus_interface=dbus.PROPERTIES_IFACE)
  1973. res = if_obj.Get(WPAS_DBUS_IFACE, "ScanInterval",
  1974. dbus_interface=dbus.PROPERTIES_IFACE)
  1975. if res != 3:
  1976. raise Exception("Unexpected ScanInterval value %d (expected %d)" % (res, i))
  1977. try:
  1978. if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.UInt16(100),
  1979. dbus_interface=dbus.PROPERTIES_IFACE)
  1980. raise Exception("Invalid Set(ScanInterval,100) accepted")
  1981. except dbus.exceptions.DBusException, e:
  1982. if "Error.Failed: wrong property type" not in str(e):
  1983. raise Exception("Unexpected error message for invalid Set(ScanInterval,100): " + str(e))
  1984. try:
  1985. if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.Int32(-1),
  1986. dbus_interface=dbus.PROPERTIES_IFACE)
  1987. raise Exception("Invalid Set(ScanInterval,-1) accepted")
  1988. except dbus.exceptions.DBusException, e:
  1989. if "Error.Failed: scan_interval must be >= 0" not in str(e):
  1990. raise Exception("Unexpected error message for invalid Set(ScanInterval,-1): " + str(e))
  1991. if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.Int32(5),
  1992. dbus_interface=dbus.PROPERTIES_IFACE)
  1993. def test_dbus_probe_req_reporting(dev, apdev):
  1994. """D-Bus Probe Request reporting"""
  1995. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1996. dev[1].p2p_find(social=True)
  1997. class TestDbusProbe(TestDbus):
  1998. def __init__(self, bus):
  1999. TestDbus.__init__(self, bus)
  2000. self.reported = False
  2001. def __enter__(self):
  2002. gobject.timeout_add(1, self.run_test)
  2003. gobject.timeout_add(15000, self.timeout)
  2004. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2005. "GroupStarted")
  2006. self.add_signal(self.probeRequest, WPAS_DBUS_IFACE, "ProbeRequest",
  2007. byte_arrays=True)
  2008. self.loop.run()
  2009. return self
  2010. def groupStarted(self, properties):
  2011. logger.debug("groupStarted: " + str(properties))
  2012. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  2013. properties['interface_object'])
  2014. self.iface = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE)
  2015. self.iface.SubscribeProbeReq()
  2016. self.group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2017. def probeRequest(self, args):
  2018. logger.debug("probeRequest: args=%s" % str(args))
  2019. self.reported = True
  2020. self.loop.quit()
  2021. def run_test(self, *args):
  2022. logger.debug("run_test")
  2023. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2024. params = dbus.Dictionary({ 'frequency': 2412 })
  2025. p2p.GroupAdd(params)
  2026. return False
  2027. def success(self):
  2028. return self.reported
  2029. with TestDbusProbe(bus) as t:
  2030. if not t.success():
  2031. raise Exception("Expected signals not seen")
  2032. t.iface.UnsubscribeProbeReq()
  2033. try:
  2034. t.iface.UnsubscribeProbeReq()
  2035. raise Exception("Invalid UnsubscribeProbeReq() accepted")
  2036. except dbus.exceptions.DBusException, e:
  2037. if "NoSubscription" not in str(e):
  2038. raise Exception("Unexpected error message for invalid UnsubscribeProbeReq(): " + str(e))
  2039. t.group_p2p.Disconnect()
  2040. with TestDbusProbe(bus) as t:
  2041. if not t.success():
  2042. raise Exception("Expected signals not seen")
  2043. # On purpose, leave ProbeReq subscription in place to test automatic
  2044. # cleanup.
  2045. dev[1].p2p_stop_find()
  2046. def test_dbus_probe_req_reporting_oom(dev, apdev):
  2047. """D-Bus Probe Request reporting (OOM)"""
  2048. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2049. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  2050. # Need to make sure this process has not already subscribed to avoid false
  2051. # failures due to the operation succeeding due to os_strdup() not even
  2052. # getting called.
  2053. try:
  2054. iface.UnsubscribeProbeReq()
  2055. was_subscribed = True
  2056. except dbus.exceptions.DBusException, e:
  2057. was_subscribed = False
  2058. pass
  2059. with alloc_fail_dbus(dev[0], 1, "wpas_dbus_handler_subscribe_preq",
  2060. "SubscribeProbeReq"):
  2061. iface.SubscribeProbeReq()
  2062. if was_subscribed:
  2063. # On purpose, leave ProbeReq subscription in place to test automatic
  2064. # cleanup.
  2065. iface.SubscribeProbeReq()
  2066. def test_dbus_p2p_invalid(dev, apdev):
  2067. """D-Bus invalid P2P operations"""
  2068. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2069. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2070. try:
  2071. p2p.RejectPeer(path + "/Peers/00112233445566")
  2072. raise Exception("Invalid RejectPeer accepted")
  2073. except dbus.exceptions.DBusException, e:
  2074. if "UnknownError: Failed to call wpas_p2p_reject" not in str(e):
  2075. raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
  2076. try:
  2077. p2p.RejectPeer("/foo")
  2078. raise Exception("Invalid RejectPeer accepted")
  2079. except dbus.exceptions.DBusException, e:
  2080. if "InvalidArgs" not in str(e):
  2081. raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
  2082. tests = [ { },
  2083. { 'peer': 'foo' },
  2084. { 'foo': "bar" },
  2085. { 'iface': "abc" },
  2086. { 'iface': 123 } ]
  2087. for t in tests:
  2088. try:
  2089. p2p.RemoveClient(t)
  2090. raise Exception("Invalid RemoveClient accepted")
  2091. except dbus.exceptions.DBusException, e:
  2092. if "InvalidArgs" not in str(e):
  2093. raise Exception("Unexpected error message for invalid RemoveClient(): " + str(e))
  2094. tests = [ {'DiscoveryType': 'foo'},
  2095. {'RequestedDeviceTypes': 'foo'},
  2096. {'RequestedDeviceTypes': ['foo']},
  2097. {'RequestedDeviceTypes': ['1','2','3','4','5','6','7','8','9',
  2098. '10','11','12','13','14','15','16',
  2099. '17']},
  2100. {'RequestedDeviceTypes': dbus.Array([], signature="s")},
  2101. {'RequestedDeviceTypes': dbus.Array([['foo']], signature="as")},
  2102. {'RequestedDeviceTypes': dbus.Array([], signature="i")},
  2103. {'RequestedDeviceTypes': [dbus.ByteArray('12345678'),
  2104. dbus.ByteArray('1234567')]},
  2105. {'Foo': dbus.Int16(1)},
  2106. {'Foo': dbus.UInt16(1)},
  2107. {'Foo': dbus.Int64(1)},
  2108. {'Foo': dbus.UInt64(1)},
  2109. {'Foo': dbus.Double(1.23)},
  2110. {'Foo': dbus.Signature('s')},
  2111. {'Foo': 'bar'}]
  2112. for t in tests:
  2113. try:
  2114. p2p.Find(dbus.Dictionary(t))
  2115. raise Exception("Invalid Find accepted")
  2116. except dbus.exceptions.DBusException, e:
  2117. if "InvalidArgs" not in str(e):
  2118. raise Exception("Unexpected error message for invalid Find(): " + str(e))
  2119. for p in [ "/foo",
  2120. "/fi/w1/wpa_supplicant1/Interfaces/1234",
  2121. "/fi/w1/wpa_supplicant1/Interfaces/1234/Networks/1234" ]:
  2122. try:
  2123. p2p.RemovePersistentGroup(dbus.ObjectPath(p))
  2124. raise Exception("Invalid RemovePersistentGroup accepted")
  2125. except dbus.exceptions.DBusException, e:
  2126. if "InvalidArgs" not in str(e):
  2127. raise Exception("Unexpected error message for invalid RemovePersistentGroup: " + str(e))
  2128. try:
  2129. dev[0].request("P2P_SET disabled 1")
  2130. p2p.Listen(5)
  2131. raise Exception("Invalid Listen accepted")
  2132. except dbus.exceptions.DBusException, e:
  2133. if "UnknownError: Could not start P2P listen" not in str(e):
  2134. raise Exception("Unexpected error message for invalid Listen: " + str(e))
  2135. finally:
  2136. dev[0].request("P2P_SET disabled 0")
  2137. test_obj = bus.get_object(WPAS_DBUS_SERVICE, path, introspect=False)
  2138. test_p2p = dbus.Interface(test_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2139. try:
  2140. test_p2p.Listen("foo")
  2141. raise Exception("Invalid Listen accepted")
  2142. except dbus.exceptions.DBusException, e:
  2143. if "InvalidArgs" not in str(e):
  2144. raise Exception("Unexpected error message for invalid Listen: " + str(e))
  2145. try:
  2146. dev[0].request("P2P_SET disabled 1")
  2147. p2p.ExtendedListen(dbus.Dictionary({}))
  2148. raise Exception("Invalid ExtendedListen accepted")
  2149. except dbus.exceptions.DBusException, e:
  2150. if "UnknownError: failed to initiate a p2p_ext_listen" not in str(e):
  2151. raise Exception("Unexpected error message for invalid ExtendedListen: " + str(e))
  2152. finally:
  2153. dev[0].request("P2P_SET disabled 0")
  2154. try:
  2155. dev[0].request("P2P_SET disabled 1")
  2156. args = { 'duration1': 30000, 'interval1': 102400,
  2157. 'duration2': 20000, 'interval2': 102400 }
  2158. p2p.PresenceRequest(args)
  2159. raise Exception("Invalid PresenceRequest accepted")
  2160. except dbus.exceptions.DBusException, e:
  2161. if "UnknownError: Failed to invoke presence request" not in str(e):
  2162. raise Exception("Unexpected error message for invalid PresenceRequest: " + str(e))
  2163. finally:
  2164. dev[0].request("P2P_SET disabled 0")
  2165. try:
  2166. params = dbus.Dictionary({'frequency': dbus.Int32(-1)})
  2167. p2p.GroupAdd(params)
  2168. raise Exception("Invalid GroupAdd accepted")
  2169. except dbus.exceptions.DBusException, e:
  2170. if "InvalidArgs" not in str(e):
  2171. raise Exception("Unexpected error message for invalid GroupAdd: " + str(e))
  2172. try:
  2173. params = dbus.Dictionary({'persistent_group_object':
  2174. dbus.ObjectPath(path),
  2175. 'frequency': 2412})
  2176. p2p.GroupAdd(params)
  2177. raise Exception("Invalid GroupAdd accepted")
  2178. except dbus.exceptions.DBusException, e:
  2179. if "InvalidArgs" not in str(e):
  2180. raise Exception("Unexpected error message for invalid GroupAdd: " + str(e))
  2181. try:
  2182. p2p.Disconnect()
  2183. raise Exception("Invalid Disconnect accepted")
  2184. except dbus.exceptions.DBusException, e:
  2185. if "UnknownError: failed to disconnect" not in str(e):
  2186. raise Exception("Unexpected error message for invalid Disconnect: " + str(e))
  2187. try:
  2188. dev[0].request("P2P_SET disabled 1")
  2189. p2p.Flush()
  2190. raise Exception("Invalid Flush accepted")
  2191. except dbus.exceptions.DBusException, e:
  2192. if "Error.Failed: P2P is not available for this interface" not in str(e):
  2193. raise Exception("Unexpected error message for invalid Flush: " + str(e))
  2194. finally:
  2195. dev[0].request("P2P_SET disabled 0")
  2196. try:
  2197. dev[0].request("P2P_SET disabled 1")
  2198. args = { 'peer': path,
  2199. 'join': True,
  2200. 'wps_method': 'pbc',
  2201. 'frequency': 2412 }
  2202. pin = p2p.Connect(args)
  2203. raise Exception("Invalid Connect accepted")
  2204. except dbus.exceptions.DBusException, e:
  2205. if "Error.Failed: P2P is not available for this interface" not in str(e):
  2206. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  2207. finally:
  2208. dev[0].request("P2P_SET disabled 0")
  2209. tests = [ { 'frequency': dbus.Int32(-1) },
  2210. { 'wps_method': 'pbc' },
  2211. { 'wps_method': 'foo' } ]
  2212. for args in tests:
  2213. try:
  2214. pin = p2p.Connect(args)
  2215. raise Exception("Invalid Connect accepted")
  2216. except dbus.exceptions.DBusException, e:
  2217. if "InvalidArgs" not in str(e):
  2218. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  2219. try:
  2220. dev[0].request("P2P_SET disabled 1")
  2221. args = { 'peer': path }
  2222. pin = p2p.Invite(args)
  2223. raise Exception("Invalid Invite accepted")
  2224. except dbus.exceptions.DBusException, e:
  2225. if "Error.Failed: P2P is not available for this interface" not in str(e):
  2226. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  2227. finally:
  2228. dev[0].request("P2P_SET disabled 0")
  2229. try:
  2230. args = { 'foo': 'bar' }
  2231. pin = p2p.Invite(args)
  2232. raise Exception("Invalid Invite accepted")
  2233. except dbus.exceptions.DBusException, e:
  2234. if "InvalidArgs" not in str(e):
  2235. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  2236. tests = [ (path, 'display', "InvalidArgs"),
  2237. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2238. 'display',
  2239. "UnknownError: Failed to send provision discovery request"),
  2240. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2241. 'keypad',
  2242. "UnknownError: Failed to send provision discovery request"),
  2243. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2244. 'pbc',
  2245. "UnknownError: Failed to send provision discovery request"),
  2246. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2247. 'pushbutton',
  2248. "UnknownError: Failed to send provision discovery request"),
  2249. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2250. 'foo', "InvalidArgs") ]
  2251. for (p,method,err) in tests:
  2252. try:
  2253. p2p.ProvisionDiscoveryRequest(p, method)
  2254. raise Exception("Invalid ProvisionDiscoveryRequest accepted")
  2255. except dbus.exceptions.DBusException, e:
  2256. if err not in str(e):
  2257. raise Exception("Unexpected error message for invalid ProvisionDiscoveryRequest: " + str(e))
  2258. try:
  2259. dev[0].request("P2P_SET disabled 1")
  2260. if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Peers",
  2261. dbus_interface=dbus.PROPERTIES_IFACE)
  2262. raise Exception("Invalid Get(Peers) accepted")
  2263. except dbus.exceptions.DBusException, e:
  2264. if "Error.Failed: P2P is not available for this interface" not in str(e):
  2265. raise Exception("Unexpected error message for invalid Get(Peers): " + str(e))
  2266. finally:
  2267. dev[0].request("P2P_SET disabled 0")
  2268. def test_dbus_p2p_oom(dev, apdev):
  2269. """D-Bus P2P operations and OOM"""
  2270. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2271. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2272. with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_entry_get_string_array",
  2273. "Find", "InvalidArgs"):
  2274. p2p.Find(dbus.Dictionary({ 'Foo': [ 'bar' ] }))
  2275. with alloc_fail_dbus(dev[0], 2, "_wpa_dbus_dict_entry_get_string_array",
  2276. "Find", "InvalidArgs"):
  2277. p2p.Find(dbus.Dictionary({ 'Foo': [ 'bar' ] }))
  2278. with alloc_fail_dbus(dev[0], 10, "_wpa_dbus_dict_entry_get_string_array",
  2279. "Find", "InvalidArgs"):
  2280. p2p.Find(dbus.Dictionary({ 'Foo': [ '1','2','3','4','5','6','7','8','9' ] }))
  2281. with alloc_fail_dbus(dev[0], 1, ":=_wpa_dbus_dict_entry_get_binarray",
  2282. "Find", "InvalidArgs"):
  2283. p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123') ] }))
  2284. with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_entry_get_byte_array;_wpa_dbus_dict_entry_get_binarray",
  2285. "Find", "InvalidArgs"):
  2286. p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123') ] }))
  2287. with alloc_fail_dbus(dev[0], 2, "=_wpa_dbus_dict_entry_get_binarray",
  2288. "Find", "InvalidArgs"):
  2289. p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123'),
  2290. dbus.ByteArray('123'),
  2291. dbus.ByteArray('123'),
  2292. dbus.ByteArray('123'),
  2293. dbus.ByteArray('123'),
  2294. dbus.ByteArray('123'),
  2295. dbus.ByteArray('123'),
  2296. dbus.ByteArray('123'),
  2297. dbus.ByteArray('123'),
  2298. dbus.ByteArray('123'),
  2299. dbus.ByteArray('123') ] }))
  2300. with alloc_fail_dbus(dev[0], 1, "wpabuf_alloc_ext_data;_wpa_dbus_dict_entry_get_binarray",
  2301. "Find", "InvalidArgs"):
  2302. p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123') ] }))
  2303. with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_fill_value_from_variant;wpas_dbus_handler_p2p_find",
  2304. "Find", "InvalidArgs"):
  2305. p2p.Find(dbus.Dictionary({ 'Foo': path }))
  2306. with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_entry_get_byte_array",
  2307. "AddService", "InvalidArgs"):
  2308. args = { 'service_type': 'bonjour',
  2309. 'response': dbus.ByteArray(500*'b') }
  2310. p2p.AddService(args)
  2311. with alloc_fail_dbus(dev[0], 2, "_wpa_dbus_dict_entry_get_byte_array",
  2312. "AddService", "InvalidArgs"):
  2313. p2p.AddService(args)
  2314. def test_dbus_p2p_discovery(dev, apdev):
  2315. """D-Bus P2P discovery"""
  2316. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2317. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2318. addr0 = dev[0].p2p_dev_addr()
  2319. dev[1].request("SET sec_device_type 1-0050F204-2")
  2320. dev[1].request("VENDOR_ELEM_ADD 1 dd0c0050f2041049000411223344")
  2321. dev[1].p2p_listen()
  2322. addr1 = dev[1].p2p_dev_addr()
  2323. a1 = binascii.unhexlify(addr1.replace(':',''))
  2324. wfd_devinfo = "00001c440028"
  2325. dev[2].request("SET wifi_display 1")
  2326. dev[2].request("WFD_SUBELEM_SET 0 0006" + wfd_devinfo)
  2327. wfd = binascii.unhexlify('000006' + wfd_devinfo)
  2328. dev[2].p2p_listen()
  2329. addr2 = dev[2].p2p_dev_addr()
  2330. a2 = binascii.unhexlify(addr2.replace(':',''))
  2331. res = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
  2332. dbus_interface=dbus.PROPERTIES_IFACE)
  2333. if 'Peers' not in res:
  2334. raise Exception("GetAll result missing Peers")
  2335. if len(res['Peers']) != 0:
  2336. raise Exception("Unexpected peer(s) in the list")
  2337. args = {'DiscoveryType': 'social',
  2338. 'RequestedDeviceTypes': [dbus.ByteArray('12345678')],
  2339. 'Timeout': dbus.Int32(1) }
  2340. p2p.Find(dbus.Dictionary(args))
  2341. p2p.StopFind()
  2342. class TestDbusP2p(TestDbus):
  2343. def __init__(self, bus):
  2344. TestDbus.__init__(self, bus)
  2345. self.found = False
  2346. self.found2 = False
  2347. self.lost = False
  2348. self.find_stopped = False
  2349. def __enter__(self):
  2350. gobject.timeout_add(1, self.run_test)
  2351. gobject.timeout_add(15000, self.timeout)
  2352. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2353. "DeviceFound")
  2354. self.add_signal(self.deviceLost, WPAS_DBUS_IFACE_P2PDEVICE,
  2355. "DeviceLost")
  2356. self.add_signal(self.provisionDiscoveryResponseEnterPin,
  2357. WPAS_DBUS_IFACE_P2PDEVICE,
  2358. "ProvisionDiscoveryResponseEnterPin")
  2359. self.add_signal(self.findStopped, WPAS_DBUS_IFACE_P2PDEVICE,
  2360. "FindStopped")
  2361. self.loop.run()
  2362. return self
  2363. def deviceFound(self, path):
  2364. logger.debug("deviceFound: path=%s" % path)
  2365. res = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Peers",
  2366. dbus_interface=dbus.PROPERTIES_IFACE)
  2367. if len(res) < 1:
  2368. raise Exception("Unexpected number of peers")
  2369. if path not in res:
  2370. raise Exception("Mismatch in peer object path")
  2371. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  2372. res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2373. dbus_interface=dbus.PROPERTIES_IFACE,
  2374. byte_arrays=True)
  2375. logger.debug("peer properties: " + str(res))
  2376. if res['DeviceAddress'] == a1:
  2377. if 'SecondaryDeviceTypes' not in res:
  2378. raise Exception("Missing SecondaryDeviceTypes")
  2379. sec = res['SecondaryDeviceTypes']
  2380. if len(sec) < 1:
  2381. raise Exception("Secondary device type missing")
  2382. if "\x00\x01\x00\x50\xF2\x04\x00\x02" not in sec:
  2383. raise Exception("Secondary device type mismatch")
  2384. if 'VendorExtension' not in res:
  2385. raise Exception("Missing VendorExtension")
  2386. vendor = res['VendorExtension']
  2387. if len(vendor) < 1:
  2388. raise Exception("Vendor extension missing")
  2389. if "\x11\x22\x33\x44" not in vendor:
  2390. raise Exception("Secondary device type mismatch")
  2391. self.found = True
  2392. elif res['DeviceAddress'] == a2:
  2393. if 'IEs' not in res:
  2394. raise Exception("IEs missing")
  2395. if res['IEs'] != wfd:
  2396. raise Exception("IEs mismatch")
  2397. self.found2 = True
  2398. else:
  2399. raise Exception("Unexpected peer device address")
  2400. if self.found and self.found2:
  2401. p2p.StopFind()
  2402. p2p.RejectPeer(path)
  2403. p2p.ProvisionDiscoveryRequest(path, 'display')
  2404. def deviceLost(self, path):
  2405. logger.debug("deviceLost: path=%s" % path)
  2406. self.lost = True
  2407. try:
  2408. p2p.RejectPeer(path)
  2409. raise Exception("Invalid RejectPeer accepted")
  2410. except dbus.exceptions.DBusException, e:
  2411. if "UnknownError: Failed to call wpas_p2p_reject" not in str(e):
  2412. raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
  2413. self.loop.quit()
  2414. def provisionDiscoveryResponseEnterPin(self, peer_object):
  2415. logger.debug("provisionDiscoveryResponseEnterPin - peer=%s" % peer_object)
  2416. p2p.Flush()
  2417. def findStopped(self):
  2418. logger.debug("findStopped")
  2419. self.find_stopped = True
  2420. def run_test(self, *args):
  2421. logger.debug("run_test")
  2422. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social',
  2423. 'Timeout': dbus.Int32(10)}))
  2424. return False
  2425. def success(self):
  2426. return self.found and self.lost and self.found2 and self.find_stopped
  2427. with TestDbusP2p(bus) as t:
  2428. if not t.success():
  2429. raise Exception("Expected signals not seen")
  2430. dev[1].request("VENDOR_ELEM_REMOVE 1 *")
  2431. dev[1].p2p_stop_find()
  2432. p2p.Listen(1)
  2433. dev[2].p2p_stop_find()
  2434. dev[2].request("P2P_FLUSH")
  2435. if not dev[2].discover_peer(addr0):
  2436. raise Exception("Peer not found")
  2437. p2p.StopFind()
  2438. dev[2].p2p_stop_find()
  2439. try:
  2440. p2p.ExtendedListen(dbus.Dictionary({'foo': 100}))
  2441. raise Exception("Invalid ExtendedListen accepted")
  2442. except dbus.exceptions.DBusException, e:
  2443. if "InvalidArgs" not in str(e):
  2444. raise Exception("Unexpected error message for invalid ExtendedListen(): " + str(e))
  2445. p2p.ExtendedListen(dbus.Dictionary({'period': 100, 'interval': 1000}))
  2446. p2p.ExtendedListen(dbus.Dictionary({}))
  2447. dev[0].global_request("P2P_EXT_LISTEN")
  2448. def test_dbus_p2p_service_discovery(dev, apdev):
  2449. """D-Bus P2P service discovery"""
  2450. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2451. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2452. addr0 = dev[0].p2p_dev_addr()
  2453. addr1 = dev[1].p2p_dev_addr()
  2454. bonjour_query = dbus.ByteArray(binascii.unhexlify('0b5f6166706f766572746370c00c000c01'))
  2455. bonjour_response = dbus.ByteArray(binascii.unhexlify('074578616d706c65c027'))
  2456. args = { 'service_type': 'bonjour',
  2457. 'query': bonjour_query,
  2458. 'response': bonjour_response }
  2459. p2p.AddService(args)
  2460. p2p.FlushService()
  2461. p2p.AddService(args)
  2462. try:
  2463. p2p.DeleteService(args)
  2464. raise Exception("Invalid DeleteService() accepted")
  2465. except dbus.exceptions.DBusException, e:
  2466. if "InvalidArgs" not in str(e):
  2467. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  2468. args = { 'service_type': 'bonjour',
  2469. 'query': bonjour_query }
  2470. p2p.DeleteService(args)
  2471. try:
  2472. p2p.DeleteService(args)
  2473. raise Exception("Invalid DeleteService() accepted")
  2474. except dbus.exceptions.DBusException, e:
  2475. if "InvalidArgs" not in str(e):
  2476. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  2477. args = { 'service_type': 'upnp',
  2478. 'version': 0x10,
  2479. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' }
  2480. p2p.AddService(args)
  2481. p2p.DeleteService(args)
  2482. try:
  2483. p2p.DeleteService(args)
  2484. raise Exception("Invalid DeleteService() accepted")
  2485. except dbus.exceptions.DBusException, e:
  2486. if "InvalidArgs" not in str(e):
  2487. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  2488. tests = [ { 'service_type': 'foo' },
  2489. { 'service_type': 'foo', 'query': bonjour_query },
  2490. { 'service_type': 'upnp' },
  2491. { 'service_type': 'upnp', 'version': 0x10 },
  2492. { 'service_type': 'upnp',
  2493. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
  2494. { 'version': 0x10,
  2495. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
  2496. { 'service_type': 'upnp', 'foo': 'bar' },
  2497. { 'service_type': 'bonjour' },
  2498. { 'service_type': 'bonjour', 'query': 'foo' },
  2499. { 'service_type': 'bonjour', 'foo': 'bar' } ]
  2500. for args in tests:
  2501. try:
  2502. p2p.DeleteService(args)
  2503. raise Exception("Invalid DeleteService() accepted")
  2504. except dbus.exceptions.DBusException, e:
  2505. if "InvalidArgs" not in str(e):
  2506. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  2507. tests = [ { 'service_type': 'foo' },
  2508. { 'service_type': 'upnp' },
  2509. { 'service_type': 'upnp', 'version': 0x10 },
  2510. { 'service_type': 'upnp',
  2511. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
  2512. { 'version': 0x10,
  2513. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
  2514. { 'service_type': 'upnp', 'foo': 'bar' },
  2515. { 'service_type': 'bonjour' },
  2516. { 'service_type': 'bonjour', 'query': 'foo' },
  2517. { 'service_type': 'bonjour', 'response': 'foo' },
  2518. { 'service_type': 'bonjour', 'query': bonjour_query },
  2519. { 'service_type': 'bonjour', 'response': bonjour_response },
  2520. { 'service_type': 'bonjour', 'query': dbus.ByteArray(500*'a') },
  2521. { 'service_type': 'bonjour', 'foo': 'bar' } ]
  2522. for args in tests:
  2523. try:
  2524. p2p.AddService(args)
  2525. raise Exception("Invalid AddService() accepted")
  2526. except dbus.exceptions.DBusException, e:
  2527. if "InvalidArgs" not in str(e):
  2528. raise Exception("Unexpected error message for invalid AddService(): " + str(e))
  2529. args = { 'tlv': dbus.ByteArray("\x02\x00\x00\x01") }
  2530. ref = p2p.ServiceDiscoveryRequest(args)
  2531. p2p.ServiceDiscoveryCancelRequest(ref)
  2532. try:
  2533. p2p.ServiceDiscoveryCancelRequest(ref)
  2534. raise Exception("Invalid ServiceDiscoveryCancelRequest() accepted")
  2535. except dbus.exceptions.DBusException, e:
  2536. if "InvalidArgs" not in str(e):
  2537. raise Exception("Unexpected error message for invalid AddService(): " + str(e))
  2538. try:
  2539. p2p.ServiceDiscoveryCancelRequest(dbus.UInt64(0))
  2540. raise Exception("Invalid ServiceDiscoveryCancelRequest() accepted")
  2541. except dbus.exceptions.DBusException, e:
  2542. if "InvalidArgs" not in str(e):
  2543. raise Exception("Unexpected error message for invalid AddService(): " + str(e))
  2544. args = { 'service_type': 'upnp',
  2545. 'version': 0x10,
  2546. 'service': 'ssdp:foo' }
  2547. ref = p2p.ServiceDiscoveryRequest(args)
  2548. p2p.ServiceDiscoveryCancelRequest(ref)
  2549. tests = [ { 'service_type': 'foo' },
  2550. { 'foo': 'bar' },
  2551. { 'tlv': 'foo' },
  2552. { },
  2553. { 'version': 0 },
  2554. { 'service_type': 'upnp',
  2555. 'service': 'ssdp:foo' },
  2556. { 'service_type': 'upnp',
  2557. 'version': 0x10 },
  2558. { 'service_type': 'upnp',
  2559. 'version': 0x10,
  2560. 'service': 'ssdp:foo',
  2561. 'peer_object': dbus.ObjectPath(path + "/Peers") },
  2562. { 'service_type': 'upnp',
  2563. 'version': 0x10,
  2564. 'service': 'ssdp:foo',
  2565. 'peer_object': path + "/Peers" },
  2566. { 'service_type': 'upnp',
  2567. 'version': 0x10,
  2568. 'service': 'ssdp:foo',
  2569. 'peer_object': dbus.ObjectPath(path + "/Peers/00112233445566") } ]
  2570. for args in tests:
  2571. try:
  2572. p2p.ServiceDiscoveryRequest(args)
  2573. raise Exception("Invalid ServiceDiscoveryRequest accepted")
  2574. except dbus.exceptions.DBusException, e:
  2575. if "InvalidArgs" not in str(e):
  2576. raise Exception("Unexpected error message for invalid ServiceDiscoveryRequest(): " + str(e))
  2577. args = { 'foo': 'bar' }
  2578. try:
  2579. p2p.ServiceDiscoveryResponse(dbus.Dictionary(args, signature='sv'))
  2580. raise Exception("Invalid ServiceDiscoveryResponse accepted")
  2581. except dbus.exceptions.DBusException, e:
  2582. if "InvalidArgs" not in str(e):
  2583. raise Exception("Unexpected error message for invalid ServiceDiscoveryResponse(): " + str(e))
  2584. def test_dbus_p2p_service_discovery_query(dev, apdev):
  2585. """D-Bus P2P service discovery query"""
  2586. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2587. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2588. addr0 = dev[0].p2p_dev_addr()
  2589. dev[1].request("P2P_SERVICE_ADD bonjour 0b5f6166706f766572746370c00c000c01 074578616d706c65c027")
  2590. dev[1].p2p_listen()
  2591. addr1 = dev[1].p2p_dev_addr()
  2592. class TestDbusP2p(TestDbus):
  2593. def __init__(self, bus):
  2594. TestDbus.__init__(self, bus)
  2595. self.done = False
  2596. def __enter__(self):
  2597. gobject.timeout_add(1, self.run_test)
  2598. gobject.timeout_add(15000, self.timeout)
  2599. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2600. "DeviceFound")
  2601. self.add_signal(self.serviceDiscoveryResponse,
  2602. WPAS_DBUS_IFACE_P2PDEVICE,
  2603. "ServiceDiscoveryResponse", byte_arrays=True)
  2604. self.loop.run()
  2605. return self
  2606. def deviceFound(self, path):
  2607. logger.debug("deviceFound: path=%s" % path)
  2608. args = { 'peer_object': path,
  2609. 'tlv': dbus.ByteArray("\x02\x00\x00\x01") }
  2610. p2p.ServiceDiscoveryRequest(args)
  2611. def serviceDiscoveryResponse(self, sd_request):
  2612. logger.debug("serviceDiscoveryResponse: sd_request=%s" % str(sd_request))
  2613. self.done = True
  2614. self.loop.quit()
  2615. def run_test(self, *args):
  2616. logger.debug("run_test")
  2617. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social',
  2618. 'Timeout': dbus.Int32(10)}))
  2619. return False
  2620. def success(self):
  2621. return self.done
  2622. with TestDbusP2p(bus) as t:
  2623. if not t.success():
  2624. raise Exception("Expected signals not seen")
  2625. dev[1].p2p_stop_find()
  2626. def test_dbus_p2p_service_discovery_external(dev, apdev):
  2627. """D-Bus P2P service discovery with external response"""
  2628. try:
  2629. _test_dbus_p2p_service_discovery_external(dev, apdev)
  2630. finally:
  2631. dev[0].request("P2P_SERV_DISC_EXTERNAL 0")
  2632. def _test_dbus_p2p_service_discovery_external(dev, apdev):
  2633. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2634. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2635. addr0 = dev[0].p2p_dev_addr()
  2636. addr1 = dev[1].p2p_dev_addr()
  2637. resp = "0300000101"
  2638. dev[1].request("P2P_FLUSH")
  2639. dev[1].request("P2P_SERV_DISC_REQ " + addr0 + " 02000001")
  2640. dev[1].p2p_find(social=True)
  2641. class TestDbusP2p(TestDbus):
  2642. def __init__(self, bus):
  2643. TestDbus.__init__(self, bus)
  2644. self.sd = False
  2645. def __enter__(self):
  2646. gobject.timeout_add(1, self.run_test)
  2647. gobject.timeout_add(15000, self.timeout)
  2648. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2649. "DeviceFound")
  2650. self.add_signal(self.serviceDiscoveryRequest,
  2651. WPAS_DBUS_IFACE_P2PDEVICE,
  2652. "ServiceDiscoveryRequest")
  2653. self.loop.run()
  2654. return self
  2655. def deviceFound(self, path):
  2656. logger.debug("deviceFound: path=%s" % path)
  2657. def serviceDiscoveryRequest(self, sd_request):
  2658. logger.debug("serviceDiscoveryRequest: sd_request=%s" % str(sd_request))
  2659. self.sd = True
  2660. args = { 'peer_object': sd_request['peer_object'],
  2661. 'frequency': sd_request['frequency'],
  2662. 'dialog_token': sd_request['dialog_token'],
  2663. 'tlvs': dbus.ByteArray(binascii.unhexlify(resp)) }
  2664. p2p.ServiceDiscoveryResponse(dbus.Dictionary(args, signature='sv'))
  2665. self.loop.quit()
  2666. def run_test(self, *args):
  2667. logger.debug("run_test")
  2668. p2p.ServiceDiscoveryExternal(1)
  2669. p2p.ServiceUpdate()
  2670. p2p.Listen(15)
  2671. return False
  2672. def success(self):
  2673. return self.sd
  2674. with TestDbusP2p(bus) as t:
  2675. if not t.success():
  2676. raise Exception("Expected signals not seen")
  2677. ev = dev[1].wait_global_event(["P2P-SERV-DISC-RESP"], timeout=5)
  2678. if ev is None:
  2679. raise Exception("Service discovery timed out")
  2680. if addr0 not in ev:
  2681. raise Exception("Unexpected address in SD Response: " + ev)
  2682. if ev.split(' ')[4] != resp:
  2683. raise Exception("Unexpected response data SD Response: " + ev)
  2684. dev[1].p2p_stop_find()
  2685. p2p.StopFind()
  2686. p2p.ServiceDiscoveryExternal(0)
  2687. def test_dbus_p2p_autogo(dev, apdev):
  2688. """D-Bus P2P autonomous GO"""
  2689. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2690. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2691. addr0 = dev[0].p2p_dev_addr()
  2692. class TestDbusP2p(TestDbus):
  2693. def __init__(self, bus):
  2694. TestDbus.__init__(self, bus)
  2695. self.first = True
  2696. self.waiting_end = False
  2697. self.exceptions = False
  2698. self.deauthorized = False
  2699. self.done = False
  2700. def __enter__(self):
  2701. gobject.timeout_add(1, self.run_test)
  2702. gobject.timeout_add(15000, self.timeout)
  2703. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2704. "DeviceFound")
  2705. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2706. "GroupStarted")
  2707. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2708. "GroupFinished")
  2709. self.add_signal(self.persistentGroupAdded,
  2710. WPAS_DBUS_IFACE_P2PDEVICE,
  2711. "PersistentGroupAdded")
  2712. self.add_signal(self.persistentGroupRemoved,
  2713. WPAS_DBUS_IFACE_P2PDEVICE,
  2714. "PersistentGroupRemoved")
  2715. self.add_signal(self.provisionDiscoveryRequestDisplayPin,
  2716. WPAS_DBUS_IFACE_P2PDEVICE,
  2717. "ProvisionDiscoveryRequestDisplayPin")
  2718. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  2719. "StaAuthorized")
  2720. self.add_signal(self.staDeauthorized, WPAS_DBUS_IFACE,
  2721. "StaDeauthorized")
  2722. self.loop.run()
  2723. return self
  2724. def groupStarted(self, properties):
  2725. logger.debug("groupStarted: " + str(properties))
  2726. self.group = properties['group_object']
  2727. self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  2728. properties['interface_object'])
  2729. role = self.g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Role",
  2730. dbus_interface=dbus.PROPERTIES_IFACE)
  2731. if role != "GO":
  2732. self.exceptions = True
  2733. raise Exception("Unexpected role reported: " + role)
  2734. group = self.g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Group",
  2735. dbus_interface=dbus.PROPERTIES_IFACE)
  2736. if group != properties['group_object']:
  2737. self.exceptions = True
  2738. raise Exception("Unexpected Group reported: " + str(group))
  2739. go = self.g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PeerGO",
  2740. dbus_interface=dbus.PROPERTIES_IFACE)
  2741. if go != '/':
  2742. self.exceptions = True
  2743. raise Exception("Unexpected PeerGO value: " + str(go))
  2744. if self.first:
  2745. self.first = False
  2746. logger.info("Remove persistent group instance")
  2747. group_p2p = dbus.Interface(self.g_if_obj,
  2748. WPAS_DBUS_IFACE_P2PDEVICE)
  2749. group_p2p.Disconnect()
  2750. else:
  2751. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2752. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 join")
  2753. def groupFinished(self, properties):
  2754. logger.debug("groupFinished: " + str(properties))
  2755. if self.waiting_end:
  2756. logger.info("Remove persistent group")
  2757. p2p.RemovePersistentGroup(self.persistent)
  2758. else:
  2759. logger.info("Re-start persistent group")
  2760. params = dbus.Dictionary({'persistent_group_object':
  2761. self.persistent,
  2762. 'frequency': 2412})
  2763. p2p.GroupAdd(params)
  2764. def persistentGroupAdded(self, path, properties):
  2765. logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
  2766. self.persistent = path
  2767. def persistentGroupRemoved(self, path):
  2768. logger.debug("persistentGroupRemoved: %s" % path)
  2769. self.done = True
  2770. self.loop.quit()
  2771. def deviceFound(self, path):
  2772. logger.debug("deviceFound: path=%s" % path)
  2773. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  2774. self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2775. dbus_interface=dbus.PROPERTIES_IFACE,
  2776. byte_arrays=True)
  2777. logger.debug('peer properties: ' + str(self.peer))
  2778. def provisionDiscoveryRequestDisplayPin(self, peer_object, pin):
  2779. logger.debug("provisionDiscoveryRequestDisplayPin - peer=%s pin=%s" % (peer_object, pin))
  2780. self.peer_path = peer_object
  2781. peer = binascii.unhexlify(peer_object.split('/')[-1])
  2782. addr = ""
  2783. for p in peer:
  2784. if len(addr) > 0:
  2785. addr += ':'
  2786. addr += '%02x' % ord(p)
  2787. params = { 'Role': 'registrar',
  2788. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  2789. 'Bssid': self.peer['DeviceAddress'],
  2790. 'Type': 'pin' }
  2791. wps = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_WPS)
  2792. try:
  2793. wps.Start(params)
  2794. self.exceptions = True
  2795. raise Exception("Invalid WPS.Start() accepted")
  2796. except dbus.exceptions.DBusException, e:
  2797. if "InvalidArgs" not in str(e):
  2798. self.exceptions = True
  2799. raise Exception("Unexpected error message: " + str(e))
  2800. params = { 'Role': 'registrar',
  2801. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  2802. 'Type': 'pin',
  2803. 'Pin': '12345670' }
  2804. logger.info("Authorize peer to connect to the group")
  2805. wps.Start(params)
  2806. def staAuthorized(self, name):
  2807. logger.debug("staAuthorized: " + name)
  2808. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, self.peer_path)
  2809. res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2810. dbus_interface=dbus.PROPERTIES_IFACE,
  2811. byte_arrays=True)
  2812. logger.debug("Peer properties: " + str(res))
  2813. if 'Groups' not in res or len(res['Groups']) != 1:
  2814. self.exceptions = True
  2815. raise Exception("Unexpected number of peer Groups entries")
  2816. if res['Groups'][0] != self.group:
  2817. self.exceptions = True
  2818. raise Exception("Unexpected peer Groups[0] value")
  2819. g_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group)
  2820. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  2821. dbus_interface=dbus.PROPERTIES_IFACE,
  2822. byte_arrays=True)
  2823. logger.debug("Group properties: " + str(res))
  2824. if 'Members' not in res or len(res['Members']) != 1:
  2825. self.exceptions = True
  2826. raise Exception("Unexpected number of group members")
  2827. ext = dbus.ByteArray("\x11\x22\x33\x44")
  2828. # Earlier implementation of this interface was a bit strange. The
  2829. # property is defined to have aay signature and that is what the
  2830. # getter returned. However, the setter expected there to be a
  2831. # dictionary with 'WPSVendorExtensions' as the key surrounding these
  2832. # values.. The current implementations maintains support for that
  2833. # for backwards compability reasons. Verify that encoding first.
  2834. vals = dbus.Dictionary({ 'WPSVendorExtensions': [ ext ]},
  2835. signature='sv')
  2836. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
  2837. dbus_interface=dbus.PROPERTIES_IFACE)
  2838. res = g_obj.Get(WPAS_DBUS_GROUP, 'WPSVendorExtensions',
  2839. dbus_interface=dbus.PROPERTIES_IFACE,
  2840. byte_arrays=True)
  2841. if len(res) != 1:
  2842. self.exceptions = True
  2843. raise Exception("Unexpected number of vendor extensions")
  2844. if res[0] != ext:
  2845. self.exceptions = True
  2846. raise Exception("Vendor extension value changed")
  2847. # And now verify that the more appropriate encoding is accepted as
  2848. # well.
  2849. res.append(dbus.ByteArray('\xaa\xbb\xcc\xdd\xee\xff'))
  2850. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
  2851. dbus_interface=dbus.PROPERTIES_IFACE)
  2852. res2 = g_obj.Get(WPAS_DBUS_GROUP, 'WPSVendorExtensions',
  2853. dbus_interface=dbus.PROPERTIES_IFACE,
  2854. byte_arrays=True)
  2855. if len(res) != 2:
  2856. self.exceptions = True
  2857. raise Exception("Unexpected number of vendor extensions")
  2858. if res[0] != res2[0] or res[1] != res2[1]:
  2859. self.exceptions = True
  2860. raise Exception("Vendor extension value changed")
  2861. for i in range(10):
  2862. res.append(dbus.ByteArray('\xaa\xbb'))
  2863. try:
  2864. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
  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 "Error.Failed" not in str(e):
  2870. self.exceptions = True
  2871. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  2872. vals = dbus.Dictionary({ 'Foo': [ ext ]}, signature='sv')
  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 "InvalidArgs" 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. vals = [ [ "foo" ] ]
  2893. try:
  2894. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
  2895. dbus_interface=dbus.PROPERTIES_IFACE)
  2896. self.exceptions = True
  2897. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  2898. except dbus.exceptions.DBusException, e:
  2899. if "Error.Failed" not in str(e):
  2900. self.exceptions = True
  2901. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  2902. p2p.RemoveClient({ 'peer': self.peer_path })
  2903. self.waiting_end = True
  2904. group_p2p = dbus.Interface(self.g_if_obj,
  2905. WPAS_DBUS_IFACE_P2PDEVICE)
  2906. group_p2p.Disconnect()
  2907. def staDeauthorized(self, name):
  2908. logger.debug("staDeauthorized: " + name)
  2909. self.deauthorized = True
  2910. def run_test(self, *args):
  2911. logger.debug("run_test")
  2912. params = dbus.Dictionary({'persistent': True,
  2913. 'frequency': 2412})
  2914. logger.info("Add a persistent group")
  2915. p2p.GroupAdd(params)
  2916. return False
  2917. def success(self):
  2918. return self.done and self.deauthorized and not self.exceptions
  2919. with TestDbusP2p(bus) as t:
  2920. if not t.success():
  2921. raise Exception("Expected signals not seen")
  2922. dev[1].wait_go_ending_session()
  2923. def test_dbus_p2p_autogo_pbc(dev, apdev):
  2924. """D-Bus P2P autonomous GO and PBC"""
  2925. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2926. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2927. addr0 = dev[0].p2p_dev_addr()
  2928. class TestDbusP2p(TestDbus):
  2929. def __init__(self, bus):
  2930. TestDbus.__init__(self, bus)
  2931. self.first = True
  2932. self.waiting_end = False
  2933. self.done = False
  2934. def __enter__(self):
  2935. gobject.timeout_add(1, self.run_test)
  2936. gobject.timeout_add(15000, self.timeout)
  2937. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2938. "DeviceFound")
  2939. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2940. "GroupStarted")
  2941. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2942. "GroupFinished")
  2943. self.add_signal(self.provisionDiscoveryPBCRequest,
  2944. WPAS_DBUS_IFACE_P2PDEVICE,
  2945. "ProvisionDiscoveryPBCRequest")
  2946. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  2947. "StaAuthorized")
  2948. self.loop.run()
  2949. return self
  2950. def groupStarted(self, properties):
  2951. logger.debug("groupStarted: " + str(properties))
  2952. self.group = properties['group_object']
  2953. self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  2954. properties['interface_object'])
  2955. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2956. dev1.global_request("P2P_CONNECT " + addr0 + " pbc join")
  2957. def groupFinished(self, properties):
  2958. logger.debug("groupFinished: " + str(properties))
  2959. self.done = True
  2960. self.loop.quit()
  2961. def deviceFound(self, path):
  2962. logger.debug("deviceFound: path=%s" % path)
  2963. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  2964. self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2965. dbus_interface=dbus.PROPERTIES_IFACE,
  2966. byte_arrays=True)
  2967. logger.debug('peer properties: ' + str(self.peer))
  2968. def provisionDiscoveryPBCRequest(self, peer_object):
  2969. logger.debug("provisionDiscoveryPBCRequest - peer=%s" % peer_object)
  2970. self.peer_path = peer_object
  2971. peer = binascii.unhexlify(peer_object.split('/')[-1])
  2972. addr = ""
  2973. for p in peer:
  2974. if len(addr) > 0:
  2975. addr += ':'
  2976. addr += '%02x' % ord(p)
  2977. params = { 'Role': 'registrar',
  2978. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  2979. 'Type': 'pbc' }
  2980. logger.info("Authorize peer to connect to the group")
  2981. wps = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_WPS)
  2982. wps.Start(params)
  2983. def staAuthorized(self, name):
  2984. logger.debug("staAuthorized: " + name)
  2985. group_p2p = dbus.Interface(self.g_if_obj,
  2986. WPAS_DBUS_IFACE_P2PDEVICE)
  2987. group_p2p.Disconnect()
  2988. def run_test(self, *args):
  2989. logger.debug("run_test")
  2990. params = dbus.Dictionary({'frequency': 2412})
  2991. p2p.GroupAdd(params)
  2992. return False
  2993. def success(self):
  2994. return self.done
  2995. with TestDbusP2p(bus) as t:
  2996. if not t.success():
  2997. raise Exception("Expected signals not seen")
  2998. dev[1].wait_go_ending_session()
  2999. dev[1].flush_scan_cache()
  3000. def test_dbus_p2p_autogo_legacy(dev, apdev):
  3001. """D-Bus P2P autonomous GO and legacy STA"""
  3002. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3003. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3004. addr0 = dev[0].p2p_dev_addr()
  3005. class TestDbusP2p(TestDbus):
  3006. def __init__(self, bus):
  3007. TestDbus.__init__(self, bus)
  3008. self.done = False
  3009. def __enter__(self):
  3010. gobject.timeout_add(1, self.run_test)
  3011. gobject.timeout_add(15000, self.timeout)
  3012. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3013. "GroupStarted")
  3014. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3015. "GroupFinished")
  3016. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  3017. "StaAuthorized")
  3018. self.loop.run()
  3019. return self
  3020. def groupStarted(self, properties):
  3021. logger.debug("groupStarted: " + str(properties))
  3022. g_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3023. properties['group_object'])
  3024. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  3025. dbus_interface=dbus.PROPERTIES_IFACE,
  3026. byte_arrays=True)
  3027. bssid = ':'.join([binascii.hexlify(l) for l in res['BSSID']])
  3028. pin = '12345670'
  3029. params = { 'Role': 'enrollee',
  3030. 'Type': 'pin',
  3031. 'Pin': pin }
  3032. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3033. properties['interface_object'])
  3034. wps = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_WPS)
  3035. wps.Start(params)
  3036. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3037. dev1.scan_for_bss(bssid, freq=2412)
  3038. dev1.request("WPS_PIN " + bssid + " " + pin)
  3039. self.group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3040. def groupFinished(self, properties):
  3041. logger.debug("groupFinished: " + str(properties))
  3042. self.done = True
  3043. self.loop.quit()
  3044. def staAuthorized(self, name):
  3045. logger.debug("staAuthorized: " + name)
  3046. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3047. dev1.request("DISCONNECT")
  3048. self.group_p2p.Disconnect()
  3049. def run_test(self, *args):
  3050. logger.debug("run_test")
  3051. params = dbus.Dictionary({'frequency': 2412})
  3052. p2p.GroupAdd(params)
  3053. return False
  3054. def success(self):
  3055. return self.done
  3056. with TestDbusP2p(bus) as t:
  3057. if not t.success():
  3058. raise Exception("Expected signals not seen")
  3059. def test_dbus_p2p_join(dev, apdev):
  3060. """D-Bus P2P join an autonomous GO"""
  3061. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3062. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3063. addr1 = dev[1].p2p_dev_addr()
  3064. addr2 = dev[2].p2p_dev_addr()
  3065. dev[1].p2p_start_go(freq=2412)
  3066. dev1_group_ifname = dev[1].group_ifname
  3067. dev[2].p2p_listen()
  3068. class TestDbusP2p(TestDbus):
  3069. def __init__(self, bus):
  3070. TestDbus.__init__(self, bus)
  3071. self.done = False
  3072. self.peer = None
  3073. self.go = None
  3074. def __enter__(self):
  3075. gobject.timeout_add(1, self.run_test)
  3076. gobject.timeout_add(15000, self.timeout)
  3077. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3078. "DeviceFound")
  3079. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3080. "GroupStarted")
  3081. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3082. "GroupFinished")
  3083. self.add_signal(self.invitationResult, WPAS_DBUS_IFACE_P2PDEVICE,
  3084. "InvitationResult")
  3085. self.loop.run()
  3086. return self
  3087. def deviceFound(self, path):
  3088. logger.debug("deviceFound: path=%s" % path)
  3089. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  3090. res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  3091. dbus_interface=dbus.PROPERTIES_IFACE,
  3092. byte_arrays=True)
  3093. logger.debug('peer properties: ' + str(res))
  3094. if addr2.replace(':','') in path:
  3095. self.peer = path
  3096. elif addr1.replace(':','') in path:
  3097. self.go = path
  3098. if self.peer and self.go:
  3099. logger.info("Join the group")
  3100. p2p.StopFind()
  3101. args = { 'peer': self.go,
  3102. 'join': True,
  3103. 'wps_method': 'pin',
  3104. 'frequency': 2412 }
  3105. pin = p2p.Connect(args)
  3106. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3107. dev1.group_ifname = dev1_group_ifname
  3108. dev1.group_request("WPS_PIN any " + pin)
  3109. def groupStarted(self, properties):
  3110. logger.debug("groupStarted: " + str(properties))
  3111. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3112. properties['interface_object'])
  3113. role = g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Role",
  3114. dbus_interface=dbus.PROPERTIES_IFACE)
  3115. if role != "client":
  3116. raise Exception("Unexpected role reported: " + role)
  3117. group = g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Group",
  3118. dbus_interface=dbus.PROPERTIES_IFACE)
  3119. if group != properties['group_object']:
  3120. raise Exception("Unexpected Group reported: " + str(group))
  3121. go = g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PeerGO",
  3122. dbus_interface=dbus.PROPERTIES_IFACE)
  3123. if go != self.go:
  3124. raise Exception("Unexpected PeerGO value: " + str(go))
  3125. g_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3126. properties['group_object'])
  3127. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  3128. dbus_interface=dbus.PROPERTIES_IFACE,
  3129. byte_arrays=True)
  3130. logger.debug("Group properties: " + str(res))
  3131. ext = dbus.ByteArray("\x11\x22\x33\x44")
  3132. try:
  3133. # Set(WPSVendorExtensions) not allowed for P2P Client
  3134. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
  3135. dbus_interface=dbus.PROPERTIES_IFACE)
  3136. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  3137. except dbus.exceptions.DBusException, e:
  3138. if "Error.Failed: Failed to set property" not in str(e):
  3139. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  3140. group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3141. args = { 'duration1': 30000, 'interval1': 102400,
  3142. 'duration2': 20000, 'interval2': 102400 }
  3143. group_p2p.PresenceRequest(args)
  3144. args = { 'peer': self.peer }
  3145. group_p2p.Invite(args)
  3146. def groupFinished(self, properties):
  3147. logger.debug("groupFinished: " + str(properties))
  3148. self.done = True
  3149. self.loop.quit()
  3150. def invitationResult(self, result):
  3151. logger.debug("invitationResult: " + str(result))
  3152. if result['status'] != 1:
  3153. raise Exception("Unexpected invitation result: " + str(result))
  3154. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3155. dev1.group_ifname = dev1_group_ifname
  3156. dev1.remove_group()
  3157. def run_test(self, *args):
  3158. logger.debug("run_test")
  3159. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  3160. return False
  3161. def success(self):
  3162. return self.done
  3163. with TestDbusP2p(bus) as t:
  3164. if not t.success():
  3165. raise Exception("Expected signals not seen")
  3166. dev[2].p2p_stop_find()
  3167. def test_dbus_p2p_invitation_received(dev, apdev):
  3168. """D-Bus P2P and InvitationReceived"""
  3169. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3170. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3171. form(dev[0], dev[1])
  3172. addr0 = dev[0].p2p_dev_addr()
  3173. dev[0].p2p_listen()
  3174. dev[0].global_request("SET persistent_reconnect 0")
  3175. if not dev[1].discover_peer(addr0, social=True):
  3176. raise Exception("Peer " + addr0 + " not found")
  3177. peer = dev[1].get_peer(addr0)
  3178. class TestDbusP2p(TestDbus):
  3179. def __init__(self, bus):
  3180. TestDbus.__init__(self, bus)
  3181. self.done = False
  3182. def __enter__(self):
  3183. gobject.timeout_add(1, self.run_test)
  3184. gobject.timeout_add(15000, self.timeout)
  3185. self.add_signal(self.invitationReceived, WPAS_DBUS_IFACE_P2PDEVICE,
  3186. "InvitationReceived")
  3187. self.loop.run()
  3188. return self
  3189. def invitationReceived(self, result):
  3190. logger.debug("invitationReceived: " + str(result))
  3191. self.done = True
  3192. self.loop.quit()
  3193. def run_test(self, *args):
  3194. logger.debug("run_test")
  3195. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3196. cmd = "P2P_INVITE persistent=" + peer['persistent'] + " peer=" + addr0
  3197. dev1.global_request(cmd)
  3198. return False
  3199. def success(self):
  3200. return self.done
  3201. with TestDbusP2p(bus) as t:
  3202. if not t.success():
  3203. raise Exception("Expected signals not seen")
  3204. dev[0].p2p_stop_find()
  3205. dev[1].p2p_stop_find()
  3206. def test_dbus_p2p_config(dev, apdev):
  3207. """D-Bus Get/Set P2PDeviceConfig"""
  3208. try:
  3209. _test_dbus_p2p_config(dev, apdev)
  3210. finally:
  3211. dev[0].request("P2P_SET ssid_postfix ")
  3212. def _test_dbus_p2p_config(dev, apdev):
  3213. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3214. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3215. res = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3216. dbus_interface=dbus.PROPERTIES_IFACE,
  3217. byte_arrays=True)
  3218. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig", res,
  3219. dbus_interface=dbus.PROPERTIES_IFACE)
  3220. res2 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3221. dbus_interface=dbus.PROPERTIES_IFACE,
  3222. byte_arrays=True)
  3223. if len(res) != len(res2):
  3224. raise Exception("Different number of parameters")
  3225. for k in res:
  3226. if res[k] != res2[k]:
  3227. raise Exception("Parameter %s value changes" % k)
  3228. changes = { 'SsidPostfix': 'foo',
  3229. 'VendorExtension': [ dbus.ByteArray('\x11\x22\x33\x44') ],
  3230. 'SecondaryDeviceTypes': [ dbus.ByteArray('\x11\x22\x33\x44\x55\x66\x77\x88') ]}
  3231. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3232. dbus.Dictionary(changes, signature='sv'),
  3233. dbus_interface=dbus.PROPERTIES_IFACE)
  3234. res2 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3235. dbus_interface=dbus.PROPERTIES_IFACE,
  3236. byte_arrays=True)
  3237. logger.debug("P2PDeviceConfig: " + str(res2))
  3238. if 'VendorExtension' not in res2 or len(res2['VendorExtension']) != 1:
  3239. raise Exception("VendorExtension does not match")
  3240. if 'SecondaryDeviceTypes' not in res2 or len(res2['SecondaryDeviceTypes']) != 1:
  3241. raise Exception("SecondaryDeviceType does not match")
  3242. changes = { 'SsidPostfix': '',
  3243. 'VendorExtension': dbus.Array([], signature="ay"),
  3244. 'SecondaryDeviceTypes': dbus.Array([], signature="ay") }
  3245. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3246. dbus.Dictionary(changes, signature='sv'),
  3247. dbus_interface=dbus.PROPERTIES_IFACE)
  3248. res3 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3249. dbus_interface=dbus.PROPERTIES_IFACE,
  3250. byte_arrays=True)
  3251. logger.debug("P2PDeviceConfig: " + str(res3))
  3252. if 'VendorExtension' in res3:
  3253. raise Exception("VendorExtension not removed")
  3254. if 'SecondaryDeviceTypes' in res3:
  3255. raise Exception("SecondaryDeviceType not removed")
  3256. try:
  3257. dev[0].request("P2P_SET disabled 1")
  3258. if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3259. dbus_interface=dbus.PROPERTIES_IFACE,
  3260. byte_arrays=True)
  3261. raise Exception("Invalid Get(P2PDeviceConfig) accepted")
  3262. except dbus.exceptions.DBusException, e:
  3263. if "Error.Failed: P2P is not available for this interface" not in str(e):
  3264. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  3265. finally:
  3266. dev[0].request("P2P_SET disabled 0")
  3267. try:
  3268. dev[0].request("P2P_SET disabled 1")
  3269. changes = { 'SsidPostfix': 'foo' }
  3270. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3271. dbus.Dictionary(changes, signature='sv'),
  3272. dbus_interface=dbus.PROPERTIES_IFACE)
  3273. raise Exception("Invalid Set(P2PDeviceConfig) accepted")
  3274. except dbus.exceptions.DBusException, e:
  3275. if "Error.Failed: P2P is not available for this interface" not in str(e):
  3276. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  3277. finally:
  3278. dev[0].request("P2P_SET disabled 0")
  3279. tests = [ { 'DeviceName': 123 },
  3280. { 'SsidPostfix': 123 },
  3281. { 'Foo': 'Bar' } ]
  3282. for changes in tests:
  3283. try:
  3284. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3285. dbus.Dictionary(changes, signature='sv'),
  3286. dbus_interface=dbus.PROPERTIES_IFACE)
  3287. raise Exception("Invalid Set(P2PDeviceConfig) accepted")
  3288. except dbus.exceptions.DBusException, e:
  3289. if "InvalidArgs" not in str(e):
  3290. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  3291. def test_dbus_p2p_persistent(dev, apdev):
  3292. """D-Bus P2P persistent group"""
  3293. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3294. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3295. class TestDbusP2p(TestDbus):
  3296. def __init__(self, bus):
  3297. TestDbus.__init__(self, bus)
  3298. def __enter__(self):
  3299. gobject.timeout_add(1, self.run_test)
  3300. gobject.timeout_add(15000, self.timeout)
  3301. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3302. "GroupStarted")
  3303. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3304. "GroupFinished")
  3305. self.add_signal(self.persistentGroupAdded,
  3306. WPAS_DBUS_IFACE_P2PDEVICE,
  3307. "PersistentGroupAdded")
  3308. self.loop.run()
  3309. return self
  3310. def groupStarted(self, properties):
  3311. logger.debug("groupStarted: " + str(properties))
  3312. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3313. properties['interface_object'])
  3314. group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3315. group_p2p.Disconnect()
  3316. def groupFinished(self, properties):
  3317. logger.debug("groupFinished: " + str(properties))
  3318. self.loop.quit()
  3319. def persistentGroupAdded(self, path, properties):
  3320. logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
  3321. self.persistent = path
  3322. def run_test(self, *args):
  3323. logger.debug("run_test")
  3324. params = dbus.Dictionary({'persistent': True,
  3325. 'frequency': 2412})
  3326. logger.info("Add a persistent group")
  3327. p2p.GroupAdd(params)
  3328. return False
  3329. def success(self):
  3330. return True
  3331. with TestDbusP2p(bus) as t:
  3332. if not t.success():
  3333. raise Exception("Expected signals not seen")
  3334. persistent = t.persistent
  3335. p_obj = bus.get_object(WPAS_DBUS_SERVICE, persistent)
  3336. res = p_obj.Get(WPAS_DBUS_PERSISTENT_GROUP, "Properties",
  3337. dbus_interface=dbus.PROPERTIES_IFACE, byte_arrays=True)
  3338. logger.info("Persistent group Properties: " + str(res))
  3339. vals = dbus.Dictionary({ 'ssid': 'DIRECT-foo' }, signature='sv')
  3340. p_obj.Set(WPAS_DBUS_PERSISTENT_GROUP, "Properties", vals,
  3341. dbus_interface=dbus.PROPERTIES_IFACE)
  3342. res2 = p_obj.Get(WPAS_DBUS_PERSISTENT_GROUP, "Properties",
  3343. dbus_interface=dbus.PROPERTIES_IFACE)
  3344. if len(res) != len(res2):
  3345. raise Exception("Different number of parameters")
  3346. for k in res:
  3347. if k != 'ssid' and res[k] != res2[k]:
  3348. raise Exception("Parameter %s value changes" % k)
  3349. if res2['ssid'] != '"DIRECT-foo"':
  3350. raise Exception("Unexpected ssid")
  3351. args = dbus.Dictionary({ 'ssid': 'DIRECT-testing',
  3352. 'psk': '1234567890' }, signature='sv')
  3353. group = p2p.AddPersistentGroup(args)
  3354. groups = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PersistentGroups",
  3355. dbus_interface=dbus.PROPERTIES_IFACE)
  3356. if len(groups) != 2:
  3357. raise Exception("Unexpected number of persistent groups: " + str(groups))
  3358. p2p.RemoveAllPersistentGroups()
  3359. groups = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PersistentGroups",
  3360. dbus_interface=dbus.PROPERTIES_IFACE)
  3361. if len(groups) != 0:
  3362. raise Exception("Unexpected number of persistent groups: " + str(groups))
  3363. try:
  3364. p2p.RemovePersistentGroup(persistent)
  3365. raise Exception("Invalid RemovePersistentGroup accepted")
  3366. except dbus.exceptions.DBusException, e:
  3367. if "NetworkUnknown: There is no such persistent group" not in str(e):
  3368. raise Exception("Unexpected error message for invalid RemovePersistentGroup: " + str(e))
  3369. def test_dbus_p2p_reinvoke_persistent(dev, apdev):
  3370. """D-Bus P2P reinvoke persistent group"""
  3371. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3372. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3373. addr0 = dev[0].p2p_dev_addr()
  3374. class TestDbusP2p(TestDbus):
  3375. def __init__(self, bus):
  3376. TestDbus.__init__(self, bus)
  3377. self.first = True
  3378. self.waiting_end = False
  3379. self.done = False
  3380. self.invited = False
  3381. def __enter__(self):
  3382. gobject.timeout_add(1, self.run_test)
  3383. gobject.timeout_add(15000, self.timeout)
  3384. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3385. "DeviceFound")
  3386. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3387. "GroupStarted")
  3388. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3389. "GroupFinished")
  3390. self.add_signal(self.persistentGroupAdded,
  3391. WPAS_DBUS_IFACE_P2PDEVICE,
  3392. "PersistentGroupAdded")
  3393. self.add_signal(self.provisionDiscoveryRequestDisplayPin,
  3394. WPAS_DBUS_IFACE_P2PDEVICE,
  3395. "ProvisionDiscoveryRequestDisplayPin")
  3396. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  3397. "StaAuthorized")
  3398. self.loop.run()
  3399. return self
  3400. def groupStarted(self, properties):
  3401. logger.debug("groupStarted: " + str(properties))
  3402. self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3403. properties['interface_object'])
  3404. if not self.invited:
  3405. g_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3406. properties['group_object'])
  3407. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  3408. dbus_interface=dbus.PROPERTIES_IFACE,
  3409. byte_arrays=True)
  3410. bssid = ':'.join([binascii.hexlify(l) for l in res['BSSID']])
  3411. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3412. dev1.scan_for_bss(bssid, freq=2412)
  3413. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 join")
  3414. def groupFinished(self, properties):
  3415. logger.debug("groupFinished: " + str(properties))
  3416. if self.invited:
  3417. self.done = True
  3418. self.loop.quit()
  3419. else:
  3420. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3421. dev1.global_request("SET persistent_reconnect 1")
  3422. dev1.p2p_listen()
  3423. args = { 'persistent_group_object': dbus.ObjectPath(path),
  3424. 'peer': self.peer_path }
  3425. try:
  3426. pin = p2p.Invite(args)
  3427. raise Exception("Invalid Invite accepted")
  3428. except dbus.exceptions.DBusException, e:
  3429. if "InvalidArgs" not in str(e):
  3430. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  3431. args = { 'persistent_group_object': self.persistent,
  3432. 'peer': self.peer_path }
  3433. pin = p2p.Invite(args)
  3434. self.invited = True
  3435. self.sta_group_ev = dev1.wait_global_event(["P2P-GROUP-STARTED"],
  3436. timeout=15)
  3437. if self.sta_group_ev is None:
  3438. raise Exception("P2P-GROUP-STARTED event not seen")
  3439. def persistentGroupAdded(self, path, properties):
  3440. logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
  3441. self.persistent = path
  3442. def deviceFound(self, path):
  3443. logger.debug("deviceFound: path=%s" % path)
  3444. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  3445. self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  3446. dbus_interface=dbus.PROPERTIES_IFACE,
  3447. byte_arrays=True)
  3448. def provisionDiscoveryRequestDisplayPin(self, peer_object, pin):
  3449. logger.debug("provisionDiscoveryRequestDisplayPin - peer=%s pin=%s" % (peer_object, pin))
  3450. self.peer_path = peer_object
  3451. peer = binascii.unhexlify(peer_object.split('/')[-1])
  3452. addr = ""
  3453. for p in peer:
  3454. if len(addr) > 0:
  3455. addr += ':'
  3456. addr += '%02x' % ord(p)
  3457. params = { 'Role': 'registrar',
  3458. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  3459. 'Bssid': self.peer['DeviceAddress'],
  3460. 'Type': 'pin',
  3461. 'Pin': '12345670' }
  3462. logger.info("Authorize peer to connect to the group")
  3463. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3464. wps = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_WPS)
  3465. wps.Start(params)
  3466. self.sta_group_ev = dev1.wait_global_event(["P2P-GROUP-STARTED"],
  3467. timeout=15)
  3468. if self.sta_group_ev is None:
  3469. raise Exception("P2P-GROUP-STARTED event not seen")
  3470. def staAuthorized(self, name):
  3471. logger.debug("staAuthorized: " + name)
  3472. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3473. dev1.group_form_result(self.sta_group_ev)
  3474. dev1.remove_group()
  3475. ev = dev1.wait_global_event(["P2P-GROUP-REMOVED"], timeout=10)
  3476. if ev is None:
  3477. raise Exception("Group removal timed out")
  3478. group_p2p = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3479. group_p2p.Disconnect()
  3480. def run_test(self, *args):
  3481. logger.debug("run_test")
  3482. params = dbus.Dictionary({'persistent': True,
  3483. 'frequency': 2412})
  3484. logger.info("Add a persistent group")
  3485. p2p.GroupAdd(params)
  3486. return False
  3487. def success(self):
  3488. return self.done
  3489. with TestDbusP2p(bus) as t:
  3490. if not t.success():
  3491. raise Exception("Expected signals not seen")
  3492. def test_dbus_p2p_go_neg_rx(dev, apdev):
  3493. """D-Bus P2P GO Negotiation receive"""
  3494. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3495. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3496. addr0 = dev[0].p2p_dev_addr()
  3497. class TestDbusP2p(TestDbus):
  3498. def __init__(self, bus):
  3499. TestDbus.__init__(self, bus)
  3500. self.done = False
  3501. def __enter__(self):
  3502. gobject.timeout_add(1, self.run_test)
  3503. gobject.timeout_add(15000, self.timeout)
  3504. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3505. "DeviceFound")
  3506. self.add_signal(self.goNegotiationRequest,
  3507. WPAS_DBUS_IFACE_P2PDEVICE,
  3508. "GONegotiationRequest",
  3509. byte_arrays=True)
  3510. self.add_signal(self.goNegotiationSuccess,
  3511. WPAS_DBUS_IFACE_P2PDEVICE,
  3512. "GONegotiationSuccess",
  3513. byte_arrays=True)
  3514. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3515. "GroupStarted")
  3516. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3517. "GroupFinished")
  3518. self.loop.run()
  3519. return self
  3520. def deviceFound(self, path):
  3521. logger.debug("deviceFound: path=%s" % path)
  3522. def goNegotiationRequest(self, path, dev_passwd_id, go_intent=0):
  3523. logger.debug("goNegotiationRequest: path=%s dev_passwd_id=%d go_intent=%d" % (path, dev_passwd_id, go_intent))
  3524. if dev_passwd_id != 1:
  3525. raise Exception("Unexpected dev_passwd_id=%d" % dev_passwd_id)
  3526. args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
  3527. 'go_intent': 15, 'persistent': False, 'frequency': 5175 }
  3528. try:
  3529. p2p.Connect(args)
  3530. raise Exception("Invalid Connect accepted")
  3531. except dbus.exceptions.DBusException, e:
  3532. if "ConnectChannelUnsupported" not in str(e):
  3533. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  3534. args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
  3535. 'go_intent': 15, 'persistent': False }
  3536. p2p.Connect(args)
  3537. def goNegotiationSuccess(self, properties):
  3538. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3539. def groupStarted(self, properties):
  3540. logger.debug("groupStarted: " + str(properties))
  3541. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3542. properties['interface_object'])
  3543. group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3544. group_p2p.Disconnect()
  3545. def groupFinished(self, properties):
  3546. logger.debug("groupFinished: " + str(properties))
  3547. self.done = True
  3548. self.loop.quit()
  3549. def run_test(self, *args):
  3550. logger.debug("run_test")
  3551. p2p.Listen(10)
  3552. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3553. if not dev1.discover_peer(addr0):
  3554. raise Exception("Peer not found")
  3555. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 enter")
  3556. return False
  3557. def success(self):
  3558. return self.done
  3559. with TestDbusP2p(bus) as t:
  3560. if not t.success():
  3561. raise Exception("Expected signals not seen")
  3562. def test_dbus_p2p_go_neg_auth(dev, apdev):
  3563. """D-Bus P2P GO Negotiation authorized"""
  3564. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3565. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3566. addr0 = dev[0].p2p_dev_addr()
  3567. dev[1].p2p_listen()
  3568. class TestDbusP2p(TestDbus):
  3569. def __init__(self, bus):
  3570. TestDbus.__init__(self, bus)
  3571. self.done = False
  3572. self.peer_joined = False
  3573. self.peer_disconnected = False
  3574. def __enter__(self):
  3575. gobject.timeout_add(1, self.run_test)
  3576. gobject.timeout_add(15000, self.timeout)
  3577. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3578. "DeviceFound")
  3579. self.add_signal(self.goNegotiationSuccess,
  3580. WPAS_DBUS_IFACE_P2PDEVICE,
  3581. "GONegotiationSuccess",
  3582. byte_arrays=True)
  3583. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3584. "GroupStarted")
  3585. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3586. "GroupFinished")
  3587. self.add_signal(self.staDeauthorized, WPAS_DBUS_IFACE,
  3588. "StaDeauthorized")
  3589. self.add_signal(self.peerJoined, WPAS_DBUS_GROUP,
  3590. "PeerJoined")
  3591. self.add_signal(self.peerDisconnected, WPAS_DBUS_GROUP,
  3592. "PeerDisconnected")
  3593. self.loop.run()
  3594. return self
  3595. def deviceFound(self, path):
  3596. logger.debug("deviceFound: path=%s" % path)
  3597. args = { 'peer': path, 'wps_method': 'keypad',
  3598. 'go_intent': 15, 'authorize_only': True }
  3599. try:
  3600. p2p.Connect(args)
  3601. raise Exception("Invalid Connect accepted")
  3602. except dbus.exceptions.DBusException, e:
  3603. if "InvalidArgs" not in str(e):
  3604. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  3605. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  3606. 'go_intent': 15, 'authorize_only': True }
  3607. p2p.Connect(args)
  3608. p2p.Listen(10)
  3609. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3610. if not dev1.discover_peer(addr0):
  3611. raise Exception("Peer not found")
  3612. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=0")
  3613. ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
  3614. if ev is None:
  3615. raise Exception("Group formation timed out")
  3616. self.sta_group_ev = ev
  3617. def goNegotiationSuccess(self, properties):
  3618. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3619. def groupStarted(self, properties):
  3620. logger.debug("groupStarted: " + str(properties))
  3621. self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3622. properties['interface_object'])
  3623. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3624. dev1.group_form_result(self.sta_group_ev)
  3625. dev1.remove_group()
  3626. def staDeauthorized(self, name):
  3627. logger.debug("staDeuthorized: " + name)
  3628. group_p2p = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3629. group_p2p.Disconnect()
  3630. def peerJoined(self, peer):
  3631. logger.debug("peerJoined: " + peer)
  3632. self.peer_joined = True
  3633. def peerDisconnected(self, peer):
  3634. logger.debug("peerDisconnected: " + peer)
  3635. self.peer_disconnected = True
  3636. def groupFinished(self, properties):
  3637. logger.debug("groupFinished: " + str(properties))
  3638. self.done = True
  3639. self.loop.quit()
  3640. def run_test(self, *args):
  3641. logger.debug("run_test")
  3642. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  3643. return False
  3644. def success(self):
  3645. return self.done and self.peer_joined and self.peer_disconnected
  3646. with TestDbusP2p(bus) as t:
  3647. if not t.success():
  3648. raise Exception("Expected signals not seen")
  3649. def test_dbus_p2p_go_neg_init(dev, apdev):
  3650. """D-Bus P2P GO Negotiation initiation"""
  3651. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3652. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3653. addr0 = dev[0].p2p_dev_addr()
  3654. dev[1].p2p_listen()
  3655. class TestDbusP2p(TestDbus):
  3656. def __init__(self, bus):
  3657. TestDbus.__init__(self, bus)
  3658. self.done = False
  3659. self.peer_group_added = False
  3660. self.peer_group_removed = False
  3661. def __enter__(self):
  3662. gobject.timeout_add(1, self.run_test)
  3663. gobject.timeout_add(15000, self.timeout)
  3664. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3665. "DeviceFound")
  3666. self.add_signal(self.goNegotiationSuccess,
  3667. WPAS_DBUS_IFACE_P2PDEVICE,
  3668. "GONegotiationSuccess",
  3669. byte_arrays=True)
  3670. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3671. "GroupStarted")
  3672. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3673. "GroupFinished")
  3674. self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
  3675. "PropertiesChanged")
  3676. self.loop.run()
  3677. return self
  3678. def deviceFound(self, path):
  3679. logger.debug("deviceFound: path=%s" % path)
  3680. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3681. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  3682. 'go_intent': 0 }
  3683. p2p.Connect(args)
  3684. ev = dev1.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
  3685. if ev is None:
  3686. raise Exception("Timeout while waiting for GO Neg Request")
  3687. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=15")
  3688. ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
  3689. if ev is None:
  3690. raise Exception("Group formation timed out")
  3691. self.sta_group_ev = ev
  3692. def goNegotiationSuccess(self, properties):
  3693. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3694. def groupStarted(self, properties):
  3695. logger.debug("groupStarted: " + str(properties))
  3696. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3697. properties['interface_object'])
  3698. group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3699. group_p2p.Disconnect()
  3700. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3701. dev1.group_form_result(self.sta_group_ev)
  3702. dev1.remove_group()
  3703. def groupFinished(self, properties):
  3704. logger.debug("groupFinished: " + str(properties))
  3705. self.done = True
  3706. def propertiesChanged(self, interface_name, changed_properties,
  3707. invalidated_properties):
  3708. logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
  3709. if interface_name != WPAS_DBUS_P2P_PEER:
  3710. return
  3711. if "Groups" not in changed_properties:
  3712. return
  3713. if len(changed_properties["Groups"]) > 0:
  3714. self.peer_group_added = True
  3715. if len(changed_properties["Groups"]) == 0:
  3716. self.peer_group_removed = True
  3717. self.loop.quit()
  3718. def run_test(self, *args):
  3719. logger.debug("run_test")
  3720. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  3721. return False
  3722. def success(self):
  3723. return self.done and self.peer_group_added and self.peer_group_removed
  3724. with TestDbusP2p(bus) as t:
  3725. if not t.success():
  3726. raise Exception("Expected signals not seen")
  3727. def test_dbus_p2p_group_termination_by_go(dev, apdev):
  3728. """D-Bus P2P group removal on GO terminating the group"""
  3729. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3730. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3731. addr0 = dev[0].p2p_dev_addr()
  3732. dev[1].p2p_listen()
  3733. class TestDbusP2p(TestDbus):
  3734. def __init__(self, bus):
  3735. TestDbus.__init__(self, bus)
  3736. self.done = False
  3737. self.peer_group_added = False
  3738. self.peer_group_removed = False
  3739. def __enter__(self):
  3740. gobject.timeout_add(1, self.run_test)
  3741. gobject.timeout_add(15000, self.timeout)
  3742. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3743. "DeviceFound")
  3744. self.add_signal(self.goNegotiationSuccess,
  3745. WPAS_DBUS_IFACE_P2PDEVICE,
  3746. "GONegotiationSuccess",
  3747. byte_arrays=True)
  3748. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3749. "GroupStarted")
  3750. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3751. "GroupFinished")
  3752. self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
  3753. "PropertiesChanged")
  3754. self.loop.run()
  3755. return self
  3756. def deviceFound(self, path):
  3757. logger.debug("deviceFound: path=%s" % path)
  3758. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3759. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  3760. 'go_intent': 0 }
  3761. p2p.Connect(args)
  3762. ev = dev1.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
  3763. if ev is None:
  3764. raise Exception("Timeout while waiting for GO Neg Request")
  3765. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=15")
  3766. ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
  3767. if ev is None:
  3768. raise Exception("Group formation timed out")
  3769. self.sta_group_ev = ev
  3770. def goNegotiationSuccess(self, properties):
  3771. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3772. def groupStarted(self, properties):
  3773. logger.debug("groupStarted: " + str(properties))
  3774. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3775. properties['interface_object'])
  3776. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3777. dev1.group_form_result(self.sta_group_ev)
  3778. dev1.remove_group()
  3779. def groupFinished(self, properties):
  3780. logger.debug("groupFinished: " + str(properties))
  3781. self.done = True
  3782. def propertiesChanged(self, interface_name, changed_properties,
  3783. invalidated_properties):
  3784. logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
  3785. if interface_name != WPAS_DBUS_P2P_PEER:
  3786. return
  3787. if "Groups" not in changed_properties:
  3788. return
  3789. if len(changed_properties["Groups"]) > 0:
  3790. self.peer_group_added = True
  3791. if len(changed_properties["Groups"]) == 0 and self.peer_group_added:
  3792. self.peer_group_removed = True
  3793. self.loop.quit()
  3794. def run_test(self, *args):
  3795. logger.debug("run_test")
  3796. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  3797. return False
  3798. def success(self):
  3799. return self.done and self.peer_group_added and self.peer_group_removed
  3800. with TestDbusP2p(bus) as t:
  3801. if not t.success():
  3802. raise Exception("Expected signals not seen")
  3803. def test_dbus_p2p_group_idle_timeout(dev, apdev):
  3804. """D-Bus P2P group removal on idle timeout"""
  3805. try:
  3806. dev[0].global_request("SET p2p_group_idle 1")
  3807. _test_dbus_p2p_group_idle_timeout(dev, apdev)
  3808. finally:
  3809. dev[0].global_request("SET p2p_group_idle 0")
  3810. def _test_dbus_p2p_group_idle_timeout(dev, apdev):
  3811. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3812. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3813. addr0 = dev[0].p2p_dev_addr()
  3814. dev[1].p2p_listen()
  3815. class TestDbusP2p(TestDbus):
  3816. def __init__(self, bus):
  3817. TestDbus.__init__(self, bus)
  3818. self.done = False
  3819. self.group_started = False
  3820. self.peer_group_added = False
  3821. self.peer_group_removed = False
  3822. def __enter__(self):
  3823. gobject.timeout_add(1, self.run_test)
  3824. gobject.timeout_add(15000, self.timeout)
  3825. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3826. "DeviceFound")
  3827. self.add_signal(self.goNegotiationSuccess,
  3828. WPAS_DBUS_IFACE_P2PDEVICE,
  3829. "GONegotiationSuccess",
  3830. byte_arrays=True)
  3831. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3832. "GroupStarted")
  3833. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3834. "GroupFinished")
  3835. self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
  3836. "PropertiesChanged")
  3837. self.loop.run()
  3838. return self
  3839. def deviceFound(self, path):
  3840. logger.debug("deviceFound: path=%s" % path)
  3841. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3842. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  3843. 'go_intent': 0 }
  3844. p2p.Connect(args)
  3845. ev = dev1.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
  3846. if ev is None:
  3847. raise Exception("Timeout while waiting for GO Neg Request")
  3848. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=15")
  3849. ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
  3850. if ev is None:
  3851. raise Exception("Group formation timed out")
  3852. self.sta_group_ev = ev
  3853. def goNegotiationSuccess(self, properties):
  3854. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3855. def groupStarted(self, properties):
  3856. logger.debug("groupStarted: " + str(properties))
  3857. self.group_started = True
  3858. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3859. properties['interface_object'])
  3860. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3861. dev1.group_form_result(self.sta_group_ev)
  3862. ifaddr = dev1.group_request("STA-FIRST").splitlines()[0]
  3863. # Force disassociation with different reason code so that the
  3864. # P2P Client using D-Bus does not get normal group termination event
  3865. # from the GO.
  3866. dev1.group_request("DEAUTHENTICATE " + ifaddr + " reason=0 test=0")
  3867. dev1.remove_group()
  3868. def groupFinished(self, properties):
  3869. logger.debug("groupFinished: " + str(properties))
  3870. self.done = True
  3871. def propertiesChanged(self, interface_name, changed_properties,
  3872. invalidated_properties):
  3873. logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
  3874. if interface_name != WPAS_DBUS_P2P_PEER:
  3875. return
  3876. if not self.group_started:
  3877. return
  3878. if "Groups" not in changed_properties:
  3879. return
  3880. if len(changed_properties["Groups"]) > 0:
  3881. self.peer_group_added = True
  3882. if len(changed_properties["Groups"]) == 0:
  3883. self.peer_group_removed = True
  3884. self.loop.quit()
  3885. def run_test(self, *args):
  3886. logger.debug("run_test")
  3887. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  3888. return False
  3889. def success(self):
  3890. return self.done and self.peer_group_added and self.peer_group_removed
  3891. with TestDbusP2p(bus) as t:
  3892. if not t.success():
  3893. raise Exception("Expected signals not seen")
  3894. def test_dbus_p2p_wps_failure(dev, apdev):
  3895. """D-Bus P2P WPS failure"""
  3896. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3897. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3898. addr0 = dev[0].p2p_dev_addr()
  3899. class TestDbusP2p(TestDbus):
  3900. def __init__(self, bus):
  3901. TestDbus.__init__(self, bus)
  3902. self.wps_failed = False
  3903. self.formation_failure = False
  3904. def __enter__(self):
  3905. gobject.timeout_add(1, self.run_test)
  3906. gobject.timeout_add(15000, self.timeout)
  3907. self.add_signal(self.goNegotiationRequest,
  3908. WPAS_DBUS_IFACE_P2PDEVICE,
  3909. "GONegotiationRequest",
  3910. byte_arrays=True)
  3911. self.add_signal(self.goNegotiationSuccess,
  3912. WPAS_DBUS_IFACE_P2PDEVICE,
  3913. "GONegotiationSuccess",
  3914. byte_arrays=True)
  3915. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3916. "GroupStarted")
  3917. self.add_signal(self.wpsFailed, WPAS_DBUS_IFACE_P2PDEVICE,
  3918. "WpsFailed")
  3919. self.add_signal(self.groupFormationFailure,
  3920. WPAS_DBUS_IFACE_P2PDEVICE,
  3921. "GroupFormationFailure")
  3922. self.loop.run()
  3923. return self
  3924. def goNegotiationRequest(self, path, dev_passwd_id, go_intent=0):
  3925. logger.debug("goNegotiationRequest: path=%s dev_passwd_id=%d go_intent=%d" % (path, dev_passwd_id, go_intent))
  3926. if dev_passwd_id != 1:
  3927. raise Exception("Unexpected dev_passwd_id=%d" % dev_passwd_id)
  3928. args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
  3929. 'go_intent': 15 }
  3930. p2p.Connect(args)
  3931. def goNegotiationSuccess(self, properties):
  3932. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3933. def groupStarted(self, properties):
  3934. logger.debug("groupStarted: " + str(properties))
  3935. raise Exception("Unexpected GroupStarted")
  3936. def wpsFailed(self, name, args):
  3937. logger.debug("wpsFailed - name=%s args=%s" % (name, str(args)))
  3938. self.wps_failed = True
  3939. if self.formation_failure:
  3940. self.loop.quit()
  3941. def groupFormationFailure(self, reason):
  3942. logger.debug("groupFormationFailure - reason=%s" % reason)
  3943. self.formation_failure = True
  3944. if self.wps_failed:
  3945. self.loop.quit()
  3946. def run_test(self, *args):
  3947. logger.debug("run_test")
  3948. p2p.Listen(10)
  3949. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3950. if not dev1.discover_peer(addr0):
  3951. raise Exception("Peer not found")
  3952. dev1.global_request("P2P_CONNECT " + addr0 + " 87654321 enter")
  3953. return False
  3954. def success(self):
  3955. return self.wps_failed and self.formation_failure
  3956. with TestDbusP2p(bus) as t:
  3957. if not t.success():
  3958. raise Exception("Expected signals not seen")
  3959. def test_dbus_p2p_two_groups(dev, apdev):
  3960. """D-Bus P2P with two concurrent groups"""
  3961. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3962. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3963. dev[0].request("SET p2p_no_group_iface 0")
  3964. addr0 = dev[0].p2p_dev_addr()
  3965. addr1 = dev[1].p2p_dev_addr()
  3966. addr2 = dev[2].p2p_dev_addr()
  3967. dev[1].p2p_start_go(freq=2412)
  3968. dev1_group_ifname = dev[1].group_ifname
  3969. class TestDbusP2p(TestDbus):
  3970. def __init__(self, bus):
  3971. TestDbus.__init__(self, bus)
  3972. self.done = False
  3973. self.peer = None
  3974. self.go = None
  3975. self.group1 = None
  3976. self.group2 = None
  3977. self.groups_removed = False
  3978. def __enter__(self):
  3979. gobject.timeout_add(1, self.run_test)
  3980. gobject.timeout_add(15000, self.timeout)
  3981. self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
  3982. "PropertiesChanged", byte_arrays=True)
  3983. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3984. "DeviceFound")
  3985. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3986. "GroupStarted")
  3987. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3988. "GroupFinished")
  3989. self.add_signal(self.peerJoined, WPAS_DBUS_GROUP,
  3990. "PeerJoined")
  3991. self.loop.run()
  3992. return self
  3993. def propertiesChanged(self, interface_name, changed_properties,
  3994. invalidated_properties):
  3995. logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
  3996. def deviceFound(self, path):
  3997. logger.debug("deviceFound: path=%s" % path)
  3998. if addr2.replace(':','') in path:
  3999. self.peer = path
  4000. elif addr1.replace(':','') in path:
  4001. self.go = path
  4002. if self.go and not self.group1:
  4003. logger.info("Join the group")
  4004. p2p.StopFind()
  4005. pin = '12345670'
  4006. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  4007. dev1.group_ifname = dev1_group_ifname
  4008. dev1.group_request("WPS_PIN any " + pin)
  4009. args = { 'peer': self.go,
  4010. 'join': True,
  4011. 'wps_method': 'pin',
  4012. 'pin': pin,
  4013. 'frequency': 2412 }
  4014. p2p.Connect(args)
  4015. def groupStarted(self, properties):
  4016. logger.debug("groupStarted: " + str(properties))
  4017. prop = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
  4018. dbus_interface=dbus.PROPERTIES_IFACE)
  4019. logger.debug("p2pdevice properties: " + str(prop))
  4020. g_obj = bus.get_object(WPAS_DBUS_SERVICE,
  4021. properties['group_object'])
  4022. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  4023. dbus_interface=dbus.PROPERTIES_IFACE,
  4024. byte_arrays=True)
  4025. logger.debug("Group properties: " + str(res))
  4026. if not self.group1:
  4027. self.group1 = properties['group_object']
  4028. self.group1iface = properties['interface_object']
  4029. self.g1_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  4030. self.group1iface)
  4031. logger.info("Start autonomous GO")
  4032. params = dbus.Dictionary({ 'frequency': 2412 })
  4033. p2p.GroupAdd(params)
  4034. elif not self.group2:
  4035. self.group2 = properties['group_object']
  4036. self.group2iface = properties['interface_object']
  4037. self.g2_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  4038. self.group2iface)
  4039. self.g2_bssid = res['BSSID']
  4040. if self.group1 and self.group2:
  4041. logger.info("Authorize peer to join the group")
  4042. a2 = binascii.unhexlify(addr2.replace(':',''))
  4043. params = { 'Role': 'enrollee',
  4044. 'P2PDeviceAddress': dbus.ByteArray(a2),
  4045. 'Bssid': dbus.ByteArray(a2),
  4046. 'Type': 'pin',
  4047. 'Pin': '12345670' }
  4048. g_wps = dbus.Interface(self.g2_if_obj, WPAS_DBUS_IFACE_WPS)
  4049. g_wps.Start(params)
  4050. bssid = ':'.join([binascii.hexlify(l) for l in self.g2_bssid])
  4051. dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2')
  4052. dev2.scan_for_bss(bssid, freq=2412)
  4053. dev2.global_request("P2P_CONNECT " + bssid + " 12345670 join freq=2412")
  4054. ev = dev2.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
  4055. if ev is None:
  4056. raise Exception("Group join timed out")
  4057. self.dev2_group_ev = ev
  4058. def groupFinished(self, properties):
  4059. logger.debug("groupFinished: " + str(properties))
  4060. if self.group1 == properties['group_object']:
  4061. self.group1 = None
  4062. elif self.group2 == properties['group_object']:
  4063. self.group2 = None
  4064. if not self.group1 and not self.group2:
  4065. self.done = True
  4066. self.loop.quit()
  4067. def peerJoined(self, peer):
  4068. logger.debug("peerJoined: " + peer)
  4069. if self.groups_removed:
  4070. return
  4071. self.check_results()
  4072. dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2')
  4073. dev2.group_form_result(self.dev2_group_ev)
  4074. dev2.remove_group()
  4075. logger.info("Disconnect group2")
  4076. group_p2p = dbus.Interface(self.g2_if_obj,
  4077. WPAS_DBUS_IFACE_P2PDEVICE)
  4078. group_p2p.Disconnect()
  4079. logger.info("Disconnect group1")
  4080. group_p2p = dbus.Interface(self.g1_if_obj,
  4081. WPAS_DBUS_IFACE_P2PDEVICE)
  4082. group_p2p.Disconnect()
  4083. self.groups_removed = True
  4084. def check_results(self):
  4085. logger.info("Check results with two concurrent groups in operation")
  4086. g1_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group1)
  4087. res1 = g1_obj.GetAll(WPAS_DBUS_GROUP,
  4088. dbus_interface=dbus.PROPERTIES_IFACE,
  4089. byte_arrays=True)
  4090. g2_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group2)
  4091. res2 = g2_obj.GetAll(WPAS_DBUS_GROUP,
  4092. dbus_interface=dbus.PROPERTIES_IFACE,
  4093. byte_arrays=True)
  4094. logger.info("group1 = " + self.group1)
  4095. logger.debug("Group properties: " + str(res1))
  4096. logger.info("group2 = " + self.group2)
  4097. logger.debug("Group properties: " + str(res2))
  4098. prop = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
  4099. dbus_interface=dbus.PROPERTIES_IFACE)
  4100. logger.debug("p2pdevice properties: " + str(prop))
  4101. if res1['Role'] != 'client':
  4102. raise Exception("Group1 role reported incorrectly: " + res1['Role'])
  4103. if res2['Role'] != 'GO':
  4104. raise Exception("Group2 role reported incorrectly: " + res2['Role'])
  4105. if prop['Role'] != 'device':
  4106. raise Exception("p2pdevice role reported incorrectly: " + prop['Role'])
  4107. if len(res2['Members']) != 1:
  4108. raise Exception("Unexpected Members value for group 2")
  4109. def run_test(self, *args):
  4110. logger.debug("run_test")
  4111. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  4112. return False
  4113. def success(self):
  4114. return self.done
  4115. with TestDbusP2p(bus) as t:
  4116. if not t.success():
  4117. raise Exception("Expected signals not seen")
  4118. dev[1].remove_group()
  4119. def test_dbus_p2p_cancel(dev, apdev):
  4120. """D-Bus P2P Cancel"""
  4121. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4122. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  4123. try:
  4124. p2p.Cancel()
  4125. raise Exception("Unexpected p2p.Cancel() success")
  4126. except dbus.exceptions.DBusException, e:
  4127. pass
  4128. addr0 = dev[0].p2p_dev_addr()
  4129. dev[1].p2p_listen()
  4130. class TestDbusP2p(TestDbus):
  4131. def __init__(self, bus):
  4132. TestDbus.__init__(self, bus)
  4133. self.done = False
  4134. def __enter__(self):
  4135. gobject.timeout_add(1, self.run_test)
  4136. gobject.timeout_add(15000, self.timeout)
  4137. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  4138. "DeviceFound")
  4139. self.loop.run()
  4140. return self
  4141. def deviceFound(self, path):
  4142. logger.debug("deviceFound: path=%s" % path)
  4143. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  4144. 'go_intent': 0 }
  4145. p2p.Connect(args)
  4146. p2p.Cancel()
  4147. self.done = True
  4148. self.loop.quit()
  4149. def run_test(self, *args):
  4150. logger.debug("run_test")
  4151. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  4152. return False
  4153. def success(self):
  4154. return self.done
  4155. with TestDbusP2p(bus) as t:
  4156. if not t.success():
  4157. raise Exception("Expected signals not seen")
  4158. def test_dbus_introspect(dev, apdev):
  4159. """D-Bus introspection"""
  4160. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4161. res = if_obj.Introspect(WPAS_DBUS_IFACE,
  4162. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  4163. logger.info("Initial Introspect: " + str(res))
  4164. if res is None or "Introspectable" not in res or "GroupStarted" not in res:
  4165. raise Exception("Unexpected initial Introspect response: " + str(res))
  4166. if "FastReauth" not in res or "PassiveScan" not in res:
  4167. raise Exception("Unexpected initial Introspect response: " + str(res))
  4168. with alloc_fail(dev[0], 1, "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 not None:
  4173. raise Exception("Unexpected Introspect response")
  4174. with alloc_fail(dev[0], 1, "=add_interface;wpa_dbus_introspect"):
  4175. res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
  4176. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  4177. logger.info("Introspect: " + str(res2))
  4178. if res2 is None:
  4179. raise Exception("No Introspect response")
  4180. if len(res2) >= len(res):
  4181. raise Exception("Unexpected Introspect response")
  4182. with alloc_fail(dev[0], 1, "wpabuf_alloc;add_interface;wpa_dbus_introspect"):
  4183. res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
  4184. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  4185. logger.info("Introspect: " + str(res2))
  4186. if res2 is None:
  4187. raise Exception("No Introspect response")
  4188. if len(res2) >= len(res):
  4189. raise Exception("Unexpected Introspect response")
  4190. with alloc_fail(dev[0], 2, "=add_interface;wpa_dbus_introspect"):
  4191. res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
  4192. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  4193. logger.info("Introspect: " + str(res2))
  4194. if res2 is None:
  4195. raise Exception("No Introspect response")
  4196. if len(res2) >= len(res):
  4197. raise Exception("Unexpected Introspect response")
  4198. def test_dbus_ap(dev, apdev):
  4199. """D-Bus AddNetwork for AP mode"""
  4200. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4201. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  4202. ssid = "test-wpa2-psk"
  4203. passphrase = 'qwertyuiop'
  4204. class TestDbusConnect(TestDbus):
  4205. def __init__(self, bus):
  4206. TestDbus.__init__(self, bus)
  4207. self.started = False
  4208. def __enter__(self):
  4209. gobject.timeout_add(1, self.run_connect)
  4210. gobject.timeout_add(15000, self.timeout)
  4211. self.add_signal(self.networkAdded, WPAS_DBUS_IFACE, "NetworkAdded")
  4212. self.add_signal(self.networkSelected, WPAS_DBUS_IFACE,
  4213. "NetworkSelected")
  4214. self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
  4215. "PropertiesChanged")
  4216. self.loop.run()
  4217. return self
  4218. def networkAdded(self, network, properties):
  4219. logger.debug("networkAdded: %s" % str(network))
  4220. logger.debug(str(properties))
  4221. def networkSelected(self, network):
  4222. logger.debug("networkSelected: %s" % str(network))
  4223. self.network_selected = True
  4224. def propertiesChanged(self, properties):
  4225. logger.debug("propertiesChanged: %s" % str(properties))
  4226. if 'State' in properties and properties['State'] == "completed":
  4227. self.started = True
  4228. self.loop.quit()
  4229. def run_connect(self, *args):
  4230. logger.debug("run_connect")
  4231. args = dbus.Dictionary({ 'ssid': ssid,
  4232. 'key_mgmt': 'WPA-PSK',
  4233. 'psk': passphrase,
  4234. 'mode': 2,
  4235. 'frequency': 2412 },
  4236. signature='sv')
  4237. self.netw = iface.AddNetwork(args)
  4238. iface.SelectNetwork(self.netw)
  4239. return False
  4240. def success(self):
  4241. return self.started
  4242. with TestDbusConnect(bus) as t:
  4243. if not t.success():
  4244. raise Exception("Expected signals not seen")
  4245. dev[1].connect(ssid, psk=passphrase, scan_freq="2412")
  4246. def test_dbus_connect_wpa_eap(dev, apdev):
  4247. """D-Bus AddNetwork and connection with WPA+WPA2-Enterprise AP"""
  4248. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4249. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  4250. ssid = "test-wpa-eap"
  4251. params = hostapd.wpa_eap_params(ssid=ssid)
  4252. params["wpa"] = "3"
  4253. params["rsn_pairwise"] = "CCMP"
  4254. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  4255. class TestDbusConnect(TestDbus):
  4256. def __init__(self, bus):
  4257. TestDbus.__init__(self, bus)
  4258. self.done = False
  4259. def __enter__(self):
  4260. gobject.timeout_add(1, self.run_connect)
  4261. gobject.timeout_add(15000, self.timeout)
  4262. self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
  4263. "PropertiesChanged")
  4264. self.add_signal(self.eap, WPAS_DBUS_IFACE, "EAP")
  4265. self.loop.run()
  4266. return self
  4267. def propertiesChanged(self, properties):
  4268. logger.debug("propertiesChanged: %s" % str(properties))
  4269. if 'State' in properties and properties['State'] == "completed":
  4270. self.done = True
  4271. self.loop.quit()
  4272. def eap(self, status, parameter):
  4273. logger.debug("EAP: status=%s parameter=%s" % (status, parameter))
  4274. def run_connect(self, *args):
  4275. logger.debug("run_connect")
  4276. args = dbus.Dictionary({ 'ssid': ssid,
  4277. 'key_mgmt': 'WPA-EAP',
  4278. 'eap': 'PEAP',
  4279. 'identity': 'user',
  4280. 'password': 'password',
  4281. 'ca_cert': 'auth_serv/ca.pem',
  4282. 'phase2': 'auth=MSCHAPV2',
  4283. 'scan_freq': 2412 },
  4284. signature='sv')
  4285. self.netw = iface.AddNetwork(args)
  4286. iface.SelectNetwork(self.netw)
  4287. return False
  4288. def success(self):
  4289. return self.done
  4290. with TestDbusConnect(bus) as t:
  4291. if not t.success():
  4292. raise Exception("Expected signals not seen")
  4293. def test_dbus_ap_scan_2_ap_mode_scan(dev, apdev):
  4294. """AP_SCAN 2 AP mode and D-Bus Scan()"""
  4295. try:
  4296. _test_dbus_ap_scan_2_ap_mode_scan(dev, apdev)
  4297. finally:
  4298. dev[0].request("AP_SCAN 1")
  4299. def _test_dbus_ap_scan_2_ap_mode_scan(dev, apdev):
  4300. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4301. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  4302. if "OK" not in dev[0].request("AP_SCAN 2"):
  4303. raise Exception("Failed to set AP_SCAN 2")
  4304. id = dev[0].add_network()
  4305. dev[0].set_network(id, "mode", "2")
  4306. dev[0].set_network_quoted(id, "ssid", "wpas-ap-open")
  4307. dev[0].set_network(id, "key_mgmt", "NONE")
  4308. dev[0].set_network(id, "frequency", "2412")
  4309. dev[0].set_network(id, "scan_freq", "2412")
  4310. dev[0].set_network(id, "disabled", "0")
  4311. dev[0].select_network(id)
  4312. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=5)
  4313. if ev is None:
  4314. raise Exception("AP failed to start")
  4315. with fail_test(dev[0], 1, "wpa_driver_nl80211_scan"):
  4316. iface.Scan({'Type': 'active',
  4317. 'AllowRoam': True,
  4318. 'Channels': [(dbus.UInt32(2412), dbus.UInt32(20))]})
  4319. ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED",
  4320. "AP-DISABLED"], timeout=5)
  4321. if ev is None:
  4322. raise Exception("CTRL-EVENT-SCAN-FAILED not seen")
  4323. if "AP-DISABLED" in ev:
  4324. raise Exception("Unexpected AP-DISABLED event")
  4325. if "retry=1" in ev:
  4326. # Wait for the retry to scan happen
  4327. ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED",
  4328. "AP-DISABLED"], timeout=5)
  4329. if ev is None:
  4330. raise Exception("CTRL-EVENT-SCAN-FAILED not seen - retry")
  4331. if "AP-DISABLED" in ev:
  4332. raise Exception("Unexpected AP-DISABLED event - retry")
  4333. dev[1].connect("wpas-ap-open", key_mgmt="NONE", scan_freq="2412")
  4334. dev[1].request("DISCONNECT")
  4335. dev[1].wait_disconnected()
  4336. dev[0].request("DISCONNECT")
  4337. dev[0].wait_disconnected()
  4338. def test_dbus_expectdisconnect(dev, apdev):
  4339. """D-Bus ExpectDisconnect"""
  4340. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4341. wpas = dbus.Interface(wpas_obj, WPAS_DBUS_SERVICE)
  4342. params = { "ssid": "test-open" }
  4343. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  4344. dev[0].connect("test-open", key_mgmt="NONE", scan_freq="2412")
  4345. # This does not really verify the behavior other than by going through the
  4346. # code path for additional coverage.
  4347. wpas.ExpectDisconnect()
  4348. dev[0].request("DISCONNECT")
  4349. dev[0].wait_disconnected()
  4350. def test_dbus_save_config(dev, apdev):
  4351. """D-Bus SaveConfig"""
  4352. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4353. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  4354. try:
  4355. iface.SaveConfig()
  4356. raise Exception("SaveConfig() accepted unexpectedly")
  4357. except dbus.exceptions.DBusException, e:
  4358. if not str(e).startswith("fi.w1.wpa_supplicant1.UnknownError: Not allowed to update configuration"):
  4359. raise Exception("Unexpected error message for SaveConfig(): " + str(e))