test_dbus.py 182 KB

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