test_dbus.py 201 KB

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