test_dbus.py 212 KB

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