test_dbus.py 220 KB

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