test_dbus.py 182 KB

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