test_dbus.py 147 KB

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