test_dbus.py 224 KB

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