test_dbus.py 202 KB

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