test_dbus.py 184 KB

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