test_dbus.py 215 KB

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