test_dbus.py 222 KB

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