test_dbus.py 147 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637
  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. return _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. return _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. return _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. return _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. return _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. return _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. def test_dbus_tdls(dev, apdev):
  1171. """D-Bus TDLS"""
  1172. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1173. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1174. hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "test-open" })
  1175. connect_2sta_open(dev, hapd)
  1176. addr1 = dev[1].p2p_interface_addr()
  1177. class TestDbusTdls(TestDbus):
  1178. def __init__(self, bus):
  1179. TestDbus.__init__(self, bus)
  1180. self.tdls_setup = False
  1181. self.tdls_teardown = False
  1182. def __enter__(self):
  1183. gobject.timeout_add(1, self.run_tdls)
  1184. gobject.timeout_add(15000, self.timeout)
  1185. self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
  1186. "PropertiesChanged")
  1187. self.loop.run()
  1188. return self
  1189. def propertiesChanged(self, properties):
  1190. logger.debug("propertiesChanged: %s" % str(properties))
  1191. def run_tdls(self, *args):
  1192. logger.debug("run_tdls")
  1193. iface.TDLSDiscover(addr1)
  1194. gobject.timeout_add(100, self.run_tdls2)
  1195. return False
  1196. def run_tdls2(self, *args):
  1197. logger.debug("run_tdls2")
  1198. iface.TDLSSetup(addr1)
  1199. gobject.timeout_add(500, self.run_tdls3)
  1200. return False
  1201. def run_tdls3(self, *args):
  1202. logger.debug("run_tdls3")
  1203. res = iface.TDLSStatus(addr1)
  1204. if res == "connected":
  1205. self.tdls_setup = True
  1206. else:
  1207. logger.info("Unexpected TDLSStatus: " + res)
  1208. iface.TDLSTeardown(addr1)
  1209. gobject.timeout_add(200, self.run_tdls4)
  1210. return False
  1211. def run_tdls4(self, *args):
  1212. logger.debug("run_tdls4")
  1213. res = iface.TDLSStatus(addr1)
  1214. if res == "peer does not exist":
  1215. self.tdls_teardown = True
  1216. else:
  1217. logger.info("Unexpected TDLSStatus: " + res)
  1218. self.loop.quit()
  1219. return False
  1220. def success(self):
  1221. return self.tdls_setup and self.tdls_teardown
  1222. with TestDbusTdls(bus) as t:
  1223. if not t.success():
  1224. raise Exception("Expected signals not seen")
  1225. def test_dbus_pkcs11(dev, apdev):
  1226. """D-Bus SetPKCS11EngineAndModulePath()"""
  1227. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1228. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1229. try:
  1230. iface.SetPKCS11EngineAndModulePath("foo", "bar")
  1231. except dbus.exceptions.DBusException, e:
  1232. if "Error.Failed: Reinit of the EAPOL" not in str(e):
  1233. raise Exception("Unexpected error message for invalid SetPKCS11EngineAndModulePath: " + str(e))
  1234. try:
  1235. iface.SetPKCS11EngineAndModulePath("foo", "")
  1236. except dbus.exceptions.DBusException, e:
  1237. if "Error.Failed: Reinit of the EAPOL" not in str(e):
  1238. raise Exception("Unexpected error message for invalid SetPKCS11EngineAndModulePath: " + str(e))
  1239. iface.SetPKCS11EngineAndModulePath("", "bar")
  1240. res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11EnginePath",
  1241. dbus_interface=dbus.PROPERTIES_IFACE)
  1242. if res != "":
  1243. raise Exception("Unexpected PKCS11EnginePath value: " + res)
  1244. res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11ModulePath",
  1245. dbus_interface=dbus.PROPERTIES_IFACE)
  1246. if res != "bar":
  1247. raise Exception("Unexpected PKCS11ModulePath value: " + res)
  1248. iface.SetPKCS11EngineAndModulePath("", "")
  1249. res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11EnginePath",
  1250. dbus_interface=dbus.PROPERTIES_IFACE)
  1251. if res != "":
  1252. raise Exception("Unexpected PKCS11EnginePath value: " + res)
  1253. res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11ModulePath",
  1254. dbus_interface=dbus.PROPERTIES_IFACE)
  1255. if res != "":
  1256. raise Exception("Unexpected PKCS11ModulePath value: " + res)
  1257. def test_dbus_apscan(dev, apdev):
  1258. """D-Bus Get/Set ApScan"""
  1259. try:
  1260. return _test_dbus_apscan(dev, apdev)
  1261. finally:
  1262. dev[0].request("AP_SCAN 1")
  1263. def _test_dbus_apscan(dev, apdev):
  1264. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1265. res = if_obj.Get(WPAS_DBUS_IFACE, "ApScan",
  1266. dbus_interface=dbus.PROPERTIES_IFACE)
  1267. if res != 1:
  1268. raise Exception("Unexpected initial ApScan value: %d" % res)
  1269. for i in range(3):
  1270. if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.UInt32(i),
  1271. dbus_interface=dbus.PROPERTIES_IFACE)
  1272. res = if_obj.Get(WPAS_DBUS_IFACE, "ApScan",
  1273. dbus_interface=dbus.PROPERTIES_IFACE)
  1274. if res != i:
  1275. raise Exception("Unexpected ApScan value %d (expected %d)" % (res, i))
  1276. try:
  1277. if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.Int16(-1),
  1278. dbus_interface=dbus.PROPERTIES_IFACE)
  1279. raise Exception("Invalid Set(ApScan,-1) accepted")
  1280. except dbus.exceptions.DBusException, e:
  1281. if "Error.Failed: wrong property type" not in str(e):
  1282. raise Exception("Unexpected error message for invalid Set(ApScan,-1): " + str(e))
  1283. try:
  1284. if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.UInt32(123),
  1285. dbus_interface=dbus.PROPERTIES_IFACE)
  1286. raise Exception("Invalid Set(ApScan,123) accepted")
  1287. except dbus.exceptions.DBusException, e:
  1288. if "Error.Failed: ap_scan must be 0, 1, or 2" not in str(e):
  1289. raise Exception("Unexpected error message for invalid Set(ApScan,123): " + str(e))
  1290. if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.UInt32(1),
  1291. dbus_interface=dbus.PROPERTIES_IFACE)
  1292. def test_dbus_fastreauth(dev, apdev):
  1293. """D-Bus Get/Set FastReauth"""
  1294. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1295. res = if_obj.Get(WPAS_DBUS_IFACE, "FastReauth",
  1296. dbus_interface=dbus.PROPERTIES_IFACE)
  1297. if res != True:
  1298. raise Exception("Unexpected initial FastReauth value: " + str(res))
  1299. for i in [ False, True ]:
  1300. if_obj.Set(WPAS_DBUS_IFACE, "FastReauth", dbus.Boolean(i),
  1301. dbus_interface=dbus.PROPERTIES_IFACE)
  1302. res = if_obj.Get(WPAS_DBUS_IFACE, "FastReauth",
  1303. dbus_interface=dbus.PROPERTIES_IFACE)
  1304. if res != i:
  1305. raise Exception("Unexpected FastReauth value %d (expected %d)" % (res, i))
  1306. try:
  1307. if_obj.Set(WPAS_DBUS_IFACE, "FastReauth", dbus.Int16(-1),
  1308. dbus_interface=dbus.PROPERTIES_IFACE)
  1309. raise Exception("Invalid Set(FastReauth,-1) accepted")
  1310. except dbus.exceptions.DBusException, e:
  1311. if "Error.Failed: wrong property type" not in str(e):
  1312. raise Exception("Unexpected error message for invalid Set(ApScan,-1): " + str(e))
  1313. if_obj.Set(WPAS_DBUS_IFACE, "FastReauth", dbus.Boolean(True),
  1314. dbus_interface=dbus.PROPERTIES_IFACE)
  1315. def test_dbus_bss_expire(dev, apdev):
  1316. """D-Bus Get/Set BSSExpireAge and BSSExpireCount"""
  1317. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1318. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.UInt32(179),
  1319. dbus_interface=dbus.PROPERTIES_IFACE)
  1320. res = if_obj.Get(WPAS_DBUS_IFACE, "BSSExpireAge",
  1321. dbus_interface=dbus.PROPERTIES_IFACE)
  1322. if res != 179:
  1323. raise Exception("Unexpected BSSExpireAge value %d (expected %d)" % (res, i))
  1324. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.UInt32(3),
  1325. dbus_interface=dbus.PROPERTIES_IFACE)
  1326. res = if_obj.Get(WPAS_DBUS_IFACE, "BSSExpireCount",
  1327. dbus_interface=dbus.PROPERTIES_IFACE)
  1328. if res != 3:
  1329. raise Exception("Unexpected BSSExpireCount value %d (expected %d)" % (res, i))
  1330. try:
  1331. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.Int16(-1),
  1332. dbus_interface=dbus.PROPERTIES_IFACE)
  1333. raise Exception("Invalid Set(BSSExpireAge,-1) accepted")
  1334. except dbus.exceptions.DBusException, e:
  1335. if "Error.Failed: wrong property type" not in str(e):
  1336. raise Exception("Unexpected error message for invalid Set(BSSExpireAge,-1): " + str(e))
  1337. try:
  1338. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.UInt32(9),
  1339. dbus_interface=dbus.PROPERTIES_IFACE)
  1340. raise Exception("Invalid Set(BSSExpireAge,9) accepted")
  1341. except dbus.exceptions.DBusException, e:
  1342. if "Error.Failed: BSSExpireAge must be >= 10" not in str(e):
  1343. raise Exception("Unexpected error message for invalid Set(BSSExpireAge,9): " + str(e))
  1344. try:
  1345. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.Int16(-1),
  1346. dbus_interface=dbus.PROPERTIES_IFACE)
  1347. raise Exception("Invalid Set(BSSExpireCount,-1) accepted")
  1348. except dbus.exceptions.DBusException, e:
  1349. if "Error.Failed: wrong property type" not in str(e):
  1350. raise Exception("Unexpected error message for invalid Set(BSSExpireCount,-1): " + str(e))
  1351. try:
  1352. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.UInt32(0),
  1353. dbus_interface=dbus.PROPERTIES_IFACE)
  1354. raise Exception("Invalid Set(BSSExpireCount,0) accepted")
  1355. except dbus.exceptions.DBusException, e:
  1356. if "Error.Failed: BSSExpireCount must be > 0" not in str(e):
  1357. raise Exception("Unexpected error message for invalid Set(BSSExpireCount,0): " + str(e))
  1358. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.UInt32(180),
  1359. dbus_interface=dbus.PROPERTIES_IFACE)
  1360. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.UInt32(2),
  1361. dbus_interface=dbus.PROPERTIES_IFACE)
  1362. def test_dbus_country(dev, apdev):
  1363. """D-Bus Get/Set Country"""
  1364. try:
  1365. return _test_dbus_country(dev, apdev)
  1366. finally:
  1367. dev[0].request("SET country 00")
  1368. subprocess.call(['iw', 'reg', 'set', '00'])
  1369. def _test_dbus_country(dev, apdev):
  1370. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1371. # work around issues with possible pending regdom event from the end of
  1372. # the previous test case
  1373. time.sleep(0.2)
  1374. dev[0].dump_monitor()
  1375. if_obj.Set(WPAS_DBUS_IFACE, "Country", "FI",
  1376. dbus_interface=dbus.PROPERTIES_IFACE)
  1377. res = if_obj.Get(WPAS_DBUS_IFACE, "Country",
  1378. dbus_interface=dbus.PROPERTIES_IFACE)
  1379. if res != "FI":
  1380. raise Exception("Unexpected Country value %s (expected FI)" % res)
  1381. ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"])
  1382. if ev is None:
  1383. raise Exception("regdom change event not seen")
  1384. if "init=USER type=COUNTRY alpha2=FI" not in ev:
  1385. raise Exception("Unexpected event contents: " + ev)
  1386. try:
  1387. if_obj.Set(WPAS_DBUS_IFACE, "Country", dbus.Int16(-1),
  1388. dbus_interface=dbus.PROPERTIES_IFACE)
  1389. raise Exception("Invalid Set(Country,-1) accepted")
  1390. except dbus.exceptions.DBusException, e:
  1391. if "Error.Failed: wrong property type" not in str(e):
  1392. raise Exception("Unexpected error message for invalid Set(Country,-1): " + str(e))
  1393. try:
  1394. if_obj.Set(WPAS_DBUS_IFACE, "Country", "F",
  1395. dbus_interface=dbus.PROPERTIES_IFACE)
  1396. raise Exception("Invalid Set(Country,F) accepted")
  1397. except dbus.exceptions.DBusException, e:
  1398. if "Error.Failed: invalid country code" not in str(e):
  1399. raise Exception("Unexpected error message for invalid Set(Country,F): " + str(e))
  1400. if_obj.Set(WPAS_DBUS_IFACE, "Country", "00",
  1401. dbus_interface=dbus.PROPERTIES_IFACE)
  1402. ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"])
  1403. if ev is None:
  1404. raise Exception("regdom change event not seen")
  1405. if "init=CORE type=WORLD" not in ev:
  1406. raise Exception("Unexpected event contents: " + ev)
  1407. def test_dbus_scan_interval(dev, apdev):
  1408. """D-Bus Get/Set ScanInterval"""
  1409. try:
  1410. _test_dbus_scan_interval(dev, apdev)
  1411. finally:
  1412. dev[0].request("SCAN_INTERVAL 5")
  1413. def _test_dbus_scan_interval(dev, apdev):
  1414. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1415. if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.Int32(3),
  1416. dbus_interface=dbus.PROPERTIES_IFACE)
  1417. res = if_obj.Get(WPAS_DBUS_IFACE, "ScanInterval",
  1418. dbus_interface=dbus.PROPERTIES_IFACE)
  1419. if res != 3:
  1420. raise Exception("Unexpected ScanInterval value %d (expected %d)" % (res, i))
  1421. try:
  1422. if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.UInt16(100),
  1423. dbus_interface=dbus.PROPERTIES_IFACE)
  1424. raise Exception("Invalid Set(ScanInterval,100) accepted")
  1425. except dbus.exceptions.DBusException, e:
  1426. if "Error.Failed: wrong property type" not in str(e):
  1427. raise Exception("Unexpected error message for invalid Set(ScanInterval,100): " + str(e))
  1428. try:
  1429. if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.Int32(-1),
  1430. dbus_interface=dbus.PROPERTIES_IFACE)
  1431. raise Exception("Invalid Set(ScanInterval,-1) accepted")
  1432. except dbus.exceptions.DBusException, e:
  1433. if "Error.Failed: scan_interval must be >= 0" not in str(e):
  1434. raise Exception("Unexpected error message for invalid Set(ScanInterval,-1): " + str(e))
  1435. if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.Int32(5),
  1436. dbus_interface=dbus.PROPERTIES_IFACE)
  1437. def test_dbus_probe_req_reporting(dev, apdev):
  1438. """D-Bus Probe Request reporting"""
  1439. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1440. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1441. dev[0].p2p_start_go(freq=2412)
  1442. dev[1].p2p_find(social=True)
  1443. class TestDbusProbe(TestDbus):
  1444. def __init__(self, bus):
  1445. TestDbus.__init__(self, bus)
  1446. self.reported = False
  1447. def __enter__(self):
  1448. gobject.timeout_add(1, self.run_test)
  1449. gobject.timeout_add(15000, self.timeout)
  1450. self.add_signal(self.probeRequest, WPAS_DBUS_IFACE, "ProbeRequest",
  1451. byte_arrays=True)
  1452. iface.SubscribeProbeReq()
  1453. self.loop.run()
  1454. return self
  1455. def probeRequest(self, args):
  1456. logger.debug("probeRequest: args=%s" % str(args))
  1457. self.reported = True
  1458. self.loop.quit()
  1459. def run_test(self, *args):
  1460. logger.debug("run_test")
  1461. return False
  1462. def success(self):
  1463. return self.reported
  1464. with TestDbusProbe(bus) as t:
  1465. if not t.success():
  1466. raise Exception("Expected signals not seen")
  1467. iface.UnsubscribeProbeReq()
  1468. try:
  1469. iface.UnsubscribeProbeReq()
  1470. raise Exception("Invalid UnsubscribeProbeReq() accepted")
  1471. except dbus.exceptions.DBusException, e:
  1472. if "NoSubscription" not in str(e):
  1473. raise Exception("Unexpected error message for invalid UnsubscribeProbeReq(): " + str(e))
  1474. with TestDbusProbe(bus) as t:
  1475. if not t.success():
  1476. raise Exception("Expected signals not seen")
  1477. # On purpose, leave ProbeReq subscription in place to test automatic
  1478. # cleanup.
  1479. dev[1].p2p_stop_find()
  1480. dev[0].remove_group()
  1481. def test_dbus_p2p_invalid(dev, apdev):
  1482. """D-Bus invalid P2P operations"""
  1483. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1484. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  1485. try:
  1486. p2p.RejectPeer(path + "/Peers/00112233445566")
  1487. raise Exception("Invalid RejectPeer accepted")
  1488. except dbus.exceptions.DBusException, e:
  1489. if "UnknownError: Failed to call wpas_p2p_reject" not in str(e):
  1490. raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
  1491. try:
  1492. p2p.RejectPeer("/foo")
  1493. raise Exception("Invalid RejectPeer accepted")
  1494. except dbus.exceptions.DBusException, e:
  1495. if "InvalidArgs" not in str(e):
  1496. raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
  1497. tests = [ {'DiscoveryType': 'foo'},
  1498. {'RequestedDeviceTypes': 'foo'},
  1499. {'RequestedDeviceTypes': ['foo']},
  1500. {'RequestedDeviceTypes': ['1','2','3','4','5','6','7','8','9',
  1501. '10','11','12','13','14','15','16',
  1502. '17']},
  1503. {'RequestedDeviceTypes': dbus.Array([], signature="s")},
  1504. {'RequestedDeviceTypes': dbus.Array([['foo']], signature="as")},
  1505. {'RequestedDeviceTypes': dbus.Array([], signature="i")},
  1506. {'RequestedDeviceTypes': [dbus.ByteArray('12345678'),
  1507. dbus.ByteArray('1234567')]},
  1508. {'Foo': dbus.Int16(1)},
  1509. {'Foo': dbus.UInt16(1)},
  1510. {'Foo': dbus.Int64(1)},
  1511. {'Foo': dbus.UInt64(1)},
  1512. {'Foo': dbus.Double(1.23)},
  1513. {'Foo': dbus.Signature('s')},
  1514. {'Foo': 'bar'}]
  1515. for t in tests:
  1516. try:
  1517. p2p.Find(dbus.Dictionary(t))
  1518. raise Exception("Invalid Find accepted")
  1519. except dbus.exceptions.DBusException, e:
  1520. if "InvalidArgs" not in str(e):
  1521. raise Exception("Unexpected error message for invalid Find(): " + str(e))
  1522. for p in [ "/foo",
  1523. "/fi/w1/wpa_supplicant1/Interfaces/1234",
  1524. "/fi/w1/wpa_supplicant1/Interfaces/1234/Networks/1234" ]:
  1525. try:
  1526. p2p.RemovePersistentGroup(dbus.ObjectPath(p))
  1527. raise Exception("Invalid RemovePersistentGroup accepted")
  1528. except dbus.exceptions.DBusException, e:
  1529. if "InvalidArgs" not in str(e):
  1530. raise Exception("Unexpected error message for invalid RemovePersistentGroup: " + str(e))
  1531. try:
  1532. dev[0].request("P2P_SET disabled 1")
  1533. p2p.Listen(5)
  1534. raise Exception("Invalid Listen accepted")
  1535. except dbus.exceptions.DBusException, e:
  1536. if "UnknownError: Could not start P2P listen" not in str(e):
  1537. raise Exception("Unexpected error message for invalid Listen: " + str(e))
  1538. finally:
  1539. dev[0].request("P2P_SET disabled 0")
  1540. test_obj = bus.get_object(WPAS_DBUS_SERVICE, path, introspect=False)
  1541. test_p2p = dbus.Interface(test_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  1542. try:
  1543. test_p2p.Listen("foo")
  1544. raise Exception("Invalid Listen accepted")
  1545. except dbus.exceptions.DBusException, e:
  1546. if "InvalidArgs" not in str(e):
  1547. raise Exception("Unexpected error message for invalid Listen: " + str(e))
  1548. try:
  1549. dev[0].request("P2P_SET disabled 1")
  1550. p2p.ExtendedListen(dbus.Dictionary({}))
  1551. raise Exception("Invalid ExtendedListen accepted")
  1552. except dbus.exceptions.DBusException, e:
  1553. if "UnknownError: failed to initiate a p2p_ext_listen" not in str(e):
  1554. raise Exception("Unexpected error message for invalid ExtendedListen: " + str(e))
  1555. finally:
  1556. dev[0].request("P2P_SET disabled 0")
  1557. try:
  1558. dev[0].request("P2P_SET disabled 1")
  1559. args = { 'duration1': 30000, 'interval1': 102400,
  1560. 'duration2': 20000, 'interval2': 102400 }
  1561. p2p.PresenceRequest(args)
  1562. raise Exception("Invalid PresenceRequest accepted")
  1563. except dbus.exceptions.DBusException, e:
  1564. if "UnknownError: Failed to invoke presence request" not in str(e):
  1565. raise Exception("Unexpected error message for invalid PresenceRequest: " + str(e))
  1566. finally:
  1567. dev[0].request("P2P_SET disabled 0")
  1568. try:
  1569. params = dbus.Dictionary({'frequency': dbus.Int32(-1)})
  1570. p2p.GroupAdd(params)
  1571. raise Exception("Invalid GroupAdd accepted")
  1572. except dbus.exceptions.DBusException, e:
  1573. if "InvalidArgs" not in str(e):
  1574. raise Exception("Unexpected error message for invalid GroupAdd: " + str(e))
  1575. try:
  1576. params = dbus.Dictionary({'persistent_group_object':
  1577. dbus.ObjectPath(path),
  1578. 'frequency': 2412})
  1579. p2p.GroupAdd(params)
  1580. raise Exception("Invalid GroupAdd accepted")
  1581. except dbus.exceptions.DBusException, e:
  1582. if "InvalidArgs" not in str(e):
  1583. raise Exception("Unexpected error message for invalid GroupAdd: " + str(e))
  1584. try:
  1585. p2p.Disconnect()
  1586. raise Exception("Invalid Disconnect accepted")
  1587. except dbus.exceptions.DBusException, e:
  1588. if "UnknownError: failed to disconnect" not in str(e):
  1589. raise Exception("Unexpected error message for invalid Disconnect: " + str(e))
  1590. try:
  1591. dev[0].request("P2P_SET disabled 1")
  1592. p2p.Flush()
  1593. raise Exception("Invalid Flush accepted")
  1594. except dbus.exceptions.DBusException, e:
  1595. if "Error.Failed: P2P is not available for this interface" not in str(e):
  1596. raise Exception("Unexpected error message for invalid Flush: " + str(e))
  1597. finally:
  1598. dev[0].request("P2P_SET disabled 0")
  1599. try:
  1600. dev[0].request("P2P_SET disabled 1")
  1601. args = { 'peer': path,
  1602. 'join': True,
  1603. 'wps_method': 'pbc',
  1604. 'frequency': 2412 }
  1605. pin = p2p.Connect(args)
  1606. raise Exception("Invalid Connect accepted")
  1607. except dbus.exceptions.DBusException, e:
  1608. if "Error.Failed: P2P is not available for this interface" not in str(e):
  1609. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  1610. finally:
  1611. dev[0].request("P2P_SET disabled 0")
  1612. tests = [ { 'frequency': dbus.Int32(-1) },
  1613. { 'wps_method': 'pbc' },
  1614. { 'wps_method': 'foo' } ]
  1615. for args in tests:
  1616. try:
  1617. pin = p2p.Connect(args)
  1618. raise Exception("Invalid Connect accepted")
  1619. except dbus.exceptions.DBusException, e:
  1620. if "InvalidArgs" not in str(e):
  1621. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  1622. try:
  1623. dev[0].request("P2P_SET disabled 1")
  1624. args = { 'peer': path }
  1625. pin = p2p.Invite(args)
  1626. raise Exception("Invalid Invite accepted")
  1627. except dbus.exceptions.DBusException, e:
  1628. if "Error.Failed: P2P is not available for this interface" not in str(e):
  1629. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  1630. finally:
  1631. dev[0].request("P2P_SET disabled 0")
  1632. try:
  1633. args = { 'foo': 'bar' }
  1634. pin = p2p.Invite(args)
  1635. raise Exception("Invalid Invite accepted")
  1636. except dbus.exceptions.DBusException, e:
  1637. if "InvalidArgs" not in str(e):
  1638. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  1639. tests = [ (path, 'display', "InvalidArgs"),
  1640. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  1641. 'display',
  1642. "UnknownError: Failed to send provision discovery request"),
  1643. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  1644. 'keypad',
  1645. "UnknownError: Failed to send provision discovery request"),
  1646. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  1647. 'pbc',
  1648. "UnknownError: Failed to send provision discovery request"),
  1649. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  1650. 'pushbutton',
  1651. "UnknownError: Failed to send provision discovery request"),
  1652. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  1653. 'foo', "InvalidArgs") ]
  1654. for (p,method,err) in tests:
  1655. try:
  1656. p2p.ProvisionDiscoveryRequest(p, method)
  1657. raise Exception("Invalid ProvisionDiscoveryRequest accepted")
  1658. except dbus.exceptions.DBusException, e:
  1659. if err not in str(e):
  1660. raise Exception("Unexpected error message for invalid ProvisionDiscoveryRequest: " + str(e))
  1661. try:
  1662. dev[0].request("P2P_SET disabled 1")
  1663. if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Peers",
  1664. dbus_interface=dbus.PROPERTIES_IFACE)
  1665. raise Exception("Invalid Get(Peers) accepted")
  1666. except dbus.exceptions.DBusException, e:
  1667. if "Error.Failed: P2P is not available for this interface" not in str(e):
  1668. raise Exception("Unexpected error message for invalid Get(Peers): " + str(e))
  1669. finally:
  1670. dev[0].request("P2P_SET disabled 0")
  1671. def test_dbus_p2p_discovery(dev, apdev):
  1672. """D-Bus P2P discovery"""
  1673. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1674. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  1675. addr0 = dev[0].p2p_dev_addr()
  1676. dev[1].request("SET sec_device_type 1-0050F204-2")
  1677. dev[1].request("VENDOR_ELEM_ADD 1 dd0c0050f2041049000411223344")
  1678. dev[1].p2p_listen()
  1679. addr1 = dev[1].p2p_dev_addr()
  1680. a1 = binascii.unhexlify(addr1.replace(':',''))
  1681. wfd_devinfo = "00001c440028"
  1682. dev[2].request("SET wifi_display 1")
  1683. dev[2].request("WFD_SUBELEM_SET 0 0006" + wfd_devinfo)
  1684. wfd = binascii.unhexlify('000006' + wfd_devinfo)
  1685. dev[2].p2p_listen()
  1686. addr2 = dev[2].p2p_dev_addr()
  1687. a2 = binascii.unhexlify(addr2.replace(':',''))
  1688. res = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
  1689. dbus_interface=dbus.PROPERTIES_IFACE)
  1690. if 'Peers' not in res:
  1691. raise Exception("GetAll result missing Peers")
  1692. if len(res['Peers']) != 0:
  1693. raise Exception("Unexpected peer(s) in the list")
  1694. args = {'DiscoveryType': 'social',
  1695. 'RequestedDeviceTypes': [dbus.ByteArray('12345678')],
  1696. 'Timeout': dbus.Int32(1) }
  1697. p2p.Find(dbus.Dictionary(args))
  1698. p2p.StopFind()
  1699. class TestDbusP2p(TestDbus):
  1700. def __init__(self, bus):
  1701. TestDbus.__init__(self, bus)
  1702. self.found = False
  1703. self.found2 = False
  1704. self.lost = False
  1705. def __enter__(self):
  1706. gobject.timeout_add(1, self.run_test)
  1707. gobject.timeout_add(15000, self.timeout)
  1708. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  1709. "DeviceFound")
  1710. self.add_signal(self.deviceLost, WPAS_DBUS_IFACE_P2PDEVICE,
  1711. "DeviceLost")
  1712. self.add_signal(self.provisionDiscoveryResponseEnterPin,
  1713. WPAS_DBUS_IFACE_P2PDEVICE,
  1714. "ProvisionDiscoveryResponseEnterPin")
  1715. self.loop.run()
  1716. return self
  1717. def deviceFound(self, path):
  1718. logger.debug("deviceFound: path=%s" % path)
  1719. res = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Peers",
  1720. dbus_interface=dbus.PROPERTIES_IFACE)
  1721. if len(res) < 1:
  1722. raise Exception("Unexpected number of peers")
  1723. if path not in res:
  1724. raise Exception("Mismatch in peer object path")
  1725. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  1726. res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  1727. dbus_interface=dbus.PROPERTIES_IFACE,
  1728. byte_arrays=True)
  1729. logger.debug("peer properties: " + str(res))
  1730. if res['DeviceAddress'] == a1:
  1731. if 'SecondaryDeviceTypes' not in res:
  1732. raise Exception("Missing SecondaryDeviceTypes")
  1733. sec = res['SecondaryDeviceTypes']
  1734. if len(sec) < 1:
  1735. raise Exception("Secondary device type missing")
  1736. if "\x00\x01\x00\x50\xF2\x04\x00\x02" not in sec:
  1737. raise Exception("Secondary device type mismatch")
  1738. if 'VendorExtension' not in res:
  1739. raise Exception("Missing VendorExtension")
  1740. vendor = res['VendorExtension']
  1741. if len(vendor) < 1:
  1742. raise Exception("Vendor extension missing")
  1743. if "\x11\x22\x33\x44" not in vendor:
  1744. raise Exception("Secondary device type mismatch")
  1745. self.found = True
  1746. elif res['DeviceAddress'] == a2:
  1747. if 'IEs' not in res:
  1748. raise Exception("IEs missing")
  1749. if res['IEs'] != wfd:
  1750. raise Exception("IEs mismatch")
  1751. self.found2 = True
  1752. else:
  1753. raise Exception("Unexpected peer device address")
  1754. if self.found and self.found2:
  1755. p2p.StopFind()
  1756. p2p.RejectPeer(path)
  1757. p2p.ProvisionDiscoveryRequest(path, 'display')
  1758. def deviceLost(self, path):
  1759. logger.debug("deviceLost: path=%s" % path)
  1760. self.lost = True
  1761. try:
  1762. p2p.RejectPeer(path)
  1763. raise Exception("Invalid RejectPeer accepted")
  1764. except dbus.exceptions.DBusException, e:
  1765. if "UnknownError: Failed to call wpas_p2p_reject" not in str(e):
  1766. raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
  1767. self.loop.quit()
  1768. def provisionDiscoveryResponseEnterPin(self, peer_object):
  1769. logger.debug("provisionDiscoveryResponseEnterPin - peer=%s" % peer_object)
  1770. p2p.Flush()
  1771. def run_test(self, *args):
  1772. logger.debug("run_test")
  1773. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social',
  1774. 'Timeout': dbus.Int32(10)}))
  1775. return False
  1776. def success(self):
  1777. return self.found and self.lost and self.found2
  1778. with TestDbusP2p(bus) as t:
  1779. if not t.success():
  1780. raise Exception("Expected signals not seen")
  1781. dev[1].request("VENDOR_ELEM_REMOVE 1 *")
  1782. dev[1].p2p_stop_find()
  1783. p2p.Listen(1)
  1784. dev[2].p2p_stop_find()
  1785. dev[2].request("P2P_FLUSH")
  1786. if not dev[2].discover_peer(addr0):
  1787. raise Exception("Peer not found")
  1788. p2p.StopFind()
  1789. dev[2].p2p_stop_find()
  1790. try:
  1791. p2p.ExtendedListen(dbus.Dictionary({'foo': 100}))
  1792. raise Exception("Invalid ExtendedListen accepted")
  1793. except dbus.exceptions.DBusException, e:
  1794. if "InvalidArgs" not in str(e):
  1795. raise Exception("Unexpected error message for invalid ExtendedListen(): " + str(e))
  1796. p2p.ExtendedListen(dbus.Dictionary({'period': 100, 'interval': 1000}))
  1797. p2p.ExtendedListen(dbus.Dictionary({}))
  1798. dev[0].global_request("P2P_EXT_LISTEN")
  1799. def test_dbus_p2p_service_discovery(dev, apdev):
  1800. """D-Bus P2P service discovery"""
  1801. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1802. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  1803. addr0 = dev[0].p2p_dev_addr()
  1804. addr1 = dev[1].p2p_dev_addr()
  1805. bonjour_query = dbus.ByteArray(binascii.unhexlify('0b5f6166706f766572746370c00c000c01'))
  1806. bonjour_response = dbus.ByteArray(binascii.unhexlify('074578616d706c65c027'))
  1807. args = { 'service_type': 'bonjour',
  1808. 'query': bonjour_query,
  1809. 'response': bonjour_response }
  1810. p2p.AddService(args)
  1811. p2p.FlushService()
  1812. p2p.AddService(args)
  1813. try:
  1814. p2p.DeleteService(args)
  1815. raise Exception("Invalid DeleteService() accepted")
  1816. except dbus.exceptions.DBusException, e:
  1817. if "InvalidArgs" not in str(e):
  1818. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  1819. args = { 'service_type': 'bonjour',
  1820. 'query': bonjour_query }
  1821. p2p.DeleteService(args)
  1822. try:
  1823. p2p.DeleteService(args)
  1824. raise Exception("Invalid DeleteService() accepted")
  1825. except dbus.exceptions.DBusException, e:
  1826. if "InvalidArgs" not in str(e):
  1827. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  1828. args = { 'service_type': 'upnp',
  1829. 'version': 0x10,
  1830. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' }
  1831. p2p.AddService(args)
  1832. p2p.DeleteService(args)
  1833. try:
  1834. p2p.DeleteService(args)
  1835. raise Exception("Invalid DeleteService() accepted")
  1836. except dbus.exceptions.DBusException, e:
  1837. if "InvalidArgs" not in str(e):
  1838. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  1839. tests = [ { 'service_type': 'foo' },
  1840. { 'service_type': 'foo', 'query': bonjour_query },
  1841. { 'service_type': 'upnp' },
  1842. { 'service_type': 'upnp', 'version': 0x10 },
  1843. { 'service_type': 'upnp',
  1844. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
  1845. { 'version': 0x10,
  1846. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
  1847. { 'service_type': 'upnp', 'foo': 'bar' },
  1848. { 'service_type': 'bonjour' },
  1849. { 'service_type': 'bonjour', 'query': 'foo' },
  1850. { 'service_type': 'bonjour', 'foo': 'bar' } ]
  1851. for args in tests:
  1852. try:
  1853. p2p.DeleteService(args)
  1854. raise Exception("Invalid DeleteService() accepted")
  1855. except dbus.exceptions.DBusException, e:
  1856. if "InvalidArgs" not in str(e):
  1857. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  1858. tests = [ { 'service_type': 'foo' },
  1859. { 'service_type': 'upnp' },
  1860. { 'service_type': 'upnp', 'version': 0x10 },
  1861. { 'service_type': 'upnp',
  1862. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
  1863. { 'version': 0x10,
  1864. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
  1865. { 'service_type': 'upnp', 'foo': 'bar' },
  1866. { 'service_type': 'bonjour' },
  1867. { 'service_type': 'bonjour', 'query': 'foo' },
  1868. { 'service_type': 'bonjour', 'response': 'foo' },
  1869. { 'service_type': 'bonjour', 'query': bonjour_query },
  1870. { 'service_type': 'bonjour', 'response': bonjour_response },
  1871. { 'service_type': 'bonjour', 'query': dbus.ByteArray(500*'a') },
  1872. { 'service_type': 'bonjour', 'foo': 'bar' } ]
  1873. for args in tests:
  1874. try:
  1875. p2p.AddService(args)
  1876. raise Exception("Invalid AddService() accepted")
  1877. except dbus.exceptions.DBusException, e:
  1878. if "InvalidArgs" not in str(e):
  1879. raise Exception("Unexpected error message for invalid AddService(): " + str(e))
  1880. args = { 'tlv': dbus.ByteArray("\x02\x00\x00\x01") }
  1881. ref = p2p.ServiceDiscoveryRequest(args)
  1882. p2p.ServiceDiscoveryCancelRequest(ref)
  1883. try:
  1884. p2p.ServiceDiscoveryCancelRequest(ref)
  1885. raise Exception("Invalid ServiceDiscoveryCancelRequest() accepted")
  1886. except dbus.exceptions.DBusException, e:
  1887. if "InvalidArgs" not in str(e):
  1888. raise Exception("Unexpected error message for invalid AddService(): " + str(e))
  1889. try:
  1890. p2p.ServiceDiscoveryCancelRequest(dbus.UInt64(0))
  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. args = { 'service_type': 'upnp',
  1896. 'version': 0x10,
  1897. 'service': 'ssdp:foo' }
  1898. ref = p2p.ServiceDiscoveryRequest(args)
  1899. p2p.ServiceDiscoveryCancelRequest(ref)
  1900. tests = [ { 'service_type': 'foo' },
  1901. { 'foo': 'bar' },
  1902. { 'tlv': 'foo' },
  1903. { },
  1904. { 'version': 0 },
  1905. { 'service_type': 'upnp',
  1906. 'service': 'ssdp:foo' },
  1907. { 'service_type': 'upnp',
  1908. 'version': 0x10 },
  1909. { 'service_type': 'upnp',
  1910. 'version': 0x10,
  1911. 'service': 'ssdp:foo',
  1912. 'peer_object': dbus.ObjectPath(path + "/Peers") },
  1913. { 'service_type': 'upnp',
  1914. 'version': 0x10,
  1915. 'service': 'ssdp:foo',
  1916. 'peer_object': path + "/Peers" },
  1917. { 'service_type': 'upnp',
  1918. 'version': 0x10,
  1919. 'service': 'ssdp:foo',
  1920. 'peer_object': dbus.ObjectPath(path + "/Peers/00112233445566") } ]
  1921. for args in tests:
  1922. try:
  1923. p2p.ServiceDiscoveryRequest(args)
  1924. raise Exception("Invalid ServiceDiscoveryRequest accepted")
  1925. except dbus.exceptions.DBusException, e:
  1926. if "InvalidArgs" not in str(e):
  1927. raise Exception("Unexpected error message for invalid ServiceDiscoveryRequest(): " + str(e))
  1928. args = { 'foo': 'bar' }
  1929. try:
  1930. p2p.ServiceDiscoveryResponse(dbus.Dictionary(args, signature='sv'))
  1931. raise Exception("Invalid ServiceDiscoveryResponse accepted")
  1932. except dbus.exceptions.DBusException, e:
  1933. if "InvalidArgs" not in str(e):
  1934. raise Exception("Unexpected error message for invalid ServiceDiscoveryResponse(): " + str(e))
  1935. def test_dbus_p2p_service_discovery_query(dev, apdev):
  1936. """D-Bus P2P service discovery query"""
  1937. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1938. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  1939. addr0 = dev[0].p2p_dev_addr()
  1940. dev[1].request("P2P_SERVICE_ADD bonjour 0b5f6166706f766572746370c00c000c01 074578616d706c65c027")
  1941. dev[1].p2p_listen()
  1942. addr1 = dev[1].p2p_dev_addr()
  1943. class TestDbusP2p(TestDbus):
  1944. def __init__(self, bus):
  1945. TestDbus.__init__(self, bus)
  1946. self.done = False
  1947. def __enter__(self):
  1948. gobject.timeout_add(1, self.run_test)
  1949. gobject.timeout_add(15000, self.timeout)
  1950. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  1951. "DeviceFound")
  1952. self.add_signal(self.serviceDiscoveryResponse,
  1953. WPAS_DBUS_IFACE_P2PDEVICE,
  1954. "ServiceDiscoveryResponse", byte_arrays=True)
  1955. self.loop.run()
  1956. return self
  1957. def deviceFound(self, path):
  1958. logger.debug("deviceFound: path=%s" % path)
  1959. args = { 'peer_object': path,
  1960. 'tlv': dbus.ByteArray("\x02\x00\x00\x01") }
  1961. p2p.ServiceDiscoveryRequest(args)
  1962. def serviceDiscoveryResponse(self, sd_request):
  1963. logger.debug("serviceDiscoveryResponse: sd_request=%s" % str(sd_request))
  1964. self.done = True
  1965. self.loop.quit()
  1966. def run_test(self, *args):
  1967. logger.debug("run_test")
  1968. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social',
  1969. 'Timeout': dbus.Int32(10)}))
  1970. return False
  1971. def success(self):
  1972. return self.done
  1973. with TestDbusP2p(bus) as t:
  1974. if not t.success():
  1975. raise Exception("Expected signals not seen")
  1976. dev[1].p2p_stop_find()
  1977. def test_dbus_p2p_service_discovery_external(dev, apdev):
  1978. """D-Bus P2P service discovery with external response"""
  1979. try:
  1980. _test_dbus_p2p_service_discovery_external(dev, apdev)
  1981. finally:
  1982. dev[0].request("P2P_SERV_DISC_EXTERNAL 0")
  1983. def _test_dbus_p2p_service_discovery_external(dev, apdev):
  1984. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1985. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  1986. addr0 = dev[0].p2p_dev_addr()
  1987. addr1 = dev[1].p2p_dev_addr()
  1988. resp = "0300000101"
  1989. dev[1].request("P2P_FLUSH")
  1990. dev[1].request("P2P_SERV_DISC_REQ " + addr0 + " 02000001")
  1991. dev[1].p2p_find(social=True)
  1992. class TestDbusP2p(TestDbus):
  1993. def __init__(self, bus):
  1994. TestDbus.__init__(self, bus)
  1995. self.sd = False
  1996. def __enter__(self):
  1997. gobject.timeout_add(1, self.run_test)
  1998. gobject.timeout_add(15000, self.timeout)
  1999. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2000. "DeviceFound")
  2001. self.add_signal(self.serviceDiscoveryRequest,
  2002. WPAS_DBUS_IFACE_P2PDEVICE,
  2003. "ServiceDiscoveryRequest")
  2004. self.loop.run()
  2005. return self
  2006. def deviceFound(self, path):
  2007. logger.debug("deviceFound: path=%s" % path)
  2008. def serviceDiscoveryRequest(self, sd_request):
  2009. logger.debug("serviceDiscoveryRequest: sd_request=%s" % str(sd_request))
  2010. self.sd = True
  2011. args = { 'peer_object': sd_request['peer_object'],
  2012. 'frequency': sd_request['frequency'],
  2013. 'dialog_token': sd_request['dialog_token'],
  2014. 'tlvs': dbus.ByteArray(binascii.unhexlify(resp)) }
  2015. p2p.ServiceDiscoveryResponse(dbus.Dictionary(args, signature='sv'))
  2016. self.loop.quit()
  2017. def run_test(self, *args):
  2018. logger.debug("run_test")
  2019. p2p.ServiceDiscoveryExternal(1)
  2020. p2p.ServiceUpdate()
  2021. p2p.Listen(15)
  2022. return False
  2023. def success(self):
  2024. return self.sd
  2025. with TestDbusP2p(bus) as t:
  2026. if not t.success():
  2027. raise Exception("Expected signals not seen")
  2028. ev = dev[1].wait_global_event(["P2P-SERV-DISC-RESP"], timeout=5)
  2029. if ev is None:
  2030. raise Exception("Service discovery timed out")
  2031. if addr0 not in ev:
  2032. raise Exception("Unexpected address in SD Response: " + ev)
  2033. if ev.split(' ')[4] != resp:
  2034. raise Exception("Unexpected response data SD Response: " + ev)
  2035. dev[1].p2p_stop_find()
  2036. p2p.StopFind()
  2037. p2p.ServiceDiscoveryExternal(0)
  2038. def test_dbus_p2p_autogo(dev, apdev):
  2039. """D-Bus P2P autonomous GO"""
  2040. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2041. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2042. wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
  2043. addr0 = dev[0].p2p_dev_addr()
  2044. class TestDbusP2p(TestDbus):
  2045. def __init__(self, bus):
  2046. TestDbus.__init__(self, bus)
  2047. self.first = True
  2048. self.waiting_end = False
  2049. self.done = False
  2050. def __enter__(self):
  2051. gobject.timeout_add(1, self.run_test)
  2052. gobject.timeout_add(15000, self.timeout)
  2053. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2054. "DeviceFound")
  2055. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2056. "GroupStarted")
  2057. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2058. "GroupFinished")
  2059. self.add_signal(self.persistentGroupAdded,
  2060. WPAS_DBUS_IFACE_P2PDEVICE,
  2061. "PersistentGroupAdded")
  2062. self.add_signal(self.persistentGroupRemoved,
  2063. WPAS_DBUS_IFACE_P2PDEVICE,
  2064. "PersistentGroupRemoved")
  2065. self.add_signal(self.provisionDiscoveryRequestDisplayPin,
  2066. WPAS_DBUS_IFACE_P2PDEVICE,
  2067. "ProvisionDiscoveryRequestDisplayPin")
  2068. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  2069. "StaAuthorized")
  2070. self.loop.run()
  2071. return self
  2072. def groupStarted(self, properties):
  2073. logger.debug("groupStarted: " + str(properties))
  2074. self.group = properties['group_object']
  2075. role = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Role",
  2076. dbus_interface=dbus.PROPERTIES_IFACE)
  2077. if role != "GO":
  2078. raise Exception("Unexpected role reported: " + role)
  2079. group = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Group",
  2080. dbus_interface=dbus.PROPERTIES_IFACE)
  2081. if group != properties['group_object']:
  2082. raise Exception("Unexpected Group reported: " + str(group))
  2083. go = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PeerGO",
  2084. dbus_interface=dbus.PROPERTIES_IFACE)
  2085. if go != '/':
  2086. raise Exception("Unexpected PeerGO value: " + str(go))
  2087. if self.first:
  2088. self.first = False
  2089. logger.info("Remove persistent group instance")
  2090. p2p.Disconnect()
  2091. else:
  2092. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2093. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 join")
  2094. def groupFinished(self, properties):
  2095. logger.debug("groupFinished: " + str(properties))
  2096. if self.waiting_end:
  2097. logger.info("Remove persistent group")
  2098. p2p.RemovePersistentGroup(self.persistent)
  2099. else:
  2100. logger.info("Re-start persistent group")
  2101. params = dbus.Dictionary({'persistent_group_object':
  2102. self.persistent,
  2103. 'frequency': 2412})
  2104. p2p.GroupAdd(params)
  2105. def persistentGroupAdded(self, path, properties):
  2106. logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
  2107. self.persistent = path
  2108. def persistentGroupRemoved(self, path):
  2109. logger.debug("persistentGroupRemoved: %s" % path)
  2110. self.done = True
  2111. self.loop.quit()
  2112. def deviceFound(self, path):
  2113. logger.debug("deviceFound: path=%s" % path)
  2114. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  2115. self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2116. dbus_interface=dbus.PROPERTIES_IFACE,
  2117. byte_arrays=True)
  2118. logger.debug('peer properties: ' + str(self.peer))
  2119. def provisionDiscoveryRequestDisplayPin(self, peer_object, pin):
  2120. logger.debug("provisionDiscoveryRequestDisplayPin - peer=%s pin=%s" % (peer_object, pin))
  2121. self.peer_path = peer_object
  2122. peer = binascii.unhexlify(peer_object.split('/')[-1])
  2123. addr = ""
  2124. for p in peer:
  2125. if len(addr) > 0:
  2126. addr += ':'
  2127. addr += '%02x' % ord(p)
  2128. params = { 'Role': 'registrar',
  2129. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  2130. 'Bssid': self.peer['DeviceAddress'],
  2131. 'Type': 'pin',
  2132. 'Pin': '12345670' }
  2133. logger.info("Authorize peer to connect to the group")
  2134. wps.Start(params)
  2135. def staAuthorized(self, name):
  2136. logger.debug("staAuthorized: " + name)
  2137. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, self.peer_path)
  2138. res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2139. dbus_interface=dbus.PROPERTIES_IFACE,
  2140. byte_arrays=True)
  2141. if 'Groups' not in res or len(res['Groups']) != 1:
  2142. raise Exception("Unexpected number of peer Groups entries")
  2143. if res['Groups'][0] != self.group:
  2144. raise Exception("Unexpected peer Groups[0] value")
  2145. g_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group)
  2146. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  2147. dbus_interface=dbus.PROPERTIES_IFACE,
  2148. byte_arrays=True)
  2149. logger.debug("Group properties: " + str(res))
  2150. if 'Members' not in res or len(res['Members']) != 1:
  2151. raise Exception("Unexpected number of group members")
  2152. ext = dbus.ByteArray("\x11\x22\x33\x44")
  2153. # Earlier implementation of this interface was a bit strange. The
  2154. # property is defined to have aay signature and that is what the
  2155. # getter returned. However, the setter expected there to be a
  2156. # dictionary with 'WPSVendorExtensions' as the key surrounding these
  2157. # values.. The current implementations maintains support for that
  2158. # for backwards compability reasons. Verify that encoding first.
  2159. vals = dbus.Dictionary({ 'WPSVendorExtensions': [ ext ]},
  2160. signature='sv')
  2161. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
  2162. dbus_interface=dbus.PROPERTIES_IFACE)
  2163. res = g_obj.Get(WPAS_DBUS_GROUP, 'WPSVendorExtensions',
  2164. dbus_interface=dbus.PROPERTIES_IFACE,
  2165. byte_arrays=True)
  2166. if len(res) != 1:
  2167. raise Exception("Unexpected number of vendor extensions")
  2168. if res[0] != ext:
  2169. raise Exception("Vendor extension value changed")
  2170. # And now verify that the more appropriate encoding is accepted as
  2171. # well.
  2172. res.append(dbus.ByteArray('\xaa\xbb\xcc\xdd\xee\xff'))
  2173. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
  2174. dbus_interface=dbus.PROPERTIES_IFACE)
  2175. res2 = g_obj.Get(WPAS_DBUS_GROUP, 'WPSVendorExtensions',
  2176. dbus_interface=dbus.PROPERTIES_IFACE,
  2177. byte_arrays=True)
  2178. if len(res) != 2:
  2179. raise Exception("Unexpected number of vendor extensions")
  2180. if res[0] != res2[0] or res[1] != res2[1]:
  2181. raise Exception("Vendor extension value changed")
  2182. for i in range(10):
  2183. res.append(dbus.ByteArray('\xaa\xbb'))
  2184. try:
  2185. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
  2186. dbus_interface=dbus.PROPERTIES_IFACE)
  2187. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  2188. except dbus.exceptions.DBusException, e:
  2189. if "Error.Failed" not in str(e):
  2190. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  2191. vals = dbus.Dictionary({ 'Foo': [ ext ]}, signature='sv')
  2192. try:
  2193. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
  2194. dbus_interface=dbus.PROPERTIES_IFACE)
  2195. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  2196. except dbus.exceptions.DBusException, e:
  2197. if "InvalidArgs" not in str(e):
  2198. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  2199. vals = [ "foo" ]
  2200. try:
  2201. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
  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 = [ [ "foo" ] ]
  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 "Error.Failed" not in str(e):
  2214. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  2215. self.waiting_end = True
  2216. p2p.Disconnect()
  2217. def run_test(self, *args):
  2218. logger.debug("run_test")
  2219. params = dbus.Dictionary({'persistent': True,
  2220. 'frequency': 2412})
  2221. logger.info("Add a persistent group")
  2222. p2p.GroupAdd(params)
  2223. return False
  2224. def success(self):
  2225. return self.done
  2226. with TestDbusP2p(bus) as t:
  2227. if not t.success():
  2228. raise Exception("Expected signals not seen")
  2229. dev[1].wait_go_ending_session()
  2230. def test_dbus_p2p_autogo_pbc(dev, apdev):
  2231. """D-Bus P2P autonomous GO and PBC"""
  2232. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2233. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2234. wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
  2235. addr0 = dev[0].p2p_dev_addr()
  2236. class TestDbusP2p(TestDbus):
  2237. def __init__(self, bus):
  2238. TestDbus.__init__(self, bus)
  2239. self.first = True
  2240. self.waiting_end = False
  2241. self.done = False
  2242. def __enter__(self):
  2243. gobject.timeout_add(1, self.run_test)
  2244. gobject.timeout_add(15000, self.timeout)
  2245. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2246. "DeviceFound")
  2247. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2248. "GroupStarted")
  2249. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2250. "GroupFinished")
  2251. self.add_signal(self.provisionDiscoveryPBCRequest,
  2252. WPAS_DBUS_IFACE_P2PDEVICE,
  2253. "ProvisionDiscoveryPBCRequest")
  2254. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  2255. "StaAuthorized")
  2256. self.loop.run()
  2257. return self
  2258. def groupStarted(self, properties):
  2259. logger.debug("groupStarted: " + str(properties))
  2260. self.group = properties['group_object']
  2261. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2262. dev1.global_request("P2P_CONNECT " + addr0 + " pbc join")
  2263. def groupFinished(self, properties):
  2264. logger.debug("groupFinished: " + str(properties))
  2265. self.done = True
  2266. self.loop.quit()
  2267. def deviceFound(self, path):
  2268. logger.debug("deviceFound: path=%s" % path)
  2269. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  2270. self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2271. dbus_interface=dbus.PROPERTIES_IFACE,
  2272. byte_arrays=True)
  2273. logger.debug('peer properties: ' + str(self.peer))
  2274. def provisionDiscoveryPBCRequest(self, peer_object):
  2275. logger.debug("provisionDiscoveryPBCRequest - peer=%s" % peer_object)
  2276. self.peer_path = peer_object
  2277. peer = binascii.unhexlify(peer_object.split('/')[-1])
  2278. addr = ""
  2279. for p in peer:
  2280. if len(addr) > 0:
  2281. addr += ':'
  2282. addr += '%02x' % ord(p)
  2283. params = { 'Role': 'registrar',
  2284. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  2285. 'Bssid': self.peer['DeviceAddress'],
  2286. 'Type': 'pbc' }
  2287. logger.info("Authorize peer to connect to the group")
  2288. wps.Start(params)
  2289. def staAuthorized(self, name):
  2290. logger.debug("staAuthorized: " + name)
  2291. p2p.Disconnect()
  2292. def run_test(self, *args):
  2293. logger.debug("run_test")
  2294. params = dbus.Dictionary({'frequency': 2412})
  2295. p2p.GroupAdd(params)
  2296. return False
  2297. def success(self):
  2298. return self.done
  2299. with TestDbusP2p(bus) as t:
  2300. if not t.success():
  2301. raise Exception("Expected signals not seen")
  2302. dev[1].wait_go_ending_session()
  2303. dev[1].flush_scan_cache()
  2304. def test_dbus_p2p_autogo_legacy(dev, apdev):
  2305. """D-Bus P2P autonomous GO and legacy STA"""
  2306. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2307. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2308. wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
  2309. addr0 = dev[0].p2p_dev_addr()
  2310. class TestDbusP2p(TestDbus):
  2311. def __init__(self, bus):
  2312. TestDbus.__init__(self, bus)
  2313. self.done = False
  2314. def __enter__(self):
  2315. gobject.timeout_add(1, self.run_test)
  2316. gobject.timeout_add(15000, self.timeout)
  2317. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2318. "GroupStarted")
  2319. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2320. "GroupFinished")
  2321. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  2322. "StaAuthorized")
  2323. self.loop.run()
  2324. return self
  2325. def groupStarted(self, properties):
  2326. logger.debug("groupStarted: " + str(properties))
  2327. pin = '12345670'
  2328. params = { 'Role': 'enrollee',
  2329. 'Type': 'pin',
  2330. 'Pin': pin }
  2331. wps.Start(params)
  2332. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2333. dev1.scan_for_bss(addr0, freq=2412)
  2334. dev1.request("WPS_PIN " + addr0 + " " + pin)
  2335. def groupFinished(self, properties):
  2336. logger.debug("groupFinished: " + str(properties))
  2337. self.done = True
  2338. self.loop.quit()
  2339. def staAuthorized(self, name):
  2340. logger.debug("staAuthorized: " + name)
  2341. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2342. dev1.request("DISCONNECT")
  2343. p2p.Disconnect()
  2344. def run_test(self, *args):
  2345. logger.debug("run_test")
  2346. params = dbus.Dictionary({'frequency': 2412})
  2347. p2p.GroupAdd(params)
  2348. return False
  2349. def success(self):
  2350. return self.done
  2351. with TestDbusP2p(bus) as t:
  2352. if not t.success():
  2353. raise Exception("Expected signals not seen")
  2354. def test_dbus_p2p_join(dev, apdev):
  2355. """D-Bus P2P join an autonomous GO"""
  2356. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2357. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2358. addr1 = dev[1].p2p_dev_addr()
  2359. addr2 = dev[2].p2p_dev_addr()
  2360. dev[1].p2p_start_go(freq=2412)
  2361. dev[2].p2p_listen()
  2362. class TestDbusP2p(TestDbus):
  2363. def __init__(self, bus):
  2364. TestDbus.__init__(self, bus)
  2365. self.done = False
  2366. self.peer = None
  2367. self.go = None
  2368. def __enter__(self):
  2369. gobject.timeout_add(1, self.run_test)
  2370. gobject.timeout_add(15000, self.timeout)
  2371. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2372. "DeviceFound")
  2373. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2374. "GroupStarted")
  2375. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2376. "GroupFinished")
  2377. self.add_signal(self.invitationResult, WPAS_DBUS_IFACE_P2PDEVICE,
  2378. "InvitationResult")
  2379. self.loop.run()
  2380. return self
  2381. def deviceFound(self, path):
  2382. logger.debug("deviceFound: path=%s" % path)
  2383. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  2384. res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2385. dbus_interface=dbus.PROPERTIES_IFACE,
  2386. byte_arrays=True)
  2387. logger.debug('peer properties: ' + str(res))
  2388. if addr2.replace(':','') in path:
  2389. self.peer = path
  2390. elif addr1.replace(':','') in path:
  2391. self.go = path
  2392. if self.peer and self.go:
  2393. logger.info("Join the group")
  2394. p2p.StopFind()
  2395. args = { 'peer': self.go,
  2396. 'join': True,
  2397. 'wps_method': 'pin',
  2398. 'frequency': 2412 }
  2399. pin = p2p.Connect(args)
  2400. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2401. dev1.request("WPS_PIN any " + pin)
  2402. def groupStarted(self, properties):
  2403. logger.debug("groupStarted: " + str(properties))
  2404. role = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Role",
  2405. dbus_interface=dbus.PROPERTIES_IFACE)
  2406. if role != "client":
  2407. raise Exception("Unexpected role reported: " + role)
  2408. group = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Group",
  2409. dbus_interface=dbus.PROPERTIES_IFACE)
  2410. if group != properties['group_object']:
  2411. raise Exception("Unexpected Group reported: " + str(group))
  2412. go = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PeerGO",
  2413. dbus_interface=dbus.PROPERTIES_IFACE)
  2414. if go != self.go:
  2415. raise Exception("Unexpected PeerGO value: " + str(go))
  2416. g_obj = bus.get_object(WPAS_DBUS_SERVICE,
  2417. properties['group_object'])
  2418. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  2419. dbus_interface=dbus.PROPERTIES_IFACE,
  2420. byte_arrays=True)
  2421. logger.debug("Group properties: " + str(res))
  2422. ext = dbus.ByteArray("\x11\x22\x33\x44")
  2423. try:
  2424. # Set(WPSVendorExtensions) not allowed for P2P Client
  2425. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
  2426. dbus_interface=dbus.PROPERTIES_IFACE)
  2427. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  2428. except dbus.exceptions.DBusException, e:
  2429. if "Error.Failed: Failed to set property" not in str(e):
  2430. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  2431. args = { 'duration1': 30000, 'interval1': 102400,
  2432. 'duration2': 20000, 'interval2': 102400 }
  2433. p2p.PresenceRequest(args)
  2434. args = { 'peer': self.peer }
  2435. p2p.Invite(args)
  2436. def groupFinished(self, properties):
  2437. logger.debug("groupFinished: " + str(properties))
  2438. self.done = True
  2439. self.loop.quit()
  2440. def invitationResult(self, result):
  2441. logger.debug("invitationResult: " + str(result))
  2442. if result['status'] != 1:
  2443. raise Exception("Unexpected invitation result: " + str(result))
  2444. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2445. dev1.remove_group()
  2446. def run_test(self, *args):
  2447. logger.debug("run_test")
  2448. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  2449. return False
  2450. def success(self):
  2451. return self.done
  2452. with TestDbusP2p(bus) as t:
  2453. if not t.success():
  2454. raise Exception("Expected signals not seen")
  2455. dev[2].p2p_stop_find()
  2456. def test_dbus_p2p_config(dev, apdev):
  2457. """D-Bus Get/Set P2PDeviceConfig"""
  2458. try:
  2459. _test_dbus_p2p_config(dev, apdev)
  2460. finally:
  2461. dev[0].request("P2P_SET ssid_postfix ")
  2462. def _test_dbus_p2p_config(dev, apdev):
  2463. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2464. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2465. res = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  2466. dbus_interface=dbus.PROPERTIES_IFACE,
  2467. byte_arrays=True)
  2468. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig", res,
  2469. dbus_interface=dbus.PROPERTIES_IFACE)
  2470. res2 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  2471. dbus_interface=dbus.PROPERTIES_IFACE,
  2472. byte_arrays=True)
  2473. if len(res) != len(res2):
  2474. raise Exception("Different number of parameters")
  2475. for k in res:
  2476. if res[k] != res2[k]:
  2477. raise Exception("Parameter %s value changes" % k)
  2478. changes = { 'SsidPostfix': 'foo',
  2479. 'VendorExtension': [ dbus.ByteArray('\x11\x22\x33\x44') ],
  2480. 'SecondaryDeviceTypes': [ dbus.ByteArray('\x11\x22\x33\x44\x55\x66\x77\x88') ]}
  2481. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  2482. dbus.Dictionary(changes, signature='sv'),
  2483. dbus_interface=dbus.PROPERTIES_IFACE)
  2484. res2 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  2485. dbus_interface=dbus.PROPERTIES_IFACE,
  2486. byte_arrays=True)
  2487. logger.debug("P2PDeviceConfig: " + str(res2))
  2488. if 'VendorExtension' not in res2 or len(res2['VendorExtension']) != 1:
  2489. raise Exception("VendorExtension does not match")
  2490. if 'SecondaryDeviceTypes' not in res2 or len(res2['SecondaryDeviceTypes']) != 1:
  2491. raise Exception("SecondaryDeviceType does not match")
  2492. changes = { 'SsidPostfix': '',
  2493. 'VendorExtension': dbus.Array([], signature="ay"),
  2494. 'SecondaryDeviceTypes': dbus.Array([], signature="ay") }
  2495. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  2496. dbus.Dictionary(changes, signature='sv'),
  2497. dbus_interface=dbus.PROPERTIES_IFACE)
  2498. res3 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  2499. dbus_interface=dbus.PROPERTIES_IFACE,
  2500. byte_arrays=True)
  2501. logger.debug("P2PDeviceConfig: " + str(res3))
  2502. if 'VendorExtension' in res3:
  2503. raise Exception("VendorExtension not removed")
  2504. if 'SecondaryDeviceTypes' in res3:
  2505. raise Exception("SecondaryDeviceType not removed")
  2506. try:
  2507. dev[0].request("P2P_SET disabled 1")
  2508. if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  2509. dbus_interface=dbus.PROPERTIES_IFACE,
  2510. byte_arrays=True)
  2511. raise Exception("Invalid Get(P2PDeviceConfig) accepted")
  2512. except dbus.exceptions.DBusException, e:
  2513. if "Error.Failed: P2P is not available for this interface" not in str(e):
  2514. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  2515. finally:
  2516. dev[0].request("P2P_SET disabled 0")
  2517. try:
  2518. dev[0].request("P2P_SET disabled 1")
  2519. changes = { 'SsidPostfix': 'foo' }
  2520. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  2521. dbus.Dictionary(changes, signature='sv'),
  2522. dbus_interface=dbus.PROPERTIES_IFACE)
  2523. raise Exception("Invalid Set(P2PDeviceConfig) accepted")
  2524. except dbus.exceptions.DBusException, e:
  2525. if "Error.Failed: P2P is not available for this interface" not in str(e):
  2526. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  2527. finally:
  2528. dev[0].request("P2P_SET disabled 0")
  2529. tests = [ { 'DeviceName': 123 },
  2530. { 'SsidPostfix': 123 },
  2531. { 'Foo': 'Bar' } ]
  2532. for changes in tests:
  2533. try:
  2534. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  2535. dbus.Dictionary(changes, signature='sv'),
  2536. dbus_interface=dbus.PROPERTIES_IFACE)
  2537. raise Exception("Invalid Set(P2PDeviceConfig) accepted")
  2538. except dbus.exceptions.DBusException, e:
  2539. if "InvalidArgs" not in str(e):
  2540. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  2541. def test_dbus_p2p_persistent(dev, apdev):
  2542. """D-Bus P2P persistent group"""
  2543. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2544. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2545. class TestDbusP2p(TestDbus):
  2546. def __init__(self, bus):
  2547. TestDbus.__init__(self, bus)
  2548. def __enter__(self):
  2549. gobject.timeout_add(1, self.run_test)
  2550. gobject.timeout_add(15000, self.timeout)
  2551. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2552. "GroupStarted")
  2553. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2554. "GroupFinished")
  2555. self.add_signal(self.persistentGroupAdded,
  2556. WPAS_DBUS_IFACE_P2PDEVICE,
  2557. "PersistentGroupAdded")
  2558. self.loop.run()
  2559. return self
  2560. def groupStarted(self, properties):
  2561. logger.debug("groupStarted: " + str(properties))
  2562. p2p.Disconnect()
  2563. def groupFinished(self, properties):
  2564. logger.debug("groupFinished: " + str(properties))
  2565. self.loop.quit()
  2566. def persistentGroupAdded(self, path, properties):
  2567. logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
  2568. self.persistent = path
  2569. def run_test(self, *args):
  2570. logger.debug("run_test")
  2571. params = dbus.Dictionary({'persistent': True,
  2572. 'frequency': 2412})
  2573. logger.info("Add a persistent group")
  2574. p2p.GroupAdd(params)
  2575. return False
  2576. def success(self):
  2577. return True
  2578. with TestDbusP2p(bus) as t:
  2579. if not t.success():
  2580. raise Exception("Expected signals not seen")
  2581. persistent = t.persistent
  2582. p_obj = bus.get_object(WPAS_DBUS_SERVICE, persistent)
  2583. res = p_obj.Get(WPAS_DBUS_PERSISTENT_GROUP, "Properties",
  2584. dbus_interface=dbus.PROPERTIES_IFACE, byte_arrays=True)
  2585. logger.info("Persistent group Properties: " + str(res))
  2586. vals = dbus.Dictionary({ 'ssid': 'DIRECT-foo' }, signature='sv')
  2587. p_obj.Set(WPAS_DBUS_PERSISTENT_GROUP, "Properties", vals,
  2588. dbus_interface=dbus.PROPERTIES_IFACE)
  2589. res2 = p_obj.Get(WPAS_DBUS_PERSISTENT_GROUP, "Properties",
  2590. dbus_interface=dbus.PROPERTIES_IFACE)
  2591. if len(res) != len(res2):
  2592. raise Exception("Different number of parameters")
  2593. for k in res:
  2594. if k != 'ssid' and res[k] != res2[k]:
  2595. raise Exception("Parameter %s value changes" % k)
  2596. if res2['ssid'] != '"DIRECT-foo"':
  2597. raise Exception("Unexpected ssid")
  2598. args = dbus.Dictionary({ 'ssid': 'DIRECT-testing',
  2599. 'psk': '1234567890' }, signature='sv')
  2600. group = p2p.AddPersistentGroup(args)
  2601. groups = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PersistentGroups",
  2602. dbus_interface=dbus.PROPERTIES_IFACE)
  2603. if len(groups) != 2:
  2604. raise Exception("Unexpected number of persistent groups: " + str(groups))
  2605. p2p.RemoveAllPersistentGroups()
  2606. groups = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PersistentGroups",
  2607. dbus_interface=dbus.PROPERTIES_IFACE)
  2608. if len(groups) != 0:
  2609. raise Exception("Unexpected number of persistent groups: " + str(groups))
  2610. try:
  2611. p2p.RemovePersistentGroup(persistent)
  2612. raise Exception("Invalid RemovePersistentGroup accepted")
  2613. except dbus.exceptions.DBusException, e:
  2614. if "NetworkUnknown: There is no such persistent group" not in str(e):
  2615. raise Exception("Unexpected error message for invalid RemovePersistentGroup: " + str(e))
  2616. def test_dbus_p2p_reinvoke_persistent(dev, apdev):
  2617. """D-Bus P2P reinvoke persistent group"""
  2618. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2619. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2620. wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
  2621. addr0 = dev[0].p2p_dev_addr()
  2622. class TestDbusP2p(TestDbus):
  2623. def __init__(self, bus):
  2624. TestDbus.__init__(self, bus)
  2625. self.first = True
  2626. self.waiting_end = False
  2627. self.done = False
  2628. self.invited = False
  2629. def __enter__(self):
  2630. gobject.timeout_add(1, self.run_test)
  2631. gobject.timeout_add(15000, self.timeout)
  2632. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2633. "DeviceFound")
  2634. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2635. "GroupStarted")
  2636. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2637. "GroupFinished")
  2638. self.add_signal(self.persistentGroupAdded,
  2639. WPAS_DBUS_IFACE_P2PDEVICE,
  2640. "PersistentGroupAdded")
  2641. self.add_signal(self.provisionDiscoveryRequestDisplayPin,
  2642. WPAS_DBUS_IFACE_P2PDEVICE,
  2643. "ProvisionDiscoveryRequestDisplayPin")
  2644. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  2645. "StaAuthorized")
  2646. self.loop.run()
  2647. return self
  2648. def groupStarted(self, properties):
  2649. logger.debug("groupStarted: " + str(properties))
  2650. if not self.invited:
  2651. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2652. dev1.scan_for_bss(addr0, freq=2412)
  2653. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 join")
  2654. def groupFinished(self, properties):
  2655. logger.debug("groupFinished: " + str(properties))
  2656. if self.invited:
  2657. self.done = True
  2658. self.loop.quit()
  2659. else:
  2660. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2661. dev1.request("SET persistent_reconnect 1")
  2662. dev1.p2p_listen()
  2663. args = { 'persistent_group_object': dbus.ObjectPath(path),
  2664. 'peer': self.peer_path }
  2665. try:
  2666. pin = p2p.Invite(args)
  2667. raise Exception("Invalid Invite accepted")
  2668. except dbus.exceptions.DBusException, e:
  2669. if "InvalidArgs" not in str(e):
  2670. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  2671. args = { 'persistent_group_object': self.persistent,
  2672. 'peer': self.peer_path }
  2673. pin = p2p.Invite(args)
  2674. self.invited = True
  2675. def persistentGroupAdded(self, path, properties):
  2676. logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
  2677. self.persistent = path
  2678. def deviceFound(self, path):
  2679. logger.debug("deviceFound: path=%s" % path)
  2680. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  2681. self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2682. dbus_interface=dbus.PROPERTIES_IFACE,
  2683. byte_arrays=True)
  2684. def provisionDiscoveryRequestDisplayPin(self, peer_object, pin):
  2685. logger.debug("provisionDiscoveryRequestDisplayPin - peer=%s pin=%s" % (peer_object, pin))
  2686. self.peer_path = peer_object
  2687. peer = binascii.unhexlify(peer_object.split('/')[-1])
  2688. addr = ""
  2689. for p in peer:
  2690. if len(addr) > 0:
  2691. addr += ':'
  2692. addr += '%02x' % ord(p)
  2693. params = { 'Role': 'registrar',
  2694. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  2695. 'Bssid': self.peer['DeviceAddress'],
  2696. 'Type': 'pin',
  2697. 'Pin': '12345670' }
  2698. logger.info("Authorize peer to connect to the group")
  2699. wps.Start(params)
  2700. def staAuthorized(self, name):
  2701. logger.debug("staAuthorized: " + name)
  2702. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2703. dev1.remove_group()
  2704. ev = dev1.wait_event(["P2P-GROUP-REMOVED"], timeout=10)
  2705. if ev is None:
  2706. raise Exception("Group removal timed out")
  2707. p2p.Disconnect()
  2708. def run_test(self, *args):
  2709. logger.debug("run_test")
  2710. params = dbus.Dictionary({'persistent': True,
  2711. 'frequency': 2412})
  2712. logger.info("Add a persistent group")
  2713. p2p.GroupAdd(params)
  2714. return False
  2715. def success(self):
  2716. return self.done
  2717. with TestDbusP2p(bus) as t:
  2718. if not t.success():
  2719. raise Exception("Expected signals not seen")
  2720. def test_dbus_p2p_go_neg_rx(dev, apdev):
  2721. """D-Bus P2P GO Negotiation receive"""
  2722. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2723. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2724. addr0 = dev[0].p2p_dev_addr()
  2725. class TestDbusP2p(TestDbus):
  2726. def __init__(self, bus):
  2727. TestDbus.__init__(self, bus)
  2728. self.done = False
  2729. def __enter__(self):
  2730. gobject.timeout_add(1, self.run_test)
  2731. gobject.timeout_add(15000, self.timeout)
  2732. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2733. "DeviceFound")
  2734. self.add_signal(self.goNegotiationRequest,
  2735. WPAS_DBUS_IFACE_P2PDEVICE,
  2736. "GONegotiationRequest",
  2737. byte_arrays=True)
  2738. self.add_signal(self.goNegotiationSuccess,
  2739. WPAS_DBUS_IFACE_P2PDEVICE,
  2740. "GONegotiationSuccess",
  2741. byte_arrays=True)
  2742. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2743. "GroupStarted")
  2744. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2745. "GroupFinished")
  2746. self.loop.run()
  2747. return self
  2748. def deviceFound(self, path):
  2749. logger.debug("deviceFound: path=%s" % path)
  2750. def goNegotiationRequest(self, path, dev_passwd_id):
  2751. logger.debug("goNegotiationRequest: path=%s dev_passwd_id=%d" % (path, dev_passwd_id))
  2752. if dev_passwd_id != 1:
  2753. raise Exception("Unexpected dev_passwd_id=%d" % dev_passwd_id)
  2754. args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
  2755. 'go_intent': 15, 'persistent': False, 'frequency': 5175 }
  2756. try:
  2757. p2p.Connect(args)
  2758. raise Exception("Invalid Connect accepted")
  2759. except dbus.exceptions.DBusException, e:
  2760. if "ConnectChannelUnsupported" not in str(e):
  2761. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  2762. args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
  2763. 'go_intent': 15, 'persistent': False }
  2764. p2p.Connect(args)
  2765. def goNegotiationSuccess(self, properties):
  2766. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  2767. def groupStarted(self, properties):
  2768. logger.debug("groupStarted: " + str(properties))
  2769. p2p.Disconnect()
  2770. def groupFinished(self, properties):
  2771. logger.debug("groupFinished: " + str(properties))
  2772. self.done = True
  2773. self.loop.quit()
  2774. def run_test(self, *args):
  2775. logger.debug("run_test")
  2776. p2p.Listen(10)
  2777. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2778. if not dev1.discover_peer(addr0):
  2779. raise Exception("Peer not found")
  2780. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 enter")
  2781. return False
  2782. def success(self):
  2783. return self.done
  2784. with TestDbusP2p(bus) as t:
  2785. if not t.success():
  2786. raise Exception("Expected signals not seen")
  2787. def test_dbus_p2p_go_neg_auth(dev, apdev):
  2788. """D-Bus P2P GO Negotiation authorized"""
  2789. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2790. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2791. addr0 = dev[0].p2p_dev_addr()
  2792. dev[1].p2p_listen()
  2793. class TestDbusP2p(TestDbus):
  2794. def __init__(self, bus):
  2795. TestDbus.__init__(self, bus)
  2796. self.done = False
  2797. self.peer_joined = False
  2798. self.peer_disconnected = False
  2799. def __enter__(self):
  2800. gobject.timeout_add(1, self.run_test)
  2801. gobject.timeout_add(15000, self.timeout)
  2802. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2803. "DeviceFound")
  2804. self.add_signal(self.goNegotiationSuccess,
  2805. WPAS_DBUS_IFACE_P2PDEVICE,
  2806. "GONegotiationSuccess",
  2807. byte_arrays=True)
  2808. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2809. "GroupStarted")
  2810. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2811. "GroupFinished")
  2812. self.add_signal(self.staDeauthorized, WPAS_DBUS_IFACE,
  2813. "StaDeauthorized")
  2814. self.add_signal(self.peerJoined, WPAS_DBUS_GROUP,
  2815. "PeerJoined")
  2816. self.add_signal(self.peerDisconnected, WPAS_DBUS_GROUP,
  2817. "PeerDisconnected")
  2818. self.loop.run()
  2819. return self
  2820. def deviceFound(self, path):
  2821. logger.debug("deviceFound: path=%s" % path)
  2822. args = { 'peer': path, 'wps_method': 'keypad',
  2823. 'go_intent': 15, 'authorize_only': True }
  2824. try:
  2825. p2p.Connect(args)
  2826. raise Exception("Invalid Connect accepted")
  2827. except dbus.exceptions.DBusException, e:
  2828. if "InvalidArgs" not in str(e):
  2829. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  2830. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  2831. 'go_intent': 15, 'authorize_only': True }
  2832. p2p.Connect(args)
  2833. p2p.Listen(10)
  2834. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2835. if not dev1.discover_peer(addr0):
  2836. raise Exception("Peer not found")
  2837. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=0")
  2838. ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
  2839. if ev is None:
  2840. raise Exception("Group formation timed out")
  2841. def goNegotiationSuccess(self, properties):
  2842. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  2843. def groupStarted(self, properties):
  2844. logger.debug("groupStarted: " + str(properties))
  2845. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2846. dev1.remove_group()
  2847. def staDeauthorized(self, name):
  2848. logger.debug("staDeuthorized: " + name)
  2849. p2p.Disconnect()
  2850. def peerJoined(self, peer):
  2851. logger.debug("peerJoined: " + peer)
  2852. self.peer_joined = True
  2853. def peerDisconnected(self, peer):
  2854. logger.debug("peerDisconnected: " + peer)
  2855. self.peer_disconnected = True
  2856. def groupFinished(self, properties):
  2857. logger.debug("groupFinished: " + str(properties))
  2858. self.done = True
  2859. self.loop.quit()
  2860. def run_test(self, *args):
  2861. logger.debug("run_test")
  2862. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  2863. return False
  2864. def success(self):
  2865. return self.done and self.peer_joined and self.peer_disconnected
  2866. with TestDbusP2p(bus) as t:
  2867. if not t.success():
  2868. raise Exception("Expected signals not seen")
  2869. def test_dbus_p2p_go_neg_init(dev, apdev):
  2870. """D-Bus P2P GO Negotiation initiation"""
  2871. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2872. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2873. addr0 = dev[0].p2p_dev_addr()
  2874. dev[1].p2p_listen()
  2875. class TestDbusP2p(TestDbus):
  2876. def __init__(self, bus):
  2877. TestDbus.__init__(self, bus)
  2878. self.done = False
  2879. def __enter__(self):
  2880. gobject.timeout_add(1, self.run_test)
  2881. gobject.timeout_add(15000, self.timeout)
  2882. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2883. "DeviceFound")
  2884. self.add_signal(self.goNegotiationSuccess,
  2885. WPAS_DBUS_IFACE_P2PDEVICE,
  2886. "GONegotiationSuccess",
  2887. byte_arrays=True)
  2888. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2889. "GroupStarted")
  2890. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2891. "GroupFinished")
  2892. self.loop.run()
  2893. return self
  2894. def deviceFound(self, path):
  2895. logger.debug("deviceFound: path=%s" % path)
  2896. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2897. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  2898. 'go_intent': 0 }
  2899. p2p.Connect(args)
  2900. ev = dev1.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
  2901. if ev is None:
  2902. raise Exception("Timeout while waiting for GO Neg Request")
  2903. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=15")
  2904. ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
  2905. if ev is None:
  2906. raise Exception("Group formation timed out")
  2907. def goNegotiationSuccess(self, properties):
  2908. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  2909. def groupStarted(self, properties):
  2910. logger.debug("groupStarted: " + str(properties))
  2911. p2p.Disconnect()
  2912. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2913. dev1.remove_group()
  2914. def groupFinished(self, properties):
  2915. logger.debug("groupFinished: " + str(properties))
  2916. self.done = True
  2917. self.loop.quit()
  2918. def run_test(self, *args):
  2919. logger.debug("run_test")
  2920. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  2921. return False
  2922. def success(self):
  2923. return self.done
  2924. with TestDbusP2p(bus) as t:
  2925. if not t.success():
  2926. raise Exception("Expected signals not seen")
  2927. def test_dbus_p2p_wps_failure(dev, apdev):
  2928. """D-Bus P2P WPS failure"""
  2929. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2930. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2931. addr0 = dev[0].p2p_dev_addr()
  2932. class TestDbusP2p(TestDbus):
  2933. def __init__(self, bus):
  2934. TestDbus.__init__(self, bus)
  2935. self.done = False
  2936. def __enter__(self):
  2937. gobject.timeout_add(1, self.run_test)
  2938. gobject.timeout_add(15000, self.timeout)
  2939. self.add_signal(self.goNegotiationRequest,
  2940. WPAS_DBUS_IFACE_P2PDEVICE,
  2941. "GONegotiationRequest",
  2942. byte_arrays=True)
  2943. self.add_signal(self.goNegotiationSuccess,
  2944. WPAS_DBUS_IFACE_P2PDEVICE,
  2945. "GONegotiationSuccess",
  2946. byte_arrays=True)
  2947. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2948. "GroupStarted")
  2949. self.add_signal(self.wpsFailed, WPAS_DBUS_IFACE_P2PDEVICE,
  2950. "WpsFailed")
  2951. self.loop.run()
  2952. return self
  2953. def goNegotiationRequest(self, path, dev_passwd_id):
  2954. logger.debug("goNegotiationRequest: path=%s dev_passwd_id=%d" % (path, dev_passwd_id))
  2955. if dev_passwd_id != 1:
  2956. raise Exception("Unexpected dev_passwd_id=%d" % dev_passwd_id)
  2957. args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
  2958. 'go_intent': 15 }
  2959. p2p.Connect(args)
  2960. def goNegotiationSuccess(self, properties):
  2961. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  2962. def groupStarted(self, properties):
  2963. logger.debug("groupStarted: " + str(properties))
  2964. raise Exception("Unexpected GroupStarted")
  2965. def wpsFailed(self, name, args):
  2966. logger.debug("wpsFailed - name=%s args=%s" % (name, str(args)))
  2967. self.done = True
  2968. self.loop.quit()
  2969. def run_test(self, *args):
  2970. logger.debug("run_test")
  2971. p2p.Listen(10)
  2972. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2973. if not dev1.discover_peer(addr0):
  2974. raise Exception("Peer not found")
  2975. dev1.global_request("P2P_CONNECT " + addr0 + " 87654321 enter")
  2976. return False
  2977. def success(self):
  2978. return self.done
  2979. with TestDbusP2p(bus) as t:
  2980. if not t.success():
  2981. raise Exception("Expected signals not seen")
  2982. def test_dbus_p2p_two_groups(dev, apdev):
  2983. """D-Bus P2P with two concurrent groups"""
  2984. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2985. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2986. dev[0].request("SET p2p_no_group_iface 0")
  2987. addr0 = dev[0].p2p_dev_addr()
  2988. addr1 = dev[1].p2p_dev_addr()
  2989. addr2 = dev[2].p2p_dev_addr()
  2990. dev[1].p2p_start_go(freq=2412)
  2991. class TestDbusP2p(TestDbus):
  2992. def __init__(self, bus):
  2993. TestDbus.__init__(self, bus)
  2994. self.done = False
  2995. self.peer = None
  2996. self.go = None
  2997. self.group1 = None
  2998. self.group2 = None
  2999. def __enter__(self):
  3000. gobject.timeout_add(1, self.run_test)
  3001. gobject.timeout_add(15000, self.timeout)
  3002. self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
  3003. "PropertiesChanged", byte_arrays=True)
  3004. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3005. "DeviceFound")
  3006. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3007. "GroupStarted")
  3008. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3009. "GroupFinished")
  3010. self.add_signal(self.peerJoined, WPAS_DBUS_GROUP,
  3011. "PeerJoined")
  3012. self.loop.run()
  3013. return self
  3014. def propertiesChanged(self, interface_name, changed_properties,
  3015. invalidated_properties):
  3016. logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
  3017. def deviceFound(self, path):
  3018. logger.debug("deviceFound: path=%s" % path)
  3019. if addr2.replace(':','') in path:
  3020. self.peer = path
  3021. elif addr1.replace(':','') in path:
  3022. self.go = path
  3023. if self.go and not self.group1:
  3024. logger.info("Join the group")
  3025. p2p.StopFind()
  3026. pin = '12345670'
  3027. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3028. dev1.request("WPS_PIN any " + pin)
  3029. args = { 'peer': self.go,
  3030. 'join': True,
  3031. 'wps_method': 'pin',
  3032. 'pin': pin,
  3033. 'frequency': 2412 }
  3034. p2p.Connect(args)
  3035. def groupStarted(self, properties):
  3036. logger.debug("groupStarted: " + str(properties))
  3037. prop = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
  3038. dbus_interface=dbus.PROPERTIES_IFACE)
  3039. logger.debug("p2pdevice properties: " + str(prop))
  3040. g_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3041. properties['group_object'])
  3042. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  3043. dbus_interface=dbus.PROPERTIES_IFACE,
  3044. byte_arrays=True)
  3045. logger.debug("Group properties: " + str(res))
  3046. if not self.group1:
  3047. self.group1 = properties['group_object']
  3048. self.group1iface = properties['interface_object']
  3049. self.g1_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3050. self.group1iface)
  3051. logger.info("Start autonomous GO")
  3052. params = dbus.Dictionary({ 'frequency': 2412 })
  3053. p2p.GroupAdd(params)
  3054. elif not self.group2:
  3055. self.group2 = properties['group_object']
  3056. self.group2iface = properties['interface_object']
  3057. self.g2_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3058. self.group2iface)
  3059. self.g2_bssid = res['BSSID']
  3060. if self.group1 and self.group2:
  3061. logger.info("Authorize peer to join the group")
  3062. a2 = binascii.unhexlify(addr2.replace(':',''))
  3063. params = { 'Role': 'enrollee',
  3064. 'P2PDeviceAddress': dbus.ByteArray(a2),
  3065. 'Bssid': dbus.ByteArray(a2),
  3066. 'Type': 'pin',
  3067. 'Pin': '12345670' }
  3068. g_wps = dbus.Interface(self.g2_if_obj, WPAS_DBUS_IFACE_WPS)
  3069. g_wps.Start(params)
  3070. bssid = ':'.join([binascii.hexlify(l) for l in self.g2_bssid])
  3071. dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2')
  3072. dev2.scan_for_bss(bssid, freq=2412)
  3073. dev2.global_request("P2P_CONNECT " + bssid + " 12345670 join freq=2412")
  3074. def groupFinished(self, properties):
  3075. logger.debug("groupFinished: " + str(properties))
  3076. if self.group1 == properties['group_object']:
  3077. self.group1 = None
  3078. elif self.group2 == properties['group_object']:
  3079. self.group2 = None
  3080. if not self.group1 and not self.group2:
  3081. self.done = True
  3082. self.loop.quit()
  3083. def peerJoined(self, peer):
  3084. logger.debug("peerJoined: " + peer)
  3085. self.check_results()
  3086. dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2')
  3087. dev2.remove_group()
  3088. logger.info("Disconnect group2")
  3089. group_p2p = dbus.Interface(self.g2_if_obj,
  3090. WPAS_DBUS_IFACE_P2PDEVICE)
  3091. group_p2p.Disconnect()
  3092. logger.info("Disconnect group1")
  3093. group_p2p = dbus.Interface(self.g1_if_obj,
  3094. WPAS_DBUS_IFACE_P2PDEVICE)
  3095. group_p2p.Disconnect()
  3096. def check_results(self):
  3097. logger.info("Check results with two concurrent groups in operation")
  3098. g1_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group1)
  3099. res1 = g1_obj.GetAll(WPAS_DBUS_GROUP,
  3100. dbus_interface=dbus.PROPERTIES_IFACE,
  3101. byte_arrays=True)
  3102. g2_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group2)
  3103. res2 = g2_obj.GetAll(WPAS_DBUS_GROUP,
  3104. dbus_interface=dbus.PROPERTIES_IFACE,
  3105. byte_arrays=True)
  3106. logger.info("group1 = " + self.group1)
  3107. logger.debug("Group properties: " + str(res1))
  3108. logger.info("group2 = " + self.group2)
  3109. logger.debug("Group properties: " + str(res2))
  3110. prop = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
  3111. dbus_interface=dbus.PROPERTIES_IFACE)
  3112. logger.debug("p2pdevice properties: " + str(prop))
  3113. if res1['Role'] != 'client':
  3114. raise Exception("Group1 role reported incorrectly: " + res1['Role'])
  3115. if res2['Role'] != 'GO':
  3116. raise Exception("Group2 role reported incorrectly: " + res2['Role'])
  3117. if prop['Role'] != 'device':
  3118. raise Exception("p2pdevice role reported incorrectly: " + prop['Role'])
  3119. if len(res2['Members']) != 1:
  3120. raise Exception("Unexpected Members value for group 2")
  3121. def run_test(self, *args):
  3122. logger.debug("run_test")
  3123. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  3124. return False
  3125. def success(self):
  3126. return self.done
  3127. with TestDbusP2p(bus) as t:
  3128. if not t.success():
  3129. raise Exception("Expected signals not seen")
  3130. dev[1].remove_group()