test_dbus.py 172 KB

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