test_dbus.py 171 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172
  1. # wpa_supplicant D-Bus interface tests
  2. # Copyright (c) 2014-2015, Jouni Malinen <j@w1.fi>
  3. #
  4. # This software may be distributed under the terms of the BSD license.
  5. # See README for more details.
  6. import binascii
  7. import gobject
  8. import logging
  9. logger = logging.getLogger()
  10. import subprocess
  11. import time
  12. try:
  13. import dbus
  14. dbus_imported = True
  15. except ImportError:
  16. dbus_imported = False
  17. import hostapd
  18. from wpasupplicant import WpaSupplicant
  19. from utils import HwsimSkip, 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. with alloc_fail_dbus(dev[0], 1, "wpas_dbus_handler_subscribe_preq",
  1849. "SubscribeProbeReq"):
  1850. iface.SubscribeProbeReq()
  1851. def test_dbus_p2p_invalid(dev, apdev):
  1852. """D-Bus invalid P2P operations"""
  1853. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1854. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  1855. try:
  1856. p2p.RejectPeer(path + "/Peers/00112233445566")
  1857. raise Exception("Invalid RejectPeer accepted")
  1858. except dbus.exceptions.DBusException, e:
  1859. if "UnknownError: Failed to call wpas_p2p_reject" not in str(e):
  1860. raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
  1861. try:
  1862. p2p.RejectPeer("/foo")
  1863. raise Exception("Invalid RejectPeer accepted")
  1864. except dbus.exceptions.DBusException, e:
  1865. if "InvalidArgs" not in str(e):
  1866. raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
  1867. tests = [ {'DiscoveryType': 'foo'},
  1868. {'RequestedDeviceTypes': 'foo'},
  1869. {'RequestedDeviceTypes': ['foo']},
  1870. {'RequestedDeviceTypes': ['1','2','3','4','5','6','7','8','9',
  1871. '10','11','12','13','14','15','16',
  1872. '17']},
  1873. {'RequestedDeviceTypes': dbus.Array([], signature="s")},
  1874. {'RequestedDeviceTypes': dbus.Array([['foo']], signature="as")},
  1875. {'RequestedDeviceTypes': dbus.Array([], signature="i")},
  1876. {'RequestedDeviceTypes': [dbus.ByteArray('12345678'),
  1877. dbus.ByteArray('1234567')]},
  1878. {'Foo': dbus.Int16(1)},
  1879. {'Foo': dbus.UInt16(1)},
  1880. {'Foo': dbus.Int64(1)},
  1881. {'Foo': dbus.UInt64(1)},
  1882. {'Foo': dbus.Double(1.23)},
  1883. {'Foo': dbus.Signature('s')},
  1884. {'Foo': 'bar'}]
  1885. for t in tests:
  1886. try:
  1887. p2p.Find(dbus.Dictionary(t))
  1888. raise Exception("Invalid Find accepted")
  1889. except dbus.exceptions.DBusException, e:
  1890. if "InvalidArgs" not in str(e):
  1891. raise Exception("Unexpected error message for invalid Find(): " + str(e))
  1892. for p in [ "/foo",
  1893. "/fi/w1/wpa_supplicant1/Interfaces/1234",
  1894. "/fi/w1/wpa_supplicant1/Interfaces/1234/Networks/1234" ]:
  1895. try:
  1896. p2p.RemovePersistentGroup(dbus.ObjectPath(p))
  1897. raise Exception("Invalid RemovePersistentGroup accepted")
  1898. except dbus.exceptions.DBusException, e:
  1899. if "InvalidArgs" not in str(e):
  1900. raise Exception("Unexpected error message for invalid RemovePersistentGroup: " + str(e))
  1901. try:
  1902. dev[0].request("P2P_SET disabled 1")
  1903. p2p.Listen(5)
  1904. raise Exception("Invalid Listen accepted")
  1905. except dbus.exceptions.DBusException, e:
  1906. if "UnknownError: Could not start P2P listen" not in str(e):
  1907. raise Exception("Unexpected error message for invalid Listen: " + str(e))
  1908. finally:
  1909. dev[0].request("P2P_SET disabled 0")
  1910. test_obj = bus.get_object(WPAS_DBUS_SERVICE, path, introspect=False)
  1911. test_p2p = dbus.Interface(test_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  1912. try:
  1913. test_p2p.Listen("foo")
  1914. raise Exception("Invalid Listen accepted")
  1915. except dbus.exceptions.DBusException, e:
  1916. if "InvalidArgs" not in str(e):
  1917. raise Exception("Unexpected error message for invalid Listen: " + str(e))
  1918. try:
  1919. dev[0].request("P2P_SET disabled 1")
  1920. p2p.ExtendedListen(dbus.Dictionary({}))
  1921. raise Exception("Invalid ExtendedListen accepted")
  1922. except dbus.exceptions.DBusException, e:
  1923. if "UnknownError: failed to initiate a p2p_ext_listen" not in str(e):
  1924. raise Exception("Unexpected error message for invalid ExtendedListen: " + str(e))
  1925. finally:
  1926. dev[0].request("P2P_SET disabled 0")
  1927. try:
  1928. dev[0].request("P2P_SET disabled 1")
  1929. args = { 'duration1': 30000, 'interval1': 102400,
  1930. 'duration2': 20000, 'interval2': 102400 }
  1931. p2p.PresenceRequest(args)
  1932. raise Exception("Invalid PresenceRequest accepted")
  1933. except dbus.exceptions.DBusException, e:
  1934. if "UnknownError: Failed to invoke presence request" not in str(e):
  1935. raise Exception("Unexpected error message for invalid PresenceRequest: " + str(e))
  1936. finally:
  1937. dev[0].request("P2P_SET disabled 0")
  1938. try:
  1939. params = dbus.Dictionary({'frequency': dbus.Int32(-1)})
  1940. p2p.GroupAdd(params)
  1941. raise Exception("Invalid GroupAdd accepted")
  1942. except dbus.exceptions.DBusException, e:
  1943. if "InvalidArgs" not in str(e):
  1944. raise Exception("Unexpected error message for invalid GroupAdd: " + str(e))
  1945. try:
  1946. params = dbus.Dictionary({'persistent_group_object':
  1947. dbus.ObjectPath(path),
  1948. 'frequency': 2412})
  1949. p2p.GroupAdd(params)
  1950. raise Exception("Invalid GroupAdd accepted")
  1951. except dbus.exceptions.DBusException, e:
  1952. if "InvalidArgs" not in str(e):
  1953. raise Exception("Unexpected error message for invalid GroupAdd: " + str(e))
  1954. try:
  1955. p2p.Disconnect()
  1956. raise Exception("Invalid Disconnect accepted")
  1957. except dbus.exceptions.DBusException, e:
  1958. if "UnknownError: failed to disconnect" not in str(e):
  1959. raise Exception("Unexpected error message for invalid Disconnect: " + str(e))
  1960. try:
  1961. dev[0].request("P2P_SET disabled 1")
  1962. p2p.Flush()
  1963. raise Exception("Invalid Flush accepted")
  1964. except dbus.exceptions.DBusException, e:
  1965. if "Error.Failed: P2P is not available for this interface" not in str(e):
  1966. raise Exception("Unexpected error message for invalid Flush: " + str(e))
  1967. finally:
  1968. dev[0].request("P2P_SET disabled 0")
  1969. try:
  1970. dev[0].request("P2P_SET disabled 1")
  1971. args = { 'peer': path,
  1972. 'join': True,
  1973. 'wps_method': 'pbc',
  1974. 'frequency': 2412 }
  1975. pin = p2p.Connect(args)
  1976. raise Exception("Invalid Connect 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 Connect: " + str(e))
  1980. finally:
  1981. dev[0].request("P2P_SET disabled 0")
  1982. tests = [ { 'frequency': dbus.Int32(-1) },
  1983. { 'wps_method': 'pbc' },
  1984. { 'wps_method': 'foo' } ]
  1985. for args in tests:
  1986. try:
  1987. pin = p2p.Connect(args)
  1988. raise Exception("Invalid Connect accepted")
  1989. except dbus.exceptions.DBusException, e:
  1990. if "InvalidArgs" not in str(e):
  1991. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  1992. try:
  1993. dev[0].request("P2P_SET disabled 1")
  1994. args = { 'peer': path }
  1995. pin = p2p.Invite(args)
  1996. raise Exception("Invalid Invite accepted")
  1997. except dbus.exceptions.DBusException, e:
  1998. if "Error.Failed: P2P is not available for this interface" not in str(e):
  1999. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  2000. finally:
  2001. dev[0].request("P2P_SET disabled 0")
  2002. try:
  2003. args = { 'foo': 'bar' }
  2004. pin = p2p.Invite(args)
  2005. raise Exception("Invalid Invite accepted")
  2006. except dbus.exceptions.DBusException, e:
  2007. if "InvalidArgs" not in str(e):
  2008. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  2009. tests = [ (path, 'display', "InvalidArgs"),
  2010. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2011. 'display',
  2012. "UnknownError: Failed to send provision discovery request"),
  2013. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2014. 'keypad',
  2015. "UnknownError: Failed to send provision discovery request"),
  2016. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2017. 'pbc',
  2018. "UnknownError: Failed to send provision discovery request"),
  2019. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2020. 'pushbutton',
  2021. "UnknownError: Failed to send provision discovery request"),
  2022. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2023. 'foo', "InvalidArgs") ]
  2024. for (p,method,err) in tests:
  2025. try:
  2026. p2p.ProvisionDiscoveryRequest(p, method)
  2027. raise Exception("Invalid ProvisionDiscoveryRequest accepted")
  2028. except dbus.exceptions.DBusException, e:
  2029. if err not in str(e):
  2030. raise Exception("Unexpected error message for invalid ProvisionDiscoveryRequest: " + str(e))
  2031. try:
  2032. dev[0].request("P2P_SET disabled 1")
  2033. if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Peers",
  2034. dbus_interface=dbus.PROPERTIES_IFACE)
  2035. raise Exception("Invalid Get(Peers) accepted")
  2036. except dbus.exceptions.DBusException, e:
  2037. if "Error.Failed: P2P is not available for this interface" not in str(e):
  2038. raise Exception("Unexpected error message for invalid Get(Peers): " + str(e))
  2039. finally:
  2040. dev[0].request("P2P_SET disabled 0")
  2041. def test_dbus_p2p_oom(dev, apdev):
  2042. """D-Bus P2P operations and OOM"""
  2043. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2044. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2045. with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_entry_get_string_array",
  2046. "Find", "InvalidArgs"):
  2047. p2p.Find(dbus.Dictionary({ 'Foo': [ 'bar' ] }))
  2048. with alloc_fail_dbus(dev[0], 2, "_wpa_dbus_dict_entry_get_string_array",
  2049. "Find", "InvalidArgs"):
  2050. p2p.Find(dbus.Dictionary({ 'Foo': [ 'bar' ] }))
  2051. with alloc_fail_dbus(dev[0], 10, "_wpa_dbus_dict_entry_get_string_array",
  2052. "Find", "InvalidArgs"):
  2053. p2p.Find(dbus.Dictionary({ 'Foo': [ '1','2','3','4','5','6','7','8','9' ] }))
  2054. with alloc_fail_dbus(dev[0], 1, ":=_wpa_dbus_dict_entry_get_binarray",
  2055. "Find", "InvalidArgs"):
  2056. p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123') ] }))
  2057. with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_entry_get_byte_array;_wpa_dbus_dict_entry_get_binarray",
  2058. "Find", "InvalidArgs"):
  2059. p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123') ] }))
  2060. with alloc_fail_dbus(dev[0], 2, "=_wpa_dbus_dict_entry_get_binarray",
  2061. "Find", "InvalidArgs"):
  2062. p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123'),
  2063. dbus.ByteArray('123'),
  2064. dbus.ByteArray('123'),
  2065. dbus.ByteArray('123'),
  2066. dbus.ByteArray('123'),
  2067. dbus.ByteArray('123'),
  2068. dbus.ByteArray('123'),
  2069. dbus.ByteArray('123'),
  2070. dbus.ByteArray('123'),
  2071. dbus.ByteArray('123'),
  2072. dbus.ByteArray('123') ] }))
  2073. with alloc_fail_dbus(dev[0], 1, "wpabuf_alloc_ext_data;_wpa_dbus_dict_entry_get_binarray",
  2074. "Find", "InvalidArgs"):
  2075. p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123') ] }))
  2076. with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_fill_value_from_variant;wpas_dbus_handler_p2p_find",
  2077. "Find", "InvalidArgs"):
  2078. p2p.Find(dbus.Dictionary({ 'Foo': path }))
  2079. with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_entry_get_byte_array",
  2080. "AddService", "InvalidArgs"):
  2081. args = { 'service_type': 'bonjour',
  2082. 'response': dbus.ByteArray(500*'b') }
  2083. p2p.AddService(args)
  2084. with alloc_fail_dbus(dev[0], 2, "_wpa_dbus_dict_entry_get_byte_array",
  2085. "AddService", "InvalidArgs"):
  2086. p2p.AddService(args)
  2087. def test_dbus_p2p_discovery(dev, apdev):
  2088. """D-Bus P2P discovery"""
  2089. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2090. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2091. addr0 = dev[0].p2p_dev_addr()
  2092. dev[1].request("SET sec_device_type 1-0050F204-2")
  2093. dev[1].request("VENDOR_ELEM_ADD 1 dd0c0050f2041049000411223344")
  2094. dev[1].p2p_listen()
  2095. addr1 = dev[1].p2p_dev_addr()
  2096. a1 = binascii.unhexlify(addr1.replace(':',''))
  2097. wfd_devinfo = "00001c440028"
  2098. dev[2].request("SET wifi_display 1")
  2099. dev[2].request("WFD_SUBELEM_SET 0 0006" + wfd_devinfo)
  2100. wfd = binascii.unhexlify('000006' + wfd_devinfo)
  2101. dev[2].p2p_listen()
  2102. addr2 = dev[2].p2p_dev_addr()
  2103. a2 = binascii.unhexlify(addr2.replace(':',''))
  2104. res = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
  2105. dbus_interface=dbus.PROPERTIES_IFACE)
  2106. if 'Peers' not in res:
  2107. raise Exception("GetAll result missing Peers")
  2108. if len(res['Peers']) != 0:
  2109. raise Exception("Unexpected peer(s) in the list")
  2110. args = {'DiscoveryType': 'social',
  2111. 'RequestedDeviceTypes': [dbus.ByteArray('12345678')],
  2112. 'Timeout': dbus.Int32(1) }
  2113. p2p.Find(dbus.Dictionary(args))
  2114. p2p.StopFind()
  2115. class TestDbusP2p(TestDbus):
  2116. def __init__(self, bus):
  2117. TestDbus.__init__(self, bus)
  2118. self.found = False
  2119. self.found2 = False
  2120. self.lost = False
  2121. def __enter__(self):
  2122. gobject.timeout_add(1, self.run_test)
  2123. gobject.timeout_add(15000, self.timeout)
  2124. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2125. "DeviceFound")
  2126. self.add_signal(self.deviceLost, WPAS_DBUS_IFACE_P2PDEVICE,
  2127. "DeviceLost")
  2128. self.add_signal(self.provisionDiscoveryResponseEnterPin,
  2129. WPAS_DBUS_IFACE_P2PDEVICE,
  2130. "ProvisionDiscoveryResponseEnterPin")
  2131. self.loop.run()
  2132. return self
  2133. def deviceFound(self, path):
  2134. logger.debug("deviceFound: path=%s" % path)
  2135. res = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Peers",
  2136. dbus_interface=dbus.PROPERTIES_IFACE)
  2137. if len(res) < 1:
  2138. raise Exception("Unexpected number of peers")
  2139. if path not in res:
  2140. raise Exception("Mismatch in peer object path")
  2141. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  2142. res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2143. dbus_interface=dbus.PROPERTIES_IFACE,
  2144. byte_arrays=True)
  2145. logger.debug("peer properties: " + str(res))
  2146. if res['DeviceAddress'] == a1:
  2147. if 'SecondaryDeviceTypes' not in res:
  2148. raise Exception("Missing SecondaryDeviceTypes")
  2149. sec = res['SecondaryDeviceTypes']
  2150. if len(sec) < 1:
  2151. raise Exception("Secondary device type missing")
  2152. if "\x00\x01\x00\x50\xF2\x04\x00\x02" not in sec:
  2153. raise Exception("Secondary device type mismatch")
  2154. if 'VendorExtension' not in res:
  2155. raise Exception("Missing VendorExtension")
  2156. vendor = res['VendorExtension']
  2157. if len(vendor) < 1:
  2158. raise Exception("Vendor extension missing")
  2159. if "\x11\x22\x33\x44" not in vendor:
  2160. raise Exception("Secondary device type mismatch")
  2161. self.found = True
  2162. elif res['DeviceAddress'] == a2:
  2163. if 'IEs' not in res:
  2164. raise Exception("IEs missing")
  2165. if res['IEs'] != wfd:
  2166. raise Exception("IEs mismatch")
  2167. self.found2 = True
  2168. else:
  2169. raise Exception("Unexpected peer device address")
  2170. if self.found and self.found2:
  2171. p2p.StopFind()
  2172. p2p.RejectPeer(path)
  2173. p2p.ProvisionDiscoveryRequest(path, 'display')
  2174. def deviceLost(self, path):
  2175. logger.debug("deviceLost: path=%s" % path)
  2176. self.lost = True
  2177. try:
  2178. p2p.RejectPeer(path)
  2179. raise Exception("Invalid RejectPeer accepted")
  2180. except dbus.exceptions.DBusException, e:
  2181. if "UnknownError: Failed to call wpas_p2p_reject" not in str(e):
  2182. raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
  2183. self.loop.quit()
  2184. def provisionDiscoveryResponseEnterPin(self, peer_object):
  2185. logger.debug("provisionDiscoveryResponseEnterPin - peer=%s" % peer_object)
  2186. p2p.Flush()
  2187. def run_test(self, *args):
  2188. logger.debug("run_test")
  2189. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social',
  2190. 'Timeout': dbus.Int32(10)}))
  2191. return False
  2192. def success(self):
  2193. return self.found and self.lost and self.found2
  2194. with TestDbusP2p(bus) as t:
  2195. if not t.success():
  2196. raise Exception("Expected signals not seen")
  2197. dev[1].request("VENDOR_ELEM_REMOVE 1 *")
  2198. dev[1].p2p_stop_find()
  2199. p2p.Listen(1)
  2200. dev[2].p2p_stop_find()
  2201. dev[2].request("P2P_FLUSH")
  2202. if not dev[2].discover_peer(addr0):
  2203. raise Exception("Peer not found")
  2204. p2p.StopFind()
  2205. dev[2].p2p_stop_find()
  2206. try:
  2207. p2p.ExtendedListen(dbus.Dictionary({'foo': 100}))
  2208. raise Exception("Invalid ExtendedListen accepted")
  2209. except dbus.exceptions.DBusException, e:
  2210. if "InvalidArgs" not in str(e):
  2211. raise Exception("Unexpected error message for invalid ExtendedListen(): " + str(e))
  2212. p2p.ExtendedListen(dbus.Dictionary({'period': 100, 'interval': 1000}))
  2213. p2p.ExtendedListen(dbus.Dictionary({}))
  2214. dev[0].global_request("P2P_EXT_LISTEN")
  2215. def test_dbus_p2p_service_discovery(dev, apdev):
  2216. """D-Bus P2P service discovery"""
  2217. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2218. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2219. addr0 = dev[0].p2p_dev_addr()
  2220. addr1 = dev[1].p2p_dev_addr()
  2221. bonjour_query = dbus.ByteArray(binascii.unhexlify('0b5f6166706f766572746370c00c000c01'))
  2222. bonjour_response = dbus.ByteArray(binascii.unhexlify('074578616d706c65c027'))
  2223. args = { 'service_type': 'bonjour',
  2224. 'query': bonjour_query,
  2225. 'response': bonjour_response }
  2226. p2p.AddService(args)
  2227. p2p.FlushService()
  2228. p2p.AddService(args)
  2229. try:
  2230. p2p.DeleteService(args)
  2231. raise Exception("Invalid DeleteService() accepted")
  2232. except dbus.exceptions.DBusException, e:
  2233. if "InvalidArgs" not in str(e):
  2234. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  2235. args = { 'service_type': 'bonjour',
  2236. 'query': bonjour_query }
  2237. p2p.DeleteService(args)
  2238. try:
  2239. p2p.DeleteService(args)
  2240. raise Exception("Invalid DeleteService() accepted")
  2241. except dbus.exceptions.DBusException, e:
  2242. if "InvalidArgs" not in str(e):
  2243. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  2244. args = { 'service_type': 'upnp',
  2245. 'version': 0x10,
  2246. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' }
  2247. p2p.AddService(args)
  2248. p2p.DeleteService(args)
  2249. try:
  2250. p2p.DeleteService(args)
  2251. raise Exception("Invalid DeleteService() accepted")
  2252. except dbus.exceptions.DBusException, e:
  2253. if "InvalidArgs" not in str(e):
  2254. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  2255. tests = [ { 'service_type': 'foo' },
  2256. { 'service_type': 'foo', 'query': bonjour_query },
  2257. { 'service_type': 'upnp' },
  2258. { 'service_type': 'upnp', 'version': 0x10 },
  2259. { 'service_type': 'upnp',
  2260. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
  2261. { 'version': 0x10,
  2262. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
  2263. { 'service_type': 'upnp', 'foo': 'bar' },
  2264. { 'service_type': 'bonjour' },
  2265. { 'service_type': 'bonjour', 'query': 'foo' },
  2266. { 'service_type': 'bonjour', 'foo': 'bar' } ]
  2267. for args in tests:
  2268. try:
  2269. p2p.DeleteService(args)
  2270. raise Exception("Invalid DeleteService() accepted")
  2271. except dbus.exceptions.DBusException, e:
  2272. if "InvalidArgs" not in str(e):
  2273. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  2274. tests = [ { 'service_type': 'foo' },
  2275. { 'service_type': 'upnp' },
  2276. { 'service_type': 'upnp', 'version': 0x10 },
  2277. { 'service_type': 'upnp',
  2278. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
  2279. { 'version': 0x10,
  2280. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
  2281. { 'service_type': 'upnp', 'foo': 'bar' },
  2282. { 'service_type': 'bonjour' },
  2283. { 'service_type': 'bonjour', 'query': 'foo' },
  2284. { 'service_type': 'bonjour', 'response': 'foo' },
  2285. { 'service_type': 'bonjour', 'query': bonjour_query },
  2286. { 'service_type': 'bonjour', 'response': bonjour_response },
  2287. { 'service_type': 'bonjour', 'query': dbus.ByteArray(500*'a') },
  2288. { 'service_type': 'bonjour', 'foo': 'bar' } ]
  2289. for args in tests:
  2290. try:
  2291. p2p.AddService(args)
  2292. raise Exception("Invalid AddService() accepted")
  2293. except dbus.exceptions.DBusException, e:
  2294. if "InvalidArgs" not in str(e):
  2295. raise Exception("Unexpected error message for invalid AddService(): " + str(e))
  2296. args = { 'tlv': dbus.ByteArray("\x02\x00\x00\x01") }
  2297. ref = p2p.ServiceDiscoveryRequest(args)
  2298. p2p.ServiceDiscoveryCancelRequest(ref)
  2299. try:
  2300. p2p.ServiceDiscoveryCancelRequest(ref)
  2301. raise Exception("Invalid ServiceDiscoveryCancelRequest() accepted")
  2302. except dbus.exceptions.DBusException, e:
  2303. if "InvalidArgs" not in str(e):
  2304. raise Exception("Unexpected error message for invalid AddService(): " + str(e))
  2305. try:
  2306. p2p.ServiceDiscoveryCancelRequest(dbus.UInt64(0))
  2307. raise Exception("Invalid ServiceDiscoveryCancelRequest() accepted")
  2308. except dbus.exceptions.DBusException, e:
  2309. if "InvalidArgs" not in str(e):
  2310. raise Exception("Unexpected error message for invalid AddService(): " + str(e))
  2311. args = { 'service_type': 'upnp',
  2312. 'version': 0x10,
  2313. 'service': 'ssdp:foo' }
  2314. ref = p2p.ServiceDiscoveryRequest(args)
  2315. p2p.ServiceDiscoveryCancelRequest(ref)
  2316. tests = [ { 'service_type': 'foo' },
  2317. { 'foo': 'bar' },
  2318. { 'tlv': 'foo' },
  2319. { },
  2320. { 'version': 0 },
  2321. { 'service_type': 'upnp',
  2322. 'service': 'ssdp:foo' },
  2323. { 'service_type': 'upnp',
  2324. 'version': 0x10 },
  2325. { 'service_type': 'upnp',
  2326. 'version': 0x10,
  2327. 'service': 'ssdp:foo',
  2328. 'peer_object': dbus.ObjectPath(path + "/Peers") },
  2329. { 'service_type': 'upnp',
  2330. 'version': 0x10,
  2331. 'service': 'ssdp:foo',
  2332. 'peer_object': path + "/Peers" },
  2333. { 'service_type': 'upnp',
  2334. 'version': 0x10,
  2335. 'service': 'ssdp:foo',
  2336. 'peer_object': dbus.ObjectPath(path + "/Peers/00112233445566") } ]
  2337. for args in tests:
  2338. try:
  2339. p2p.ServiceDiscoveryRequest(args)
  2340. raise Exception("Invalid ServiceDiscoveryRequest accepted")
  2341. except dbus.exceptions.DBusException, e:
  2342. if "InvalidArgs" not in str(e):
  2343. raise Exception("Unexpected error message for invalid ServiceDiscoveryRequest(): " + str(e))
  2344. args = { 'foo': 'bar' }
  2345. try:
  2346. p2p.ServiceDiscoveryResponse(dbus.Dictionary(args, signature='sv'))
  2347. raise Exception("Invalid ServiceDiscoveryResponse accepted")
  2348. except dbus.exceptions.DBusException, e:
  2349. if "InvalidArgs" not in str(e):
  2350. raise Exception("Unexpected error message for invalid ServiceDiscoveryResponse(): " + str(e))
  2351. def test_dbus_p2p_service_discovery_query(dev, apdev):
  2352. """D-Bus P2P service discovery query"""
  2353. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2354. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2355. addr0 = dev[0].p2p_dev_addr()
  2356. dev[1].request("P2P_SERVICE_ADD bonjour 0b5f6166706f766572746370c00c000c01 074578616d706c65c027")
  2357. dev[1].p2p_listen()
  2358. addr1 = dev[1].p2p_dev_addr()
  2359. class TestDbusP2p(TestDbus):
  2360. def __init__(self, bus):
  2361. TestDbus.__init__(self, bus)
  2362. self.done = False
  2363. def __enter__(self):
  2364. gobject.timeout_add(1, self.run_test)
  2365. gobject.timeout_add(15000, self.timeout)
  2366. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2367. "DeviceFound")
  2368. self.add_signal(self.serviceDiscoveryResponse,
  2369. WPAS_DBUS_IFACE_P2PDEVICE,
  2370. "ServiceDiscoveryResponse", byte_arrays=True)
  2371. self.loop.run()
  2372. return self
  2373. def deviceFound(self, path):
  2374. logger.debug("deviceFound: path=%s" % path)
  2375. args = { 'peer_object': path,
  2376. 'tlv': dbus.ByteArray("\x02\x00\x00\x01") }
  2377. p2p.ServiceDiscoveryRequest(args)
  2378. def serviceDiscoveryResponse(self, sd_request):
  2379. logger.debug("serviceDiscoveryResponse: sd_request=%s" % str(sd_request))
  2380. self.done = True
  2381. self.loop.quit()
  2382. def run_test(self, *args):
  2383. logger.debug("run_test")
  2384. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social',
  2385. 'Timeout': dbus.Int32(10)}))
  2386. return False
  2387. def success(self):
  2388. return self.done
  2389. with TestDbusP2p(bus) as t:
  2390. if not t.success():
  2391. raise Exception("Expected signals not seen")
  2392. dev[1].p2p_stop_find()
  2393. def test_dbus_p2p_service_discovery_external(dev, apdev):
  2394. """D-Bus P2P service discovery with external response"""
  2395. try:
  2396. _test_dbus_p2p_service_discovery_external(dev, apdev)
  2397. finally:
  2398. dev[0].request("P2P_SERV_DISC_EXTERNAL 0")
  2399. def _test_dbus_p2p_service_discovery_external(dev, apdev):
  2400. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2401. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2402. addr0 = dev[0].p2p_dev_addr()
  2403. addr1 = dev[1].p2p_dev_addr()
  2404. resp = "0300000101"
  2405. dev[1].request("P2P_FLUSH")
  2406. dev[1].request("P2P_SERV_DISC_REQ " + addr0 + " 02000001")
  2407. dev[1].p2p_find(social=True)
  2408. class TestDbusP2p(TestDbus):
  2409. def __init__(self, bus):
  2410. TestDbus.__init__(self, bus)
  2411. self.sd = False
  2412. def __enter__(self):
  2413. gobject.timeout_add(1, self.run_test)
  2414. gobject.timeout_add(15000, self.timeout)
  2415. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2416. "DeviceFound")
  2417. self.add_signal(self.serviceDiscoveryRequest,
  2418. WPAS_DBUS_IFACE_P2PDEVICE,
  2419. "ServiceDiscoveryRequest")
  2420. self.loop.run()
  2421. return self
  2422. def deviceFound(self, path):
  2423. logger.debug("deviceFound: path=%s" % path)
  2424. def serviceDiscoveryRequest(self, sd_request):
  2425. logger.debug("serviceDiscoveryRequest: sd_request=%s" % str(sd_request))
  2426. self.sd = True
  2427. args = { 'peer_object': sd_request['peer_object'],
  2428. 'frequency': sd_request['frequency'],
  2429. 'dialog_token': sd_request['dialog_token'],
  2430. 'tlvs': dbus.ByteArray(binascii.unhexlify(resp)) }
  2431. p2p.ServiceDiscoveryResponse(dbus.Dictionary(args, signature='sv'))
  2432. self.loop.quit()
  2433. def run_test(self, *args):
  2434. logger.debug("run_test")
  2435. p2p.ServiceDiscoveryExternal(1)
  2436. p2p.ServiceUpdate()
  2437. p2p.Listen(15)
  2438. return False
  2439. def success(self):
  2440. return self.sd
  2441. with TestDbusP2p(bus) as t:
  2442. if not t.success():
  2443. raise Exception("Expected signals not seen")
  2444. ev = dev[1].wait_global_event(["P2P-SERV-DISC-RESP"], timeout=5)
  2445. if ev is None:
  2446. raise Exception("Service discovery timed out")
  2447. if addr0 not in ev:
  2448. raise Exception("Unexpected address in SD Response: " + ev)
  2449. if ev.split(' ')[4] != resp:
  2450. raise Exception("Unexpected response data SD Response: " + ev)
  2451. dev[1].p2p_stop_find()
  2452. p2p.StopFind()
  2453. p2p.ServiceDiscoveryExternal(0)
  2454. def test_dbus_p2p_autogo(dev, apdev):
  2455. """D-Bus P2P autonomous GO"""
  2456. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2457. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2458. wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
  2459. addr0 = dev[0].p2p_dev_addr()
  2460. class TestDbusP2p(TestDbus):
  2461. def __init__(self, bus):
  2462. TestDbus.__init__(self, bus)
  2463. self.first = True
  2464. self.waiting_end = False
  2465. self.done = False
  2466. def __enter__(self):
  2467. gobject.timeout_add(1, self.run_test)
  2468. gobject.timeout_add(15000, self.timeout)
  2469. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2470. "DeviceFound")
  2471. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2472. "GroupStarted")
  2473. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2474. "GroupFinished")
  2475. self.add_signal(self.persistentGroupAdded,
  2476. WPAS_DBUS_IFACE_P2PDEVICE,
  2477. "PersistentGroupAdded")
  2478. self.add_signal(self.persistentGroupRemoved,
  2479. WPAS_DBUS_IFACE_P2PDEVICE,
  2480. "PersistentGroupRemoved")
  2481. self.add_signal(self.provisionDiscoveryRequestDisplayPin,
  2482. WPAS_DBUS_IFACE_P2PDEVICE,
  2483. "ProvisionDiscoveryRequestDisplayPin")
  2484. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  2485. "StaAuthorized")
  2486. self.loop.run()
  2487. return self
  2488. def groupStarted(self, properties):
  2489. logger.debug("groupStarted: " + str(properties))
  2490. self.group = properties['group_object']
  2491. role = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Role",
  2492. dbus_interface=dbus.PROPERTIES_IFACE)
  2493. if role != "GO":
  2494. raise Exception("Unexpected role reported: " + role)
  2495. group = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Group",
  2496. dbus_interface=dbus.PROPERTIES_IFACE)
  2497. if group != properties['group_object']:
  2498. raise Exception("Unexpected Group reported: " + str(group))
  2499. go = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PeerGO",
  2500. dbus_interface=dbus.PROPERTIES_IFACE)
  2501. if go != '/':
  2502. raise Exception("Unexpected PeerGO value: " + str(go))
  2503. if self.first:
  2504. self.first = False
  2505. logger.info("Remove persistent group instance")
  2506. p2p.Disconnect()
  2507. else:
  2508. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2509. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 join")
  2510. def groupFinished(self, properties):
  2511. logger.debug("groupFinished: " + str(properties))
  2512. if self.waiting_end:
  2513. logger.info("Remove persistent group")
  2514. p2p.RemovePersistentGroup(self.persistent)
  2515. else:
  2516. logger.info("Re-start persistent group")
  2517. params = dbus.Dictionary({'persistent_group_object':
  2518. self.persistent,
  2519. 'frequency': 2412})
  2520. p2p.GroupAdd(params)
  2521. def persistentGroupAdded(self, path, properties):
  2522. logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
  2523. self.persistent = path
  2524. def persistentGroupRemoved(self, path):
  2525. logger.debug("persistentGroupRemoved: %s" % path)
  2526. self.done = True
  2527. self.loop.quit()
  2528. def deviceFound(self, path):
  2529. logger.debug("deviceFound: path=%s" % path)
  2530. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  2531. self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2532. dbus_interface=dbus.PROPERTIES_IFACE,
  2533. byte_arrays=True)
  2534. logger.debug('peer properties: ' + str(self.peer))
  2535. def provisionDiscoveryRequestDisplayPin(self, peer_object, pin):
  2536. logger.debug("provisionDiscoveryRequestDisplayPin - peer=%s pin=%s" % (peer_object, pin))
  2537. self.peer_path = peer_object
  2538. peer = binascii.unhexlify(peer_object.split('/')[-1])
  2539. addr = ""
  2540. for p in peer:
  2541. if len(addr) > 0:
  2542. addr += ':'
  2543. addr += '%02x' % ord(p)
  2544. params = { 'Role': 'registrar',
  2545. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  2546. 'Bssid': self.peer['DeviceAddress'],
  2547. 'Type': 'pin' }
  2548. try:
  2549. wps.Start(params)
  2550. raise Exception("Invalid WPS.Start() accepted")
  2551. except dbus.exceptions.DBusException, e:
  2552. if "InvalidArgs" not in str(e):
  2553. raise Exception("Unexpected error message: " + str(e))
  2554. params = { 'Role': 'registrar',
  2555. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  2556. 'Bssid': self.peer['DeviceAddress'],
  2557. 'Type': 'pin',
  2558. 'Pin': '12345670' }
  2559. logger.info("Authorize peer to connect to the group")
  2560. wps.Start(params)
  2561. def staAuthorized(self, name):
  2562. logger.debug("staAuthorized: " + name)
  2563. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, self.peer_path)
  2564. res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2565. dbus_interface=dbus.PROPERTIES_IFACE,
  2566. byte_arrays=True)
  2567. if 'Groups' not in res or len(res['Groups']) != 1:
  2568. raise Exception("Unexpected number of peer Groups entries")
  2569. if res['Groups'][0] != self.group:
  2570. raise Exception("Unexpected peer Groups[0] value")
  2571. g_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group)
  2572. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  2573. dbus_interface=dbus.PROPERTIES_IFACE,
  2574. byte_arrays=True)
  2575. logger.debug("Group properties: " + str(res))
  2576. if 'Members' not in res or len(res['Members']) != 1:
  2577. raise Exception("Unexpected number of group members")
  2578. ext = dbus.ByteArray("\x11\x22\x33\x44")
  2579. # Earlier implementation of this interface was a bit strange. The
  2580. # property is defined to have aay signature and that is what the
  2581. # getter returned. However, the setter expected there to be a
  2582. # dictionary with 'WPSVendorExtensions' as the key surrounding these
  2583. # values.. The current implementations maintains support for that
  2584. # for backwards compability reasons. Verify that encoding first.
  2585. vals = dbus.Dictionary({ 'WPSVendorExtensions': [ ext ]},
  2586. signature='sv')
  2587. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
  2588. dbus_interface=dbus.PROPERTIES_IFACE)
  2589. res = g_obj.Get(WPAS_DBUS_GROUP, 'WPSVendorExtensions',
  2590. dbus_interface=dbus.PROPERTIES_IFACE,
  2591. byte_arrays=True)
  2592. if len(res) != 1:
  2593. raise Exception("Unexpected number of vendor extensions")
  2594. if res[0] != ext:
  2595. raise Exception("Vendor extension value changed")
  2596. # And now verify that the more appropriate encoding is accepted as
  2597. # well.
  2598. res.append(dbus.ByteArray('\xaa\xbb\xcc\xdd\xee\xff'))
  2599. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
  2600. dbus_interface=dbus.PROPERTIES_IFACE)
  2601. res2 = g_obj.Get(WPAS_DBUS_GROUP, 'WPSVendorExtensions',
  2602. dbus_interface=dbus.PROPERTIES_IFACE,
  2603. byte_arrays=True)
  2604. if len(res) != 2:
  2605. raise Exception("Unexpected number of vendor extensions")
  2606. if res[0] != res2[0] or res[1] != res2[1]:
  2607. raise Exception("Vendor extension value changed")
  2608. for i in range(10):
  2609. res.append(dbus.ByteArray('\xaa\xbb'))
  2610. try:
  2611. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
  2612. dbus_interface=dbus.PROPERTIES_IFACE)
  2613. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  2614. except dbus.exceptions.DBusException, e:
  2615. if "Error.Failed" not in str(e):
  2616. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  2617. vals = dbus.Dictionary({ 'Foo': [ ext ]}, signature='sv')
  2618. try:
  2619. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
  2620. dbus_interface=dbus.PROPERTIES_IFACE)
  2621. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  2622. except dbus.exceptions.DBusException, e:
  2623. if "InvalidArgs" not in str(e):
  2624. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  2625. vals = [ "foo" ]
  2626. try:
  2627. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
  2628. dbus_interface=dbus.PROPERTIES_IFACE)
  2629. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  2630. except dbus.exceptions.DBusException, e:
  2631. if "Error.Failed" not in str(e):
  2632. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  2633. vals = [ [ "foo" ] ]
  2634. try:
  2635. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
  2636. dbus_interface=dbus.PROPERTIES_IFACE)
  2637. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  2638. except dbus.exceptions.DBusException, e:
  2639. if "Error.Failed" not in str(e):
  2640. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  2641. self.waiting_end = True
  2642. p2p.Disconnect()
  2643. def run_test(self, *args):
  2644. logger.debug("run_test")
  2645. params = dbus.Dictionary({'persistent': True,
  2646. 'frequency': 2412})
  2647. logger.info("Add a persistent group")
  2648. p2p.GroupAdd(params)
  2649. return False
  2650. def success(self):
  2651. return self.done
  2652. with TestDbusP2p(bus) as t:
  2653. if not t.success():
  2654. raise Exception("Expected signals not seen")
  2655. dev[1].wait_go_ending_session()
  2656. def test_dbus_p2p_autogo_pbc(dev, apdev):
  2657. """D-Bus P2P autonomous GO and PBC"""
  2658. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2659. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2660. wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
  2661. addr0 = dev[0].p2p_dev_addr()
  2662. class TestDbusP2p(TestDbus):
  2663. def __init__(self, bus):
  2664. TestDbus.__init__(self, bus)
  2665. self.first = True
  2666. self.waiting_end = False
  2667. self.done = False
  2668. def __enter__(self):
  2669. gobject.timeout_add(1, self.run_test)
  2670. gobject.timeout_add(15000, self.timeout)
  2671. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2672. "DeviceFound")
  2673. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2674. "GroupStarted")
  2675. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2676. "GroupFinished")
  2677. self.add_signal(self.provisionDiscoveryPBCRequest,
  2678. WPAS_DBUS_IFACE_P2PDEVICE,
  2679. "ProvisionDiscoveryPBCRequest")
  2680. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  2681. "StaAuthorized")
  2682. self.loop.run()
  2683. return self
  2684. def groupStarted(self, properties):
  2685. logger.debug("groupStarted: " + str(properties))
  2686. self.group = properties['group_object']
  2687. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2688. dev1.global_request("P2P_CONNECT " + addr0 + " pbc join")
  2689. def groupFinished(self, properties):
  2690. logger.debug("groupFinished: " + str(properties))
  2691. self.done = True
  2692. self.loop.quit()
  2693. def deviceFound(self, path):
  2694. logger.debug("deviceFound: path=%s" % path)
  2695. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  2696. self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2697. dbus_interface=dbus.PROPERTIES_IFACE,
  2698. byte_arrays=True)
  2699. logger.debug('peer properties: ' + str(self.peer))
  2700. def provisionDiscoveryPBCRequest(self, peer_object):
  2701. logger.debug("provisionDiscoveryPBCRequest - peer=%s" % peer_object)
  2702. self.peer_path = peer_object
  2703. peer = binascii.unhexlify(peer_object.split('/')[-1])
  2704. addr = ""
  2705. for p in peer:
  2706. if len(addr) > 0:
  2707. addr += ':'
  2708. addr += '%02x' % ord(p)
  2709. params = { 'Role': 'registrar',
  2710. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  2711. 'Bssid': self.peer['DeviceAddress'],
  2712. 'Type': 'pbc' }
  2713. logger.info("Authorize peer to connect to the group")
  2714. wps.Start(params)
  2715. def staAuthorized(self, name):
  2716. logger.debug("staAuthorized: " + name)
  2717. p2p.Disconnect()
  2718. def run_test(self, *args):
  2719. logger.debug("run_test")
  2720. params = dbus.Dictionary({'frequency': 2412})
  2721. p2p.GroupAdd(params)
  2722. return False
  2723. def success(self):
  2724. return self.done
  2725. with TestDbusP2p(bus) as t:
  2726. if not t.success():
  2727. raise Exception("Expected signals not seen")
  2728. dev[1].wait_go_ending_session()
  2729. dev[1].flush_scan_cache()
  2730. def test_dbus_p2p_autogo_legacy(dev, apdev):
  2731. """D-Bus P2P autonomous GO and legacy STA"""
  2732. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2733. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2734. wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
  2735. addr0 = dev[0].p2p_dev_addr()
  2736. class TestDbusP2p(TestDbus):
  2737. def __init__(self, bus):
  2738. TestDbus.__init__(self, bus)
  2739. self.done = False
  2740. def __enter__(self):
  2741. gobject.timeout_add(1, self.run_test)
  2742. gobject.timeout_add(15000, self.timeout)
  2743. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2744. "GroupStarted")
  2745. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2746. "GroupFinished")
  2747. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  2748. "StaAuthorized")
  2749. self.loop.run()
  2750. return self
  2751. def groupStarted(self, properties):
  2752. logger.debug("groupStarted: " + str(properties))
  2753. pin = '12345670'
  2754. params = { 'Role': 'enrollee',
  2755. 'Type': 'pin',
  2756. 'Pin': pin }
  2757. wps.Start(params)
  2758. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2759. dev1.scan_for_bss(addr0, freq=2412)
  2760. dev1.request("WPS_PIN " + addr0 + " " + pin)
  2761. def groupFinished(self, properties):
  2762. logger.debug("groupFinished: " + str(properties))
  2763. self.done = True
  2764. self.loop.quit()
  2765. def staAuthorized(self, name):
  2766. logger.debug("staAuthorized: " + name)
  2767. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2768. dev1.request("DISCONNECT")
  2769. p2p.Disconnect()
  2770. def run_test(self, *args):
  2771. logger.debug("run_test")
  2772. params = dbus.Dictionary({'frequency': 2412})
  2773. p2p.GroupAdd(params)
  2774. return False
  2775. def success(self):
  2776. return self.done
  2777. with TestDbusP2p(bus) as t:
  2778. if not t.success():
  2779. raise Exception("Expected signals not seen")
  2780. def test_dbus_p2p_join(dev, apdev):
  2781. """D-Bus P2P join an autonomous GO"""
  2782. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2783. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2784. addr1 = dev[1].p2p_dev_addr()
  2785. addr2 = dev[2].p2p_dev_addr()
  2786. dev[1].p2p_start_go(freq=2412)
  2787. dev[2].p2p_listen()
  2788. class TestDbusP2p(TestDbus):
  2789. def __init__(self, bus):
  2790. TestDbus.__init__(self, bus)
  2791. self.done = False
  2792. self.peer = None
  2793. self.go = None
  2794. def __enter__(self):
  2795. gobject.timeout_add(1, self.run_test)
  2796. gobject.timeout_add(15000, self.timeout)
  2797. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2798. "DeviceFound")
  2799. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2800. "GroupStarted")
  2801. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2802. "GroupFinished")
  2803. self.add_signal(self.invitationResult, WPAS_DBUS_IFACE_P2PDEVICE,
  2804. "InvitationResult")
  2805. self.loop.run()
  2806. return self
  2807. def deviceFound(self, path):
  2808. logger.debug("deviceFound: path=%s" % path)
  2809. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  2810. res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2811. dbus_interface=dbus.PROPERTIES_IFACE,
  2812. byte_arrays=True)
  2813. logger.debug('peer properties: ' + str(res))
  2814. if addr2.replace(':','') in path:
  2815. self.peer = path
  2816. elif addr1.replace(':','') in path:
  2817. self.go = path
  2818. if self.peer and self.go:
  2819. logger.info("Join the group")
  2820. p2p.StopFind()
  2821. args = { 'peer': self.go,
  2822. 'join': True,
  2823. 'wps_method': 'pin',
  2824. 'frequency': 2412 }
  2825. pin = p2p.Connect(args)
  2826. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2827. dev1.request("WPS_PIN any " + pin)
  2828. def groupStarted(self, properties):
  2829. logger.debug("groupStarted: " + str(properties))
  2830. role = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Role",
  2831. dbus_interface=dbus.PROPERTIES_IFACE)
  2832. if role != "client":
  2833. raise Exception("Unexpected role reported: " + role)
  2834. group = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Group",
  2835. dbus_interface=dbus.PROPERTIES_IFACE)
  2836. if group != properties['group_object']:
  2837. raise Exception("Unexpected Group reported: " + str(group))
  2838. go = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PeerGO",
  2839. dbus_interface=dbus.PROPERTIES_IFACE)
  2840. if go != self.go:
  2841. raise Exception("Unexpected PeerGO value: " + str(go))
  2842. g_obj = bus.get_object(WPAS_DBUS_SERVICE,
  2843. properties['group_object'])
  2844. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  2845. dbus_interface=dbus.PROPERTIES_IFACE,
  2846. byte_arrays=True)
  2847. logger.debug("Group properties: " + str(res))
  2848. ext = dbus.ByteArray("\x11\x22\x33\x44")
  2849. try:
  2850. # Set(WPSVendorExtensions) not allowed for P2P Client
  2851. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
  2852. dbus_interface=dbus.PROPERTIES_IFACE)
  2853. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  2854. except dbus.exceptions.DBusException, e:
  2855. if "Error.Failed: Failed to set property" not in str(e):
  2856. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  2857. args = { 'duration1': 30000, 'interval1': 102400,
  2858. 'duration2': 20000, 'interval2': 102400 }
  2859. p2p.PresenceRequest(args)
  2860. args = { 'peer': self.peer }
  2861. p2p.Invite(args)
  2862. def groupFinished(self, properties):
  2863. logger.debug("groupFinished: " + str(properties))
  2864. self.done = True
  2865. self.loop.quit()
  2866. def invitationResult(self, result):
  2867. logger.debug("invitationResult: " + str(result))
  2868. if result['status'] != 1:
  2869. raise Exception("Unexpected invitation result: " + str(result))
  2870. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2871. dev1.remove_group()
  2872. def run_test(self, *args):
  2873. logger.debug("run_test")
  2874. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  2875. return False
  2876. def success(self):
  2877. return self.done
  2878. with TestDbusP2p(bus) as t:
  2879. if not t.success():
  2880. raise Exception("Expected signals not seen")
  2881. dev[2].p2p_stop_find()
  2882. def test_dbus_p2p_config(dev, apdev):
  2883. """D-Bus Get/Set P2PDeviceConfig"""
  2884. try:
  2885. _test_dbus_p2p_config(dev, apdev)
  2886. finally:
  2887. dev[0].request("P2P_SET ssid_postfix ")
  2888. def _test_dbus_p2p_config(dev, apdev):
  2889. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2890. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2891. res = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  2892. dbus_interface=dbus.PROPERTIES_IFACE,
  2893. byte_arrays=True)
  2894. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig", res,
  2895. dbus_interface=dbus.PROPERTIES_IFACE)
  2896. res2 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  2897. dbus_interface=dbus.PROPERTIES_IFACE,
  2898. byte_arrays=True)
  2899. if len(res) != len(res2):
  2900. raise Exception("Different number of parameters")
  2901. for k in res:
  2902. if res[k] != res2[k]:
  2903. raise Exception("Parameter %s value changes" % k)
  2904. changes = { 'SsidPostfix': 'foo',
  2905. 'VendorExtension': [ dbus.ByteArray('\x11\x22\x33\x44') ],
  2906. 'SecondaryDeviceTypes': [ dbus.ByteArray('\x11\x22\x33\x44\x55\x66\x77\x88') ]}
  2907. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  2908. dbus.Dictionary(changes, signature='sv'),
  2909. dbus_interface=dbus.PROPERTIES_IFACE)
  2910. res2 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  2911. dbus_interface=dbus.PROPERTIES_IFACE,
  2912. byte_arrays=True)
  2913. logger.debug("P2PDeviceConfig: " + str(res2))
  2914. if 'VendorExtension' not in res2 or len(res2['VendorExtension']) != 1:
  2915. raise Exception("VendorExtension does not match")
  2916. if 'SecondaryDeviceTypes' not in res2 or len(res2['SecondaryDeviceTypes']) != 1:
  2917. raise Exception("SecondaryDeviceType does not match")
  2918. changes = { 'SsidPostfix': '',
  2919. 'VendorExtension': dbus.Array([], signature="ay"),
  2920. 'SecondaryDeviceTypes': dbus.Array([], signature="ay") }
  2921. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  2922. dbus.Dictionary(changes, signature='sv'),
  2923. dbus_interface=dbus.PROPERTIES_IFACE)
  2924. res3 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  2925. dbus_interface=dbus.PROPERTIES_IFACE,
  2926. byte_arrays=True)
  2927. logger.debug("P2PDeviceConfig: " + str(res3))
  2928. if 'VendorExtension' in res3:
  2929. raise Exception("VendorExtension not removed")
  2930. if 'SecondaryDeviceTypes' in res3:
  2931. raise Exception("SecondaryDeviceType not removed")
  2932. try:
  2933. dev[0].request("P2P_SET disabled 1")
  2934. if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  2935. dbus_interface=dbus.PROPERTIES_IFACE,
  2936. byte_arrays=True)
  2937. raise Exception("Invalid Get(P2PDeviceConfig) accepted")
  2938. except dbus.exceptions.DBusException, e:
  2939. if "Error.Failed: P2P is not available for this interface" not in str(e):
  2940. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  2941. finally:
  2942. dev[0].request("P2P_SET disabled 0")
  2943. try:
  2944. dev[0].request("P2P_SET disabled 1")
  2945. changes = { 'SsidPostfix': 'foo' }
  2946. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  2947. dbus.Dictionary(changes, signature='sv'),
  2948. dbus_interface=dbus.PROPERTIES_IFACE)
  2949. raise Exception("Invalid Set(P2PDeviceConfig) accepted")
  2950. except dbus.exceptions.DBusException, e:
  2951. if "Error.Failed: P2P is not available for this interface" not in str(e):
  2952. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  2953. finally:
  2954. dev[0].request("P2P_SET disabled 0")
  2955. tests = [ { 'DeviceName': 123 },
  2956. { 'SsidPostfix': 123 },
  2957. { 'Foo': 'Bar' } ]
  2958. for changes in tests:
  2959. try:
  2960. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  2961. dbus.Dictionary(changes, signature='sv'),
  2962. dbus_interface=dbus.PROPERTIES_IFACE)
  2963. raise Exception("Invalid Set(P2PDeviceConfig) accepted")
  2964. except dbus.exceptions.DBusException, e:
  2965. if "InvalidArgs" not in str(e):
  2966. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  2967. def test_dbus_p2p_persistent(dev, apdev):
  2968. """D-Bus P2P persistent group"""
  2969. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2970. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2971. class TestDbusP2p(TestDbus):
  2972. def __init__(self, bus):
  2973. TestDbus.__init__(self, bus)
  2974. def __enter__(self):
  2975. gobject.timeout_add(1, self.run_test)
  2976. gobject.timeout_add(15000, self.timeout)
  2977. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2978. "GroupStarted")
  2979. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2980. "GroupFinished")
  2981. self.add_signal(self.persistentGroupAdded,
  2982. WPAS_DBUS_IFACE_P2PDEVICE,
  2983. "PersistentGroupAdded")
  2984. self.loop.run()
  2985. return self
  2986. def groupStarted(self, properties):
  2987. logger.debug("groupStarted: " + str(properties))
  2988. p2p.Disconnect()
  2989. def groupFinished(self, properties):
  2990. logger.debug("groupFinished: " + str(properties))
  2991. self.loop.quit()
  2992. def persistentGroupAdded(self, path, properties):
  2993. logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
  2994. self.persistent = path
  2995. def run_test(self, *args):
  2996. logger.debug("run_test")
  2997. params = dbus.Dictionary({'persistent': True,
  2998. 'frequency': 2412})
  2999. logger.info("Add a persistent group")
  3000. p2p.GroupAdd(params)
  3001. return False
  3002. def success(self):
  3003. return True
  3004. with TestDbusP2p(bus) as t:
  3005. if not t.success():
  3006. raise Exception("Expected signals not seen")
  3007. persistent = t.persistent
  3008. p_obj = bus.get_object(WPAS_DBUS_SERVICE, persistent)
  3009. res = p_obj.Get(WPAS_DBUS_PERSISTENT_GROUP, "Properties",
  3010. dbus_interface=dbus.PROPERTIES_IFACE, byte_arrays=True)
  3011. logger.info("Persistent group Properties: " + str(res))
  3012. vals = dbus.Dictionary({ 'ssid': 'DIRECT-foo' }, signature='sv')
  3013. p_obj.Set(WPAS_DBUS_PERSISTENT_GROUP, "Properties", vals,
  3014. dbus_interface=dbus.PROPERTIES_IFACE)
  3015. res2 = p_obj.Get(WPAS_DBUS_PERSISTENT_GROUP, "Properties",
  3016. dbus_interface=dbus.PROPERTIES_IFACE)
  3017. if len(res) != len(res2):
  3018. raise Exception("Different number of parameters")
  3019. for k in res:
  3020. if k != 'ssid' and res[k] != res2[k]:
  3021. raise Exception("Parameter %s value changes" % k)
  3022. if res2['ssid'] != '"DIRECT-foo"':
  3023. raise Exception("Unexpected ssid")
  3024. args = dbus.Dictionary({ 'ssid': 'DIRECT-testing',
  3025. 'psk': '1234567890' }, signature='sv')
  3026. group = p2p.AddPersistentGroup(args)
  3027. groups = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PersistentGroups",
  3028. dbus_interface=dbus.PROPERTIES_IFACE)
  3029. if len(groups) != 2:
  3030. raise Exception("Unexpected number of persistent groups: " + str(groups))
  3031. p2p.RemoveAllPersistentGroups()
  3032. groups = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PersistentGroups",
  3033. dbus_interface=dbus.PROPERTIES_IFACE)
  3034. if len(groups) != 0:
  3035. raise Exception("Unexpected number of persistent groups: " + str(groups))
  3036. try:
  3037. p2p.RemovePersistentGroup(persistent)
  3038. raise Exception("Invalid RemovePersistentGroup accepted")
  3039. except dbus.exceptions.DBusException, e:
  3040. if "NetworkUnknown: There is no such persistent group" not in str(e):
  3041. raise Exception("Unexpected error message for invalid RemovePersistentGroup: " + str(e))
  3042. def test_dbus_p2p_reinvoke_persistent(dev, apdev):
  3043. """D-Bus P2P reinvoke persistent group"""
  3044. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3045. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3046. wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
  3047. addr0 = dev[0].p2p_dev_addr()
  3048. class TestDbusP2p(TestDbus):
  3049. def __init__(self, bus):
  3050. TestDbus.__init__(self, bus)
  3051. self.first = True
  3052. self.waiting_end = False
  3053. self.done = False
  3054. self.invited = False
  3055. def __enter__(self):
  3056. gobject.timeout_add(1, self.run_test)
  3057. gobject.timeout_add(15000, self.timeout)
  3058. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3059. "DeviceFound")
  3060. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3061. "GroupStarted")
  3062. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3063. "GroupFinished")
  3064. self.add_signal(self.persistentGroupAdded,
  3065. WPAS_DBUS_IFACE_P2PDEVICE,
  3066. "PersistentGroupAdded")
  3067. self.add_signal(self.provisionDiscoveryRequestDisplayPin,
  3068. WPAS_DBUS_IFACE_P2PDEVICE,
  3069. "ProvisionDiscoveryRequestDisplayPin")
  3070. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  3071. "StaAuthorized")
  3072. self.loop.run()
  3073. return self
  3074. def groupStarted(self, properties):
  3075. logger.debug("groupStarted: " + str(properties))
  3076. if not self.invited:
  3077. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3078. dev1.scan_for_bss(addr0, freq=2412)
  3079. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 join")
  3080. def groupFinished(self, properties):
  3081. logger.debug("groupFinished: " + str(properties))
  3082. if self.invited:
  3083. self.done = True
  3084. self.loop.quit()
  3085. else:
  3086. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3087. dev1.request("SET persistent_reconnect 1")
  3088. dev1.p2p_listen()
  3089. args = { 'persistent_group_object': dbus.ObjectPath(path),
  3090. 'peer': self.peer_path }
  3091. try:
  3092. pin = p2p.Invite(args)
  3093. raise Exception("Invalid Invite accepted")
  3094. except dbus.exceptions.DBusException, e:
  3095. if "InvalidArgs" not in str(e):
  3096. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  3097. args = { 'persistent_group_object': self.persistent,
  3098. 'peer': self.peer_path }
  3099. pin = p2p.Invite(args)
  3100. self.invited = True
  3101. def persistentGroupAdded(self, path, properties):
  3102. logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
  3103. self.persistent = path
  3104. def deviceFound(self, path):
  3105. logger.debug("deviceFound: path=%s" % path)
  3106. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  3107. self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  3108. dbus_interface=dbus.PROPERTIES_IFACE,
  3109. byte_arrays=True)
  3110. def provisionDiscoveryRequestDisplayPin(self, peer_object, pin):
  3111. logger.debug("provisionDiscoveryRequestDisplayPin - peer=%s pin=%s" % (peer_object, pin))
  3112. self.peer_path = peer_object
  3113. peer = binascii.unhexlify(peer_object.split('/')[-1])
  3114. addr = ""
  3115. for p in peer:
  3116. if len(addr) > 0:
  3117. addr += ':'
  3118. addr += '%02x' % ord(p)
  3119. params = { 'Role': 'registrar',
  3120. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  3121. 'Bssid': self.peer['DeviceAddress'],
  3122. 'Type': 'pin',
  3123. 'Pin': '12345670' }
  3124. logger.info("Authorize peer to connect to the group")
  3125. wps.Start(params)
  3126. def staAuthorized(self, name):
  3127. logger.debug("staAuthorized: " + name)
  3128. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3129. dev1.remove_group()
  3130. ev = dev1.wait_event(["P2P-GROUP-REMOVED"], timeout=10)
  3131. if ev is None:
  3132. raise Exception("Group removal timed out")
  3133. p2p.Disconnect()
  3134. def run_test(self, *args):
  3135. logger.debug("run_test")
  3136. params = dbus.Dictionary({'persistent': True,
  3137. 'frequency': 2412})
  3138. logger.info("Add a persistent group")
  3139. p2p.GroupAdd(params)
  3140. return False
  3141. def success(self):
  3142. return self.done
  3143. with TestDbusP2p(bus) as t:
  3144. if not t.success():
  3145. raise Exception("Expected signals not seen")
  3146. def test_dbus_p2p_go_neg_rx(dev, apdev):
  3147. """D-Bus P2P GO Negotiation receive"""
  3148. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3149. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3150. addr0 = dev[0].p2p_dev_addr()
  3151. class TestDbusP2p(TestDbus):
  3152. def __init__(self, bus):
  3153. TestDbus.__init__(self, bus)
  3154. self.done = False
  3155. def __enter__(self):
  3156. gobject.timeout_add(1, self.run_test)
  3157. gobject.timeout_add(15000, self.timeout)
  3158. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3159. "DeviceFound")
  3160. self.add_signal(self.goNegotiationRequest,
  3161. WPAS_DBUS_IFACE_P2PDEVICE,
  3162. "GONegotiationRequest",
  3163. byte_arrays=True)
  3164. self.add_signal(self.goNegotiationSuccess,
  3165. WPAS_DBUS_IFACE_P2PDEVICE,
  3166. "GONegotiationSuccess",
  3167. byte_arrays=True)
  3168. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3169. "GroupStarted")
  3170. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3171. "GroupFinished")
  3172. self.loop.run()
  3173. return self
  3174. def deviceFound(self, path):
  3175. logger.debug("deviceFound: path=%s" % path)
  3176. def goNegotiationRequest(self, path, dev_passwd_id):
  3177. logger.debug("goNegotiationRequest: path=%s dev_passwd_id=%d" % (path, dev_passwd_id))
  3178. if dev_passwd_id != 1:
  3179. raise Exception("Unexpected dev_passwd_id=%d" % dev_passwd_id)
  3180. args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
  3181. 'go_intent': 15, 'persistent': False, 'frequency': 5175 }
  3182. try:
  3183. p2p.Connect(args)
  3184. raise Exception("Invalid Connect accepted")
  3185. except dbus.exceptions.DBusException, e:
  3186. if "ConnectChannelUnsupported" not in str(e):
  3187. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  3188. args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
  3189. 'go_intent': 15, 'persistent': False }
  3190. p2p.Connect(args)
  3191. def goNegotiationSuccess(self, properties):
  3192. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3193. def groupStarted(self, properties):
  3194. logger.debug("groupStarted: " + str(properties))
  3195. p2p.Disconnect()
  3196. def groupFinished(self, properties):
  3197. logger.debug("groupFinished: " + str(properties))
  3198. self.done = True
  3199. self.loop.quit()
  3200. def run_test(self, *args):
  3201. logger.debug("run_test")
  3202. p2p.Listen(10)
  3203. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3204. if not dev1.discover_peer(addr0):
  3205. raise Exception("Peer not found")
  3206. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 enter")
  3207. return False
  3208. def success(self):
  3209. return self.done
  3210. with TestDbusP2p(bus) as t:
  3211. if not t.success():
  3212. raise Exception("Expected signals not seen")
  3213. def test_dbus_p2p_go_neg_auth(dev, apdev):
  3214. """D-Bus P2P GO Negotiation authorized"""
  3215. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3216. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3217. addr0 = dev[0].p2p_dev_addr()
  3218. dev[1].p2p_listen()
  3219. class TestDbusP2p(TestDbus):
  3220. def __init__(self, bus):
  3221. TestDbus.__init__(self, bus)
  3222. self.done = False
  3223. self.peer_joined = False
  3224. self.peer_disconnected = False
  3225. def __enter__(self):
  3226. gobject.timeout_add(1, self.run_test)
  3227. gobject.timeout_add(15000, self.timeout)
  3228. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3229. "DeviceFound")
  3230. self.add_signal(self.goNegotiationSuccess,
  3231. WPAS_DBUS_IFACE_P2PDEVICE,
  3232. "GONegotiationSuccess",
  3233. byte_arrays=True)
  3234. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3235. "GroupStarted")
  3236. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3237. "GroupFinished")
  3238. self.add_signal(self.staDeauthorized, WPAS_DBUS_IFACE,
  3239. "StaDeauthorized")
  3240. self.add_signal(self.peerJoined, WPAS_DBUS_GROUP,
  3241. "PeerJoined")
  3242. self.add_signal(self.peerDisconnected, WPAS_DBUS_GROUP,
  3243. "PeerDisconnected")
  3244. self.loop.run()
  3245. return self
  3246. def deviceFound(self, path):
  3247. logger.debug("deviceFound: path=%s" % path)
  3248. args = { 'peer': path, 'wps_method': 'keypad',
  3249. 'go_intent': 15, 'authorize_only': True }
  3250. try:
  3251. p2p.Connect(args)
  3252. raise Exception("Invalid Connect accepted")
  3253. except dbus.exceptions.DBusException, e:
  3254. if "InvalidArgs" not in str(e):
  3255. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  3256. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  3257. 'go_intent': 15, 'authorize_only': True }
  3258. p2p.Connect(args)
  3259. p2p.Listen(10)
  3260. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3261. if not dev1.discover_peer(addr0):
  3262. raise Exception("Peer not found")
  3263. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=0")
  3264. ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
  3265. if ev is None:
  3266. raise Exception("Group formation timed out")
  3267. def goNegotiationSuccess(self, properties):
  3268. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3269. def groupStarted(self, properties):
  3270. logger.debug("groupStarted: " + str(properties))
  3271. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3272. dev1.remove_group()
  3273. def staDeauthorized(self, name):
  3274. logger.debug("staDeuthorized: " + name)
  3275. p2p.Disconnect()
  3276. def peerJoined(self, peer):
  3277. logger.debug("peerJoined: " + peer)
  3278. self.peer_joined = True
  3279. def peerDisconnected(self, peer):
  3280. logger.debug("peerDisconnected: " + peer)
  3281. self.peer_disconnected = True
  3282. def groupFinished(self, properties):
  3283. logger.debug("groupFinished: " + str(properties))
  3284. self.done = True
  3285. self.loop.quit()
  3286. def run_test(self, *args):
  3287. logger.debug("run_test")
  3288. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  3289. return False
  3290. def success(self):
  3291. return self.done and self.peer_joined and self.peer_disconnected
  3292. with TestDbusP2p(bus) as t:
  3293. if not t.success():
  3294. raise Exception("Expected signals not seen")
  3295. def test_dbus_p2p_go_neg_init(dev, apdev):
  3296. """D-Bus P2P GO Negotiation initiation"""
  3297. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3298. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3299. addr0 = dev[0].p2p_dev_addr()
  3300. dev[1].p2p_listen()
  3301. class TestDbusP2p(TestDbus):
  3302. def __init__(self, bus):
  3303. TestDbus.__init__(self, bus)
  3304. self.done = False
  3305. def __enter__(self):
  3306. gobject.timeout_add(1, self.run_test)
  3307. gobject.timeout_add(15000, self.timeout)
  3308. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3309. "DeviceFound")
  3310. self.add_signal(self.goNegotiationSuccess,
  3311. WPAS_DBUS_IFACE_P2PDEVICE,
  3312. "GONegotiationSuccess",
  3313. byte_arrays=True)
  3314. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3315. "GroupStarted")
  3316. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3317. "GroupFinished")
  3318. self.loop.run()
  3319. return self
  3320. def deviceFound(self, path):
  3321. logger.debug("deviceFound: path=%s" % path)
  3322. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3323. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  3324. 'go_intent': 0 }
  3325. p2p.Connect(args)
  3326. ev = dev1.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
  3327. if ev is None:
  3328. raise Exception("Timeout while waiting for GO Neg Request")
  3329. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=15")
  3330. ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
  3331. if ev is None:
  3332. raise Exception("Group formation timed out")
  3333. def goNegotiationSuccess(self, properties):
  3334. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3335. def groupStarted(self, properties):
  3336. logger.debug("groupStarted: " + str(properties))
  3337. p2p.Disconnect()
  3338. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3339. dev1.remove_group()
  3340. def groupFinished(self, properties):
  3341. logger.debug("groupFinished: " + str(properties))
  3342. self.done = True
  3343. self.loop.quit()
  3344. def run_test(self, *args):
  3345. logger.debug("run_test")
  3346. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  3347. return False
  3348. def success(self):
  3349. return self.done
  3350. with TestDbusP2p(bus) as t:
  3351. if not t.success():
  3352. raise Exception("Expected signals not seen")
  3353. def test_dbus_p2p_wps_failure(dev, apdev):
  3354. """D-Bus P2P WPS failure"""
  3355. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3356. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3357. addr0 = dev[0].p2p_dev_addr()
  3358. class TestDbusP2p(TestDbus):
  3359. def __init__(self, bus):
  3360. TestDbus.__init__(self, bus)
  3361. self.done = False
  3362. def __enter__(self):
  3363. gobject.timeout_add(1, self.run_test)
  3364. gobject.timeout_add(15000, self.timeout)
  3365. self.add_signal(self.goNegotiationRequest,
  3366. WPAS_DBUS_IFACE_P2PDEVICE,
  3367. "GONegotiationRequest",
  3368. byte_arrays=True)
  3369. self.add_signal(self.goNegotiationSuccess,
  3370. WPAS_DBUS_IFACE_P2PDEVICE,
  3371. "GONegotiationSuccess",
  3372. byte_arrays=True)
  3373. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3374. "GroupStarted")
  3375. self.add_signal(self.wpsFailed, WPAS_DBUS_IFACE_P2PDEVICE,
  3376. "WpsFailed")
  3377. self.loop.run()
  3378. return self
  3379. def goNegotiationRequest(self, path, dev_passwd_id):
  3380. logger.debug("goNegotiationRequest: path=%s dev_passwd_id=%d" % (path, dev_passwd_id))
  3381. if dev_passwd_id != 1:
  3382. raise Exception("Unexpected dev_passwd_id=%d" % dev_passwd_id)
  3383. args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
  3384. 'go_intent': 15 }
  3385. p2p.Connect(args)
  3386. def goNegotiationSuccess(self, properties):
  3387. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3388. def groupStarted(self, properties):
  3389. logger.debug("groupStarted: " + str(properties))
  3390. raise Exception("Unexpected GroupStarted")
  3391. def wpsFailed(self, name, args):
  3392. logger.debug("wpsFailed - name=%s args=%s" % (name, str(args)))
  3393. self.done = True
  3394. self.loop.quit()
  3395. def run_test(self, *args):
  3396. logger.debug("run_test")
  3397. p2p.Listen(10)
  3398. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3399. if not dev1.discover_peer(addr0):
  3400. raise Exception("Peer not found")
  3401. dev1.global_request("P2P_CONNECT " + addr0 + " 87654321 enter")
  3402. return False
  3403. def success(self):
  3404. return self.done
  3405. with TestDbusP2p(bus) as t:
  3406. if not t.success():
  3407. raise Exception("Expected signals not seen")
  3408. def test_dbus_p2p_two_groups(dev, apdev):
  3409. """D-Bus P2P with two concurrent groups"""
  3410. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3411. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3412. dev[0].request("SET p2p_no_group_iface 0")
  3413. addr0 = dev[0].p2p_dev_addr()
  3414. addr1 = dev[1].p2p_dev_addr()
  3415. addr2 = dev[2].p2p_dev_addr()
  3416. dev[1].p2p_start_go(freq=2412)
  3417. class TestDbusP2p(TestDbus):
  3418. def __init__(self, bus):
  3419. TestDbus.__init__(self, bus)
  3420. self.done = False
  3421. self.peer = None
  3422. self.go = None
  3423. self.group1 = None
  3424. self.group2 = None
  3425. def __enter__(self):
  3426. gobject.timeout_add(1, self.run_test)
  3427. gobject.timeout_add(15000, self.timeout)
  3428. self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
  3429. "PropertiesChanged", byte_arrays=True)
  3430. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3431. "DeviceFound")
  3432. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3433. "GroupStarted")
  3434. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3435. "GroupFinished")
  3436. self.add_signal(self.peerJoined, WPAS_DBUS_GROUP,
  3437. "PeerJoined")
  3438. self.loop.run()
  3439. return self
  3440. def propertiesChanged(self, interface_name, changed_properties,
  3441. invalidated_properties):
  3442. logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
  3443. def deviceFound(self, path):
  3444. logger.debug("deviceFound: path=%s" % path)
  3445. if addr2.replace(':','') in path:
  3446. self.peer = path
  3447. elif addr1.replace(':','') in path:
  3448. self.go = path
  3449. if self.go and not self.group1:
  3450. logger.info("Join the group")
  3451. p2p.StopFind()
  3452. pin = '12345670'
  3453. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3454. dev1.request("WPS_PIN any " + pin)
  3455. args = { 'peer': self.go,
  3456. 'join': True,
  3457. 'wps_method': 'pin',
  3458. 'pin': pin,
  3459. 'frequency': 2412 }
  3460. p2p.Connect(args)
  3461. def groupStarted(self, properties):
  3462. logger.debug("groupStarted: " + str(properties))
  3463. prop = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
  3464. dbus_interface=dbus.PROPERTIES_IFACE)
  3465. logger.debug("p2pdevice properties: " + str(prop))
  3466. g_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3467. properties['group_object'])
  3468. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  3469. dbus_interface=dbus.PROPERTIES_IFACE,
  3470. byte_arrays=True)
  3471. logger.debug("Group properties: " + str(res))
  3472. if not self.group1:
  3473. self.group1 = properties['group_object']
  3474. self.group1iface = properties['interface_object']
  3475. self.g1_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3476. self.group1iface)
  3477. logger.info("Start autonomous GO")
  3478. params = dbus.Dictionary({ 'frequency': 2412 })
  3479. p2p.GroupAdd(params)
  3480. elif not self.group2:
  3481. self.group2 = properties['group_object']
  3482. self.group2iface = properties['interface_object']
  3483. self.g2_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3484. self.group2iface)
  3485. self.g2_bssid = res['BSSID']
  3486. if self.group1 and self.group2:
  3487. logger.info("Authorize peer to join the group")
  3488. a2 = binascii.unhexlify(addr2.replace(':',''))
  3489. params = { 'Role': 'enrollee',
  3490. 'P2PDeviceAddress': dbus.ByteArray(a2),
  3491. 'Bssid': dbus.ByteArray(a2),
  3492. 'Type': 'pin',
  3493. 'Pin': '12345670' }
  3494. g_wps = dbus.Interface(self.g2_if_obj, WPAS_DBUS_IFACE_WPS)
  3495. g_wps.Start(params)
  3496. bssid = ':'.join([binascii.hexlify(l) for l in self.g2_bssid])
  3497. dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2')
  3498. dev2.scan_for_bss(bssid, freq=2412)
  3499. dev2.global_request("P2P_CONNECT " + bssid + " 12345670 join freq=2412")
  3500. def groupFinished(self, properties):
  3501. logger.debug("groupFinished: " + str(properties))
  3502. if self.group1 == properties['group_object']:
  3503. self.group1 = None
  3504. elif self.group2 == properties['group_object']:
  3505. self.group2 = None
  3506. if not self.group1 and not self.group2:
  3507. self.done = True
  3508. self.loop.quit()
  3509. def peerJoined(self, peer):
  3510. logger.debug("peerJoined: " + peer)
  3511. self.check_results()
  3512. dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2')
  3513. dev2.remove_group()
  3514. logger.info("Disconnect group2")
  3515. group_p2p = dbus.Interface(self.g2_if_obj,
  3516. WPAS_DBUS_IFACE_P2PDEVICE)
  3517. group_p2p.Disconnect()
  3518. logger.info("Disconnect group1")
  3519. group_p2p = dbus.Interface(self.g1_if_obj,
  3520. WPAS_DBUS_IFACE_P2PDEVICE)
  3521. group_p2p.Disconnect()
  3522. def check_results(self):
  3523. logger.info("Check results with two concurrent groups in operation")
  3524. g1_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group1)
  3525. res1 = g1_obj.GetAll(WPAS_DBUS_GROUP,
  3526. dbus_interface=dbus.PROPERTIES_IFACE,
  3527. byte_arrays=True)
  3528. g2_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group2)
  3529. res2 = g2_obj.GetAll(WPAS_DBUS_GROUP,
  3530. dbus_interface=dbus.PROPERTIES_IFACE,
  3531. byte_arrays=True)
  3532. logger.info("group1 = " + self.group1)
  3533. logger.debug("Group properties: " + str(res1))
  3534. logger.info("group2 = " + self.group2)
  3535. logger.debug("Group properties: " + str(res2))
  3536. prop = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
  3537. dbus_interface=dbus.PROPERTIES_IFACE)
  3538. logger.debug("p2pdevice properties: " + str(prop))
  3539. if res1['Role'] != 'client':
  3540. raise Exception("Group1 role reported incorrectly: " + res1['Role'])
  3541. if res2['Role'] != 'GO':
  3542. raise Exception("Group2 role reported incorrectly: " + res2['Role'])
  3543. if prop['Role'] != 'device':
  3544. raise Exception("p2pdevice role reported incorrectly: " + prop['Role'])
  3545. if len(res2['Members']) != 1:
  3546. raise Exception("Unexpected Members value for group 2")
  3547. def run_test(self, *args):
  3548. logger.debug("run_test")
  3549. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  3550. return False
  3551. def success(self):
  3552. return self.done
  3553. with TestDbusP2p(bus) as t:
  3554. if not t.success():
  3555. raise Exception("Expected signals not seen")
  3556. dev[1].remove_group()
  3557. def test_dbus_introspect(dev, apdev):
  3558. """D-Bus introspection"""
  3559. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3560. res = if_obj.Introspect(WPAS_DBUS_IFACE,
  3561. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  3562. logger.info("Initial Introspect: " + str(res))
  3563. if res is None or "Introspectable" not in res or "GroupStarted" not in res:
  3564. raise Exception("Unexpected initial Introspect response: " + str(res))
  3565. with alloc_fail(dev[0], 1, "wpa_dbus_introspect"):
  3566. res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
  3567. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  3568. logger.info("Introspect: " + str(res2))
  3569. if res2 is not None:
  3570. raise Exception("Unexpected Introspect response")
  3571. with alloc_fail(dev[0], 1, "=add_interface;wpa_dbus_introspect"):
  3572. res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
  3573. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  3574. logger.info("Introspect: " + str(res2))
  3575. if res2 is None:
  3576. raise Exception("No Introspect response")
  3577. if len(res2) >= len(res):
  3578. raise Exception("Unexpected Introspect response")
  3579. with alloc_fail(dev[0], 1, "wpabuf_alloc;add_interface;wpa_dbus_introspect"):
  3580. res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
  3581. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  3582. logger.info("Introspect: " + str(res2))
  3583. if res2 is None:
  3584. raise Exception("No Introspect response")
  3585. if len(res2) >= len(res):
  3586. raise Exception("Unexpected Introspect response")
  3587. with alloc_fail(dev[0], 2, "=add_interface;wpa_dbus_introspect"):
  3588. res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
  3589. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  3590. logger.info("Introspect: " + str(res2))
  3591. if res2 is None:
  3592. raise Exception("No Introspect response")
  3593. if len(res2) >= len(res):
  3594. raise Exception("Unexpected Introspect response")