test_dbus.py 174 KB

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