test_dbus.py 177 KB

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