test_dbus.py 148 KB

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