test_dbus.py 198 KB

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