12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216 |
- # wpa_supplicant D-Bus interface tests
- # Copyright (c) 2014-2015, Jouni Malinen <j@w1.fi>
- #
- # This software may be distributed under the terms of the BSD license.
- # See README for more details.
- import binascii
- import logging
- logger = logging.getLogger()
- import subprocess
- import time
- try:
- import gobject
- import dbus
- dbus_imported = True
- except ImportError:
- dbus_imported = False
- import hostapd
- from wpasupplicant import WpaSupplicant
- from utils import HwsimSkip, alloc_fail, fail_test
- from p2p_utils import *
- from test_ap_tdls import connect_2sta_open
- from test_ap_eap import check_altsubject_match_support
- WPAS_DBUS_SERVICE = "fi.w1.wpa_supplicant1"
- WPAS_DBUS_PATH = "/fi/w1/wpa_supplicant1"
- WPAS_DBUS_IFACE = "fi.w1.wpa_supplicant1.Interface"
- WPAS_DBUS_IFACE_WPS = WPAS_DBUS_IFACE + ".WPS"
- WPAS_DBUS_NETWORK = "fi.w1.wpa_supplicant1.Network"
- WPAS_DBUS_BSS = "fi.w1.wpa_supplicant1.BSS"
- WPAS_DBUS_IFACE_P2PDEVICE = WPAS_DBUS_IFACE + ".P2PDevice"
- WPAS_DBUS_P2P_PEER = "fi.w1.wpa_supplicant1.Peer"
- WPAS_DBUS_GROUP = "fi.w1.wpa_supplicant1.Group"
- WPAS_DBUS_PERSISTENT_GROUP = "fi.w1.wpa_supplicant1.PersistentGroup"
- def prepare_dbus(dev):
- if not dbus_imported:
- logger.info("No dbus module available")
- raise HwsimSkip("No dbus module available")
- try:
- from dbus.mainloop.glib import DBusGMainLoop
- dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
- bus = dbus.SystemBus()
- wpas_obj = bus.get_object(WPAS_DBUS_SERVICE, WPAS_DBUS_PATH)
- wpas = dbus.Interface(wpas_obj, WPAS_DBUS_SERVICE)
- path = wpas.GetInterface(dev.ifname)
- if_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
- return (bus,wpas_obj,path,if_obj)
- except Exception, e:
- raise HwsimSkip("Could not connect to D-Bus: %s" % e)
- class TestDbus(object):
- def __init__(self, bus):
- self.loop = gobject.MainLoop()
- self.signals = []
- self.bus = bus
- def __exit__(self, type, value, traceback):
- for s in self.signals:
- s.remove()
- def add_signal(self, handler, interface, name, byte_arrays=False):
- s = self.bus.add_signal_receiver(handler, dbus_interface=interface,
- signal_name=name,
- byte_arrays=byte_arrays)
- self.signals.append(s)
- def timeout(self, *args):
- logger.debug("timeout")
- self.loop.quit()
- return False
- class alloc_fail_dbus(object):
- def __init__(self, dev, count, funcs, operation="Operation",
- expected="NoMemory"):
- self._dev = dev
- self._count = count
- self._funcs = funcs
- self._operation = operation
- self._expected = expected
- def __enter__(self):
- cmd = "TEST_ALLOC_FAIL %d:%s" % (self._count, self._funcs)
- if "OK" not in self._dev.request(cmd):
- raise HwsimSkip("TEST_ALLOC_FAIL not supported")
- def __exit__(self, type, value, traceback):
- if type is None:
- raise Exception("%s succeeded during out-of-memory" % self._operation)
- if type == dbus.exceptions.DBusException and self._expected in str(value):
- return True
- if self._dev.request("GET_ALLOC_FAIL") != "0:%s" % self._funcs:
- raise Exception("%s did not trigger allocation failure" % self._operation)
- return False
- def start_ap(ap, ssid="test-wps",
- ap_uuid="27ea801a-9e5c-4e73-bd82-f89cbcd10d7e"):
- params = { "ssid": ssid, "eap_server": "1", "wps_state": "2",
- "wpa_passphrase": "12345678", "wpa": "2",
- "wpa_key_mgmt": "WPA-PSK", "rsn_pairwise": "CCMP",
- "ap_pin": "12345670", "uuid": ap_uuid}
- return hostapd.add_ap(ap['ifname'], params)
- def test_dbus_getall(dev, apdev):
- """D-Bus GetAll"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- props = wpas_obj.GetAll(WPAS_DBUS_SERVICE,
- dbus_interface=dbus.PROPERTIES_IFACE)
- logger.debug("GetAll(fi.w1.wpa.supplicant1, /fi/w1/wpa_supplicant1) ==> " + str(props))
- props = if_obj.GetAll(WPAS_DBUS_IFACE,
- dbus_interface=dbus.PROPERTIES_IFACE)
- logger.debug("GetAll(%s, %s): %s" % (WPAS_DBUS_IFACE, path, str(props)))
- props = if_obj.GetAll(WPAS_DBUS_IFACE_WPS,
- dbus_interface=dbus.PROPERTIES_IFACE)
- logger.debug("GetAll(%s, %s): %s" % (WPAS_DBUS_IFACE_WPS, path, str(props)))
- res = if_obj.Get(WPAS_DBUS_IFACE, 'BSSs',
- dbus_interface=dbus.PROPERTIES_IFACE)
- if len(res) != 0:
- raise Exception("Unexpected BSSs entry: " + str(res))
- res = if_obj.Get(WPAS_DBUS_IFACE, 'Networks',
- dbus_interface=dbus.PROPERTIES_IFACE)
- if len(res) != 0:
- raise Exception("Unexpected Networks entry: " + str(res))
- hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "open" })
- bssid = apdev[0]['bssid']
- dev[0].scan_for_bss(bssid, freq=2412)
- id = dev[0].add_network()
- dev[0].set_network(id, "disabled", "0")
- dev[0].set_network_quoted(id, "ssid", "test")
- res = if_obj.Get(WPAS_DBUS_IFACE, 'BSSs',
- dbus_interface=dbus.PROPERTIES_IFACE)
- if len(res) != 1:
- raise Exception("Missing BSSs entry: " + str(res))
- bss_obj = bus.get_object(WPAS_DBUS_SERVICE, res[0])
- props = bss_obj.GetAll(WPAS_DBUS_BSS, dbus_interface=dbus.PROPERTIES_IFACE)
- logger.debug("GetAll(%s, %s): %s" % (WPAS_DBUS_BSS, res[0], str(props)))
- bssid_str = ''
- for item in props['BSSID']:
- if len(bssid_str) > 0:
- bssid_str += ':'
- bssid_str += '%02x' % item
- if bssid_str != bssid:
- raise Exception("Unexpected BSSID in BSSs entry")
- res = if_obj.Get(WPAS_DBUS_IFACE, 'Networks',
- dbus_interface=dbus.PROPERTIES_IFACE)
- if len(res) != 1:
- raise Exception("Missing Networks entry: " + str(res))
- net_obj = bus.get_object(WPAS_DBUS_SERVICE, res[0])
- props = net_obj.GetAll(WPAS_DBUS_NETWORK,
- dbus_interface=dbus.PROPERTIES_IFACE)
- logger.debug("GetAll(%s, %s): %s" % (WPAS_DBUS_NETWORK, res[0], str(props)))
- ssid = props['Properties']['ssid']
- if ssid != '"test"':
- raise Exception("Unexpected SSID in network entry")
- def dbus_get(dbus, wpas_obj, prop, expect=None, byte_arrays=False):
- val = wpas_obj.Get(WPAS_DBUS_SERVICE, prop,
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=byte_arrays)
- if expect is not None and val != expect:
- raise Exception("Unexpected %s: %s (expected: %s)" %
- (prop, str(val), str(expect)))
- return val
- def dbus_set(dbus, wpas_obj, prop, val):
- wpas_obj.Set(WPAS_DBUS_SERVICE, prop, val,
- dbus_interface=dbus.PROPERTIES_IFACE)
- def test_dbus_properties(dev, apdev):
- """D-Bus Get/Set fi.w1.wpa_supplicant1 properties"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- dbus_get(dbus, wpas_obj, "DebugLevel", expect="msgdump")
- dbus_set(dbus, wpas_obj, "DebugLevel", "debug")
- dbus_get(dbus, wpas_obj, "DebugLevel", expect="debug")
- for (val,err) in [ (3, "Error.Failed: wrong property type"),
- ("foo", "Error.Failed: wrong debug level value") ]:
- try:
- dbus_set(dbus, wpas_obj, "DebugLevel", val)
- raise Exception("Invalid DebugLevel value accepted: " + str(val))
- except dbus.exceptions.DBusException, e:
- if err not in str(e):
- raise Exception("Unexpected error message: " + str(e))
- dbus_set(dbus, wpas_obj, "DebugLevel", "msgdump")
- dbus_get(dbus, wpas_obj, "DebugLevel", expect="msgdump")
- dbus_get(dbus, wpas_obj, "DebugTimestamp", expect=True)
- dbus_set(dbus, wpas_obj, "DebugTimestamp", False)
- dbus_get(dbus, wpas_obj, "DebugTimestamp", expect=False)
- try:
- dbus_set(dbus, wpas_obj, "DebugTimestamp", "foo")
- raise Exception("Invalid DebugTimestamp value accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: wrong property type" not in str(e):
- raise Exception("Unexpected error message: " + str(e))
- dbus_set(dbus, wpas_obj, "DebugTimestamp", True)
- dbus_get(dbus, wpas_obj, "DebugTimestamp", expect=True)
- dbus_get(dbus, wpas_obj, "DebugShowKeys", expect=True)
- dbus_set(dbus, wpas_obj, "DebugShowKeys", False)
- dbus_get(dbus, wpas_obj, "DebugShowKeys", expect=False)
- try:
- dbus_set(dbus, wpas_obj, "DebugShowKeys", "foo")
- raise Exception("Invalid DebugShowKeys value accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: wrong property type" not in str(e):
- raise Exception("Unexpected error message: " + str(e))
- dbus_set(dbus, wpas_obj, "DebugShowKeys", True)
- dbus_get(dbus, wpas_obj, "DebugShowKeys", expect=True)
- res = dbus_get(dbus, wpas_obj, "Interfaces")
- if len(res) != 1:
- raise Exception("Unexpected Interfaces value: " + str(res))
- res = dbus_get(dbus, wpas_obj, "EapMethods")
- if len(res) < 5 or "TTLS" not in res:
- raise Exception("Unexpected EapMethods value: " + str(res))
- res = dbus_get(dbus, wpas_obj, "Capabilities")
- if len(res) < 2 or "p2p" not in res:
- raise Exception("Unexpected Capabilities value: " + str(res))
- dbus_get(dbus, wpas_obj, "WFDIEs", byte_arrays=True)
- val = binascii.unhexlify("010006020304050608")
- dbus_set(dbus, wpas_obj, "WFDIEs", dbus.ByteArray(val))
- res = dbus_get(dbus, wpas_obj, "WFDIEs", byte_arrays=True)
- if val != res:
- raise Exception("WFDIEs value changed")
- try:
- dbus_set(dbus, wpas_obj, "WFDIEs", dbus.ByteArray('\x00'))
- raise Exception("Invalid WFDIEs value accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message: " + str(e))
- dbus_set(dbus, wpas_obj, "WFDIEs", dbus.ByteArray(''))
- dbus_set(dbus, wpas_obj, "WFDIEs", dbus.ByteArray(val))
- dbus_set(dbus, wpas_obj, "WFDIEs", dbus.ByteArray(''))
- res = dbus_get(dbus, wpas_obj, "WFDIEs", byte_arrays=True)
- if len(res) != 0:
- raise Exception("WFDIEs not cleared properly")
- res = dbus_get(dbus, wpas_obj, "EapMethods")
- try:
- dbus_set(dbus, wpas_obj, "EapMethods", res)
- raise Exception("Invalid Set accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs: Property is read-only" not in str(e):
- raise Exception("Unexpected error message: " + str(e))
- try:
- wpas_obj.SetFoo(WPAS_DBUS_SERVICE, "DebugShowKeys", True,
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Unknown method accepted")
- except dbus.exceptions.DBusException, e:
- if "UnknownMethod" not in str(e):
- raise Exception("Unexpected error message: " + str(e))
- try:
- wpas_obj.Get("foo", "DebugShowKeys",
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Get accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs: No such property" not in str(e):
- raise Exception("Unexpected error message: " + str(e))
- test_obj = bus.get_object(WPAS_DBUS_SERVICE, WPAS_DBUS_PATH,
- introspect=False)
- try:
- test_obj.Get(123, "DebugShowKeys",
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Get accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs: Invalid arguments" not in str(e):
- raise Exception("Unexpected error message: " + str(e))
- try:
- test_obj.Get(WPAS_DBUS_SERVICE, 123,
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Get accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs: Invalid arguments" not in str(e):
- raise Exception("Unexpected error message: " + str(e))
- try:
- wpas_obj.Set(WPAS_DBUS_SERVICE, "WFDIEs",
- dbus.ByteArray('', variant_level=2),
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Set accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs: invalid message format" not in str(e):
- raise Exception("Unexpected error message: " + str(e))
- def test_dbus_set_global_properties(dev, apdev):
- """D-Bus Get/Set fi.w1.wpa_supplicant1 interface global properties"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- props = [ ('Okc', '0', '1'), ('ModelName', '', 'blahblahblah') ]
- for p in props:
- res = if_obj.Get(WPAS_DBUS_IFACE, p[0],
- dbus_interface=dbus.PROPERTIES_IFACE)
- if res != p[1]:
- raise Exception("Unexpected " + p[0] + " value: " + str(res))
- if_obj.Set(WPAS_DBUS_IFACE, p[0], p[2],
- dbus_interface=dbus.PROPERTIES_IFACE)
- res = if_obj.Get(WPAS_DBUS_IFACE, p[0],
- dbus_interface=dbus.PROPERTIES_IFACE)
- if res != p[2]:
- raise Exception("Unexpected " + p[0] + " value after set: " + str(res))
- def test_dbus_invalid_method(dev, apdev):
- """D-Bus invalid method"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
- try:
- wps.Foo()
- raise Exception("Unknown method accepted")
- except dbus.exceptions.DBusException, e:
- if "UnknownMethod" not in str(e):
- raise Exception("Unexpected error message: " + str(e))
- test_obj = bus.get_object(WPAS_DBUS_SERVICE, path, introspect=False)
- test_wps = dbus.Interface(test_obj, WPAS_DBUS_IFACE_WPS)
- try:
- test_wps.Start(123)
- raise Exception("WPS.Start with incorrect signature accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs: Invalid arg" not in str(e):
- raise Exception("Unexpected error message: " + str(e))
- def test_dbus_get_set_wps(dev, apdev):
- """D-Bus Get/Set for WPS properties"""
- try:
- _test_dbus_get_set_wps(dev, apdev)
- finally:
- dev[0].request("SET wps_cred_processing 0")
- dev[0].request("SET config_methods display keypad virtual_display nfc_interface p2ps")
- def _test_dbus_get_set_wps(dev, apdev):
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- if_obj.Get(WPAS_DBUS_IFACE_WPS, "ConfigMethods",
- dbus_interface=dbus.PROPERTIES_IFACE)
- val = "display keypad virtual_display nfc_interface"
- dev[0].request("SET config_methods " + val)
- config = if_obj.Get(WPAS_DBUS_IFACE_WPS, "ConfigMethods",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if config != val:
- raise Exception("Unexpected Get(ConfigMethods) result: " + config)
- val2 = "push_button display"
- if_obj.Set(WPAS_DBUS_IFACE_WPS, "ConfigMethods", val2,
- dbus_interface=dbus.PROPERTIES_IFACE)
- config = if_obj.Get(WPAS_DBUS_IFACE_WPS, "ConfigMethods",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if config != val2:
- raise Exception("Unexpected Get(ConfigMethods) result after Set: " + config)
- dev[0].request("SET config_methods " + val)
- for i in range(3):
- dev[0].request("SET wps_cred_processing " + str(i))
- val = if_obj.Get(WPAS_DBUS_IFACE_WPS, "ProcessCredentials",
- dbus_interface=dbus.PROPERTIES_IFACE)
- expected_val = False if i == 1 else True
- if val != expected_val:
- raise Exception("Unexpected Get(ProcessCredentials) result({}): {}".format(i, val))
- class TestDbusGetSet(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.signal_received = False
- self.signal_received_deprecated = False
- self.sets_done = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_sets)
- gobject.timeout_add(1000, self.timeout)
- self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE_WPS,
- "PropertiesChanged")
- self.add_signal(self.propertiesChanged2, dbus.PROPERTIES_IFACE,
- "PropertiesChanged")
- self.loop.run()
- return self
- def propertiesChanged(self, properties):
- logger.debug("PropertiesChanged: " + str(properties))
- if properties.has_key("ProcessCredentials"):
- self.signal_received_deprecated = True
- if self.sets_done and self.signal_received:
- self.loop.quit()
- def propertiesChanged2(self, interface_name, changed_properties,
- invalidated_properties):
- logger.debug("propertiesChanged2: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
- if interface_name != WPAS_DBUS_IFACE_WPS:
- return
- if changed_properties.has_key("ProcessCredentials"):
- self.signal_received = True
- if self.sets_done and self.signal_received_deprecated:
- self.loop.quit()
- def run_sets(self, *args):
- logger.debug("run_sets")
- if_obj.Set(WPAS_DBUS_IFACE_WPS, "ProcessCredentials",
- dbus.Boolean(1),
- dbus_interface=dbus.PROPERTIES_IFACE)
- if if_obj.Get(WPAS_DBUS_IFACE_WPS, "ProcessCredentials",
- dbus_interface=dbus.PROPERTIES_IFACE) != True:
- raise Exception("Unexpected Get(ProcessCredentials) result after Set");
- if_obj.Set(WPAS_DBUS_IFACE_WPS, "ProcessCredentials",
- dbus.Boolean(0),
- dbus_interface=dbus.PROPERTIES_IFACE)
- if if_obj.Get(WPAS_DBUS_IFACE_WPS, "ProcessCredentials",
- dbus_interface=dbus.PROPERTIES_IFACE) != False:
- raise Exception("Unexpected Get(ProcessCredentials) result after Set");
- self.dbus_sets_done = True
- return False
- def success(self):
- return self.signal_received and self.signal_received_deprecated
- with TestDbusGetSet(bus) as t:
- if not t.success():
- raise Exception("No signal received for ProcessCredentials change")
- def test_dbus_wps_invalid(dev, apdev):
- """D-Bus invaldi WPS operation"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
- failures = [ {'Role': 'foo', 'Type': 'pbc'},
- {'Role': 123, 'Type': 'pbc'},
- {'Type': 'pbc'},
- {'Role': 'enrollee'},
- {'Role': 'registrar'},
- {'Role': 'enrollee', 'Type': 123},
- {'Role': 'enrollee', 'Type': 'foo'},
- {'Role': 'enrollee', 'Type': 'pbc',
- 'Bssid': '02:33:44:55:66:77'},
- {'Role': 'enrollee', 'Type': 'pin', 'Pin': 123},
- {'Role': 'enrollee', 'Type': 'pbc',
- 'Bssid': dbus.ByteArray('12345')},
- {'Role': 'enrollee', 'Type': 'pbc',
- 'P2PDeviceAddress': 12345},
- {'Role': 'enrollee', 'Type': 'pbc',
- 'P2PDeviceAddress': dbus.ByteArray('12345')},
- {'Role': 'enrollee', 'Type': 'pbc', 'Foo': 'bar'} ]
- for args in failures:
- try:
- wps.Start(args)
- raise Exception("Invalid WPS.Start() arguments accepted: " + str(args))
- except dbus.exceptions.DBusException, e:
- if not str(e).startswith("fi.w1.wpa_supplicant1.InvalidArgs"):
- raise Exception("Unexpected error message: " + str(e))
- def test_dbus_wps_oom(dev, apdev):
- """D-Bus WPS operation (OOM)"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
- with alloc_fail_dbus(dev[0], 1, "=wpas_dbus_getter_state", "Get"):
- if_obj.Get(WPAS_DBUS_IFACE, "State",
- dbus_interface=dbus.PROPERTIES_IFACE)
- hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "open" })
- bssid = apdev[0]['bssid']
- dev[0].scan_for_bss(bssid, freq=2412)
- time.sleep(0.05)
- for i in range(1, 3):
- with alloc_fail_dbus(dev[0], i, "=wpas_dbus_getter_bsss", "Get"):
- if_obj.Get(WPAS_DBUS_IFACE, "BSSs",
- dbus_interface=dbus.PROPERTIES_IFACE)
- res = if_obj.Get(WPAS_DBUS_IFACE, 'BSSs',
- dbus_interface=dbus.PROPERTIES_IFACE)
- bss_obj = bus.get_object(WPAS_DBUS_SERVICE, res[0])
- with alloc_fail_dbus(dev[0], 1, "=wpas_dbus_getter_bss_rates", "Get"):
- bss_obj.Get(WPAS_DBUS_BSS, "Rates",
- dbus_interface=dbus.PROPERTIES_IFACE)
- id = dev[0].add_network()
- dev[0].set_network(id, "disabled", "0")
- dev[0].set_network_quoted(id, "ssid", "test")
- for i in range(1, 3):
- with alloc_fail_dbus(dev[0], i, "=wpas_dbus_getter_networks", "Get"):
- if_obj.Get(WPAS_DBUS_IFACE, "Networks",
- dbus_interface=dbus.PROPERTIES_IFACE)
- with alloc_fail_dbus(dev[0], 1, "wpas_dbus_getter_interfaces", "Get"):
- dbus_get(dbus, wpas_obj, "Interfaces")
- for i in range(1, 6):
- with alloc_fail_dbus(dev[0], i, "=eap_get_names_as_string_array;wpas_dbus_getter_eap_methods", "Get"):
- dbus_get(dbus, wpas_obj, "EapMethods")
- with alloc_fail_dbus(dev[0], 1, "wpas_dbus_setter_config_methods", "Set",
- expected="Error.Failed: Failed to set property"):
- val2 = "push_button display"
- if_obj.Set(WPAS_DBUS_IFACE_WPS, "ConfigMethods", val2,
- dbus_interface=dbus.PROPERTIES_IFACE)
- with alloc_fail_dbus(dev[0], 1, "=wpa_config_add_network;wpas_dbus_handler_wps_start",
- "WPS.Start",
- expected="UnknownError: WPS start failed"):
- wps.Start({'Role': 'enrollee', 'Type': 'pin', 'Pin': '12345670'})
- def test_dbus_wps_pbc(dev, apdev):
- """D-Bus WPS/PBC operation and signals"""
- try:
- _test_dbus_wps_pbc(dev, apdev)
- finally:
- dev[0].request("SET wps_cred_processing 0")
- def _test_dbus_wps_pbc(dev, apdev):
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
- hapd = start_ap(apdev[0])
- hapd.request("WPS_PBC")
- bssid = apdev[0]['bssid']
- dev[0].scan_for_bss(bssid, freq="2412")
- dev[0].request("SET wps_cred_processing 2")
- res = if_obj.Get(WPAS_DBUS_IFACE, 'BSSs',
- dbus_interface=dbus.PROPERTIES_IFACE)
- if len(res) != 1:
- raise Exception("Missing BSSs entry: " + str(res))
- bss_obj = bus.get_object(WPAS_DBUS_SERVICE, res[0])
- props = bss_obj.GetAll(WPAS_DBUS_BSS, dbus_interface=dbus.PROPERTIES_IFACE)
- logger.debug("GetAll(%s, %s): %s" % (WPAS_DBUS_BSS, res[0], str(props)))
- if 'WPS' not in props:
- raise Exception("No WPS information in the BSS entry")
- if 'Type' not in props['WPS']:
- raise Exception("No Type field in the WPS dictionary")
- if props['WPS']['Type'] != 'pbc':
- raise Exception("Unexpected WPS Type: " + props['WPS']['Type'])
- class TestDbusWps(TestDbus):
- def __init__(self, bus, wps):
- TestDbus.__init__(self, bus)
- self.success_seen = False
- self.credentials_received = False
- self.wps = wps
- def __enter__(self):
- gobject.timeout_add(1, self.start_pbc)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.wpsEvent, WPAS_DBUS_IFACE_WPS, "Event")
- self.add_signal(self.credentials, WPAS_DBUS_IFACE_WPS,
- "Credentials")
- self.loop.run()
- return self
- def wpsEvent(self, name, args):
- logger.debug("wpsEvent: %s args='%s'" % (name, str(args)))
- if name == "success":
- self.success_seen = True
- if self.credentials_received:
- self.loop.quit()
- def credentials(self, args):
- logger.debug("credentials: " + str(args))
- self.credentials_received = True
- if self.success_seen:
- self.loop.quit()
- def start_pbc(self, *args):
- logger.debug("start_pbc")
- self.wps.Start({'Role': 'enrollee', 'Type': 'pbc'})
- return False
- def success(self):
- return self.success_seen and self.credentials_received
- with TestDbusWps(bus, wps) as t:
- if not t.success():
- raise Exception("Failure in D-Bus operations")
- dev[0].wait_connected(timeout=10)
- dev[0].request("DISCONNECT")
- hapd.disable()
- dev[0].flush_scan_cache()
- def test_dbus_wps_pbc_overlap(dev, apdev):
- """D-Bus WPS/PBC operation and signal for PBC overlap"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
- hapd = start_ap(apdev[0])
- hapd2 = start_ap(apdev[1], ssid="test-wps2",
- ap_uuid="27ea801a-9e5c-4e73-bd82-f89cbcd10d7f")
- hapd.request("WPS_PBC")
- hapd2.request("WPS_PBC")
- bssid = apdev[0]['bssid']
- dev[0].scan_for_bss(bssid, freq="2412")
- bssid2 = apdev[1]['bssid']
- dev[0].scan_for_bss(bssid2, freq="2412")
- class TestDbusWps(TestDbus):
- def __init__(self, bus, wps):
- TestDbus.__init__(self, bus)
- self.overlap_seen = False
- self.wps = wps
- def __enter__(self):
- gobject.timeout_add(1, self.start_pbc)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.wpsEvent, WPAS_DBUS_IFACE_WPS, "Event")
- self.loop.run()
- return self
- def wpsEvent(self, name, args):
- logger.debug("wpsEvent: %s args='%s'" % (name, str(args)))
- if name == "pbc-overlap":
- self.overlap_seen = True
- self.loop.quit()
- def start_pbc(self, *args):
- logger.debug("start_pbc")
- self.wps.Start({'Role': 'enrollee', 'Type': 'pbc'})
- return False
- def success(self):
- return self.overlap_seen
- with TestDbusWps(bus, wps) as t:
- if not t.success():
- raise Exception("Failure in D-Bus operations")
- dev[0].request("WPS_CANCEL")
- dev[0].request("DISCONNECT")
- hapd.disable()
- dev[0].flush_scan_cache()
- def test_dbus_wps_pin(dev, apdev):
- """D-Bus WPS/PIN operation and signals"""
- try:
- _test_dbus_wps_pin(dev, apdev)
- finally:
- dev[0].request("SET wps_cred_processing 0")
- def _test_dbus_wps_pin(dev, apdev):
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
- hapd = start_ap(apdev[0])
- hapd.request("WPS_PIN any 12345670")
- bssid = apdev[0]['bssid']
- dev[0].scan_for_bss(bssid, freq="2412")
- dev[0].request("SET wps_cred_processing 2")
- class TestDbusWps(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.success_seen = False
- self.credentials_received = False
- def __enter__(self):
- gobject.timeout_add(1, self.start_pin)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.wpsEvent, WPAS_DBUS_IFACE_WPS, "Event")
- self.add_signal(self.credentials, WPAS_DBUS_IFACE_WPS,
- "Credentials")
- self.loop.run()
- return self
- def wpsEvent(self, name, args):
- logger.debug("wpsEvent: %s args='%s'" % (name, str(args)))
- if name == "success":
- self.success_seen = True
- if self.credentials_received:
- self.loop.quit()
- def credentials(self, args):
- logger.debug("credentials: " + str(args))
- self.credentials_received = True
- if self.success_seen:
- self.loop.quit()
- def start_pin(self, *args):
- logger.debug("start_pin")
- bssid_ay = dbus.ByteArray(bssid.replace(':','').decode('hex'))
- wps.Start({'Role': 'enrollee', 'Type': 'pin', 'Pin': '12345670',
- 'Bssid': bssid_ay})
- return False
- def success(self):
- return self.success_seen and self.credentials_received
- with TestDbusWps(bus) as t:
- if not t.success():
- raise Exception("Failure in D-Bus operations")
- dev[0].wait_connected(timeout=10)
- def test_dbus_wps_pin2(dev, apdev):
- """D-Bus WPS/PIN operation and signals (PIN from wpa_supplicant)"""
- try:
- _test_dbus_wps_pin2(dev, apdev)
- finally:
- dev[0].request("SET wps_cred_processing 0")
- def _test_dbus_wps_pin2(dev, apdev):
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
- hapd = start_ap(apdev[0])
- bssid = apdev[0]['bssid']
- dev[0].scan_for_bss(bssid, freq="2412")
- dev[0].request("SET wps_cred_processing 2")
- class TestDbusWps(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.success_seen = False
- self.failed = False
- def __enter__(self):
- gobject.timeout_add(1, self.start_pin)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.wpsEvent, WPAS_DBUS_IFACE_WPS, "Event")
- self.add_signal(self.credentials, WPAS_DBUS_IFACE_WPS,
- "Credentials")
- self.loop.run()
- return self
- def wpsEvent(self, name, args):
- logger.debug("wpsEvent: %s args='%s'" % (name, str(args)))
- if name == "success":
- self.success_seen = True
- if self.credentials_received:
- self.loop.quit()
- def credentials(self, args):
- logger.debug("credentials: " + str(args))
- self.credentials_received = True
- if self.success_seen:
- self.loop.quit()
- def start_pin(self, *args):
- logger.debug("start_pin")
- bssid_ay = dbus.ByteArray(bssid.replace(':','').decode('hex'))
- res = wps.Start({'Role': 'enrollee', 'Type': 'pin',
- 'Bssid': bssid_ay})
- pin = res['Pin']
- h = hostapd.Hostapd(apdev[0]['ifname'])
- h.request("WPS_PIN any " + pin)
- return False
- def success(self):
- return self.success_seen and self.credentials_received
- with TestDbusWps(bus) as t:
- if not t.success():
- raise Exception("Failure in D-Bus operations")
- dev[0].wait_connected(timeout=10)
- def test_dbus_wps_pin_m2d(dev, apdev):
- """D-Bus WPS/PIN operation and signals with M2D"""
- try:
- _test_dbus_wps_pin_m2d(dev, apdev)
- finally:
- dev[0].request("SET wps_cred_processing 0")
- def _test_dbus_wps_pin_m2d(dev, apdev):
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
- hapd = start_ap(apdev[0])
- bssid = apdev[0]['bssid']
- dev[0].scan_for_bss(bssid, freq="2412")
- dev[0].request("SET wps_cred_processing 2")
- class TestDbusWps(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.success_seen = False
- self.credentials_received = False
- def __enter__(self):
- gobject.timeout_add(1, self.start_pin)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.wpsEvent, WPAS_DBUS_IFACE_WPS, "Event")
- self.add_signal(self.credentials, WPAS_DBUS_IFACE_WPS,
- "Credentials")
- self.loop.run()
- return self
- def wpsEvent(self, name, args):
- logger.debug("wpsEvent: %s args='%s'" % (name, str(args)))
- if name == "success":
- self.success_seen = True
- if self.credentials_received:
- self.loop.quit()
- elif name == "m2d":
- h = hostapd.Hostapd(apdev[0]['ifname'])
- h.request("WPS_PIN any 12345670")
- def credentials(self, args):
- logger.debug("credentials: " + str(args))
- self.credentials_received = True
- if self.success_seen:
- self.loop.quit()
- def start_pin(self, *args):
- logger.debug("start_pin")
- bssid_ay = dbus.ByteArray(bssid.replace(':','').decode('hex'))
- wps.Start({'Role': 'enrollee', 'Type': 'pin', 'Pin': '12345670',
- 'Bssid': bssid_ay})
- return False
- def success(self):
- return self.success_seen and self.credentials_received
- with TestDbusWps(bus) as t:
- if not t.success():
- raise Exception("Failure in D-Bus operations")
- dev[0].wait_connected(timeout=10)
- def test_dbus_wps_reg(dev, apdev):
- """D-Bus WPS/Registrar operation and signals"""
- try:
- _test_dbus_wps_reg(dev, apdev)
- finally:
- dev[0].request("SET wps_cred_processing 0")
- def _test_dbus_wps_reg(dev, apdev):
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
- hapd = start_ap(apdev[0])
- hapd.request("WPS_PIN any 12345670")
- bssid = apdev[0]['bssid']
- dev[0].scan_for_bss(bssid, freq="2412")
- dev[0].request("SET wps_cred_processing 2")
- class TestDbusWps(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.credentials_received = False
- def __enter__(self):
- gobject.timeout_add(100, self.start_reg)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.wpsEvent, WPAS_DBUS_IFACE_WPS, "Event")
- self.add_signal(self.credentials, WPAS_DBUS_IFACE_WPS,
- "Credentials")
- self.loop.run()
- return self
- def wpsEvent(self, name, args):
- logger.debug("wpsEvent: %s args='%s'" % (name, str(args)))
- def credentials(self, args):
- logger.debug("credentials: " + str(args))
- self.credentials_received = True
- self.loop.quit()
- def start_reg(self, *args):
- logger.debug("start_reg")
- bssid_ay = dbus.ByteArray(bssid.replace(':','').decode('hex'))
- wps.Start({'Role': 'registrar', 'Type': 'pin',
- 'Pin': '12345670', 'Bssid': bssid_ay})
- return False
- def success(self):
- return self.credentials_received
- with TestDbusWps(bus) as t:
- if not t.success():
- raise Exception("Failure in D-Bus operations")
- dev[0].wait_connected(timeout=10)
- def test_dbus_wps_cancel(dev, apdev):
- """D-Bus WPS Cancel operation"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- wps = dbus.Interface(if_obj, WPAS_DBUS_IFACE_WPS)
- hapd = start_ap(apdev[0])
- bssid = apdev[0]['bssid']
- wps.Cancel()
- dev[0].scan_for_bss(bssid, freq="2412")
- bssid_ay = dbus.ByteArray(bssid.replace(':','').decode('hex'))
- wps.Start({'Role': 'enrollee', 'Type': 'pin', 'Pin': '12345670',
- 'Bssid': bssid_ay})
- wps.Cancel()
- dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 1)
- def test_dbus_scan_invalid(dev, apdev):
- """D-Bus invalid scan method"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- tests = [ ({}, "InvalidArgs"),
- ({'Type': 123}, "InvalidArgs"),
- ({'Type': 'foo'}, "InvalidArgs"),
- ({'Type': 'active', 'Foo': 'bar'}, "InvalidArgs"),
- ({'Type': 'active', 'SSIDs': 'foo'}, "InvalidArgs"),
- ({'Type': 'active', 'SSIDs': ['foo']}, "InvalidArgs"),
- ({'Type': 'active',
- 'SSIDs': [ dbus.ByteArray("1"), dbus.ByteArray("2"),
- dbus.ByteArray("3"), dbus.ByteArray("4"),
- dbus.ByteArray("5"), dbus.ByteArray("6"),
- dbus.ByteArray("7"), dbus.ByteArray("8"),
- dbus.ByteArray("9"), dbus.ByteArray("10"),
- dbus.ByteArray("11"), dbus.ByteArray("12"),
- dbus.ByteArray("13"), dbus.ByteArray("14"),
- dbus.ByteArray("15"), dbus.ByteArray("16"),
- dbus.ByteArray("17") ]},
- "InvalidArgs"),
- ({'Type': 'active',
- 'SSIDs': [ dbus.ByteArray("1234567890abcdef1234567890abcdef1") ]},
- "InvalidArgs"),
- ({'Type': 'active', 'IEs': 'foo'}, "InvalidArgs"),
- ({'Type': 'active', 'IEs': ['foo']}, "InvalidArgs"),
- ({'Type': 'active', 'Channels': 2412 }, "InvalidArgs"),
- ({'Type': 'active', 'Channels': [ 2412 ] }, "InvalidArgs"),
- ({'Type': 'active',
- 'Channels': [ (dbus.Int32(2412), dbus.UInt32(20)) ] },
- "InvalidArgs"),
- ({'Type': 'active',
- 'Channels': [ (dbus.UInt32(2412), dbus.Int32(20)) ] },
- "InvalidArgs"),
- ({'Type': 'active', 'AllowRoam': "yes" }, "InvalidArgs"),
- ({'Type': 'passive', 'IEs': [ dbus.ByteArray("\xdd\x00") ]},
- "InvalidArgs"),
- ({'Type': 'passive', 'SSIDs': [ dbus.ByteArray("foo") ]},
- "InvalidArgs")]
- for (t,err) in tests:
- try:
- iface.Scan(t)
- raise Exception("Invalid Scan() arguments accepted: " + str(t))
- except dbus.exceptions.DBusException, e:
- if err not in str(e):
- raise Exception("Unexpected error message for invalid Scan(%s): %s" % (str(t), str(e)))
- def test_dbus_scan_oom(dev, apdev):
- """D-Bus scan method and OOM"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- with alloc_fail_dbus(dev[0], 1,
- "wpa_scan_clone_params;wpas_dbus_handler_scan",
- "Scan", expected="ScanError: Scan request rejected"):
- iface.Scan({ 'Type': 'passive',
- 'Channels': [ (dbus.UInt32(2412), dbus.UInt32(20)) ] })
- with alloc_fail_dbus(dev[0], 1,
- "=wpas_dbus_get_scan_channels;wpas_dbus_handler_scan",
- "Scan"):
- iface.Scan({ 'Type': 'passive',
- 'Channels': [ (dbus.UInt32(2412), dbus.UInt32(20)) ] })
- with alloc_fail_dbus(dev[0], 1,
- "=wpas_dbus_get_scan_ies;wpas_dbus_handler_scan",
- "Scan"):
- iface.Scan({ 'Type': 'active',
- 'IEs': [ dbus.ByteArray("\xdd\x00") ],
- 'Channels': [ (dbus.UInt32(2412), dbus.UInt32(20)) ] })
- with alloc_fail_dbus(dev[0], 1,
- "=wpas_dbus_get_scan_ssids;wpas_dbus_handler_scan",
- "Scan"):
- iface.Scan({ 'Type': 'active',
- 'SSIDs': [ dbus.ByteArray("open"),
- dbus.ByteArray() ],
- 'Channels': [ (dbus.UInt32(2412), dbus.UInt32(20)) ] })
- def test_dbus_scan(dev, apdev):
- """D-Bus scan and related signals"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "open" })
- class TestDbusScan(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.scan_completed = 0
- self.bss_added = False
- self.fail_reason = None
- def __enter__(self):
- gobject.timeout_add(1, self.run_scan)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.scanDone, WPAS_DBUS_IFACE, "ScanDone")
- self.add_signal(self.bssAdded, WPAS_DBUS_IFACE, "BSSAdded")
- self.add_signal(self.bssRemoved, WPAS_DBUS_IFACE, "BSSRemoved")
- self.loop.run()
- return self
- def scanDone(self, success):
- logger.debug("scanDone: success=%s" % success)
- self.scan_completed += 1
- if self.scan_completed == 1:
- iface.Scan({'Type': 'passive',
- 'AllowRoam': True,
- 'Channels': [(dbus.UInt32(2412), dbus.UInt32(20))]})
- elif self.scan_completed == 2:
- iface.Scan({'Type': 'passive',
- 'AllowRoam': False})
- elif self.bss_added and self.scan_completed == 3:
- self.loop.quit()
- def bssAdded(self, bss, properties):
- logger.debug("bssAdded: %s" % bss)
- logger.debug(str(properties))
- if 'WPS' in properties:
- if 'Type' in properties['WPS']:
- self.fail_reason = "Unexpected WPS dictionary entry in non-WPS BSS"
- self.loop.quit()
- self.bss_added = True
- if self.scan_completed == 3:
- self.loop.quit()
- def bssRemoved(self, bss):
- logger.debug("bssRemoved: %s" % bss)
- def run_scan(self, *args):
- logger.debug("run_scan")
- iface.Scan({'Type': 'active',
- 'SSIDs': [ dbus.ByteArray("open"),
- dbus.ByteArray() ],
- 'IEs': [ dbus.ByteArray("\xdd\x00"),
- dbus.ByteArray() ],
- 'AllowRoam': False,
- 'Channels': [(dbus.UInt32(2412), dbus.UInt32(20))]})
- return False
- def success(self):
- return self.scan_completed == 3 and self.bss_added
- with TestDbusScan(bus) as t:
- if t.fail_reason:
- raise Exception(t.fail_reason)
- if not t.success():
- raise Exception("Expected signals not seen")
- res = if_obj.Get(WPAS_DBUS_IFACE, "BSSs",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if len(res) < 1:
- raise Exception("Scan result not in BSSs property")
- iface.FlushBSS(0)
- res = if_obj.Get(WPAS_DBUS_IFACE, "BSSs",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if len(res) != 0:
- raise Exception("FlushBSS() did not remove scan results from BSSs property")
- iface.FlushBSS(1)
- def test_dbus_scan_busy(dev, apdev):
- """D-Bus scan trigger rejection when busy with previous scan"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- if "OK" not in dev[0].request("SCAN freq=2412-2462"):
- raise Exception("Failed to start scan")
- ev = dev[0].wait_event(["CTRL-EVENT-SCAN-STARTED"], 15)
- if ev is None:
- raise Exception("Scan start timed out")
- try:
- iface.Scan({'Type': 'active', 'AllowRoam': False})
- raise Exception("Scan() accepted when busy")
- except dbus.exceptions.DBusException, e:
- if "ScanError: Scan request reject" not in str(e):
- raise Exception("Unexpected error message: " + str(e))
- ev = dev[0].wait_event(["CTRL-EVENT-SCAN-RESULTS"], 15)
- if ev is None:
- raise Exception("Scan timed out")
- def test_dbus_connect(dev, apdev):
- """D-Bus AddNetwork and connect"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- ssid = "test-wpa2-psk"
- passphrase = 'qwertyuiop'
- params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
- hapd = hostapd.add_ap(apdev[0]['ifname'], params)
- class TestDbusConnect(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.network_added = False
- self.network_selected = False
- self.network_removed = False
- self.state = 0
- def __enter__(self):
- gobject.timeout_add(1, self.run_connect)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.networkAdded, WPAS_DBUS_IFACE, "NetworkAdded")
- self.add_signal(self.networkRemoved, WPAS_DBUS_IFACE,
- "NetworkRemoved")
- self.add_signal(self.networkSelected, WPAS_DBUS_IFACE,
- "NetworkSelected")
- self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
- "PropertiesChanged")
- self.loop.run()
- return self
- def networkAdded(self, network, properties):
- logger.debug("networkAdded: %s" % str(network))
- logger.debug(str(properties))
- self.network_added = True
- def networkRemoved(self, network):
- logger.debug("networkRemoved: %s" % str(network))
- self.network_removed = True
- def networkSelected(self, network):
- logger.debug("networkSelected: %s" % str(network))
- self.network_selected = True
- def propertiesChanged(self, properties):
- logger.debug("propertiesChanged: %s" % str(properties))
- if 'State' in properties and properties['State'] == "completed":
- if self.state == 0:
- self.state = 1
- iface.Disconnect()
- elif self.state == 2:
- self.state = 3
- iface.Disconnect()
- elif self.state == 4:
- self.state = 5
- iface.Reattach()
- elif self.state == 5:
- self.state = 6
- iface.Disconnect()
- elif self.state == 7:
- self.state = 8
- res = iface.SignalPoll()
- logger.debug("SignalPoll: " + str(res))
- if 'frequency' not in res or res['frequency'] != 2412:
- self.state = -1
- logger.info("Unexpected SignalPoll result")
- iface.RemoveNetwork(self.netw)
- if 'State' in properties and properties['State'] == "disconnected":
- if self.state == 1:
- self.state = 2
- iface.SelectNetwork(self.netw)
- elif self.state == 3:
- self.state = 4
- iface.Reassociate()
- elif self.state == 6:
- self.state = 7
- iface.Reconnect()
- elif self.state == 8:
- self.state = 9
- self.loop.quit()
- def run_connect(self, *args):
- logger.debug("run_connect")
- args = dbus.Dictionary({ 'ssid': ssid,
- 'key_mgmt': 'WPA-PSK',
- 'psk': passphrase,
- 'scan_freq': 2412 },
- signature='sv')
- self.netw = iface.AddNetwork(args)
- iface.SelectNetwork(self.netw)
- return False
- def success(self):
- if not self.network_added or \
- not self.network_removed or \
- not self.network_selected:
- return False
- return self.state == 9
- with TestDbusConnect(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- def test_dbus_connect_psk_mem(dev, apdev):
- """D-Bus AddNetwork and connect with memory-only PSK"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- ssid = "test-wpa2-psk"
- passphrase = 'qwertyuiop'
- params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
- hapd = hostapd.add_ap(apdev[0]['ifname'], params)
- class TestDbusConnect(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.connected = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_connect)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
- "PropertiesChanged")
- self.add_signal(self.networkRequest, WPAS_DBUS_IFACE,
- "NetworkRequest")
- self.loop.run()
- return self
- def propertiesChanged(self, properties):
- logger.debug("propertiesChanged: %s" % str(properties))
- if 'State' in properties and properties['State'] == "completed":
- self.connected = True
- self.loop.quit()
- def networkRequest(self, path, field, txt):
- logger.debug("networkRequest: %s %s %s" % (path, field, txt))
- if field == "PSK_PASSPHRASE":
- iface.NetworkReply(path, field, '"' + passphrase + '"')
- def run_connect(self, *args):
- logger.debug("run_connect")
- args = dbus.Dictionary({ 'ssid': ssid,
- 'key_mgmt': 'WPA-PSK',
- 'mem_only_psk': 1,
- 'scan_freq': 2412 },
- signature='sv')
- self.netw = iface.AddNetwork(args)
- iface.SelectNetwork(self.netw)
- return False
- def success(self):
- return self.connected
- with TestDbusConnect(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- def test_dbus_connect_oom(dev, apdev):
- """D-Bus AddNetwork and connect when out-of-memory"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- if "OK" not in dev[0].request("TEST_ALLOC_FAIL 0:"):
- raise HwsimSkip("TEST_ALLOC_FAIL not supported in the build")
- ssid = "test-wpa2-psk"
- passphrase = 'qwertyuiop'
- params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase)
- hapd = hostapd.add_ap(apdev[0]['ifname'], params)
- class TestDbusConnect(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.network_added = False
- self.network_selected = False
- self.network_removed = False
- self.state = 0
- def __enter__(self):
- gobject.timeout_add(1, self.run_connect)
- gobject.timeout_add(1500, self.timeout)
- self.add_signal(self.networkAdded, WPAS_DBUS_IFACE, "NetworkAdded")
- self.add_signal(self.networkRemoved, WPAS_DBUS_IFACE,
- "NetworkRemoved")
- self.add_signal(self.networkSelected, WPAS_DBUS_IFACE,
- "NetworkSelected")
- self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
- "PropertiesChanged")
- self.loop.run()
- return self
- def networkAdded(self, network, properties):
- logger.debug("networkAdded: %s" % str(network))
- logger.debug(str(properties))
- self.network_added = True
- def networkRemoved(self, network):
- logger.debug("networkRemoved: %s" % str(network))
- self.network_removed = True
- def networkSelected(self, network):
- logger.debug("networkSelected: %s" % str(network))
- self.network_selected = True
- def propertiesChanged(self, properties):
- logger.debug("propertiesChanged: %s" % str(properties))
- if 'State' in properties and properties['State'] == "completed":
- if self.state == 0:
- self.state = 1
- iface.Disconnect()
- elif self.state == 2:
- self.state = 3
- iface.Disconnect()
- elif self.state == 4:
- self.state = 5
- iface.Reattach()
- elif self.state == 5:
- self.state = 6
- res = iface.SignalPoll()
- logger.debug("SignalPoll: " + str(res))
- if 'frequency' not in res or res['frequency'] != 2412:
- self.state = -1
- logger.info("Unexpected SignalPoll result")
- iface.RemoveNetwork(self.netw)
- if 'State' in properties and properties['State'] == "disconnected":
- if self.state == 1:
- self.state = 2
- iface.SelectNetwork(self.netw)
- elif self.state == 3:
- self.state = 4
- iface.Reassociate()
- elif self.state == 6:
- self.state = 7
- self.loop.quit()
- def run_connect(self, *args):
- logger.debug("run_connect")
- args = dbus.Dictionary({ 'ssid': ssid,
- 'key_mgmt': 'WPA-PSK',
- 'psk': passphrase,
- 'scan_freq': 2412 },
- signature='sv')
- try:
- self.netw = iface.AddNetwork(args)
- except Exception, e:
- logger.info("Exception on AddNetwork: " + str(e))
- self.loop.quit()
- return False
- try:
- iface.SelectNetwork(self.netw)
- except Exception, e:
- logger.info("Exception on SelectNetwork: " + str(e))
- self.loop.quit()
- return False
- def success(self):
- if not self.network_added or \
- not self.network_removed or \
- not self.network_selected:
- return False
- return self.state == 7
- count = 0
- for i in range(1, 1000):
- for j in range(3):
- dev[j].dump_monitor()
- dev[0].request("TEST_ALLOC_FAIL %d:main" % i)
- try:
- with TestDbusConnect(bus) as t:
- if not t.success():
- logger.info("Iteration %d - Expected signals not seen" % i)
- else:
- logger.info("Iteration %d - success" % i)
- state = dev[0].request('GET_ALLOC_FAIL')
- logger.info("GET_ALLOC_FAIL: " + state)
- dev[0].dump_monitor()
- dev[0].request("TEST_ALLOC_FAIL 0:")
- if i < 3:
- raise Exception("Connection succeeded during out-of-memory")
- if not state.startswith('0:'):
- count += 1
- if count == 5:
- break
- except:
- pass
- # Force regulatory update to re-fetch hw capabilities for the following
- # test cases.
- try:
- dev[0].dump_monitor()
- subprocess.call(['iw', 'reg', 'set', 'US'])
- ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
- finally:
- dev[0].dump_monitor()
- subprocess.call(['iw', 'reg', 'set', '00'])
- ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
- def test_dbus_while_not_connected(dev, apdev):
- """D-Bus invalid operations while not connected"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- try:
- iface.Disconnect()
- raise Exception("Disconnect() accepted when not connected")
- except dbus.exceptions.DBusException, e:
- if "NotConnected" not in str(e):
- raise Exception("Unexpected error message for invalid Disconnect: " + str(e))
- try:
- iface.Reattach()
- raise Exception("Reattach() accepted when not connected")
- except dbus.exceptions.DBusException, e:
- if "NotConnected" not in str(e):
- raise Exception("Unexpected error message for invalid Reattach: " + str(e))
- def test_dbus_connect_eap(dev, apdev):
- """D-Bus AddNetwork and connect to EAP network"""
- check_altsubject_match_support(dev[0])
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- ssid = "ieee8021x-open"
- params = hostapd.radius_params()
- params["ssid"] = ssid
- params["ieee8021x"] = "1"
- hapd = hostapd.add_ap(apdev[0]['ifname'], params)
- class TestDbusConnect(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.certification_received = False
- self.eap_status = False
- self.state = 0
- def __enter__(self):
- gobject.timeout_add(1, self.run_connect)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
- "PropertiesChanged")
- self.add_signal(self.certification, WPAS_DBUS_IFACE,
- "Certification", byte_arrays=True)
- self.add_signal(self.networkRequest, WPAS_DBUS_IFACE,
- "NetworkRequest")
- self.add_signal(self.eap, WPAS_DBUS_IFACE, "EAP")
- self.loop.run()
- return self
- def propertiesChanged(self, properties):
- logger.debug("propertiesChanged: %s" % str(properties))
- if 'State' in properties and properties['State'] == "completed":
- if self.state == 0:
- self.state = 1
- iface.EAPLogoff()
- logger.info("Set dNSName constraint")
- net_obj = bus.get_object(WPAS_DBUS_SERVICE, self.netw)
- args = dbus.Dictionary({ 'altsubject_match':
- self.server_dnsname },
- signature='sv')
- net_obj.Set(WPAS_DBUS_NETWORK, "Properties", args,
- dbus_interface=dbus.PROPERTIES_IFACE)
- elif self.state == 2:
- self.state = 3
- iface.Disconnect()
- logger.info("Set non-matching dNSName constraint")
- net_obj = bus.get_object(WPAS_DBUS_SERVICE, self.netw)
- args = dbus.Dictionary({ 'altsubject_match':
- self.server_dnsname + "FOO" },
- signature='sv')
- net_obj.Set(WPAS_DBUS_NETWORK, "Properties", args,
- dbus_interface=dbus.PROPERTIES_IFACE)
- if 'State' in properties and properties['State'] == "disconnected":
- if self.state == 1:
- self.state = 2
- iface.EAPLogon()
- iface.SelectNetwork(self.netw)
- if self.state == 3:
- self.state = 4
- iface.SelectNetwork(self.netw)
- def certification(self, args):
- logger.debug("certification: %s" % str(args))
- self.certification_received = True
- if args['depth'] == 0:
- # The test server certificate is supposed to have dNSName
- if len(args['altsubject']) < 1:
- raise Exception("Missing dNSName")
- dnsname = args['altsubject'][0]
- if not dnsname.startswith("DNS:"):
- raise Exception("Expected dNSName not found: " + dnsname)
- logger.info("altsubject: " + dnsname)
- self.server_dnsname = dnsname
- def eap(self, status, parameter):
- logger.debug("EAP: status=%s parameter=%s" % (status, parameter))
- if status == 'completion' and parameter == 'success':
- self.eap_status = True
- if self.state == 4 and status == 'remote certificate verification' and parameter == 'AltSubject mismatch':
- self.state = 5
- self.loop.quit()
- def networkRequest(self, path, field, txt):
- logger.debug("networkRequest: %s %s %s" % (path, field, txt))
- if field == "PASSWORD":
- iface.NetworkReply(path, field, "password")
- def run_connect(self, *args):
- logger.debug("run_connect")
- args = dbus.Dictionary({ 'ssid': ssid,
- 'key_mgmt': 'IEEE8021X',
- 'eapol_flags': 0,
- 'eap': 'TTLS',
- 'anonymous_identity': 'ttls',
- 'identity': 'pap user',
- 'ca_cert': 'auth_serv/ca.pem',
- 'phase2': 'auth=PAP',
- 'scan_freq': 2412 },
- signature='sv')
- self.netw = iface.AddNetwork(args)
- iface.SelectNetwork(self.netw)
- return False
- def success(self):
- if not self.eap_status or not self.certification_received:
- return False
- return self.state == 5
- with TestDbusConnect(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- def test_dbus_network(dev, apdev):
- """D-Bus AddNetwork/RemoveNetwork parameters and error cases"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- args = dbus.Dictionary({ 'ssid': "foo",
- 'key_mgmt': 'WPA-PSK',
- 'psk': "12345678",
- 'identity': dbus.ByteArray([ 1, 2 ]),
- 'priority': dbus.Int32(0),
- 'scan_freq': dbus.UInt32(2412) },
- signature='sv')
- netw = iface.AddNetwork(args)
- id = int(dev[0].list_networks()[0]['id'])
- val = dev[0].get_network(id, "scan_freq")
- if val != "2412":
- raise Exception("Invalid scan_freq value: " + str(val))
- iface.RemoveNetwork(netw)
- args = dbus.Dictionary({ 'ssid': "foo",
- 'key_mgmt': 'NONE',
- 'scan_freq': "2412 2432",
- 'freq_list': "2412 2417 2432" },
- signature='sv')
- netw = iface.AddNetwork(args)
- id = int(dev[0].list_networks()[0]['id'])
- val = dev[0].get_network(id, "scan_freq")
- if val != "2412 2432":
- raise Exception("Invalid scan_freq value (2): " + str(val))
- val = dev[0].get_network(id, "freq_list")
- if val != "2412 2417 2432":
- raise Exception("Invalid freq_list value: " + str(val))
- iface.RemoveNetwork(netw)
- try:
- iface.RemoveNetwork(netw)
- raise Exception("Invalid RemoveNetwork() accepted")
- except dbus.exceptions.DBusException, e:
- if "NetworkUnknown" not in str(e):
- raise Exception("Unexpected error message for invalid RemoveNetwork: " + str(e))
- try:
- iface.SelectNetwork(netw)
- raise Exception("Invalid SelectNetwork() accepted")
- except dbus.exceptions.DBusException, e:
- if "NetworkUnknown" not in str(e):
- raise Exception("Unexpected error message for invalid RemoveNetwork: " + str(e))
- args = dbus.Dictionary({ 'ssid': "foo1", 'key_mgmt': 'NONE',
- 'identity': "testuser", 'scan_freq': '2412' },
- signature='sv')
- netw1 = iface.AddNetwork(args)
- args = dbus.Dictionary({ 'ssid': "foo2", 'key_mgmt': 'NONE' },
- signature='sv')
- netw2 = iface.AddNetwork(args)
- res = if_obj.Get(WPAS_DBUS_IFACE, "Networks",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if len(res) != 2:
- raise Exception("Unexpected number of networks")
- net_obj = bus.get_object(WPAS_DBUS_SERVICE, netw1)
- res = net_obj.Get(WPAS_DBUS_NETWORK, "Enabled",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if res != False:
- raise Exception("Added network was unexpectedly enabled by default")
- net_obj.Set(WPAS_DBUS_NETWORK, "Enabled", dbus.Boolean(True),
- dbus_interface=dbus.PROPERTIES_IFACE)
- res = net_obj.Get(WPAS_DBUS_NETWORK, "Enabled",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if res != True:
- raise Exception("Set(Enabled,True) did not seem to change property value")
- net_obj.Set(WPAS_DBUS_NETWORK, "Enabled", dbus.Boolean(False),
- dbus_interface=dbus.PROPERTIES_IFACE)
- res = net_obj.Get(WPAS_DBUS_NETWORK, "Enabled",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if res != False:
- raise Exception("Set(Enabled,False) did not seem to change property value")
- try:
- net_obj.Set(WPAS_DBUS_NETWORK, "Enabled", dbus.UInt32(1),
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Set(Enabled,1) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: wrong property type" not in str(e):
- raise Exception("Unexpected error message for invalid Set(Enabled,1): " + str(e))
- args = dbus.Dictionary({ 'ssid': "foo1new" }, signature='sv')
- net_obj.Set(WPAS_DBUS_NETWORK, "Properties", args,
- dbus_interface=dbus.PROPERTIES_IFACE)
- res = net_obj.Get(WPAS_DBUS_NETWORK, "Properties",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if res['ssid'] != '"foo1new"':
- raise Exception("Set(Properties) failed to update ssid")
- if res['identity'] != '"testuser"':
- raise Exception("Set(Properties) unexpectedly changed unrelated parameter")
- iface.RemoveAllNetworks()
- res = if_obj.Get(WPAS_DBUS_IFACE, "Networks",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if len(res) != 0:
- raise Exception("Unexpected number of networks")
- iface.RemoveAllNetworks()
- tests = [ dbus.Dictionary({ 'psk': "1234567" }, signature='sv'),
- dbus.Dictionary({ 'identity': dbus.ByteArray() },
- signature='sv'),
- dbus.Dictionary({ 'identity': dbus.Byte(1) }, signature='sv'),
- dbus.Dictionary({ 'identity': "" }, signature='sv') ]
- for args in tests:
- try:
- iface.AddNetwork(args)
- raise Exception("Invalid AddNetwork args accepted: " + str(args))
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid AddNetwork: " + str(e))
- def test_dbus_network_oom(dev, apdev):
- """D-Bus AddNetwork/RemoveNetwork parameters and OOM error cases"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- args = dbus.Dictionary({ 'ssid': "foo1", 'key_mgmt': 'NONE',
- 'identity': "testuser", 'scan_freq': '2412' },
- signature='sv')
- netw1 = iface.AddNetwork(args)
- net_obj = bus.get_object(WPAS_DBUS_SERVICE, netw1)
- with alloc_fail_dbus(dev[0], 1,
- "wpa_config_get_all;wpas_dbus_getter_network_properties",
- "Get"):
- net_obj.Get(WPAS_DBUS_NETWORK, "Properties",
- dbus_interface=dbus.PROPERTIES_IFACE)
- iface.RemoveAllNetworks()
- with alloc_fail_dbus(dev[0], 1,
- "wpas_dbus_new_decompose_object_path;wpas_dbus_handler_remove_network",
- "RemoveNetwork", "InvalidArgs"):
- iface.RemoveNetwork(dbus.ObjectPath("/fi/w1/wpa_supplicant1/Interfaces/1234/Networks/1234"))
- with alloc_fail(dev[0], 1, "wpa_dbus_register_object_per_iface;wpas_dbus_register_network"):
- args = dbus.Dictionary({ 'ssid': "foo2", 'key_mgmt': 'NONE' },
- signature='sv')
- try:
- netw = iface.AddNetwork(args)
- # Currently, AddNetwork() succeeds even if os_strdup() for path
- # fails, so remove the network if that occurs.
- iface.RemoveNetwork(netw)
- except dbus.exceptions.DBusException, e:
- pass
- for i in range(1, 3):
- with alloc_fail(dev[0], i, "=wpas_dbus_register_network"):
- try:
- netw = iface.AddNetwork(args)
- # Currently, AddNetwork() succeeds even if network registration
- # fails, so remove the network if that occurs.
- iface.RemoveNetwork(netw)
- except dbus.exceptions.DBusException, e:
- pass
- with alloc_fail_dbus(dev[0], 1,
- "=wpa_config_add_network;wpas_dbus_handler_add_network",
- "AddNetwork",
- "UnknownError: wpa_supplicant could not add a network"):
- args = dbus.Dictionary({ 'ssid': "foo2", 'key_mgmt': 'NONE' },
- signature='sv')
- netw = iface.AddNetwork(args)
- tests = [ (1,
- 'wpa_dbus_dict_get_entry;set_network_properties;wpas_dbus_handler_add_network',
- dbus.Dictionary({ 'ssid': dbus.ByteArray(' ') },
- signature='sv')),
- (1, '=set_network_properties;wpas_dbus_handler_add_network',
- dbus.Dictionary({ 'ssid': 'foo' }, signature='sv')),
- (1, '=set_network_properties;wpas_dbus_handler_add_network',
- dbus.Dictionary({ 'eap': 'foo' }, signature='sv')),
- (1, '=set_network_properties;wpas_dbus_handler_add_network',
- dbus.Dictionary({ 'priority': dbus.UInt32(1) },
- signature='sv')),
- (1, '=set_network_properties;wpas_dbus_handler_add_network',
- dbus.Dictionary({ 'priority': dbus.Int32(1) },
- signature='sv')),
- (1, '=set_network_properties;wpas_dbus_handler_add_network',
- dbus.Dictionary({ 'ssid': dbus.ByteArray(' ') },
- signature='sv')) ]
- for (count,funcs,args) in tests:
- with alloc_fail_dbus(dev[0], count, funcs, "AddNetwork", "InvalidArgs"):
- netw = iface.AddNetwork(args)
- if len(if_obj.Get(WPAS_DBUS_IFACE, 'Networks',
- dbus_interface=dbus.PROPERTIES_IFACE)) > 0:
- raise Exception("Unexpected network block added")
- if len(dev[0].list_networks()) > 0:
- raise Exception("Unexpected network block visible")
- def test_dbus_interface(dev, apdev):
- """D-Bus CreateInterface/GetInterface/RemoveInterface parameters and error cases"""
- try:
- _test_dbus_interface(dev, apdev)
- finally:
- # Need to force P2P channel list update since the 'lo' interface
- # with driver=none ends up configuring default dualband channels.
- dev[0].request("SET country US")
- ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
- if ev is None:
- ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"],
- timeout=1)
- dev[0].request("SET country 00")
- ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
- if ev is None:
- ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"],
- timeout=1)
- subprocess.call(['iw', 'reg', 'set', '00'])
- def _test_dbus_interface(dev, apdev):
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- wpas = dbus.Interface(wpas_obj, WPAS_DBUS_SERVICE)
- params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none' },
- signature='sv')
- path = wpas.CreateInterface(params)
- logger.debug("New interface path: " + str(path))
- path2 = wpas.GetInterface("lo")
- if path != path2:
- raise Exception("Interface object mismatch")
- params = dbus.Dictionary({ 'Ifname': 'lo',
- 'Driver': 'none',
- 'ConfigFile': 'foo',
- 'BridgeIfname': 'foo', },
- signature='sv')
- try:
- wpas.CreateInterface(params)
- raise Exception("Invalid CreateInterface() accepted")
- except dbus.exceptions.DBusException, e:
- if "InterfaceExists" not in str(e):
- raise Exception("Unexpected error message for invalid CreateInterface: " + str(e))
- wpas.RemoveInterface(path)
- try:
- wpas.RemoveInterface(path)
- raise Exception("Invalid RemoveInterface() accepted")
- except dbus.exceptions.DBusException, e:
- if "InterfaceUnknown" not in str(e):
- raise Exception("Unexpected error message for invalid RemoveInterface: " + str(e))
- params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none',
- 'Foo': 123 },
- signature='sv')
- try:
- wpas.CreateInterface(params)
- raise Exception("Invalid CreateInterface() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid CreateInterface: " + str(e))
- params = dbus.Dictionary({ 'Driver': 'none' }, signature='sv')
- try:
- wpas.CreateInterface(params)
- raise Exception("Invalid CreateInterface() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid CreateInterface: " + str(e))
- try:
- wpas.GetInterface("lo")
- raise Exception("Invalid GetInterface() accepted")
- except dbus.exceptions.DBusException, e:
- if "InterfaceUnknown" not in str(e):
- raise Exception("Unexpected error message for invalid RemoveInterface: " + str(e))
- def test_dbus_interface_oom(dev, apdev):
- """D-Bus CreateInterface/GetInterface/RemoveInterface OOM error cases"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- wpas = dbus.Interface(wpas_obj, WPAS_DBUS_SERVICE)
- with alloc_fail_dbus(dev[0], 1, "wpa_dbus_dict_get_entry;wpas_dbus_handler_create_interface", "CreateInterface", "InvalidArgs"):
- params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none' },
- signature='sv')
- wpas.CreateInterface(params)
- for i in range(1, 1000):
- dev[0].request("TEST_ALLOC_FAIL %d:wpa_supplicant_add_iface;wpas_dbus_handler_create_interface" % i)
- params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none' },
- signature='sv')
- try:
- npath = wpas.CreateInterface(params)
- wpas.RemoveInterface(npath)
- logger.info("CreateInterface succeeds after %d allocation failures" % i)
- state = dev[0].request('GET_ALLOC_FAIL')
- logger.info("GET_ALLOC_FAIL: " + state)
- dev[0].dump_monitor()
- dev[0].request("TEST_ALLOC_FAIL 0:")
- if i < 5:
- raise Exception("CreateInterface succeeded during out-of-memory")
- if not state.startswith('0:'):
- break
- except dbus.exceptions.DBusException, e:
- pass
- for arg in [ 'Driver', 'Ifname', 'ConfigFile', 'BridgeIfname' ]:
- with alloc_fail_dbus(dev[0], 1, "=wpas_dbus_handler_create_interface",
- "CreateInterface"):
- params = dbus.Dictionary({ arg: 'foo' }, signature='sv')
- wpas.CreateInterface(params)
- def test_dbus_blob(dev, apdev):
- """D-Bus AddNetwork/RemoveNetwork parameters and error cases"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- blob = dbus.ByteArray("\x01\x02\x03")
- iface.AddBlob('blob1', blob)
- try:
- iface.AddBlob('blob1', dbus.ByteArray("\x01\x02\x04"))
- raise Exception("Invalid AddBlob() accepted")
- except dbus.exceptions.DBusException, e:
- if "BlobExists" not in str(e):
- raise Exception("Unexpected error message for invalid AddBlob: " + str(e))
- res = iface.GetBlob('blob1')
- if len(res) != len(blob):
- raise Exception("Unexpected blob data length")
- for i in range(len(res)):
- if res[i] != dbus.Byte(blob[i]):
- raise Exception("Unexpected blob data")
- res = if_obj.Get(WPAS_DBUS_IFACE, "Blobs",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if 'blob1' not in res:
- raise Exception("Added blob missing from Blobs property")
- iface.RemoveBlob('blob1')
- try:
- iface.RemoveBlob('blob1')
- raise Exception("Invalid RemoveBlob() accepted")
- except dbus.exceptions.DBusException, e:
- if "BlobUnknown" not in str(e):
- raise Exception("Unexpected error message for invalid RemoveBlob: " + str(e))
- try:
- iface.GetBlob('blob1')
- raise Exception("Invalid GetBlob() accepted")
- except dbus.exceptions.DBusException, e:
- if "BlobUnknown" not in str(e):
- raise Exception("Unexpected error message for invalid GetBlob: " + str(e))
- class TestDbusBlob(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.blob_added = False
- self.blob_removed = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_blob)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.blobAdded, WPAS_DBUS_IFACE, "BlobAdded")
- self.add_signal(self.blobRemoved, WPAS_DBUS_IFACE, "BlobRemoved")
- self.loop.run()
- return self
- def blobAdded(self, blobName):
- logger.debug("blobAdded: %s" % blobName)
- if blobName == 'blob2':
- self.blob_added = True
- def blobRemoved(self, blobName):
- logger.debug("blobRemoved: %s" % blobName)
- if blobName == 'blob2':
- self.blob_removed = True
- self.loop.quit()
- def run_blob(self, *args):
- logger.debug("run_blob")
- iface.AddBlob('blob2', dbus.ByteArray("\x01\x02\x04"))
- iface.RemoveBlob('blob2')
- return False
- def success(self):
- return self.blob_added and self.blob_removed
- with TestDbusBlob(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- def test_dbus_blob_oom(dev, apdev):
- """D-Bus AddNetwork/RemoveNetwork OOM error cases"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- for i in range(1, 4):
- with alloc_fail_dbus(dev[0], i, "wpas_dbus_handler_add_blob",
- "AddBlob"):
- iface.AddBlob('blob_no_mem', dbus.ByteArray("\x01\x02\x03\x04"))
- def test_dbus_autoscan(dev, apdev):
- """D-Bus Autoscan()"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- iface.AutoScan("foo")
- iface.AutoScan("periodic:1")
- iface.AutoScan("")
- dev[0].request("AUTOSCAN ")
- def test_dbus_autoscan_oom(dev, apdev):
- """D-Bus Autoscan() OOM"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- with alloc_fail_dbus(dev[0], 1, "wpas_dbus_handler_autoscan", "AutoScan"):
- iface.AutoScan("foo")
- dev[0].request("AUTOSCAN ")
- def test_dbus_tdls_invalid(dev, apdev):
- """D-Bus invalid TDLS operations"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "test-open" })
- connect_2sta_open(dev, hapd)
- addr1 = dev[1].p2p_interface_addr()
- try:
- iface.TDLSDiscover("foo")
- raise Exception("Invalid TDLSDiscover() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid TDLSDiscover: " + str(e))
- try:
- iface.TDLSStatus("foo")
- raise Exception("Invalid TDLSStatus() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid TDLSStatus: " + str(e))
- res = iface.TDLSStatus(addr1)
- if res != "peer does not exist":
- raise Exception("Unexpected TDLSStatus response")
- try:
- iface.TDLSSetup("foo")
- raise Exception("Invalid TDLSSetup() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid TDLSSetup: " + str(e))
- try:
- iface.TDLSTeardown("foo")
- raise Exception("Invalid TDLSTeardown() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid TDLSTeardown: " + str(e))
- try:
- iface.TDLSTeardown("00:11:22:33:44:55")
- raise Exception("TDLSTeardown accepted for unknown peer")
- except dbus.exceptions.DBusException, e:
- if "UnknownError: error performing TDLS teardown" not in str(e):
- raise Exception("Unexpected error message: " + str(e))
- def test_dbus_tdls_oom(dev, apdev):
- """D-Bus TDLS operations during OOM"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- with alloc_fail_dbus(dev[0], 1, "wpa_tdls_add_peer", "TDLSSetup",
- "UnknownError: error performing TDLS setup"):
- iface.TDLSSetup("00:11:22:33:44:55")
- def test_dbus_tdls(dev, apdev):
- """D-Bus TDLS"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "test-open" })
- connect_2sta_open(dev, hapd)
- addr1 = dev[1].p2p_interface_addr()
- class TestDbusTdls(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.tdls_setup = False
- self.tdls_teardown = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_tdls)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
- "PropertiesChanged")
- self.loop.run()
- return self
- def propertiesChanged(self, properties):
- logger.debug("propertiesChanged: %s" % str(properties))
- def run_tdls(self, *args):
- logger.debug("run_tdls")
- iface.TDLSDiscover(addr1)
- gobject.timeout_add(100, self.run_tdls2)
- return False
- def run_tdls2(self, *args):
- logger.debug("run_tdls2")
- iface.TDLSSetup(addr1)
- gobject.timeout_add(500, self.run_tdls3)
- return False
- def run_tdls3(self, *args):
- logger.debug("run_tdls3")
- res = iface.TDLSStatus(addr1)
- if res == "connected":
- self.tdls_setup = True
- else:
- logger.info("Unexpected TDLSStatus: " + res)
- iface.TDLSTeardown(addr1)
- gobject.timeout_add(200, self.run_tdls4)
- return False
- def run_tdls4(self, *args):
- logger.debug("run_tdls4")
- res = iface.TDLSStatus(addr1)
- if res == "peer does not exist":
- self.tdls_teardown = True
- else:
- logger.info("Unexpected TDLSStatus: " + res)
- self.loop.quit()
- return False
- def success(self):
- return self.tdls_setup and self.tdls_teardown
- with TestDbusTdls(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- def test_dbus_pkcs11(dev, apdev):
- """D-Bus SetPKCS11EngineAndModulePath()"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- try:
- iface.SetPKCS11EngineAndModulePath("foo", "bar")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: Reinit of the EAPOL" not in str(e):
- raise Exception("Unexpected error message for invalid SetPKCS11EngineAndModulePath: " + str(e))
- try:
- iface.SetPKCS11EngineAndModulePath("foo", "")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: Reinit of the EAPOL" not in str(e):
- raise Exception("Unexpected error message for invalid SetPKCS11EngineAndModulePath: " + str(e))
- iface.SetPKCS11EngineAndModulePath("", "bar")
- res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11EnginePath",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if res != "":
- raise Exception("Unexpected PKCS11EnginePath value: " + res)
- res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11ModulePath",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if res != "bar":
- raise Exception("Unexpected PKCS11ModulePath value: " + res)
- iface.SetPKCS11EngineAndModulePath("", "")
- res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11EnginePath",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if res != "":
- raise Exception("Unexpected PKCS11EnginePath value: " + res)
- res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11ModulePath",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if res != "":
- raise Exception("Unexpected PKCS11ModulePath value: " + res)
- def test_dbus_apscan(dev, apdev):
- """D-Bus Get/Set ApScan"""
- try:
- _test_dbus_apscan(dev, apdev)
- finally:
- dev[0].request("AP_SCAN 1")
- def _test_dbus_apscan(dev, apdev):
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- res = if_obj.Get(WPAS_DBUS_IFACE, "ApScan",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if res != 1:
- raise Exception("Unexpected initial ApScan value: %d" % res)
- for i in range(3):
- if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.UInt32(i),
- dbus_interface=dbus.PROPERTIES_IFACE)
- res = if_obj.Get(WPAS_DBUS_IFACE, "ApScan",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if res != i:
- raise Exception("Unexpected ApScan value %d (expected %d)" % (res, i))
- try:
- if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.Int16(-1),
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Set(ApScan,-1) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: wrong property type" not in str(e):
- raise Exception("Unexpected error message for invalid Set(ApScan,-1): " + str(e))
- try:
- if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.UInt32(123),
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Set(ApScan,123) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: ap_scan must be 0, 1, or 2" not in str(e):
- raise Exception("Unexpected error message for invalid Set(ApScan,123): " + str(e))
- if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.UInt32(1),
- dbus_interface=dbus.PROPERTIES_IFACE)
- def test_dbus_fastreauth(dev, apdev):
- """D-Bus Get/Set FastReauth"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- res = if_obj.Get(WPAS_DBUS_IFACE, "FastReauth",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if res != True:
- raise Exception("Unexpected initial FastReauth value: " + str(res))
- for i in [ False, True ]:
- if_obj.Set(WPAS_DBUS_IFACE, "FastReauth", dbus.Boolean(i),
- dbus_interface=dbus.PROPERTIES_IFACE)
- res = if_obj.Get(WPAS_DBUS_IFACE, "FastReauth",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if res != i:
- raise Exception("Unexpected FastReauth value %d (expected %d)" % (res, i))
- try:
- if_obj.Set(WPAS_DBUS_IFACE, "FastReauth", dbus.Int16(-1),
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Set(FastReauth,-1) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: wrong property type" not in str(e):
- raise Exception("Unexpected error message for invalid Set(ApScan,-1): " + str(e))
- if_obj.Set(WPAS_DBUS_IFACE, "FastReauth", dbus.Boolean(True),
- dbus_interface=dbus.PROPERTIES_IFACE)
- def test_dbus_bss_expire(dev, apdev):
- """D-Bus Get/Set BSSExpireAge and BSSExpireCount"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.UInt32(179),
- dbus_interface=dbus.PROPERTIES_IFACE)
- res = if_obj.Get(WPAS_DBUS_IFACE, "BSSExpireAge",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if res != 179:
- raise Exception("Unexpected BSSExpireAge value %d (expected %d)" % (res, i))
- if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.UInt32(3),
- dbus_interface=dbus.PROPERTIES_IFACE)
- res = if_obj.Get(WPAS_DBUS_IFACE, "BSSExpireCount",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if res != 3:
- raise Exception("Unexpected BSSExpireCount value %d (expected %d)" % (res, i))
- try:
- if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.Int16(-1),
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Set(BSSExpireAge,-1) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: wrong property type" not in str(e):
- raise Exception("Unexpected error message for invalid Set(BSSExpireAge,-1): " + str(e))
- try:
- if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.UInt32(9),
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Set(BSSExpireAge,9) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: BSSExpireAge must be >= 10" not in str(e):
- raise Exception("Unexpected error message for invalid Set(BSSExpireAge,9): " + str(e))
- try:
- if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.Int16(-1),
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Set(BSSExpireCount,-1) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: wrong property type" not in str(e):
- raise Exception("Unexpected error message for invalid Set(BSSExpireCount,-1): " + str(e))
- try:
- if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.UInt32(0),
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Set(BSSExpireCount,0) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: BSSExpireCount must be > 0" not in str(e):
- raise Exception("Unexpected error message for invalid Set(BSSExpireCount,0): " + str(e))
- if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.UInt32(180),
- dbus_interface=dbus.PROPERTIES_IFACE)
- if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.UInt32(2),
- dbus_interface=dbus.PROPERTIES_IFACE)
- def test_dbus_country(dev, apdev):
- """D-Bus Get/Set Country"""
- try:
- _test_dbus_country(dev, apdev)
- finally:
- dev[0].request("SET country 00")
- subprocess.call(['iw', 'reg', 'set', '00'])
- def _test_dbus_country(dev, apdev):
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- # work around issues with possible pending regdom event from the end of
- # the previous test case
- time.sleep(0.2)
- dev[0].dump_monitor()
- if_obj.Set(WPAS_DBUS_IFACE, "Country", "FI",
- dbus_interface=dbus.PROPERTIES_IFACE)
- res = if_obj.Get(WPAS_DBUS_IFACE, "Country",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if res != "FI":
- raise Exception("Unexpected Country value %s (expected FI)" % res)
- ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"])
- if ev is None:
- # For now, work around separate P2P Device interface event delivery
- ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
- if ev is None:
- raise Exception("regdom change event not seen")
- if "init=USER type=COUNTRY alpha2=FI" not in ev:
- raise Exception("Unexpected event contents: " + ev)
- try:
- if_obj.Set(WPAS_DBUS_IFACE, "Country", dbus.Int16(-1),
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Set(Country,-1) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: wrong property type" not in str(e):
- raise Exception("Unexpected error message for invalid Set(Country,-1): " + str(e))
- try:
- if_obj.Set(WPAS_DBUS_IFACE, "Country", "F",
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Set(Country,F) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: invalid country code" not in str(e):
- raise Exception("Unexpected error message for invalid Set(Country,F): " + str(e))
- if_obj.Set(WPAS_DBUS_IFACE, "Country", "00",
- dbus_interface=dbus.PROPERTIES_IFACE)
- ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"])
- if ev is None:
- # For now, work around separate P2P Device interface event delivery
- ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
- if ev is None:
- raise Exception("regdom change event not seen")
- # init=CORE was previously used due to invalid db.txt data for 00. For
- # now, allow both it and the new init=USER after fixed db.txt.
- if "init=CORE type=WORLD" not in ev and "init=USER type=WORLD" not in ev:
- raise Exception("Unexpected event contents: " + ev)
- def test_dbus_scan_interval(dev, apdev):
- """D-Bus Get/Set ScanInterval"""
- try:
- _test_dbus_scan_interval(dev, apdev)
- finally:
- dev[0].request("SCAN_INTERVAL 5")
- def _test_dbus_scan_interval(dev, apdev):
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.Int32(3),
- dbus_interface=dbus.PROPERTIES_IFACE)
- res = if_obj.Get(WPAS_DBUS_IFACE, "ScanInterval",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if res != 3:
- raise Exception("Unexpected ScanInterval value %d (expected %d)" % (res, i))
- try:
- if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.UInt16(100),
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Set(ScanInterval,100) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: wrong property type" not in str(e):
- raise Exception("Unexpected error message for invalid Set(ScanInterval,100): " + str(e))
- try:
- if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.Int32(-1),
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Set(ScanInterval,-1) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: scan_interval must be >= 0" not in str(e):
- raise Exception("Unexpected error message for invalid Set(ScanInterval,-1): " + str(e))
- if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.Int32(5),
- dbus_interface=dbus.PROPERTIES_IFACE)
- def test_dbus_probe_req_reporting(dev, apdev):
- """D-Bus Probe Request reporting"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- dev[1].p2p_find(social=True)
- class TestDbusProbe(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.reported = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupStarted")
- self.add_signal(self.probeRequest, WPAS_DBUS_IFACE, "ProbeRequest",
- byte_arrays=True)
- self.loop.run()
- return self
- def groupStarted(self, properties):
- logger.debug("groupStarted: " + str(properties))
- g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
- properties['interface_object'])
- self.iface = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE)
- self.iface.SubscribeProbeReq()
- self.group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- def probeRequest(self, args):
- logger.debug("probeRequest: args=%s" % str(args))
- self.reported = True
- self.loop.quit()
- def run_test(self, *args):
- logger.debug("run_test")
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- params = dbus.Dictionary({ 'frequency': 2412 })
- p2p.GroupAdd(params)
- return False
- def success(self):
- return self.reported
- with TestDbusProbe(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- t.iface.UnsubscribeProbeReq()
- try:
- t.iface.UnsubscribeProbeReq()
- raise Exception("Invalid UnsubscribeProbeReq() accepted")
- except dbus.exceptions.DBusException, e:
- if "NoSubscription" not in str(e):
- raise Exception("Unexpected error message for invalid UnsubscribeProbeReq(): " + str(e))
- t.group_p2p.Disconnect()
- with TestDbusProbe(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- # On purpose, leave ProbeReq subscription in place to test automatic
- # cleanup.
- dev[1].p2p_stop_find()
- def test_dbus_probe_req_reporting_oom(dev, apdev):
- """D-Bus Probe Request reporting (OOM)"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- # Need to make sure this process has not already subscribed to avoid false
- # failures due to the operation succeeding due to os_strdup() not even
- # getting called.
- try:
- iface.UnsubscribeProbeReq()
- was_subscribed = True
- except dbus.exceptions.DBusException, e:
- was_subscribed = False
- pass
- with alloc_fail_dbus(dev[0], 1, "wpas_dbus_handler_subscribe_preq",
- "SubscribeProbeReq"):
- iface.SubscribeProbeReq()
- if was_subscribed:
- # On purpose, leave ProbeReq subscription in place to test automatic
- # cleanup.
- iface.SubscribeProbeReq()
- def test_dbus_p2p_invalid(dev, apdev):
- """D-Bus invalid P2P operations"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- try:
- p2p.RejectPeer(path + "/Peers/00112233445566")
- raise Exception("Invalid RejectPeer accepted")
- except dbus.exceptions.DBusException, e:
- if "UnknownError: Failed to call wpas_p2p_reject" not in str(e):
- raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
- try:
- p2p.RejectPeer("/foo")
- raise Exception("Invalid RejectPeer accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
- tests = [ { },
- { 'peer': 'foo' },
- { 'foo': "bar" },
- { 'iface': "abc" },
- { 'iface': 123 } ]
- for t in tests:
- try:
- p2p.RemoveClient(t)
- raise Exception("Invalid RemoveClient accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid RemoveClient(): " + str(e))
- tests = [ {'DiscoveryType': 'foo'},
- {'RequestedDeviceTypes': 'foo'},
- {'RequestedDeviceTypes': ['foo']},
- {'RequestedDeviceTypes': ['1','2','3','4','5','6','7','8','9',
- '10','11','12','13','14','15','16',
- '17']},
- {'RequestedDeviceTypes': dbus.Array([], signature="s")},
- {'RequestedDeviceTypes': dbus.Array([['foo']], signature="as")},
- {'RequestedDeviceTypes': dbus.Array([], signature="i")},
- {'RequestedDeviceTypes': [dbus.ByteArray('12345678'),
- dbus.ByteArray('1234567')]},
- {'Foo': dbus.Int16(1)},
- {'Foo': dbus.UInt16(1)},
- {'Foo': dbus.Int64(1)},
- {'Foo': dbus.UInt64(1)},
- {'Foo': dbus.Double(1.23)},
- {'Foo': dbus.Signature('s')},
- {'Foo': 'bar'}]
- for t in tests:
- try:
- p2p.Find(dbus.Dictionary(t))
- raise Exception("Invalid Find accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid Find(): " + str(e))
- for p in [ "/foo",
- "/fi/w1/wpa_supplicant1/Interfaces/1234",
- "/fi/w1/wpa_supplicant1/Interfaces/1234/Networks/1234" ]:
- try:
- p2p.RemovePersistentGroup(dbus.ObjectPath(p))
- raise Exception("Invalid RemovePersistentGroup accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid RemovePersistentGroup: " + str(e))
- try:
- dev[0].request("P2P_SET disabled 1")
- p2p.Listen(5)
- raise Exception("Invalid Listen accepted")
- except dbus.exceptions.DBusException, e:
- if "UnknownError: Could not start P2P listen" not in str(e):
- raise Exception("Unexpected error message for invalid Listen: " + str(e))
- finally:
- dev[0].request("P2P_SET disabled 0")
- test_obj = bus.get_object(WPAS_DBUS_SERVICE, path, introspect=False)
- test_p2p = dbus.Interface(test_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- try:
- test_p2p.Listen("foo")
- raise Exception("Invalid Listen accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid Listen: " + str(e))
- try:
- dev[0].request("P2P_SET disabled 1")
- p2p.ExtendedListen(dbus.Dictionary({}))
- raise Exception("Invalid ExtendedListen accepted")
- except dbus.exceptions.DBusException, e:
- if "UnknownError: failed to initiate a p2p_ext_listen" not in str(e):
- raise Exception("Unexpected error message for invalid ExtendedListen: " + str(e))
- finally:
- dev[0].request("P2P_SET disabled 0")
- try:
- dev[0].request("P2P_SET disabled 1")
- args = { 'duration1': 30000, 'interval1': 102400,
- 'duration2': 20000, 'interval2': 102400 }
- p2p.PresenceRequest(args)
- raise Exception("Invalid PresenceRequest accepted")
- except dbus.exceptions.DBusException, e:
- if "UnknownError: Failed to invoke presence request" not in str(e):
- raise Exception("Unexpected error message for invalid PresenceRequest: " + str(e))
- finally:
- dev[0].request("P2P_SET disabled 0")
- try:
- params = dbus.Dictionary({'frequency': dbus.Int32(-1)})
- p2p.GroupAdd(params)
- raise Exception("Invalid GroupAdd accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid GroupAdd: " + str(e))
- try:
- params = dbus.Dictionary({'persistent_group_object':
- dbus.ObjectPath(path),
- 'frequency': 2412})
- p2p.GroupAdd(params)
- raise Exception("Invalid GroupAdd accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid GroupAdd: " + str(e))
- try:
- p2p.Disconnect()
- raise Exception("Invalid Disconnect accepted")
- except dbus.exceptions.DBusException, e:
- if "UnknownError: failed to disconnect" not in str(e):
- raise Exception("Unexpected error message for invalid Disconnect: " + str(e))
- try:
- dev[0].request("P2P_SET disabled 1")
- p2p.Flush()
- raise Exception("Invalid Flush accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: P2P is not available for this interface" not in str(e):
- raise Exception("Unexpected error message for invalid Flush: " + str(e))
- finally:
- dev[0].request("P2P_SET disabled 0")
- try:
- dev[0].request("P2P_SET disabled 1")
- args = { 'peer': path,
- 'join': True,
- 'wps_method': 'pbc',
- 'frequency': 2412 }
- pin = p2p.Connect(args)
- raise Exception("Invalid Connect accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: P2P is not available for this interface" not in str(e):
- raise Exception("Unexpected error message for invalid Connect: " + str(e))
- finally:
- dev[0].request("P2P_SET disabled 0")
- tests = [ { 'frequency': dbus.Int32(-1) },
- { 'wps_method': 'pbc' },
- { 'wps_method': 'foo' } ]
- for args in tests:
- try:
- pin = p2p.Connect(args)
- raise Exception("Invalid Connect accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid Connect: " + str(e))
- try:
- dev[0].request("P2P_SET disabled 1")
- args = { 'peer': path }
- pin = p2p.Invite(args)
- raise Exception("Invalid Invite accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: P2P is not available for this interface" not in str(e):
- raise Exception("Unexpected error message for invalid Invite: " + str(e))
- finally:
- dev[0].request("P2P_SET disabled 0")
- try:
- args = { 'foo': 'bar' }
- pin = p2p.Invite(args)
- raise Exception("Invalid Invite accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid Connect: " + str(e))
- tests = [ (path, 'display', "InvalidArgs"),
- (dbus.ObjectPath(path + "/Peers/00112233445566"),
- 'display',
- "UnknownError: Failed to send provision discovery request"),
- (dbus.ObjectPath(path + "/Peers/00112233445566"),
- 'keypad',
- "UnknownError: Failed to send provision discovery request"),
- (dbus.ObjectPath(path + "/Peers/00112233445566"),
- 'pbc',
- "UnknownError: Failed to send provision discovery request"),
- (dbus.ObjectPath(path + "/Peers/00112233445566"),
- 'pushbutton',
- "UnknownError: Failed to send provision discovery request"),
- (dbus.ObjectPath(path + "/Peers/00112233445566"),
- 'foo', "InvalidArgs") ]
- for (p,method,err) in tests:
- try:
- p2p.ProvisionDiscoveryRequest(p, method)
- raise Exception("Invalid ProvisionDiscoveryRequest accepted")
- except dbus.exceptions.DBusException, e:
- if err not in str(e):
- raise Exception("Unexpected error message for invalid ProvisionDiscoveryRequest: " + str(e))
- try:
- dev[0].request("P2P_SET disabled 1")
- if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Peers",
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Get(Peers) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: P2P is not available for this interface" not in str(e):
- raise Exception("Unexpected error message for invalid Get(Peers): " + str(e))
- finally:
- dev[0].request("P2P_SET disabled 0")
- def test_dbus_p2p_oom(dev, apdev):
- """D-Bus P2P operations and OOM"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_entry_get_string_array",
- "Find", "InvalidArgs"):
- p2p.Find(dbus.Dictionary({ 'Foo': [ 'bar' ] }))
- with alloc_fail_dbus(dev[0], 2, "_wpa_dbus_dict_entry_get_string_array",
- "Find", "InvalidArgs"):
- p2p.Find(dbus.Dictionary({ 'Foo': [ 'bar' ] }))
- with alloc_fail_dbus(dev[0], 10, "_wpa_dbus_dict_entry_get_string_array",
- "Find", "InvalidArgs"):
- p2p.Find(dbus.Dictionary({ 'Foo': [ '1','2','3','4','5','6','7','8','9' ] }))
- with alloc_fail_dbus(dev[0], 1, ":=_wpa_dbus_dict_entry_get_binarray",
- "Find", "InvalidArgs"):
- p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123') ] }))
- with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_entry_get_byte_array;_wpa_dbus_dict_entry_get_binarray",
- "Find", "InvalidArgs"):
- p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123') ] }))
- with alloc_fail_dbus(dev[0], 2, "=_wpa_dbus_dict_entry_get_binarray",
- "Find", "InvalidArgs"):
- p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123'),
- dbus.ByteArray('123'),
- dbus.ByteArray('123'),
- dbus.ByteArray('123'),
- dbus.ByteArray('123'),
- dbus.ByteArray('123'),
- dbus.ByteArray('123'),
- dbus.ByteArray('123'),
- dbus.ByteArray('123'),
- dbus.ByteArray('123'),
- dbus.ByteArray('123') ] }))
- with alloc_fail_dbus(dev[0], 1, "wpabuf_alloc_ext_data;_wpa_dbus_dict_entry_get_binarray",
- "Find", "InvalidArgs"):
- p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123') ] }))
- with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_fill_value_from_variant;wpas_dbus_handler_p2p_find",
- "Find", "InvalidArgs"):
- p2p.Find(dbus.Dictionary({ 'Foo': path }))
- with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_entry_get_byte_array",
- "AddService", "InvalidArgs"):
- args = { 'service_type': 'bonjour',
- 'response': dbus.ByteArray(500*'b') }
- p2p.AddService(args)
- with alloc_fail_dbus(dev[0], 2, "_wpa_dbus_dict_entry_get_byte_array",
- "AddService", "InvalidArgs"):
- p2p.AddService(args)
- def test_dbus_p2p_discovery(dev, apdev):
- """D-Bus P2P discovery"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- addr0 = dev[0].p2p_dev_addr()
- dev[1].request("SET sec_device_type 1-0050F204-2")
- dev[1].request("VENDOR_ELEM_ADD 1 dd0c0050f2041049000411223344")
- dev[1].p2p_listen()
- addr1 = dev[1].p2p_dev_addr()
- a1 = binascii.unhexlify(addr1.replace(':',''))
- wfd_devinfo = "00001c440028"
- dev[2].request("SET wifi_display 1")
- dev[2].request("WFD_SUBELEM_SET 0 0006" + wfd_devinfo)
- wfd = binascii.unhexlify('000006' + wfd_devinfo)
- dev[2].p2p_listen()
- addr2 = dev[2].p2p_dev_addr()
- a2 = binascii.unhexlify(addr2.replace(':',''))
- res = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
- dbus_interface=dbus.PROPERTIES_IFACE)
- if 'Peers' not in res:
- raise Exception("GetAll result missing Peers")
- if len(res['Peers']) != 0:
- raise Exception("Unexpected peer(s) in the list")
- args = {'DiscoveryType': 'social',
- 'RequestedDeviceTypes': [dbus.ByteArray('12345678')],
- 'Timeout': dbus.Int32(1) }
- p2p.Find(dbus.Dictionary(args))
- p2p.StopFind()
- class TestDbusP2p(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.found = False
- self.found2 = False
- self.lost = False
- self.find_stopped = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
- "DeviceFound")
- self.add_signal(self.deviceLost, WPAS_DBUS_IFACE_P2PDEVICE,
- "DeviceLost")
- self.add_signal(self.provisionDiscoveryResponseEnterPin,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "ProvisionDiscoveryResponseEnterPin")
- self.add_signal(self.findStopped, WPAS_DBUS_IFACE_P2PDEVICE,
- "FindStopped")
- self.loop.run()
- return self
- def deviceFound(self, path):
- logger.debug("deviceFound: path=%s" % path)
- res = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Peers",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if len(res) < 1:
- raise Exception("Unexpected number of peers")
- if path not in res:
- raise Exception("Mismatch in peer object path")
- peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
- res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- logger.debug("peer properties: " + str(res))
- if res['DeviceAddress'] == a1:
- if 'SecondaryDeviceTypes' not in res:
- raise Exception("Missing SecondaryDeviceTypes")
- sec = res['SecondaryDeviceTypes']
- if len(sec) < 1:
- raise Exception("Secondary device type missing")
- if "\x00\x01\x00\x50\xF2\x04\x00\x02" not in sec:
- raise Exception("Secondary device type mismatch")
- if 'VendorExtension' not in res:
- raise Exception("Missing VendorExtension")
- vendor = res['VendorExtension']
- if len(vendor) < 1:
- raise Exception("Vendor extension missing")
- if "\x11\x22\x33\x44" not in vendor:
- raise Exception("Secondary device type mismatch")
- self.found = True
- elif res['DeviceAddress'] == a2:
- if 'IEs' not in res:
- raise Exception("IEs missing")
- if res['IEs'] != wfd:
- raise Exception("IEs mismatch")
- self.found2 = True
- else:
- raise Exception("Unexpected peer device address")
- if self.found and self.found2:
- p2p.StopFind()
- p2p.RejectPeer(path)
- p2p.ProvisionDiscoveryRequest(path, 'display')
- def deviceLost(self, path):
- logger.debug("deviceLost: path=%s" % path)
- self.lost = True
- try:
- p2p.RejectPeer(path)
- raise Exception("Invalid RejectPeer accepted")
- except dbus.exceptions.DBusException, e:
- if "UnknownError: Failed to call wpas_p2p_reject" not in str(e):
- raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
- self.loop.quit()
- def provisionDiscoveryResponseEnterPin(self, peer_object):
- logger.debug("provisionDiscoveryResponseEnterPin - peer=%s" % peer_object)
- p2p.Flush()
- def findStopped(self):
- logger.debug("findStopped")
- self.find_stopped = True
- def run_test(self, *args):
- logger.debug("run_test")
- p2p.Find(dbus.Dictionary({'DiscoveryType': 'social',
- 'Timeout': dbus.Int32(10)}))
- return False
- def success(self):
- return self.found and self.lost and self.found2 and self.find_stopped
- with TestDbusP2p(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- dev[1].request("VENDOR_ELEM_REMOVE 1 *")
- dev[1].p2p_stop_find()
- p2p.Listen(1)
- dev[2].p2p_stop_find()
- dev[2].request("P2P_FLUSH")
- if not dev[2].discover_peer(addr0):
- raise Exception("Peer not found")
- p2p.StopFind()
- dev[2].p2p_stop_find()
- try:
- p2p.ExtendedListen(dbus.Dictionary({'foo': 100}))
- raise Exception("Invalid ExtendedListen accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid ExtendedListen(): " + str(e))
- p2p.ExtendedListen(dbus.Dictionary({'period': 100, 'interval': 1000}))
- p2p.ExtendedListen(dbus.Dictionary({}))
- dev[0].global_request("P2P_EXT_LISTEN")
- def test_dbus_p2p_service_discovery(dev, apdev):
- """D-Bus P2P service discovery"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- addr0 = dev[0].p2p_dev_addr()
- addr1 = dev[1].p2p_dev_addr()
- bonjour_query = dbus.ByteArray(binascii.unhexlify('0b5f6166706f766572746370c00c000c01'))
- bonjour_response = dbus.ByteArray(binascii.unhexlify('074578616d706c65c027'))
-
- args = { 'service_type': 'bonjour',
- 'query': bonjour_query,
- 'response': bonjour_response }
- p2p.AddService(args)
- p2p.FlushService()
- p2p.AddService(args)
- try:
- p2p.DeleteService(args)
- raise Exception("Invalid DeleteService() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
- args = { 'service_type': 'bonjour',
- 'query': bonjour_query }
- p2p.DeleteService(args)
- try:
- p2p.DeleteService(args)
- raise Exception("Invalid DeleteService() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
- args = { 'service_type': 'upnp',
- 'version': 0x10,
- 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' }
- p2p.AddService(args)
- p2p.DeleteService(args)
- try:
- p2p.DeleteService(args)
- raise Exception("Invalid DeleteService() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
- tests = [ { 'service_type': 'foo' },
- { 'service_type': 'foo', 'query': bonjour_query },
- { 'service_type': 'upnp' },
- { 'service_type': 'upnp', 'version': 0x10 },
- { 'service_type': 'upnp',
- 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
- { 'version': 0x10,
- 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
- { 'service_type': 'upnp', 'foo': 'bar' },
- { 'service_type': 'bonjour' },
- { 'service_type': 'bonjour', 'query': 'foo' },
- { 'service_type': 'bonjour', 'foo': 'bar' } ]
- for args in tests:
- try:
- p2p.DeleteService(args)
- raise Exception("Invalid DeleteService() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
- tests = [ { 'service_type': 'foo' },
- { 'service_type': 'upnp' },
- { 'service_type': 'upnp', 'version': 0x10 },
- { 'service_type': 'upnp',
- 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
- { 'version': 0x10,
- 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
- { 'service_type': 'upnp', 'foo': 'bar' },
- { 'service_type': 'bonjour' },
- { 'service_type': 'bonjour', 'query': 'foo' },
- { 'service_type': 'bonjour', 'response': 'foo' },
- { 'service_type': 'bonjour', 'query': bonjour_query },
- { 'service_type': 'bonjour', 'response': bonjour_response },
- { 'service_type': 'bonjour', 'query': dbus.ByteArray(500*'a') },
- { 'service_type': 'bonjour', 'foo': 'bar' } ]
- for args in tests:
- try:
- p2p.AddService(args)
- raise Exception("Invalid AddService() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid AddService(): " + str(e))
- args = { 'tlv': dbus.ByteArray("\x02\x00\x00\x01") }
- ref = p2p.ServiceDiscoveryRequest(args)
- p2p.ServiceDiscoveryCancelRequest(ref)
- try:
- p2p.ServiceDiscoveryCancelRequest(ref)
- raise Exception("Invalid ServiceDiscoveryCancelRequest() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid AddService(): " + str(e))
- try:
- p2p.ServiceDiscoveryCancelRequest(dbus.UInt64(0))
- raise Exception("Invalid ServiceDiscoveryCancelRequest() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid AddService(): " + str(e))
- args = { 'service_type': 'upnp',
- 'version': 0x10,
- 'service': 'ssdp:foo' }
- ref = p2p.ServiceDiscoveryRequest(args)
- p2p.ServiceDiscoveryCancelRequest(ref)
- tests = [ { 'service_type': 'foo' },
- { 'foo': 'bar' },
- { 'tlv': 'foo' },
- { },
- { 'version': 0 },
- { 'service_type': 'upnp',
- 'service': 'ssdp:foo' },
- { 'service_type': 'upnp',
- 'version': 0x10 },
- { 'service_type': 'upnp',
- 'version': 0x10,
- 'service': 'ssdp:foo',
- 'peer_object': dbus.ObjectPath(path + "/Peers") },
- { 'service_type': 'upnp',
- 'version': 0x10,
- 'service': 'ssdp:foo',
- 'peer_object': path + "/Peers" },
- { 'service_type': 'upnp',
- 'version': 0x10,
- 'service': 'ssdp:foo',
- 'peer_object': dbus.ObjectPath(path + "/Peers/00112233445566") } ]
- for args in tests:
- try:
- p2p.ServiceDiscoveryRequest(args)
- raise Exception("Invalid ServiceDiscoveryRequest accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid ServiceDiscoveryRequest(): " + str(e))
- args = { 'foo': 'bar' }
- try:
- p2p.ServiceDiscoveryResponse(dbus.Dictionary(args, signature='sv'))
- raise Exception("Invalid ServiceDiscoveryResponse accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid ServiceDiscoveryResponse(): " + str(e))
- def test_dbus_p2p_service_discovery_query(dev, apdev):
- """D-Bus P2P service discovery query"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- addr0 = dev[0].p2p_dev_addr()
- dev[1].request("P2P_SERVICE_ADD bonjour 0b5f6166706f766572746370c00c000c01 074578616d706c65c027")
- dev[1].p2p_listen()
- addr1 = dev[1].p2p_dev_addr()
- class TestDbusP2p(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.done = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
- "DeviceFound")
- self.add_signal(self.serviceDiscoveryResponse,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "ServiceDiscoveryResponse", byte_arrays=True)
- self.loop.run()
- return self
- def deviceFound(self, path):
- logger.debug("deviceFound: path=%s" % path)
- args = { 'peer_object': path,
- 'tlv': dbus.ByteArray("\x02\x00\x00\x01") }
- p2p.ServiceDiscoveryRequest(args)
- def serviceDiscoveryResponse(self, sd_request):
- logger.debug("serviceDiscoveryResponse: sd_request=%s" % str(sd_request))
- self.done = True
- self.loop.quit()
- def run_test(self, *args):
- logger.debug("run_test")
- p2p.Find(dbus.Dictionary({'DiscoveryType': 'social',
- 'Timeout': dbus.Int32(10)}))
- return False
- def success(self):
- return self.done
- with TestDbusP2p(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- dev[1].p2p_stop_find()
- def test_dbus_p2p_service_discovery_external(dev, apdev):
- """D-Bus P2P service discovery with external response"""
- try:
- _test_dbus_p2p_service_discovery_external(dev, apdev)
- finally:
- dev[0].request("P2P_SERV_DISC_EXTERNAL 0")
- def _test_dbus_p2p_service_discovery_external(dev, apdev):
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- addr0 = dev[0].p2p_dev_addr()
- addr1 = dev[1].p2p_dev_addr()
- resp = "0300000101"
- dev[1].request("P2P_FLUSH")
- dev[1].request("P2P_SERV_DISC_REQ " + addr0 + " 02000001")
- dev[1].p2p_find(social=True)
- class TestDbusP2p(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.sd = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
- "DeviceFound")
- self.add_signal(self.serviceDiscoveryRequest,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "ServiceDiscoveryRequest")
- self.loop.run()
- return self
- def deviceFound(self, path):
- logger.debug("deviceFound: path=%s" % path)
- def serviceDiscoveryRequest(self, sd_request):
- logger.debug("serviceDiscoveryRequest: sd_request=%s" % str(sd_request))
- self.sd = True
- args = { 'peer_object': sd_request['peer_object'],
- 'frequency': sd_request['frequency'],
- 'dialog_token': sd_request['dialog_token'],
- 'tlvs': dbus.ByteArray(binascii.unhexlify(resp)) }
- p2p.ServiceDiscoveryResponse(dbus.Dictionary(args, signature='sv'))
- self.loop.quit()
- def run_test(self, *args):
- logger.debug("run_test")
- p2p.ServiceDiscoveryExternal(1)
- p2p.ServiceUpdate()
- p2p.Listen(15)
- return False
- def success(self):
- return self.sd
- with TestDbusP2p(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- ev = dev[1].wait_global_event(["P2P-SERV-DISC-RESP"], timeout=5)
- if ev is None:
- raise Exception("Service discovery timed out")
- if addr0 not in ev:
- raise Exception("Unexpected address in SD Response: " + ev)
- if ev.split(' ')[4] != resp:
- raise Exception("Unexpected response data SD Response: " + ev)
- dev[1].p2p_stop_find()
- p2p.StopFind()
- p2p.ServiceDiscoveryExternal(0)
- def test_dbus_p2p_autogo(dev, apdev):
- """D-Bus P2P autonomous GO"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- addr0 = dev[0].p2p_dev_addr()
- class TestDbusP2p(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.first = True
- self.waiting_end = False
- self.exceptions = False
- self.deauthorized = False
- self.done = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
- "DeviceFound")
- self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupStarted")
- self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupFinished")
- self.add_signal(self.persistentGroupAdded,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "PersistentGroupAdded")
- self.add_signal(self.persistentGroupRemoved,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "PersistentGroupRemoved")
- self.add_signal(self.provisionDiscoveryRequestDisplayPin,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "ProvisionDiscoveryRequestDisplayPin")
- self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
- "StaAuthorized")
- self.add_signal(self.staDeauthorized, WPAS_DBUS_IFACE,
- "StaDeauthorized")
- self.loop.run()
- return self
- def groupStarted(self, properties):
- logger.debug("groupStarted: " + str(properties))
- self.group = properties['group_object']
- self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
- properties['interface_object'])
- role = self.g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Role",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if role != "GO":
- self.exceptions = True
- raise Exception("Unexpected role reported: " + role)
- group = self.g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Group",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if group != properties['group_object']:
- self.exceptions = True
- raise Exception("Unexpected Group reported: " + str(group))
- go = self.g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PeerGO",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if go != '/':
- self.exceptions = True
- raise Exception("Unexpected PeerGO value: " + str(go))
- if self.first:
- self.first = False
- logger.info("Remove persistent group instance")
- group_p2p = dbus.Interface(self.g_if_obj,
- WPAS_DBUS_IFACE_P2PDEVICE)
- group_p2p.Disconnect()
- else:
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 join")
- def groupFinished(self, properties):
- logger.debug("groupFinished: " + str(properties))
- if self.waiting_end:
- logger.info("Remove persistent group")
- p2p.RemovePersistentGroup(self.persistent)
- else:
- logger.info("Re-start persistent group")
- params = dbus.Dictionary({'persistent_group_object':
- self.persistent,
- 'frequency': 2412})
- p2p.GroupAdd(params)
- def persistentGroupAdded(self, path, properties):
- logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
- self.persistent = path
- def persistentGroupRemoved(self, path):
- logger.debug("persistentGroupRemoved: %s" % path)
- self.done = True
- self.loop.quit()
- def deviceFound(self, path):
- logger.debug("deviceFound: path=%s" % path)
- peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
- self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- logger.debug('peer properties: ' + str(self.peer))
- def provisionDiscoveryRequestDisplayPin(self, peer_object, pin):
- logger.debug("provisionDiscoveryRequestDisplayPin - peer=%s pin=%s" % (peer_object, pin))
- self.peer_path = peer_object
- peer = binascii.unhexlify(peer_object.split('/')[-1])
- addr = ""
- for p in peer:
- if len(addr) > 0:
- addr += ':'
- addr += '%02x' % ord(p)
- params = { 'Role': 'registrar',
- 'P2PDeviceAddress': self.peer['DeviceAddress'],
- 'Bssid': self.peer['DeviceAddress'],
- 'Type': 'pin' }
- wps = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_WPS)
- try:
- wps.Start(params)
- self.exceptions = True
- raise Exception("Invalid WPS.Start() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- self.exceptions = True
- raise Exception("Unexpected error message: " + str(e))
- params = { 'Role': 'registrar',
- 'P2PDeviceAddress': self.peer['DeviceAddress'],
- 'Type': 'pin',
- 'Pin': '12345670' }
- logger.info("Authorize peer to connect to the group")
- wps.Start(params)
- def staAuthorized(self, name):
- logger.debug("staAuthorized: " + name)
- peer_obj = bus.get_object(WPAS_DBUS_SERVICE, self.peer_path)
- res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- logger.debug("Peer properties: " + str(res))
- if 'Groups' not in res or len(res['Groups']) != 1:
- self.exceptions = True
- raise Exception("Unexpected number of peer Groups entries")
- if res['Groups'][0] != self.group:
- self.exceptions = True
- raise Exception("Unexpected peer Groups[0] value")
- g_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group)
- res = g_obj.GetAll(WPAS_DBUS_GROUP,
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- logger.debug("Group properties: " + str(res))
- if 'Members' not in res or len(res['Members']) != 1:
- self.exceptions = True
- raise Exception("Unexpected number of group members")
- ext = dbus.ByteArray("\x11\x22\x33\x44")
- # Earlier implementation of this interface was a bit strange. The
- # property is defined to have aay signature and that is what the
- # getter returned. However, the setter expected there to be a
- # dictionary with 'WPSVendorExtensions' as the key surrounding these
- # values.. The current implementations maintains support for that
- # for backwards compability reasons. Verify that encoding first.
- vals = dbus.Dictionary({ 'WPSVendorExtensions': [ ext ]},
- signature='sv')
- g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
- dbus_interface=dbus.PROPERTIES_IFACE)
- res = g_obj.Get(WPAS_DBUS_GROUP, 'WPSVendorExtensions',
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- if len(res) != 1:
- self.exceptions = True
- raise Exception("Unexpected number of vendor extensions")
- if res[0] != ext:
- self.exceptions = True
- raise Exception("Vendor extension value changed")
- # And now verify that the more appropriate encoding is accepted as
- # well.
- res.append(dbus.ByteArray('\xaa\xbb\xcc\xdd\xee\xff'))
- g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
- dbus_interface=dbus.PROPERTIES_IFACE)
- res2 = g_obj.Get(WPAS_DBUS_GROUP, 'WPSVendorExtensions',
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- if len(res) != 2:
- self.exceptions = True
- raise Exception("Unexpected number of vendor extensions")
- if res[0] != res2[0] or res[1] != res2[1]:
- self.exceptions = True
- raise Exception("Vendor extension value changed")
- for i in range(10):
- res.append(dbus.ByteArray('\xaa\xbb'))
- try:
- g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
- dbus_interface=dbus.PROPERTIES_IFACE)
- self.exceptions = True
- raise Exception("Invalid Set(WPSVendorExtensions) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed" not in str(e):
- self.exceptions = True
- raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
- vals = dbus.Dictionary({ 'Foo': [ ext ]}, signature='sv')
- try:
- g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
- dbus_interface=dbus.PROPERTIES_IFACE)
- self.exceptions = True
- raise Exception("Invalid Set(WPSVendorExtensions) accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- self.exceptions = True
- raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
- vals = [ "foo" ]
- try:
- g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
- dbus_interface=dbus.PROPERTIES_IFACE)
- self.exceptions = True
- raise Exception("Invalid Set(WPSVendorExtensions) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed" not in str(e):
- self.exceptions = True
- raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
- vals = [ [ "foo" ] ]
- try:
- g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
- dbus_interface=dbus.PROPERTIES_IFACE)
- self.exceptions = True
- raise Exception("Invalid Set(WPSVendorExtensions) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed" not in str(e):
- self.exceptions = True
- raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
- p2p.RemoveClient({ 'peer': self.peer_path })
- self.waiting_end = True
- group_p2p = dbus.Interface(self.g_if_obj,
- WPAS_DBUS_IFACE_P2PDEVICE)
- group_p2p.Disconnect()
- def staDeauthorized(self, name):
- logger.debug("staDeauthorized: " + name)
- self.deauthorized = True
- def run_test(self, *args):
- logger.debug("run_test")
- params = dbus.Dictionary({'persistent': True,
- 'frequency': 2412})
- logger.info("Add a persistent group")
- p2p.GroupAdd(params)
- return False
- def success(self):
- return self.done and self.deauthorized and not self.exceptions
- with TestDbusP2p(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- dev[1].wait_go_ending_session()
- def test_dbus_p2p_autogo_pbc(dev, apdev):
- """D-Bus P2P autonomous GO and PBC"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- addr0 = dev[0].p2p_dev_addr()
- class TestDbusP2p(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.first = True
- self.waiting_end = False
- self.done = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
- "DeviceFound")
- self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupStarted")
- self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupFinished")
- self.add_signal(self.provisionDiscoveryPBCRequest,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "ProvisionDiscoveryPBCRequest")
- self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
- "StaAuthorized")
- self.loop.run()
- return self
- def groupStarted(self, properties):
- logger.debug("groupStarted: " + str(properties))
- self.group = properties['group_object']
- self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
- properties['interface_object'])
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- dev1.global_request("P2P_CONNECT " + addr0 + " pbc join")
- def groupFinished(self, properties):
- logger.debug("groupFinished: " + str(properties))
- self.done = True
- self.loop.quit()
- def deviceFound(self, path):
- logger.debug("deviceFound: path=%s" % path)
- peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
- self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- logger.debug('peer properties: ' + str(self.peer))
- def provisionDiscoveryPBCRequest(self, peer_object):
- logger.debug("provisionDiscoveryPBCRequest - peer=%s" % peer_object)
- self.peer_path = peer_object
- peer = binascii.unhexlify(peer_object.split('/')[-1])
- addr = ""
- for p in peer:
- if len(addr) > 0:
- addr += ':'
- addr += '%02x' % ord(p)
- params = { 'Role': 'registrar',
- 'P2PDeviceAddress': self.peer['DeviceAddress'],
- 'Type': 'pbc' }
- logger.info("Authorize peer to connect to the group")
- wps = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_WPS)
- wps.Start(params)
- def staAuthorized(self, name):
- logger.debug("staAuthorized: " + name)
- group_p2p = dbus.Interface(self.g_if_obj,
- WPAS_DBUS_IFACE_P2PDEVICE)
- group_p2p.Disconnect()
- def run_test(self, *args):
- logger.debug("run_test")
- params = dbus.Dictionary({'frequency': 2412})
- p2p.GroupAdd(params)
- return False
- def success(self):
- return self.done
- with TestDbusP2p(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- dev[1].wait_go_ending_session()
- dev[1].flush_scan_cache()
- def test_dbus_p2p_autogo_legacy(dev, apdev):
- """D-Bus P2P autonomous GO and legacy STA"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- addr0 = dev[0].p2p_dev_addr()
- class TestDbusP2p(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.done = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupStarted")
- self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupFinished")
- self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
- "StaAuthorized")
- self.loop.run()
- return self
- def groupStarted(self, properties):
- logger.debug("groupStarted: " + str(properties))
- g_obj = bus.get_object(WPAS_DBUS_SERVICE,
- properties['group_object'])
- res = g_obj.GetAll(WPAS_DBUS_GROUP,
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- bssid = ':'.join([binascii.hexlify(l) for l in res['BSSID']])
- pin = '12345670'
- params = { 'Role': 'enrollee',
- 'Type': 'pin',
- 'Pin': pin }
- g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
- properties['interface_object'])
- wps = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_WPS)
- wps.Start(params)
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- dev1.scan_for_bss(bssid, freq=2412)
- dev1.request("WPS_PIN " + bssid + " " + pin)
- self.group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- def groupFinished(self, properties):
- logger.debug("groupFinished: " + str(properties))
- self.done = True
- self.loop.quit()
- def staAuthorized(self, name):
- logger.debug("staAuthorized: " + name)
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- dev1.request("DISCONNECT")
- self.group_p2p.Disconnect()
- def run_test(self, *args):
- logger.debug("run_test")
- params = dbus.Dictionary({'frequency': 2412})
- p2p.GroupAdd(params)
- return False
- def success(self):
- return self.done
- with TestDbusP2p(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- def test_dbus_p2p_join(dev, apdev):
- """D-Bus P2P join an autonomous GO"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- addr1 = dev[1].p2p_dev_addr()
- addr2 = dev[2].p2p_dev_addr()
- dev[1].p2p_start_go(freq=2412)
- dev1_group_ifname = dev[1].group_ifname
- dev[2].p2p_listen()
- class TestDbusP2p(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.done = False
- self.peer = None
- self.go = None
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
- "DeviceFound")
- self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupStarted")
- self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupFinished")
- self.add_signal(self.invitationResult, WPAS_DBUS_IFACE_P2PDEVICE,
- "InvitationResult")
- self.loop.run()
- return self
- def deviceFound(self, path):
- logger.debug("deviceFound: path=%s" % path)
- peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
- res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- logger.debug('peer properties: ' + str(res))
- if addr2.replace(':','') in path:
- self.peer = path
- elif addr1.replace(':','') in path:
- self.go = path
- if self.peer and self.go:
- logger.info("Join the group")
- p2p.StopFind()
- args = { 'peer': self.go,
- 'join': True,
- 'wps_method': 'pin',
- 'frequency': 2412 }
- pin = p2p.Connect(args)
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- dev1.group_ifname = dev1_group_ifname
- dev1.group_request("WPS_PIN any " + pin)
- def groupStarted(self, properties):
- logger.debug("groupStarted: " + str(properties))
- g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
- properties['interface_object'])
- role = g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Role",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if role != "client":
- raise Exception("Unexpected role reported: " + role)
- group = g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Group",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if group != properties['group_object']:
- raise Exception("Unexpected Group reported: " + str(group))
- go = g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PeerGO",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if go != self.go:
- raise Exception("Unexpected PeerGO value: " + str(go))
- g_obj = bus.get_object(WPAS_DBUS_SERVICE,
- properties['group_object'])
- res = g_obj.GetAll(WPAS_DBUS_GROUP,
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- logger.debug("Group properties: " + str(res))
- ext = dbus.ByteArray("\x11\x22\x33\x44")
- try:
- # Set(WPSVendorExtensions) not allowed for P2P Client
- g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Set(WPSVendorExtensions) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: Failed to set property" not in str(e):
- raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
- group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- args = { 'duration1': 30000, 'interval1': 102400,
- 'duration2': 20000, 'interval2': 102400 }
- group_p2p.PresenceRequest(args)
- args = { 'peer': self.peer }
- group_p2p.Invite(args)
- def groupFinished(self, properties):
- logger.debug("groupFinished: " + str(properties))
- self.done = True
- self.loop.quit()
- def invitationResult(self, result):
- logger.debug("invitationResult: " + str(result))
- if result['status'] != 1:
- raise Exception("Unexpected invitation result: " + str(result))
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- dev1.group_ifname = dev1_group_ifname
- dev1.remove_group()
- def run_test(self, *args):
- logger.debug("run_test")
- p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
- return False
- def success(self):
- return self.done
- with TestDbusP2p(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- dev[2].p2p_stop_find()
- def test_dbus_p2p_invitation_received(dev, apdev):
- """D-Bus P2P and InvitationReceived"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- form(dev[0], dev[1])
- addr0 = dev[0].p2p_dev_addr()
- dev[0].p2p_listen()
- dev[0].global_request("SET persistent_reconnect 0")
- if not dev[1].discover_peer(addr0, social=True):
- raise Exception("Peer " + addr0 + " not found")
- peer = dev[1].get_peer(addr0)
- class TestDbusP2p(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.done = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.invitationReceived, WPAS_DBUS_IFACE_P2PDEVICE,
- "InvitationReceived")
- self.loop.run()
- return self
- def invitationReceived(self, result):
- logger.debug("invitationReceived: " + str(result))
- self.done = True
- self.loop.quit()
- def run_test(self, *args):
- logger.debug("run_test")
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- cmd = "P2P_INVITE persistent=" + peer['persistent'] + " peer=" + addr0
- dev1.global_request(cmd)
- return False
- def success(self):
- return self.done
- with TestDbusP2p(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- dev[0].p2p_stop_find()
- dev[1].p2p_stop_find()
- def test_dbus_p2p_config(dev, apdev):
- """D-Bus Get/Set P2PDeviceConfig"""
- try:
- _test_dbus_p2p_config(dev, apdev)
- finally:
- dev[0].request("P2P_SET ssid_postfix ")
- def _test_dbus_p2p_config(dev, apdev):
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- res = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig", res,
- dbus_interface=dbus.PROPERTIES_IFACE)
- res2 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- if len(res) != len(res2):
- raise Exception("Different number of parameters")
- for k in res:
- if res[k] != res2[k]:
- raise Exception("Parameter %s value changes" % k)
- changes = { 'SsidPostfix': 'foo',
- 'VendorExtension': [ dbus.ByteArray('\x11\x22\x33\x44') ],
- 'SecondaryDeviceTypes': [ dbus.ByteArray('\x11\x22\x33\x44\x55\x66\x77\x88') ]}
- if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
- dbus.Dictionary(changes, signature='sv'),
- dbus_interface=dbus.PROPERTIES_IFACE)
- res2 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- logger.debug("P2PDeviceConfig: " + str(res2))
- if 'VendorExtension' not in res2 or len(res2['VendorExtension']) != 1:
- raise Exception("VendorExtension does not match")
- if 'SecondaryDeviceTypes' not in res2 or len(res2['SecondaryDeviceTypes']) != 1:
- raise Exception("SecondaryDeviceType does not match")
- changes = { 'SsidPostfix': '',
- 'VendorExtension': dbus.Array([], signature="ay"),
- 'SecondaryDeviceTypes': dbus.Array([], signature="ay") }
- if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
- dbus.Dictionary(changes, signature='sv'),
- dbus_interface=dbus.PROPERTIES_IFACE)
- res3 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- logger.debug("P2PDeviceConfig: " + str(res3))
- if 'VendorExtension' in res3:
- raise Exception("VendorExtension not removed")
- if 'SecondaryDeviceTypes' in res3:
- raise Exception("SecondaryDeviceType not removed")
- try:
- dev[0].request("P2P_SET disabled 1")
- if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- raise Exception("Invalid Get(P2PDeviceConfig) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: P2P is not available for this interface" not in str(e):
- raise Exception("Unexpected error message for invalid Invite: " + str(e))
- finally:
- dev[0].request("P2P_SET disabled 0")
- try:
- dev[0].request("P2P_SET disabled 1")
- changes = { 'SsidPostfix': 'foo' }
- if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
- dbus.Dictionary(changes, signature='sv'),
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Set(P2PDeviceConfig) accepted")
- except dbus.exceptions.DBusException, e:
- if "Error.Failed: P2P is not available for this interface" not in str(e):
- raise Exception("Unexpected error message for invalid Invite: " + str(e))
- finally:
- dev[0].request("P2P_SET disabled 0")
- tests = [ { 'DeviceName': 123 },
- { 'SsidPostfix': 123 },
- { 'Foo': 'Bar' } ]
- for changes in tests:
- try:
- if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
- dbus.Dictionary(changes, signature='sv'),
- dbus_interface=dbus.PROPERTIES_IFACE)
- raise Exception("Invalid Set(P2PDeviceConfig) accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid Invite: " + str(e))
- def test_dbus_p2p_persistent(dev, apdev):
- """D-Bus P2P persistent group"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- class TestDbusP2p(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupStarted")
- self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupFinished")
- self.add_signal(self.persistentGroupAdded,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "PersistentGroupAdded")
- self.loop.run()
- return self
- def groupStarted(self, properties):
- logger.debug("groupStarted: " + str(properties))
- g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
- properties['interface_object'])
- group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- group_p2p.Disconnect()
- def groupFinished(self, properties):
- logger.debug("groupFinished: " + str(properties))
- self.loop.quit()
- def persistentGroupAdded(self, path, properties):
- logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
- self.persistent = path
- def run_test(self, *args):
- logger.debug("run_test")
- params = dbus.Dictionary({'persistent': True,
- 'frequency': 2412})
- logger.info("Add a persistent group")
- p2p.GroupAdd(params)
- return False
- def success(self):
- return True
- with TestDbusP2p(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- persistent = t.persistent
- p_obj = bus.get_object(WPAS_DBUS_SERVICE, persistent)
- res = p_obj.Get(WPAS_DBUS_PERSISTENT_GROUP, "Properties",
- dbus_interface=dbus.PROPERTIES_IFACE, byte_arrays=True)
- logger.info("Persistent group Properties: " + str(res))
- vals = dbus.Dictionary({ 'ssid': 'DIRECT-foo' }, signature='sv')
- p_obj.Set(WPAS_DBUS_PERSISTENT_GROUP, "Properties", vals,
- dbus_interface=dbus.PROPERTIES_IFACE)
- res2 = p_obj.Get(WPAS_DBUS_PERSISTENT_GROUP, "Properties",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if len(res) != len(res2):
- raise Exception("Different number of parameters")
- for k in res:
- if k != 'ssid' and res[k] != res2[k]:
- raise Exception("Parameter %s value changes" % k)
- if res2['ssid'] != '"DIRECT-foo"':
- raise Exception("Unexpected ssid")
- args = dbus.Dictionary({ 'ssid': 'DIRECT-testing',
- 'psk': '1234567890' }, signature='sv')
- group = p2p.AddPersistentGroup(args)
- groups = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PersistentGroups",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if len(groups) != 2:
- raise Exception("Unexpected number of persistent groups: " + str(groups))
- p2p.RemoveAllPersistentGroups()
- groups = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PersistentGroups",
- dbus_interface=dbus.PROPERTIES_IFACE)
- if len(groups) != 0:
- raise Exception("Unexpected number of persistent groups: " + str(groups))
- try:
- p2p.RemovePersistentGroup(persistent)
- raise Exception("Invalid RemovePersistentGroup accepted")
- except dbus.exceptions.DBusException, e:
- if "NetworkUnknown: There is no such persistent group" not in str(e):
- raise Exception("Unexpected error message for invalid RemovePersistentGroup: " + str(e))
- def test_dbus_p2p_reinvoke_persistent(dev, apdev):
- """D-Bus P2P reinvoke persistent group"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- addr0 = dev[0].p2p_dev_addr()
- class TestDbusP2p(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.first = True
- self.waiting_end = False
- self.done = False
- self.invited = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
- "DeviceFound")
- self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupStarted")
- self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupFinished")
- self.add_signal(self.persistentGroupAdded,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "PersistentGroupAdded")
- self.add_signal(self.provisionDiscoveryRequestDisplayPin,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "ProvisionDiscoveryRequestDisplayPin")
- self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
- "StaAuthorized")
- self.loop.run()
- return self
- def groupStarted(self, properties):
- logger.debug("groupStarted: " + str(properties))
- self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
- properties['interface_object'])
- if not self.invited:
- g_obj = bus.get_object(WPAS_DBUS_SERVICE,
- properties['group_object'])
- res = g_obj.GetAll(WPAS_DBUS_GROUP,
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- bssid = ':'.join([binascii.hexlify(l) for l in res['BSSID']])
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- dev1.scan_for_bss(bssid, freq=2412)
- dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 join")
- def groupFinished(self, properties):
- logger.debug("groupFinished: " + str(properties))
- if self.invited:
- self.done = True
- self.loop.quit()
- else:
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- dev1.global_request("SET persistent_reconnect 1")
- dev1.p2p_listen()
- args = { 'persistent_group_object': dbus.ObjectPath(path),
- 'peer': self.peer_path }
- try:
- pin = p2p.Invite(args)
- raise Exception("Invalid Invite accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid Invite: " + str(e))
- args = { 'persistent_group_object': self.persistent,
- 'peer': self.peer_path }
- pin = p2p.Invite(args)
- self.invited = True
- self.sta_group_ev = dev1.wait_global_event(["P2P-GROUP-STARTED"],
- timeout=15)
- if self.sta_group_ev is None:
- raise Exception("P2P-GROUP-STARTED event not seen")
- def persistentGroupAdded(self, path, properties):
- logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
- self.persistent = path
- def deviceFound(self, path):
- logger.debug("deviceFound: path=%s" % path)
- peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
- self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- def provisionDiscoveryRequestDisplayPin(self, peer_object, pin):
- logger.debug("provisionDiscoveryRequestDisplayPin - peer=%s pin=%s" % (peer_object, pin))
- self.peer_path = peer_object
- peer = binascii.unhexlify(peer_object.split('/')[-1])
- addr = ""
- for p in peer:
- if len(addr) > 0:
- addr += ':'
- addr += '%02x' % ord(p)
- params = { 'Role': 'registrar',
- 'P2PDeviceAddress': self.peer['DeviceAddress'],
- 'Bssid': self.peer['DeviceAddress'],
- 'Type': 'pin',
- 'Pin': '12345670' }
- logger.info("Authorize peer to connect to the group")
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- wps = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_WPS)
- wps.Start(params)
- self.sta_group_ev = dev1.wait_global_event(["P2P-GROUP-STARTED"],
- timeout=15)
- if self.sta_group_ev is None:
- raise Exception("P2P-GROUP-STARTED event not seen")
- def staAuthorized(self, name):
- logger.debug("staAuthorized: " + name)
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- dev1.group_form_result(self.sta_group_ev)
- dev1.remove_group()
- ev = dev1.wait_global_event(["P2P-GROUP-REMOVED"], timeout=10)
- if ev is None:
- raise Exception("Group removal timed out")
- group_p2p = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- group_p2p.Disconnect()
- def run_test(self, *args):
- logger.debug("run_test")
- params = dbus.Dictionary({'persistent': True,
- 'frequency': 2412})
- logger.info("Add a persistent group")
- p2p.GroupAdd(params)
- return False
- def success(self):
- return self.done
- with TestDbusP2p(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- def test_dbus_p2p_go_neg_rx(dev, apdev):
- """D-Bus P2P GO Negotiation receive"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- addr0 = dev[0].p2p_dev_addr()
- class TestDbusP2p(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.done = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
- "DeviceFound")
- self.add_signal(self.goNegotiationRequest,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "GONegotiationRequest",
- byte_arrays=True)
- self.add_signal(self.goNegotiationSuccess,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "GONegotiationSuccess",
- byte_arrays=True)
- self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupStarted")
- self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupFinished")
- self.loop.run()
- return self
- def deviceFound(self, path):
- logger.debug("deviceFound: path=%s" % path)
- def goNegotiationRequest(self, path, dev_passwd_id, go_intent=0):
- logger.debug("goNegotiationRequest: path=%s dev_passwd_id=%d go_intent=%d" % (path, dev_passwd_id, go_intent))
- if dev_passwd_id != 1:
- raise Exception("Unexpected dev_passwd_id=%d" % dev_passwd_id)
- args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
- 'go_intent': 15, 'persistent': False, 'frequency': 5175 }
- try:
- p2p.Connect(args)
- raise Exception("Invalid Connect accepted")
- except dbus.exceptions.DBusException, e:
- if "ConnectChannelUnsupported" not in str(e):
- raise Exception("Unexpected error message for invalid Connect: " + str(e))
- args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
- 'go_intent': 15, 'persistent': False }
- p2p.Connect(args)
- def goNegotiationSuccess(self, properties):
- logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
- def groupStarted(self, properties):
- logger.debug("groupStarted: " + str(properties))
- g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
- properties['interface_object'])
- group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- group_p2p.Disconnect()
- def groupFinished(self, properties):
- logger.debug("groupFinished: " + str(properties))
- self.done = True
- self.loop.quit()
- def run_test(self, *args):
- logger.debug("run_test")
- p2p.Listen(10)
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- if not dev1.discover_peer(addr0):
- raise Exception("Peer not found")
- dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 enter")
- return False
- def success(self):
- return self.done
- with TestDbusP2p(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- def test_dbus_p2p_go_neg_auth(dev, apdev):
- """D-Bus P2P GO Negotiation authorized"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- addr0 = dev[0].p2p_dev_addr()
- dev[1].p2p_listen()
- class TestDbusP2p(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.done = False
- self.peer_joined = False
- self.peer_disconnected = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
- "DeviceFound")
- self.add_signal(self.goNegotiationSuccess,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "GONegotiationSuccess",
- byte_arrays=True)
- self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupStarted")
- self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupFinished")
- self.add_signal(self.staDeauthorized, WPAS_DBUS_IFACE,
- "StaDeauthorized")
- self.add_signal(self.peerJoined, WPAS_DBUS_GROUP,
- "PeerJoined")
- self.add_signal(self.peerDisconnected, WPAS_DBUS_GROUP,
- "PeerDisconnected")
- self.loop.run()
- return self
- def deviceFound(self, path):
- logger.debug("deviceFound: path=%s" % path)
- args = { 'peer': path, 'wps_method': 'keypad',
- 'go_intent': 15, 'authorize_only': True }
- try:
- p2p.Connect(args)
- raise Exception("Invalid Connect accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e):
- raise Exception("Unexpected error message for invalid Connect: " + str(e))
- args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
- 'go_intent': 15, 'authorize_only': True }
- p2p.Connect(args)
- p2p.Listen(10)
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- if not dev1.discover_peer(addr0):
- raise Exception("Peer not found")
- dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=0")
- ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
- if ev is None:
- raise Exception("Group formation timed out")
- self.sta_group_ev = ev
- def goNegotiationSuccess(self, properties):
- logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
- def groupStarted(self, properties):
- logger.debug("groupStarted: " + str(properties))
- self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
- properties['interface_object'])
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- dev1.group_form_result(self.sta_group_ev)
- dev1.remove_group()
- def staDeauthorized(self, name):
- logger.debug("staDeuthorized: " + name)
- group_p2p = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- group_p2p.Disconnect()
- def peerJoined(self, peer):
- logger.debug("peerJoined: " + peer)
- self.peer_joined = True
- def peerDisconnected(self, peer):
- logger.debug("peerDisconnected: " + peer)
- self.peer_disconnected = True
- def groupFinished(self, properties):
- logger.debug("groupFinished: " + str(properties))
- self.done = True
- self.loop.quit()
- def run_test(self, *args):
- logger.debug("run_test")
- p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
- return False
- def success(self):
- return self.done and self.peer_joined and self.peer_disconnected
- with TestDbusP2p(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- def test_dbus_p2p_go_neg_init(dev, apdev):
- """D-Bus P2P GO Negotiation initiation"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- addr0 = dev[0].p2p_dev_addr()
- dev[1].p2p_listen()
- class TestDbusP2p(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.done = False
- self.peer_group_added = False
- self.peer_group_removed = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
- "DeviceFound")
- self.add_signal(self.goNegotiationSuccess,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "GONegotiationSuccess",
- byte_arrays=True)
- self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupStarted")
- self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupFinished")
- self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
- "PropertiesChanged")
- self.loop.run()
- return self
- def deviceFound(self, path):
- logger.debug("deviceFound: path=%s" % path)
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
- 'go_intent': 0 }
- p2p.Connect(args)
- ev = dev1.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
- if ev is None:
- raise Exception("Timeout while waiting for GO Neg Request")
- dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=15")
- ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
- if ev is None:
- raise Exception("Group formation timed out")
- self.sta_group_ev = ev
- def goNegotiationSuccess(self, properties):
- logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
- def groupStarted(self, properties):
- logger.debug("groupStarted: " + str(properties))
- g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
- properties['interface_object'])
- group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- group_p2p.Disconnect()
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- dev1.group_form_result(self.sta_group_ev)
- dev1.remove_group()
- def groupFinished(self, properties):
- logger.debug("groupFinished: " + str(properties))
- self.done = True
- def propertiesChanged(self, interface_name, changed_properties,
- invalidated_properties):
- logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
- if interface_name != WPAS_DBUS_P2P_PEER:
- return
- if "Groups" not in changed_properties:
- return
- if len(changed_properties["Groups"]) > 0:
- self.peer_group_added = True
- if len(changed_properties["Groups"]) == 0:
- self.peer_group_removed = True
- self.loop.quit()
- def run_test(self, *args):
- logger.debug("run_test")
- p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
- return False
- def success(self):
- return self.done and self.peer_group_added and self.peer_group_removed
- with TestDbusP2p(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- def test_dbus_p2p_group_termination_by_go(dev, apdev):
- """D-Bus P2P group removal on GO terminating the group"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- addr0 = dev[0].p2p_dev_addr()
- dev[1].p2p_listen()
- class TestDbusP2p(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.done = False
- self.peer_group_added = False
- self.peer_group_removed = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
- "DeviceFound")
- self.add_signal(self.goNegotiationSuccess,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "GONegotiationSuccess",
- byte_arrays=True)
- self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupStarted")
- self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupFinished")
- self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
- "PropertiesChanged")
- self.loop.run()
- return self
- def deviceFound(self, path):
- logger.debug("deviceFound: path=%s" % path)
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
- 'go_intent': 0 }
- p2p.Connect(args)
- ev = dev1.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
- if ev is None:
- raise Exception("Timeout while waiting for GO Neg Request")
- dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=15")
- ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
- if ev is None:
- raise Exception("Group formation timed out")
- self.sta_group_ev = ev
- def goNegotiationSuccess(self, properties):
- logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
- def groupStarted(self, properties):
- logger.debug("groupStarted: " + str(properties))
- g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
- properties['interface_object'])
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- dev1.group_form_result(self.sta_group_ev)
- dev1.remove_group()
- def groupFinished(self, properties):
- logger.debug("groupFinished: " + str(properties))
- self.done = True
- def propertiesChanged(self, interface_name, changed_properties,
- invalidated_properties):
- logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
- if interface_name != WPAS_DBUS_P2P_PEER:
- return
- if "Groups" not in changed_properties:
- return
- if len(changed_properties["Groups"]) > 0:
- self.peer_group_added = True
- if len(changed_properties["Groups"]) == 0 and self.peer_group_added:
- self.peer_group_removed = True
- self.loop.quit()
- def run_test(self, *args):
- logger.debug("run_test")
- p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
- return False
- def success(self):
- return self.done and self.peer_group_added and self.peer_group_removed
- with TestDbusP2p(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- def test_dbus_p2p_group_idle_timeout(dev, apdev):
- """D-Bus P2P group removal on idle timeout"""
- try:
- dev[0].global_request("SET p2p_group_idle 1")
- _test_dbus_p2p_group_idle_timeout(dev, apdev)
- finally:
- dev[0].global_request("SET p2p_group_idle 0")
- def _test_dbus_p2p_group_idle_timeout(dev, apdev):
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- addr0 = dev[0].p2p_dev_addr()
- dev[1].p2p_listen()
- class TestDbusP2p(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.done = False
- self.group_started = False
- self.peer_group_added = False
- self.peer_group_removed = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
- "DeviceFound")
- self.add_signal(self.goNegotiationSuccess,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "GONegotiationSuccess",
- byte_arrays=True)
- self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupStarted")
- self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupFinished")
- self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
- "PropertiesChanged")
- self.loop.run()
- return self
- def deviceFound(self, path):
- logger.debug("deviceFound: path=%s" % path)
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
- 'go_intent': 0 }
- p2p.Connect(args)
- ev = dev1.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
- if ev is None:
- raise Exception("Timeout while waiting for GO Neg Request")
- dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=15")
- ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
- if ev is None:
- raise Exception("Group formation timed out")
- self.sta_group_ev = ev
- def goNegotiationSuccess(self, properties):
- logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
- def groupStarted(self, properties):
- logger.debug("groupStarted: " + str(properties))
- self.group_started = True
- g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
- properties['interface_object'])
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- dev1.group_form_result(self.sta_group_ev)
- ifaddr = dev1.group_request("STA-FIRST").splitlines()[0]
- # Force disassociation with different reason code so that the
- # P2P Client using D-Bus does not get normal group termination event
- # from the GO.
- dev1.group_request("DEAUTHENTICATE " + ifaddr + " reason=0 test=0")
- dev1.remove_group()
- def groupFinished(self, properties):
- logger.debug("groupFinished: " + str(properties))
- self.done = True
- def propertiesChanged(self, interface_name, changed_properties,
- invalidated_properties):
- logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
- if interface_name != WPAS_DBUS_P2P_PEER:
- return
- if not self.group_started:
- return
- if "Groups" not in changed_properties:
- return
- if len(changed_properties["Groups"]) > 0:
- self.peer_group_added = True
- if len(changed_properties["Groups"]) == 0:
- self.peer_group_removed = True
- self.loop.quit()
- def run_test(self, *args):
- logger.debug("run_test")
- p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
- return False
- def success(self):
- return self.done and self.peer_group_added and self.peer_group_removed
- with TestDbusP2p(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- def test_dbus_p2p_wps_failure(dev, apdev):
- """D-Bus P2P WPS failure"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- addr0 = dev[0].p2p_dev_addr()
- class TestDbusP2p(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.wps_failed = False
- self.formation_failure = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.goNegotiationRequest,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "GONegotiationRequest",
- byte_arrays=True)
- self.add_signal(self.goNegotiationSuccess,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "GONegotiationSuccess",
- byte_arrays=True)
- self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupStarted")
- self.add_signal(self.wpsFailed, WPAS_DBUS_IFACE_P2PDEVICE,
- "WpsFailed")
- self.add_signal(self.groupFormationFailure,
- WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupFormationFailure")
- self.loop.run()
- return self
- def goNegotiationRequest(self, path, dev_passwd_id, go_intent=0):
- logger.debug("goNegotiationRequest: path=%s dev_passwd_id=%d go_intent=%d" % (path, dev_passwd_id, go_intent))
- if dev_passwd_id != 1:
- raise Exception("Unexpected dev_passwd_id=%d" % dev_passwd_id)
- args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
- 'go_intent': 15 }
- p2p.Connect(args)
- def goNegotiationSuccess(self, properties):
- logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
- def groupStarted(self, properties):
- logger.debug("groupStarted: " + str(properties))
- raise Exception("Unexpected GroupStarted")
- def wpsFailed(self, name, args):
- logger.debug("wpsFailed - name=%s args=%s" % (name, str(args)))
- self.wps_failed = True
- if self.formation_failure:
- self.loop.quit()
- def groupFormationFailure(self, reason):
- logger.debug("groupFormationFailure - reason=%s" % reason)
- self.formation_failure = True
- if self.wps_failed:
- self.loop.quit()
- def run_test(self, *args):
- logger.debug("run_test")
- p2p.Listen(10)
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- if not dev1.discover_peer(addr0):
- raise Exception("Peer not found")
- dev1.global_request("P2P_CONNECT " + addr0 + " 87654321 enter")
- return False
- def success(self):
- return self.wps_failed and self.formation_failure
- with TestDbusP2p(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- def test_dbus_p2p_two_groups(dev, apdev):
- """D-Bus P2P with two concurrent groups"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- dev[0].request("SET p2p_no_group_iface 0")
- addr0 = dev[0].p2p_dev_addr()
- addr1 = dev[1].p2p_dev_addr()
- addr2 = dev[2].p2p_dev_addr()
- dev[1].p2p_start_go(freq=2412)
- dev1_group_ifname = dev[1].group_ifname
- class TestDbusP2p(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.done = False
- self.peer = None
- self.go = None
- self.group1 = None
- self.group2 = None
- self.groups_removed = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
- "PropertiesChanged", byte_arrays=True)
- self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
- "DeviceFound")
- self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupStarted")
- self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
- "GroupFinished")
- self.add_signal(self.peerJoined, WPAS_DBUS_GROUP,
- "PeerJoined")
- self.loop.run()
- return self
- def propertiesChanged(self, interface_name, changed_properties,
- invalidated_properties):
- logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
- def deviceFound(self, path):
- logger.debug("deviceFound: path=%s" % path)
- if addr2.replace(':','') in path:
- self.peer = path
- elif addr1.replace(':','') in path:
- self.go = path
- if self.go and not self.group1:
- logger.info("Join the group")
- p2p.StopFind()
- pin = '12345670'
- dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
- dev1.group_ifname = dev1_group_ifname
- dev1.group_request("WPS_PIN any " + pin)
- args = { 'peer': self.go,
- 'join': True,
- 'wps_method': 'pin',
- 'pin': pin,
- 'frequency': 2412 }
- p2p.Connect(args)
- def groupStarted(self, properties):
- logger.debug("groupStarted: " + str(properties))
- prop = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
- dbus_interface=dbus.PROPERTIES_IFACE)
- logger.debug("p2pdevice properties: " + str(prop))
- g_obj = bus.get_object(WPAS_DBUS_SERVICE,
- properties['group_object'])
- res = g_obj.GetAll(WPAS_DBUS_GROUP,
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- logger.debug("Group properties: " + str(res))
- if not self.group1:
- self.group1 = properties['group_object']
- self.group1iface = properties['interface_object']
- self.g1_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
- self.group1iface)
- logger.info("Start autonomous GO")
- params = dbus.Dictionary({ 'frequency': 2412 })
- p2p.GroupAdd(params)
- elif not self.group2:
- self.group2 = properties['group_object']
- self.group2iface = properties['interface_object']
- self.g2_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
- self.group2iface)
- self.g2_bssid = res['BSSID']
- if self.group1 and self.group2:
- logger.info("Authorize peer to join the group")
- a2 = binascii.unhexlify(addr2.replace(':',''))
- params = { 'Role': 'enrollee',
- 'P2PDeviceAddress': dbus.ByteArray(a2),
- 'Bssid': dbus.ByteArray(a2),
- 'Type': 'pin',
- 'Pin': '12345670' }
- g_wps = dbus.Interface(self.g2_if_obj, WPAS_DBUS_IFACE_WPS)
- g_wps.Start(params)
- bssid = ':'.join([binascii.hexlify(l) for l in self.g2_bssid])
- dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2')
- dev2.scan_for_bss(bssid, freq=2412)
- dev2.global_request("P2P_CONNECT " + bssid + " 12345670 join freq=2412")
- ev = dev2.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
- if ev is None:
- raise Exception("Group join timed out")
- self.dev2_group_ev = ev
- def groupFinished(self, properties):
- logger.debug("groupFinished: " + str(properties))
- if self.group1 == properties['group_object']:
- self.group1 = None
- elif self.group2 == properties['group_object']:
- self.group2 = None
- if not self.group1 and not self.group2:
- self.done = True
- self.loop.quit()
- def peerJoined(self, peer):
- logger.debug("peerJoined: " + peer)
- if self.groups_removed:
- return
- self.check_results()
- dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2')
- dev2.group_form_result(self.dev2_group_ev)
- dev2.remove_group()
- logger.info("Disconnect group2")
- group_p2p = dbus.Interface(self.g2_if_obj,
- WPAS_DBUS_IFACE_P2PDEVICE)
- group_p2p.Disconnect()
- logger.info("Disconnect group1")
- group_p2p = dbus.Interface(self.g1_if_obj,
- WPAS_DBUS_IFACE_P2PDEVICE)
- group_p2p.Disconnect()
- self.groups_removed = True
- def check_results(self):
- logger.info("Check results with two concurrent groups in operation")
- g1_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group1)
- res1 = g1_obj.GetAll(WPAS_DBUS_GROUP,
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- g2_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group2)
- res2 = g2_obj.GetAll(WPAS_DBUS_GROUP,
- dbus_interface=dbus.PROPERTIES_IFACE,
- byte_arrays=True)
- logger.info("group1 = " + self.group1)
- logger.debug("Group properties: " + str(res1))
- logger.info("group2 = " + self.group2)
- logger.debug("Group properties: " + str(res2))
- prop = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
- dbus_interface=dbus.PROPERTIES_IFACE)
- logger.debug("p2pdevice properties: " + str(prop))
- if res1['Role'] != 'client':
- raise Exception("Group1 role reported incorrectly: " + res1['Role'])
- if res2['Role'] != 'GO':
- raise Exception("Group2 role reported incorrectly: " + res2['Role'])
- if prop['Role'] != 'device':
- raise Exception("p2pdevice role reported incorrectly: " + prop['Role'])
- if len(res2['Members']) != 1:
- raise Exception("Unexpected Members value for group 2")
- def run_test(self, *args):
- logger.debug("run_test")
- p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
- return False
- def success(self):
- return self.done
- with TestDbusP2p(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- dev[1].remove_group()
- def test_dbus_p2p_cancel(dev, apdev):
- """D-Bus P2P Cancel"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
- try:
- p2p.Cancel()
- raise Exception("Unexpected p2p.Cancel() success")
- except dbus.exceptions.DBusException, e:
- pass
- addr0 = dev[0].p2p_dev_addr()
- dev[1].p2p_listen()
- class TestDbusP2p(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.done = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_test)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
- "DeviceFound")
- self.loop.run()
- return self
- def deviceFound(self, path):
- logger.debug("deviceFound: path=%s" % path)
- args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
- 'go_intent': 0 }
- p2p.Connect(args)
- p2p.Cancel()
- self.done = True
- self.loop.quit()
- def run_test(self, *args):
- logger.debug("run_test")
- p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
- return False
- def success(self):
- return self.done
- with TestDbusP2p(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- def test_dbus_introspect(dev, apdev):
- """D-Bus introspection"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- res = if_obj.Introspect(WPAS_DBUS_IFACE,
- dbus_interface=dbus.INTROSPECTABLE_IFACE)
- logger.info("Initial Introspect: " + str(res))
- if res is None or "Introspectable" not in res or "GroupStarted" not in res:
- raise Exception("Unexpected initial Introspect response: " + str(res))
- if "FastReauth" not in res or "PassiveScan" not in res:
- raise Exception("Unexpected initial Introspect response: " + str(res))
- with alloc_fail(dev[0], 1, "wpa_dbus_introspect"):
- res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
- dbus_interface=dbus.INTROSPECTABLE_IFACE)
- logger.info("Introspect: " + str(res2))
- if res2 is not None:
- raise Exception("Unexpected Introspect response")
- with alloc_fail(dev[0], 1, "=add_interface;wpa_dbus_introspect"):
- res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
- dbus_interface=dbus.INTROSPECTABLE_IFACE)
- logger.info("Introspect: " + str(res2))
- if res2 is None:
- raise Exception("No Introspect response")
- if len(res2) >= len(res):
- raise Exception("Unexpected Introspect response")
- with alloc_fail(dev[0], 1, "wpabuf_alloc;add_interface;wpa_dbus_introspect"):
- res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
- dbus_interface=dbus.INTROSPECTABLE_IFACE)
- logger.info("Introspect: " + str(res2))
- if res2 is None:
- raise Exception("No Introspect response")
- if len(res2) >= len(res):
- raise Exception("Unexpected Introspect response")
- with alloc_fail(dev[0], 2, "=add_interface;wpa_dbus_introspect"):
- res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
- dbus_interface=dbus.INTROSPECTABLE_IFACE)
- logger.info("Introspect: " + str(res2))
- if res2 is None:
- raise Exception("No Introspect response")
- if len(res2) >= len(res):
- raise Exception("Unexpected Introspect response")
- def test_dbus_ap(dev, apdev):
- """D-Bus AddNetwork for AP mode"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- ssid = "test-wpa2-psk"
- passphrase = 'qwertyuiop'
- class TestDbusConnect(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.started = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_connect)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.networkAdded, WPAS_DBUS_IFACE, "NetworkAdded")
- self.add_signal(self.networkSelected, WPAS_DBUS_IFACE,
- "NetworkSelected")
- self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
- "PropertiesChanged")
- self.loop.run()
- return self
- def networkAdded(self, network, properties):
- logger.debug("networkAdded: %s" % str(network))
- logger.debug(str(properties))
- def networkSelected(self, network):
- logger.debug("networkSelected: %s" % str(network))
- self.network_selected = True
- def propertiesChanged(self, properties):
- logger.debug("propertiesChanged: %s" % str(properties))
- if 'State' in properties and properties['State'] == "completed":
- self.started = True
- self.loop.quit()
- def run_connect(self, *args):
- logger.debug("run_connect")
- args = dbus.Dictionary({ 'ssid': ssid,
- 'key_mgmt': 'WPA-PSK',
- 'psk': passphrase,
- 'mode': 2,
- 'frequency': 2412 },
- signature='sv')
- self.netw = iface.AddNetwork(args)
- iface.SelectNetwork(self.netw)
- return False
- def success(self):
- return self.started
- with TestDbusConnect(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- dev[1].connect(ssid, psk=passphrase, scan_freq="2412")
- def test_dbus_connect_wpa_eap(dev, apdev):
- """D-Bus AddNetwork and connection with WPA+WPA2-Enterprise AP"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- ssid = "test-wpa-eap"
- params = hostapd.wpa_eap_params(ssid=ssid)
- params["wpa"] = "3"
- params["rsn_pairwise"] = "CCMP"
- hapd = hostapd.add_ap(apdev[0]['ifname'], params)
- class TestDbusConnect(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.done = False
- def __enter__(self):
- gobject.timeout_add(1, self.run_connect)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
- "PropertiesChanged")
- self.add_signal(self.eap, WPAS_DBUS_IFACE, "EAP")
- self.loop.run()
- return self
- def propertiesChanged(self, properties):
- logger.debug("propertiesChanged: %s" % str(properties))
- if 'State' in properties and properties['State'] == "completed":
- self.done = True
- self.loop.quit()
- def eap(self, status, parameter):
- logger.debug("EAP: status=%s parameter=%s" % (status, parameter))
- def run_connect(self, *args):
- logger.debug("run_connect")
- args = dbus.Dictionary({ 'ssid': ssid,
- 'key_mgmt': 'WPA-EAP',
- 'eap': 'PEAP',
- 'identity': 'user',
- 'password': 'password',
- 'ca_cert': 'auth_serv/ca.pem',
- 'phase2': 'auth=MSCHAPV2',
- 'scan_freq': 2412 },
- signature='sv')
- self.netw = iface.AddNetwork(args)
- iface.SelectNetwork(self.netw)
- return False
- def success(self):
- return self.done
- with TestDbusConnect(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
- def test_dbus_ap_scan_2_ap_mode_scan(dev, apdev):
- """AP_SCAN 2 AP mode and D-Bus Scan()"""
- try:
- _test_dbus_ap_scan_2_ap_mode_scan(dev, apdev)
- finally:
- dev[0].request("AP_SCAN 1")
- def _test_dbus_ap_scan_2_ap_mode_scan(dev, apdev):
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- if "OK" not in dev[0].request("AP_SCAN 2"):
- raise Exception("Failed to set AP_SCAN 2")
- id = dev[0].add_network()
- dev[0].set_network(id, "mode", "2")
- dev[0].set_network_quoted(id, "ssid", "wpas-ap-open")
- dev[0].set_network(id, "key_mgmt", "NONE")
- dev[0].set_network(id, "frequency", "2412")
- dev[0].set_network(id, "scan_freq", "2412")
- dev[0].set_network(id, "disabled", "0")
- dev[0].select_network(id)
- ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=5)
- if ev is None:
- raise Exception("AP failed to start")
- with fail_test(dev[0], 1, "wpa_driver_nl80211_scan"):
- iface.Scan({'Type': 'active',
- 'AllowRoam': True,
- 'Channels': [(dbus.UInt32(2412), dbus.UInt32(20))]})
- ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED",
- "AP-DISABLED"], timeout=5)
- if ev is None:
- raise Exception("CTRL-EVENT-SCAN-FAILED not seen")
- if "AP-DISABLED" in ev:
- raise Exception("Unexpected AP-DISABLED event")
- if "retry=1" in ev:
- # Wait for the retry to scan happen
- ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED",
- "AP-DISABLED"], timeout=5)
- if ev is None:
- raise Exception("CTRL-EVENT-SCAN-FAILED not seen - retry")
- if "AP-DISABLED" in ev:
- raise Exception("Unexpected AP-DISABLED event - retry")
- dev[1].connect("wpas-ap-open", key_mgmt="NONE", scan_freq="2412")
- dev[1].request("DISCONNECT")
- dev[1].wait_disconnected()
- dev[0].request("DISCONNECT")
- dev[0].wait_disconnected()
- def test_dbus_expectdisconnect(dev, apdev):
- """D-Bus ExpectDisconnect"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- wpas = dbus.Interface(wpas_obj, WPAS_DBUS_SERVICE)
- params = { "ssid": "test-open" }
- hapd = hostapd.add_ap(apdev[0]['ifname'], params)
- dev[0].connect("test-open", key_mgmt="NONE", scan_freq="2412")
- # This does not really verify the behavior other than by going through the
- # code path for additional coverage.
- wpas.ExpectDisconnect()
- dev[0].request("DISCONNECT")
- dev[0].wait_disconnected()
- def test_dbus_save_config(dev, apdev):
- """D-Bus SaveConfig"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- try:
- iface.SaveConfig()
- raise Exception("SaveConfig() accepted unexpectedly")
- except dbus.exceptions.DBusException, e:
- if not str(e).startswith("fi.w1.wpa_supplicant1.UnknownError: Not allowed to update configuration"):
- raise Exception("Unexpected error message for SaveConfig(): " + str(e))
- def test_dbus_vendor_elem(dev, apdev):
- """D-Bus vendor element operations"""
- try:
- _test_dbus_vendor_elem(dev, apdev)
- finally:
- dev[0].request("VENDOR_ELEM_REMOVE 1 *")
- def _test_dbus_vendor_elem(dev, apdev):
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- dev[0].request("VENDOR_ELEM_REMOVE 1 *")
- try:
- ie = dbus.ByteArray("\x00\x00")
- iface.VendorElemAdd(-1, ie)
- raise Exception("Invalid VendorElemAdd() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e) or "Invalid ID" not in str(e):
- raise Exception("Unexpected error message for invalid VendorElemAdd[1]: " + str(e))
- try:
- ie = dbus.ByteArray("")
- iface.VendorElemAdd(1, ie)
- raise Exception("Invalid VendorElemAdd() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e) or "Invalid value" not in str(e):
- raise Exception("Unexpected error message for invalid VendorElemAdd[2]: " + str(e))
- try:
- ie = dbus.ByteArray("\x00\x01")
- iface.VendorElemAdd(1, ie)
- raise Exception("Invalid VendorElemAdd() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e) or "Parse error" not in str(e):
- raise Exception("Unexpected error message for invalid VendorElemAdd[3]: " + str(e))
- try:
- iface.VendorElemGet(-1)
- raise Exception("Invalid VendorElemGet() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e) or "Invalid ID" not in str(e):
- raise Exception("Unexpected error message for invalid VendorElemGet[1]: " + str(e))
- try:
- iface.VendorElemGet(1)
- raise Exception("Invalid VendorElemGet() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e) or "ID value does not exist" not in str(e):
- raise Exception("Unexpected error message for invalid VendorElemGet[2]: " + str(e))
- try:
- ie = dbus.ByteArray("\x00\x00")
- iface.VendorElemRem(-1, ie)
- raise Exception("Invalid VendorElemRemove() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e) or "Invalid ID" not in str(e):
- raise Exception("Unexpected error message for invalid VendorElemRemove[1]: " + str(e))
- try:
- ie = dbus.ByteArray("")
- iface.VendorElemRem(1, ie)
- raise Exception("Invalid VendorElemRemove() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e) or "Invalid value" not in str(e):
- raise Exception("Unexpected error message for invalid VendorElemRemove[1]: " + str(e))
- iface.VendorElemRem(1, "*")
- ie = dbus.ByteArray("\x00\x01\x00")
- iface.VendorElemAdd(1, ie)
- val = iface.VendorElemGet(1)
- if len(val) != len(ie):
- raise Exception("Unexpected VendorElemGet length")
- for i in range(len(val)):
- if val[i] != dbus.Byte(ie[i]):
- raise Exception("Unexpected VendorElemGet data")
- ie2 = dbus.ByteArray("\xe0\x00")
- iface.VendorElemAdd(1, ie2)
- ies = ie + ie2
- val = iface.VendorElemGet(1)
- if len(val) != len(ies):
- raise Exception("Unexpected VendorElemGet length[2]")
- for i in range(len(val)):
- if val[i] != dbus.Byte(ies[i]):
- raise Exception("Unexpected VendorElemGet data[2]")
- try:
- test_ie = dbus.ByteArray("\x01\x01")
- iface.VendorElemRem(1, test_ie)
- raise Exception("Invalid VendorElemRemove() accepted")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e) or "Parse error" not in str(e):
- raise Exception("Unexpected error message for invalid VendorElemRemove[1]: " + str(e))
- iface.VendorElemRem(1, ie)
- val = iface.VendorElemGet(1)
- if len(val) != len(ie2):
- raise Exception("Unexpected VendorElemGet length[3]")
- iface.VendorElemRem(1, "*")
- try:
- iface.VendorElemGet(1)
- raise Exception("Invalid VendorElemGet() accepted after removal")
- except dbus.exceptions.DBusException, e:
- if "InvalidArgs" not in str(e) or "ID value does not exist" not in str(e):
- raise Exception("Unexpected error message for invalid VendorElemGet after removal: " + str(e))
- def test_dbus_assoc_reject(dev, apdev):
- """D-Bus AssocStatusCode"""
- (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
- iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
- ssid = "test-open"
- params = { "ssid": ssid,
- "max_listen_interval": "1" }
- hapd = hostapd.add_ap(apdev[0]['ifname'], params)
- class TestDbusConnect(TestDbus):
- def __init__(self, bus):
- TestDbus.__init__(self, bus)
- self.assoc_status_seen = False
- self.state = 0
- def __enter__(self):
- gobject.timeout_add(1, self.run_connect)
- gobject.timeout_add(15000, self.timeout)
- self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
- "PropertiesChanged")
- self.loop.run()
- return self
- def propertiesChanged(self, properties):
- logger.debug("propertiesChanged: %s" % str(properties))
- if 'AssocStatusCode' in properties:
- status = properties['AssocStatusCode']
- if status != 51:
- logger.info("Unexpected status code: " + str(status))
- else:
- self.assoc_status_seen = True
- iface.Disconnect()
- self.loop.quit()
- def run_connect(self, *args):
- args = dbus.Dictionary({ 'ssid': ssid,
- 'key_mgmt': 'NONE',
- 'scan_freq': 2412 },
- signature='sv')
- self.netw = iface.AddNetwork(args)
- iface.SelectNetwork(self.netw)
- return False
- def success(self):
- return self.assoc_status_seen
- with TestDbusConnect(bus) as t:
- if not t.success():
- raise Exception("Expected signals not seen")
|