test_dbus.py 208 KB

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