test_dbus.py 186 KB

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