test_dbus.py 183 KB

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