test_dbus.py 169 KB

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