test_dbus.py 207 KB

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