test_dbus.py 203 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918
  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. id = int(dev[0].list_networks()[0]['id'])
  1297. val = dev[0].get_network(id, "scan_freq")
  1298. if val != "2412":
  1299. raise Exception("Invalid scan_freq value: " + str(val))
  1300. iface.RemoveNetwork(netw)
  1301. args = dbus.Dictionary({ 'ssid': "foo",
  1302. 'key_mgmt': 'NONE',
  1303. 'scan_freq': "2412 2432",
  1304. 'freq_list': "2412 2417 2432" },
  1305. signature='sv')
  1306. netw = iface.AddNetwork(args)
  1307. id = int(dev[0].list_networks()[0]['id'])
  1308. val = dev[0].get_network(id, "scan_freq")
  1309. if val != "2412 2432":
  1310. raise Exception("Invalid scan_freq value (2): " + str(val))
  1311. val = dev[0].get_network(id, "freq_list")
  1312. if val != "2412 2417 2432":
  1313. raise Exception("Invalid freq_list value: " + str(val))
  1314. iface.RemoveNetwork(netw)
  1315. try:
  1316. iface.RemoveNetwork(netw)
  1317. raise Exception("Invalid RemoveNetwork() accepted")
  1318. except dbus.exceptions.DBusException, e:
  1319. if "NetworkUnknown" not in str(e):
  1320. raise Exception("Unexpected error message for invalid RemoveNetwork: " + str(e))
  1321. try:
  1322. iface.SelectNetwork(netw)
  1323. raise Exception("Invalid SelectNetwork() accepted")
  1324. except dbus.exceptions.DBusException, e:
  1325. if "NetworkUnknown" not in str(e):
  1326. raise Exception("Unexpected error message for invalid RemoveNetwork: " + str(e))
  1327. args = dbus.Dictionary({ 'ssid': "foo1", 'key_mgmt': 'NONE',
  1328. 'identity': "testuser", 'scan_freq': '2412' },
  1329. signature='sv')
  1330. netw1 = iface.AddNetwork(args)
  1331. args = dbus.Dictionary({ 'ssid': "foo2", 'key_mgmt': 'NONE' },
  1332. signature='sv')
  1333. netw2 = iface.AddNetwork(args)
  1334. res = if_obj.Get(WPAS_DBUS_IFACE, "Networks",
  1335. dbus_interface=dbus.PROPERTIES_IFACE)
  1336. if len(res) != 2:
  1337. raise Exception("Unexpected number of networks")
  1338. net_obj = bus.get_object(WPAS_DBUS_SERVICE, netw1)
  1339. res = net_obj.Get(WPAS_DBUS_NETWORK, "Enabled",
  1340. dbus_interface=dbus.PROPERTIES_IFACE)
  1341. if res != False:
  1342. raise Exception("Added network was unexpectedly enabled by default")
  1343. net_obj.Set(WPAS_DBUS_NETWORK, "Enabled", dbus.Boolean(True),
  1344. dbus_interface=dbus.PROPERTIES_IFACE)
  1345. res = net_obj.Get(WPAS_DBUS_NETWORK, "Enabled",
  1346. dbus_interface=dbus.PROPERTIES_IFACE)
  1347. if res != True:
  1348. raise Exception("Set(Enabled,True) did not seem to change property value")
  1349. net_obj.Set(WPAS_DBUS_NETWORK, "Enabled", dbus.Boolean(False),
  1350. dbus_interface=dbus.PROPERTIES_IFACE)
  1351. res = net_obj.Get(WPAS_DBUS_NETWORK, "Enabled",
  1352. dbus_interface=dbus.PROPERTIES_IFACE)
  1353. if res != False:
  1354. raise Exception("Set(Enabled,False) did not seem to change property value")
  1355. try:
  1356. net_obj.Set(WPAS_DBUS_NETWORK, "Enabled", dbus.UInt32(1),
  1357. dbus_interface=dbus.PROPERTIES_IFACE)
  1358. raise Exception("Invalid Set(Enabled,1) accepted")
  1359. except dbus.exceptions.DBusException, e:
  1360. if "Error.Failed: wrong property type" not in str(e):
  1361. raise Exception("Unexpected error message for invalid Set(Enabled,1): " + str(e))
  1362. args = dbus.Dictionary({ 'ssid': "foo1new" }, signature='sv')
  1363. net_obj.Set(WPAS_DBUS_NETWORK, "Properties", args,
  1364. dbus_interface=dbus.PROPERTIES_IFACE)
  1365. res = net_obj.Get(WPAS_DBUS_NETWORK, "Properties",
  1366. dbus_interface=dbus.PROPERTIES_IFACE)
  1367. if res['ssid'] != '"foo1new"':
  1368. raise Exception("Set(Properties) failed to update ssid")
  1369. if res['identity'] != '"testuser"':
  1370. raise Exception("Set(Properties) unexpectedly changed unrelated parameter")
  1371. iface.RemoveAllNetworks()
  1372. res = if_obj.Get(WPAS_DBUS_IFACE, "Networks",
  1373. dbus_interface=dbus.PROPERTIES_IFACE)
  1374. if len(res) != 0:
  1375. raise Exception("Unexpected number of networks")
  1376. iface.RemoveAllNetworks()
  1377. tests = [ dbus.Dictionary({ 'psk': "1234567" }, signature='sv'),
  1378. dbus.Dictionary({ 'identity': dbus.ByteArray() },
  1379. signature='sv'),
  1380. dbus.Dictionary({ 'identity': dbus.Byte(1) }, signature='sv'),
  1381. dbus.Dictionary({ 'identity': "" }, signature='sv') ]
  1382. for args in tests:
  1383. try:
  1384. iface.AddNetwork(args)
  1385. raise Exception("Invalid AddNetwork args accepted: " + str(args))
  1386. except dbus.exceptions.DBusException, e:
  1387. if "InvalidArgs" not in str(e):
  1388. raise Exception("Unexpected error message for invalid AddNetwork: " + str(e))
  1389. def test_dbus_network_oom(dev, apdev):
  1390. """D-Bus AddNetwork/RemoveNetwork parameters and OOM error cases"""
  1391. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1392. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1393. args = dbus.Dictionary({ 'ssid': "foo1", 'key_mgmt': 'NONE',
  1394. 'identity': "testuser", 'scan_freq': '2412' },
  1395. signature='sv')
  1396. netw1 = iface.AddNetwork(args)
  1397. net_obj = bus.get_object(WPAS_DBUS_SERVICE, netw1)
  1398. with alloc_fail_dbus(dev[0], 1,
  1399. "wpa_config_get_all;wpas_dbus_getter_network_properties",
  1400. "Get"):
  1401. net_obj.Get(WPAS_DBUS_NETWORK, "Properties",
  1402. dbus_interface=dbus.PROPERTIES_IFACE)
  1403. iface.RemoveAllNetworks()
  1404. with alloc_fail_dbus(dev[0], 1,
  1405. "wpas_dbus_new_decompose_object_path;wpas_dbus_handler_remove_network",
  1406. "RemoveNetwork", "InvalidArgs"):
  1407. iface.RemoveNetwork(dbus.ObjectPath("/fi/w1/wpa_supplicant1/Interfaces/1234/Networks/1234"))
  1408. with alloc_fail(dev[0], 1, "wpa_dbus_register_object_per_iface;wpas_dbus_register_network"):
  1409. args = dbus.Dictionary({ 'ssid': "foo2", 'key_mgmt': 'NONE' },
  1410. signature='sv')
  1411. try:
  1412. netw = iface.AddNetwork(args)
  1413. # Currently, AddNetwork() succeeds even if os_strdup() for path
  1414. # fails, so remove the network if that occurs.
  1415. iface.RemoveNetwork(netw)
  1416. except dbus.exceptions.DBusException, e:
  1417. pass
  1418. for i in range(1, 3):
  1419. with alloc_fail(dev[0], i, "=wpas_dbus_register_network"):
  1420. try:
  1421. netw = iface.AddNetwork(args)
  1422. # Currently, AddNetwork() succeeds even if network registration
  1423. # fails, so remove the network if that occurs.
  1424. iface.RemoveNetwork(netw)
  1425. except dbus.exceptions.DBusException, e:
  1426. pass
  1427. with alloc_fail_dbus(dev[0], 1,
  1428. "=wpa_config_add_network;wpas_dbus_handler_add_network",
  1429. "AddNetwork",
  1430. "UnknownError: wpa_supplicant could not add a network"):
  1431. args = dbus.Dictionary({ 'ssid': "foo2", 'key_mgmt': 'NONE' },
  1432. signature='sv')
  1433. netw = iface.AddNetwork(args)
  1434. tests = [ (1,
  1435. 'wpa_dbus_dict_get_entry;set_network_properties;wpas_dbus_handler_add_network',
  1436. dbus.Dictionary({ 'ssid': dbus.ByteArray(' ') },
  1437. signature='sv')),
  1438. (1, '=set_network_properties;wpas_dbus_handler_add_network',
  1439. dbus.Dictionary({ 'ssid': 'foo' }, signature='sv')),
  1440. (1, '=set_network_properties;wpas_dbus_handler_add_network',
  1441. dbus.Dictionary({ 'eap': 'foo' }, signature='sv')),
  1442. (1, '=set_network_properties;wpas_dbus_handler_add_network',
  1443. dbus.Dictionary({ 'priority': dbus.UInt32(1) },
  1444. signature='sv')),
  1445. (1, '=set_network_properties;wpas_dbus_handler_add_network',
  1446. dbus.Dictionary({ 'priority': dbus.Int32(1) },
  1447. signature='sv')),
  1448. (1, '=set_network_properties;wpas_dbus_handler_add_network',
  1449. dbus.Dictionary({ 'ssid': dbus.ByteArray(' ') },
  1450. signature='sv')) ]
  1451. for (count,funcs,args) in tests:
  1452. with alloc_fail_dbus(dev[0], count, funcs, "AddNetwork", "InvalidArgs"):
  1453. netw = iface.AddNetwork(args)
  1454. if len(if_obj.Get(WPAS_DBUS_IFACE, 'Networks',
  1455. dbus_interface=dbus.PROPERTIES_IFACE)) > 0:
  1456. raise Exception("Unexpected network block added")
  1457. if len(dev[0].list_networks()) > 0:
  1458. raise Exception("Unexpected network block visible")
  1459. def test_dbus_interface(dev, apdev):
  1460. """D-Bus CreateInterface/GetInterface/RemoveInterface parameters and error cases"""
  1461. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1462. wpas = dbus.Interface(wpas_obj, WPAS_DBUS_SERVICE)
  1463. params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none' },
  1464. signature='sv')
  1465. path = wpas.CreateInterface(params)
  1466. logger.debug("New interface path: " + str(path))
  1467. path2 = wpas.GetInterface("lo")
  1468. if path != path2:
  1469. raise Exception("Interface object mismatch")
  1470. params = dbus.Dictionary({ 'Ifname': 'lo',
  1471. 'Driver': 'none',
  1472. 'ConfigFile': 'foo',
  1473. 'BridgeIfname': 'foo', },
  1474. signature='sv')
  1475. try:
  1476. wpas.CreateInterface(params)
  1477. raise Exception("Invalid CreateInterface() accepted")
  1478. except dbus.exceptions.DBusException, e:
  1479. if "InterfaceExists" not in str(e):
  1480. raise Exception("Unexpected error message for invalid CreateInterface: " + str(e))
  1481. wpas.RemoveInterface(path)
  1482. try:
  1483. wpas.RemoveInterface(path)
  1484. raise Exception("Invalid RemoveInterface() accepted")
  1485. except dbus.exceptions.DBusException, e:
  1486. if "InterfaceUnknown" not in str(e):
  1487. raise Exception("Unexpected error message for invalid RemoveInterface: " + str(e))
  1488. params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none',
  1489. 'Foo': 123 },
  1490. signature='sv')
  1491. try:
  1492. wpas.CreateInterface(params)
  1493. raise Exception("Invalid CreateInterface() accepted")
  1494. except dbus.exceptions.DBusException, e:
  1495. if "InvalidArgs" not in str(e):
  1496. raise Exception("Unexpected error message for invalid CreateInterface: " + str(e))
  1497. params = dbus.Dictionary({ 'Driver': 'none' }, signature='sv')
  1498. try:
  1499. wpas.CreateInterface(params)
  1500. raise Exception("Invalid CreateInterface() accepted")
  1501. except dbus.exceptions.DBusException, e:
  1502. if "InvalidArgs" not in str(e):
  1503. raise Exception("Unexpected error message for invalid CreateInterface: " + str(e))
  1504. try:
  1505. wpas.GetInterface("lo")
  1506. raise Exception("Invalid GetInterface() accepted")
  1507. except dbus.exceptions.DBusException, e:
  1508. if "InterfaceUnknown" not in str(e):
  1509. raise Exception("Unexpected error message for invalid RemoveInterface: " + str(e))
  1510. def test_dbus_interface_oom(dev, apdev):
  1511. """D-Bus CreateInterface/GetInterface/RemoveInterface OOM error cases"""
  1512. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1513. wpas = dbus.Interface(wpas_obj, WPAS_DBUS_SERVICE)
  1514. with alloc_fail_dbus(dev[0], 1, "wpa_dbus_dict_get_entry;wpas_dbus_handler_create_interface", "CreateInterface", "InvalidArgs"):
  1515. params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none' },
  1516. signature='sv')
  1517. wpas.CreateInterface(params)
  1518. for i in range(1, 1000):
  1519. dev[0].request("TEST_ALLOC_FAIL %d:wpa_supplicant_add_iface;wpas_dbus_handler_create_interface" % i)
  1520. params = dbus.Dictionary({ 'Ifname': 'lo', 'Driver': 'none' },
  1521. signature='sv')
  1522. try:
  1523. npath = wpas.CreateInterface(params)
  1524. wpas.RemoveInterface(npath)
  1525. logger.info("CreateInterface succeeds after %d allocation failures" % i)
  1526. state = dev[0].request('GET_ALLOC_FAIL')
  1527. logger.info("GET_ALLOC_FAIL: " + state)
  1528. dev[0].dump_monitor()
  1529. dev[0].request("TEST_ALLOC_FAIL 0:")
  1530. if i < 5:
  1531. raise Exception("CreateInterface succeeded during out-of-memory")
  1532. if not state.startswith('0:'):
  1533. break
  1534. except dbus.exceptions.DBusException, e:
  1535. pass
  1536. for arg in [ 'Driver', 'Ifname', 'ConfigFile', 'BridgeIfname' ]:
  1537. with alloc_fail_dbus(dev[0], 1, "=wpas_dbus_handler_create_interface",
  1538. "CreateInterface"):
  1539. params = dbus.Dictionary({ arg: 'foo' }, signature='sv')
  1540. wpas.CreateInterface(params)
  1541. def test_dbus_blob(dev, apdev):
  1542. """D-Bus AddNetwork/RemoveNetwork parameters and error cases"""
  1543. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1544. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1545. blob = dbus.ByteArray("\x01\x02\x03")
  1546. iface.AddBlob('blob1', blob)
  1547. try:
  1548. iface.AddBlob('blob1', dbus.ByteArray("\x01\x02\x04"))
  1549. raise Exception("Invalid AddBlob() accepted")
  1550. except dbus.exceptions.DBusException, e:
  1551. if "BlobExists" not in str(e):
  1552. raise Exception("Unexpected error message for invalid AddBlob: " + str(e))
  1553. res = iface.GetBlob('blob1')
  1554. if len(res) != len(blob):
  1555. raise Exception("Unexpected blob data length")
  1556. for i in range(len(res)):
  1557. if res[i] != dbus.Byte(blob[i]):
  1558. raise Exception("Unexpected blob data")
  1559. res = if_obj.Get(WPAS_DBUS_IFACE, "Blobs",
  1560. dbus_interface=dbus.PROPERTIES_IFACE)
  1561. if 'blob1' not in res:
  1562. raise Exception("Added blob missing from Blobs property")
  1563. iface.RemoveBlob('blob1')
  1564. try:
  1565. iface.RemoveBlob('blob1')
  1566. raise Exception("Invalid RemoveBlob() accepted")
  1567. except dbus.exceptions.DBusException, e:
  1568. if "BlobUnknown" not in str(e):
  1569. raise Exception("Unexpected error message for invalid RemoveBlob: " + str(e))
  1570. try:
  1571. iface.GetBlob('blob1')
  1572. raise Exception("Invalid GetBlob() accepted")
  1573. except dbus.exceptions.DBusException, e:
  1574. if "BlobUnknown" not in str(e):
  1575. raise Exception("Unexpected error message for invalid GetBlob: " + str(e))
  1576. class TestDbusBlob(TestDbus):
  1577. def __init__(self, bus):
  1578. TestDbus.__init__(self, bus)
  1579. self.blob_added = False
  1580. self.blob_removed = False
  1581. def __enter__(self):
  1582. gobject.timeout_add(1, self.run_blob)
  1583. gobject.timeout_add(15000, self.timeout)
  1584. self.add_signal(self.blobAdded, WPAS_DBUS_IFACE, "BlobAdded")
  1585. self.add_signal(self.blobRemoved, WPAS_DBUS_IFACE, "BlobRemoved")
  1586. self.loop.run()
  1587. return self
  1588. def blobAdded(self, blobName):
  1589. logger.debug("blobAdded: %s" % blobName)
  1590. if blobName == 'blob2':
  1591. self.blob_added = True
  1592. def blobRemoved(self, blobName):
  1593. logger.debug("blobRemoved: %s" % blobName)
  1594. if blobName == 'blob2':
  1595. self.blob_removed = True
  1596. self.loop.quit()
  1597. def run_blob(self, *args):
  1598. logger.debug("run_blob")
  1599. iface.AddBlob('blob2', dbus.ByteArray("\x01\x02\x04"))
  1600. iface.RemoveBlob('blob2')
  1601. return False
  1602. def success(self):
  1603. return self.blob_added and self.blob_removed
  1604. with TestDbusBlob(bus) as t:
  1605. if not t.success():
  1606. raise Exception("Expected signals not seen")
  1607. def test_dbus_blob_oom(dev, apdev):
  1608. """D-Bus AddNetwork/RemoveNetwork OOM error cases"""
  1609. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1610. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1611. for i in range(1, 4):
  1612. with alloc_fail_dbus(dev[0], i, "wpas_dbus_handler_add_blob",
  1613. "AddBlob"):
  1614. iface.AddBlob('blob_no_mem', dbus.ByteArray("\x01\x02\x03\x04"))
  1615. def test_dbus_autoscan(dev, apdev):
  1616. """D-Bus Autoscan()"""
  1617. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1618. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1619. iface.AutoScan("foo")
  1620. iface.AutoScan("periodic:1")
  1621. iface.AutoScan("")
  1622. dev[0].request("AUTOSCAN ")
  1623. def test_dbus_autoscan_oom(dev, apdev):
  1624. """D-Bus Autoscan() OOM"""
  1625. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1626. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1627. with alloc_fail_dbus(dev[0], 1, "wpas_dbus_handler_autoscan", "AutoScan"):
  1628. iface.AutoScan("foo")
  1629. dev[0].request("AUTOSCAN ")
  1630. def test_dbus_tdls_invalid(dev, apdev):
  1631. """D-Bus invalid TDLS operations"""
  1632. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1633. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1634. hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "test-open" })
  1635. connect_2sta_open(dev, hapd)
  1636. addr1 = dev[1].p2p_interface_addr()
  1637. try:
  1638. iface.TDLSDiscover("foo")
  1639. raise Exception("Invalid TDLSDiscover() accepted")
  1640. except dbus.exceptions.DBusException, e:
  1641. if "InvalidArgs" not in str(e):
  1642. raise Exception("Unexpected error message for invalid TDLSDiscover: " + str(e))
  1643. try:
  1644. iface.TDLSStatus("foo")
  1645. raise Exception("Invalid TDLSStatus() accepted")
  1646. except dbus.exceptions.DBusException, e:
  1647. if "InvalidArgs" not in str(e):
  1648. raise Exception("Unexpected error message for invalid TDLSStatus: " + str(e))
  1649. res = iface.TDLSStatus(addr1)
  1650. if res != "peer does not exist":
  1651. raise Exception("Unexpected TDLSStatus response")
  1652. try:
  1653. iface.TDLSSetup("foo")
  1654. raise Exception("Invalid TDLSSetup() accepted")
  1655. except dbus.exceptions.DBusException, e:
  1656. if "InvalidArgs" not in str(e):
  1657. raise Exception("Unexpected error message for invalid TDLSSetup: " + str(e))
  1658. try:
  1659. iface.TDLSTeardown("foo")
  1660. raise Exception("Invalid TDLSTeardown() accepted")
  1661. except dbus.exceptions.DBusException, e:
  1662. if "InvalidArgs" not in str(e):
  1663. raise Exception("Unexpected error message for invalid TDLSTeardown: " + str(e))
  1664. try:
  1665. iface.TDLSTeardown("00:11:22:33:44:55")
  1666. raise Exception("TDLSTeardown accepted for unknown peer")
  1667. except dbus.exceptions.DBusException, e:
  1668. if "UnknownError: error performing TDLS teardown" not in str(e):
  1669. raise Exception("Unexpected error message: " + str(e))
  1670. def test_dbus_tdls_oom(dev, apdev):
  1671. """D-Bus TDLS operations during OOM"""
  1672. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1673. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1674. with alloc_fail_dbus(dev[0], 1, "wpa_tdls_add_peer", "TDLSSetup",
  1675. "UnknownError: error performing TDLS setup"):
  1676. iface.TDLSSetup("00:11:22:33:44:55")
  1677. def test_dbus_tdls(dev, apdev):
  1678. """D-Bus TDLS"""
  1679. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1680. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1681. hapd = hostapd.add_ap(apdev[0]['ifname'], { "ssid": "test-open" })
  1682. connect_2sta_open(dev, hapd)
  1683. addr1 = dev[1].p2p_interface_addr()
  1684. class TestDbusTdls(TestDbus):
  1685. def __init__(self, bus):
  1686. TestDbus.__init__(self, bus)
  1687. self.tdls_setup = False
  1688. self.tdls_teardown = False
  1689. def __enter__(self):
  1690. gobject.timeout_add(1, self.run_tdls)
  1691. gobject.timeout_add(15000, self.timeout)
  1692. self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
  1693. "PropertiesChanged")
  1694. self.loop.run()
  1695. return self
  1696. def propertiesChanged(self, properties):
  1697. logger.debug("propertiesChanged: %s" % str(properties))
  1698. def run_tdls(self, *args):
  1699. logger.debug("run_tdls")
  1700. iface.TDLSDiscover(addr1)
  1701. gobject.timeout_add(100, self.run_tdls2)
  1702. return False
  1703. def run_tdls2(self, *args):
  1704. logger.debug("run_tdls2")
  1705. iface.TDLSSetup(addr1)
  1706. gobject.timeout_add(500, self.run_tdls3)
  1707. return False
  1708. def run_tdls3(self, *args):
  1709. logger.debug("run_tdls3")
  1710. res = iface.TDLSStatus(addr1)
  1711. if res == "connected":
  1712. self.tdls_setup = True
  1713. else:
  1714. logger.info("Unexpected TDLSStatus: " + res)
  1715. iface.TDLSTeardown(addr1)
  1716. gobject.timeout_add(200, self.run_tdls4)
  1717. return False
  1718. def run_tdls4(self, *args):
  1719. logger.debug("run_tdls4")
  1720. res = iface.TDLSStatus(addr1)
  1721. if res == "peer does not exist":
  1722. self.tdls_teardown = True
  1723. else:
  1724. logger.info("Unexpected TDLSStatus: " + res)
  1725. self.loop.quit()
  1726. return False
  1727. def success(self):
  1728. return self.tdls_setup and self.tdls_teardown
  1729. with TestDbusTdls(bus) as t:
  1730. if not t.success():
  1731. raise Exception("Expected signals not seen")
  1732. def test_dbus_pkcs11(dev, apdev):
  1733. """D-Bus SetPKCS11EngineAndModulePath()"""
  1734. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1735. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  1736. try:
  1737. iface.SetPKCS11EngineAndModulePath("foo", "bar")
  1738. except dbus.exceptions.DBusException, e:
  1739. if "Error.Failed: Reinit of the EAPOL" not in str(e):
  1740. raise Exception("Unexpected error message for invalid SetPKCS11EngineAndModulePath: " + str(e))
  1741. try:
  1742. iface.SetPKCS11EngineAndModulePath("foo", "")
  1743. except dbus.exceptions.DBusException, e:
  1744. if "Error.Failed: Reinit of the EAPOL" not in str(e):
  1745. raise Exception("Unexpected error message for invalid SetPKCS11EngineAndModulePath: " + str(e))
  1746. iface.SetPKCS11EngineAndModulePath("", "bar")
  1747. res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11EnginePath",
  1748. dbus_interface=dbus.PROPERTIES_IFACE)
  1749. if res != "":
  1750. raise Exception("Unexpected PKCS11EnginePath value: " + res)
  1751. res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11ModulePath",
  1752. dbus_interface=dbus.PROPERTIES_IFACE)
  1753. if res != "bar":
  1754. raise Exception("Unexpected PKCS11ModulePath value: " + res)
  1755. iface.SetPKCS11EngineAndModulePath("", "")
  1756. res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11EnginePath",
  1757. dbus_interface=dbus.PROPERTIES_IFACE)
  1758. if res != "":
  1759. raise Exception("Unexpected PKCS11EnginePath value: " + res)
  1760. res = if_obj.Get(WPAS_DBUS_IFACE, "PKCS11ModulePath",
  1761. dbus_interface=dbus.PROPERTIES_IFACE)
  1762. if res != "":
  1763. raise Exception("Unexpected PKCS11ModulePath value: " + res)
  1764. def test_dbus_apscan(dev, apdev):
  1765. """D-Bus Get/Set ApScan"""
  1766. try:
  1767. _test_dbus_apscan(dev, apdev)
  1768. finally:
  1769. dev[0].request("AP_SCAN 1")
  1770. def _test_dbus_apscan(dev, apdev):
  1771. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1772. res = if_obj.Get(WPAS_DBUS_IFACE, "ApScan",
  1773. dbus_interface=dbus.PROPERTIES_IFACE)
  1774. if res != 1:
  1775. raise Exception("Unexpected initial ApScan value: %d" % res)
  1776. for i in range(3):
  1777. if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.UInt32(i),
  1778. dbus_interface=dbus.PROPERTIES_IFACE)
  1779. res = if_obj.Get(WPAS_DBUS_IFACE, "ApScan",
  1780. dbus_interface=dbus.PROPERTIES_IFACE)
  1781. if res != i:
  1782. raise Exception("Unexpected ApScan value %d (expected %d)" % (res, i))
  1783. try:
  1784. if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.Int16(-1),
  1785. dbus_interface=dbus.PROPERTIES_IFACE)
  1786. raise Exception("Invalid Set(ApScan,-1) accepted")
  1787. except dbus.exceptions.DBusException, e:
  1788. if "Error.Failed: wrong property type" not in str(e):
  1789. raise Exception("Unexpected error message for invalid Set(ApScan,-1): " + str(e))
  1790. try:
  1791. if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.UInt32(123),
  1792. dbus_interface=dbus.PROPERTIES_IFACE)
  1793. raise Exception("Invalid Set(ApScan,123) accepted")
  1794. except dbus.exceptions.DBusException, e:
  1795. if "Error.Failed: ap_scan must be 0, 1, or 2" not in str(e):
  1796. raise Exception("Unexpected error message for invalid Set(ApScan,123): " + str(e))
  1797. if_obj.Set(WPAS_DBUS_IFACE, "ApScan", dbus.UInt32(1),
  1798. dbus_interface=dbus.PROPERTIES_IFACE)
  1799. def test_dbus_fastreauth(dev, apdev):
  1800. """D-Bus Get/Set FastReauth"""
  1801. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1802. res = if_obj.Get(WPAS_DBUS_IFACE, "FastReauth",
  1803. dbus_interface=dbus.PROPERTIES_IFACE)
  1804. if res != True:
  1805. raise Exception("Unexpected initial FastReauth value: " + str(res))
  1806. for i in [ False, True ]:
  1807. if_obj.Set(WPAS_DBUS_IFACE, "FastReauth", dbus.Boolean(i),
  1808. dbus_interface=dbus.PROPERTIES_IFACE)
  1809. res = if_obj.Get(WPAS_DBUS_IFACE, "FastReauth",
  1810. dbus_interface=dbus.PROPERTIES_IFACE)
  1811. if res != i:
  1812. raise Exception("Unexpected FastReauth value %d (expected %d)" % (res, i))
  1813. try:
  1814. if_obj.Set(WPAS_DBUS_IFACE, "FastReauth", dbus.Int16(-1),
  1815. dbus_interface=dbus.PROPERTIES_IFACE)
  1816. raise Exception("Invalid Set(FastReauth,-1) accepted")
  1817. except dbus.exceptions.DBusException, e:
  1818. if "Error.Failed: wrong property type" not in str(e):
  1819. raise Exception("Unexpected error message for invalid Set(ApScan,-1): " + str(e))
  1820. if_obj.Set(WPAS_DBUS_IFACE, "FastReauth", dbus.Boolean(True),
  1821. dbus_interface=dbus.PROPERTIES_IFACE)
  1822. def test_dbus_bss_expire(dev, apdev):
  1823. """D-Bus Get/Set BSSExpireAge and BSSExpireCount"""
  1824. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1825. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.UInt32(179),
  1826. dbus_interface=dbus.PROPERTIES_IFACE)
  1827. res = if_obj.Get(WPAS_DBUS_IFACE, "BSSExpireAge",
  1828. dbus_interface=dbus.PROPERTIES_IFACE)
  1829. if res != 179:
  1830. raise Exception("Unexpected BSSExpireAge value %d (expected %d)" % (res, i))
  1831. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.UInt32(3),
  1832. dbus_interface=dbus.PROPERTIES_IFACE)
  1833. res = if_obj.Get(WPAS_DBUS_IFACE, "BSSExpireCount",
  1834. dbus_interface=dbus.PROPERTIES_IFACE)
  1835. if res != 3:
  1836. raise Exception("Unexpected BSSExpireCount value %d (expected %d)" % (res, i))
  1837. try:
  1838. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.Int16(-1),
  1839. dbus_interface=dbus.PROPERTIES_IFACE)
  1840. raise Exception("Invalid Set(BSSExpireAge,-1) accepted")
  1841. except dbus.exceptions.DBusException, e:
  1842. if "Error.Failed: wrong property type" not in str(e):
  1843. raise Exception("Unexpected error message for invalid Set(BSSExpireAge,-1): " + str(e))
  1844. try:
  1845. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.UInt32(9),
  1846. dbus_interface=dbus.PROPERTIES_IFACE)
  1847. raise Exception("Invalid Set(BSSExpireAge,9) accepted")
  1848. except dbus.exceptions.DBusException, e:
  1849. if "Error.Failed: BSSExpireAge must be >= 10" not in str(e):
  1850. raise Exception("Unexpected error message for invalid Set(BSSExpireAge,9): " + str(e))
  1851. try:
  1852. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.Int16(-1),
  1853. dbus_interface=dbus.PROPERTIES_IFACE)
  1854. raise Exception("Invalid Set(BSSExpireCount,-1) accepted")
  1855. except dbus.exceptions.DBusException, e:
  1856. if "Error.Failed: wrong property type" not in str(e):
  1857. raise Exception("Unexpected error message for invalid Set(BSSExpireCount,-1): " + str(e))
  1858. try:
  1859. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.UInt32(0),
  1860. dbus_interface=dbus.PROPERTIES_IFACE)
  1861. raise Exception("Invalid Set(BSSExpireCount,0) accepted")
  1862. except dbus.exceptions.DBusException, e:
  1863. if "Error.Failed: BSSExpireCount must be > 0" not in str(e):
  1864. raise Exception("Unexpected error message for invalid Set(BSSExpireCount,0): " + str(e))
  1865. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireAge", dbus.UInt32(180),
  1866. dbus_interface=dbus.PROPERTIES_IFACE)
  1867. if_obj.Set(WPAS_DBUS_IFACE, "BSSExpireCount", dbus.UInt32(2),
  1868. dbus_interface=dbus.PROPERTIES_IFACE)
  1869. def test_dbus_country(dev, apdev):
  1870. """D-Bus Get/Set Country"""
  1871. try:
  1872. _test_dbus_country(dev, apdev)
  1873. finally:
  1874. dev[0].request("SET country 00")
  1875. subprocess.call(['iw', 'reg', 'set', '00'])
  1876. def _test_dbus_country(dev, apdev):
  1877. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1878. # work around issues with possible pending regdom event from the end of
  1879. # the previous test case
  1880. time.sleep(0.2)
  1881. dev[0].dump_monitor()
  1882. if_obj.Set(WPAS_DBUS_IFACE, "Country", "FI",
  1883. dbus_interface=dbus.PROPERTIES_IFACE)
  1884. res = if_obj.Get(WPAS_DBUS_IFACE, "Country",
  1885. dbus_interface=dbus.PROPERTIES_IFACE)
  1886. if res != "FI":
  1887. raise Exception("Unexpected Country value %s (expected FI)" % res)
  1888. ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"])
  1889. if ev is None:
  1890. # For now, work around separate P2P Device interface event delivery
  1891. ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
  1892. if ev is None:
  1893. raise Exception("regdom change event not seen")
  1894. if "init=USER type=COUNTRY alpha2=FI" not in ev:
  1895. raise Exception("Unexpected event contents: " + ev)
  1896. try:
  1897. if_obj.Set(WPAS_DBUS_IFACE, "Country", dbus.Int16(-1),
  1898. dbus_interface=dbus.PROPERTIES_IFACE)
  1899. raise Exception("Invalid Set(Country,-1) accepted")
  1900. except dbus.exceptions.DBusException, e:
  1901. if "Error.Failed: wrong property type" not in str(e):
  1902. raise Exception("Unexpected error message for invalid Set(Country,-1): " + str(e))
  1903. try:
  1904. if_obj.Set(WPAS_DBUS_IFACE, "Country", "F",
  1905. dbus_interface=dbus.PROPERTIES_IFACE)
  1906. raise Exception("Invalid Set(Country,F) accepted")
  1907. except dbus.exceptions.DBusException, e:
  1908. if "Error.Failed: invalid country code" not in str(e):
  1909. raise Exception("Unexpected error message for invalid Set(Country,F): " + str(e))
  1910. if_obj.Set(WPAS_DBUS_IFACE, "Country", "00",
  1911. dbus_interface=dbus.PROPERTIES_IFACE)
  1912. ev = dev[0].wait_event(["CTRL-EVENT-REGDOM-CHANGE"])
  1913. if ev is None:
  1914. # For now, work around separate P2P Device interface event delivery
  1915. ev = dev[0].wait_global_event(["CTRL-EVENT-REGDOM-CHANGE"], timeout=1)
  1916. if ev is None:
  1917. raise Exception("regdom change event not seen")
  1918. if "init=CORE type=WORLD" not in ev:
  1919. raise Exception("Unexpected event contents: " + ev)
  1920. def test_dbus_scan_interval(dev, apdev):
  1921. """D-Bus Get/Set ScanInterval"""
  1922. try:
  1923. _test_dbus_scan_interval(dev, apdev)
  1924. finally:
  1925. dev[0].request("SCAN_INTERVAL 5")
  1926. def _test_dbus_scan_interval(dev, apdev):
  1927. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1928. if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.Int32(3),
  1929. dbus_interface=dbus.PROPERTIES_IFACE)
  1930. res = if_obj.Get(WPAS_DBUS_IFACE, "ScanInterval",
  1931. dbus_interface=dbus.PROPERTIES_IFACE)
  1932. if res != 3:
  1933. raise Exception("Unexpected ScanInterval value %d (expected %d)" % (res, i))
  1934. try:
  1935. if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.UInt16(100),
  1936. dbus_interface=dbus.PROPERTIES_IFACE)
  1937. raise Exception("Invalid Set(ScanInterval,100) accepted")
  1938. except dbus.exceptions.DBusException, e:
  1939. if "Error.Failed: wrong property type" not in str(e):
  1940. raise Exception("Unexpected error message for invalid Set(ScanInterval,100): " + str(e))
  1941. try:
  1942. if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.Int32(-1),
  1943. dbus_interface=dbus.PROPERTIES_IFACE)
  1944. raise Exception("Invalid Set(ScanInterval,-1) accepted")
  1945. except dbus.exceptions.DBusException, e:
  1946. if "Error.Failed: scan_interval must be >= 0" not in str(e):
  1947. raise Exception("Unexpected error message for invalid Set(ScanInterval,-1): " + str(e))
  1948. if_obj.Set(WPAS_DBUS_IFACE, "ScanInterval", dbus.Int32(5),
  1949. dbus_interface=dbus.PROPERTIES_IFACE)
  1950. def test_dbus_probe_req_reporting(dev, apdev):
  1951. """D-Bus Probe Request reporting"""
  1952. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  1953. dev[1].p2p_find(social=True)
  1954. class TestDbusProbe(TestDbus):
  1955. def __init__(self, bus):
  1956. TestDbus.__init__(self, bus)
  1957. self.reported = False
  1958. def __enter__(self):
  1959. gobject.timeout_add(1, self.run_test)
  1960. gobject.timeout_add(15000, self.timeout)
  1961. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  1962. "GroupStarted")
  1963. self.add_signal(self.probeRequest, WPAS_DBUS_IFACE, "ProbeRequest",
  1964. byte_arrays=True)
  1965. self.loop.run()
  1966. return self
  1967. def groupStarted(self, properties):
  1968. logger.debug("groupStarted: " + str(properties))
  1969. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  1970. properties['interface_object'])
  1971. self.iface = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE)
  1972. self.iface.SubscribeProbeReq()
  1973. self.group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  1974. def probeRequest(self, args):
  1975. logger.debug("probeRequest: args=%s" % str(args))
  1976. self.reported = True
  1977. self.loop.quit()
  1978. def run_test(self, *args):
  1979. logger.debug("run_test")
  1980. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  1981. params = dbus.Dictionary({ 'frequency': 2412 })
  1982. p2p.GroupAdd(params)
  1983. return False
  1984. def success(self):
  1985. return self.reported
  1986. with TestDbusProbe(bus) as t:
  1987. if not t.success():
  1988. raise Exception("Expected signals not seen")
  1989. t.iface.UnsubscribeProbeReq()
  1990. try:
  1991. t.iface.UnsubscribeProbeReq()
  1992. raise Exception("Invalid UnsubscribeProbeReq() accepted")
  1993. except dbus.exceptions.DBusException, e:
  1994. if "NoSubscription" not in str(e):
  1995. raise Exception("Unexpected error message for invalid UnsubscribeProbeReq(): " + str(e))
  1996. t.group_p2p.Disconnect()
  1997. with TestDbusProbe(bus) as t:
  1998. if not t.success():
  1999. raise Exception("Expected signals not seen")
  2000. # On purpose, leave ProbeReq subscription in place to test automatic
  2001. # cleanup.
  2002. dev[1].p2p_stop_find()
  2003. def test_dbus_probe_req_reporting_oom(dev, apdev):
  2004. """D-Bus Probe Request reporting (OOM)"""
  2005. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2006. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  2007. # Need to make sure this process has not already subscribed to avoid false
  2008. # failures due to the operation succeeding due to os_strdup() not even
  2009. # getting called.
  2010. try:
  2011. iface.UnsubscribeProbeReq()
  2012. was_subscribed = True
  2013. except dbus.exceptions.DBusException, e:
  2014. was_subscribed = False
  2015. pass
  2016. with alloc_fail_dbus(dev[0], 1, "wpas_dbus_handler_subscribe_preq",
  2017. "SubscribeProbeReq"):
  2018. iface.SubscribeProbeReq()
  2019. if was_subscribed:
  2020. # On purpose, leave ProbeReq subscription in place to test automatic
  2021. # cleanup.
  2022. iface.SubscribeProbeReq()
  2023. def test_dbus_p2p_invalid(dev, apdev):
  2024. """D-Bus invalid P2P operations"""
  2025. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2026. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2027. try:
  2028. p2p.RejectPeer(path + "/Peers/00112233445566")
  2029. raise Exception("Invalid RejectPeer accepted")
  2030. except dbus.exceptions.DBusException, e:
  2031. if "UnknownError: Failed to call wpas_p2p_reject" not in str(e):
  2032. raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
  2033. try:
  2034. p2p.RejectPeer("/foo")
  2035. raise Exception("Invalid RejectPeer accepted")
  2036. except dbus.exceptions.DBusException, e:
  2037. if "InvalidArgs" not in str(e):
  2038. raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
  2039. tests = [ { },
  2040. { 'peer': 'foo' },
  2041. { 'foo': "bar" },
  2042. { 'iface': "abc" },
  2043. { 'iface': 123 } ]
  2044. for t in tests:
  2045. try:
  2046. p2p.RemoveClient(t)
  2047. raise Exception("Invalid RemoveClient accepted")
  2048. except dbus.exceptions.DBusException, e:
  2049. if "InvalidArgs" not in str(e):
  2050. raise Exception("Unexpected error message for invalid RemoveClient(): " + str(e))
  2051. tests = [ {'DiscoveryType': 'foo'},
  2052. {'RequestedDeviceTypes': 'foo'},
  2053. {'RequestedDeviceTypes': ['foo']},
  2054. {'RequestedDeviceTypes': ['1','2','3','4','5','6','7','8','9',
  2055. '10','11','12','13','14','15','16',
  2056. '17']},
  2057. {'RequestedDeviceTypes': dbus.Array([], signature="s")},
  2058. {'RequestedDeviceTypes': dbus.Array([['foo']], signature="as")},
  2059. {'RequestedDeviceTypes': dbus.Array([], signature="i")},
  2060. {'RequestedDeviceTypes': [dbus.ByteArray('12345678'),
  2061. dbus.ByteArray('1234567')]},
  2062. {'Foo': dbus.Int16(1)},
  2063. {'Foo': dbus.UInt16(1)},
  2064. {'Foo': dbus.Int64(1)},
  2065. {'Foo': dbus.UInt64(1)},
  2066. {'Foo': dbus.Double(1.23)},
  2067. {'Foo': dbus.Signature('s')},
  2068. {'Foo': 'bar'}]
  2069. for t in tests:
  2070. try:
  2071. p2p.Find(dbus.Dictionary(t))
  2072. raise Exception("Invalid Find accepted")
  2073. except dbus.exceptions.DBusException, e:
  2074. if "InvalidArgs" not in str(e):
  2075. raise Exception("Unexpected error message for invalid Find(): " + str(e))
  2076. for p in [ "/foo",
  2077. "/fi/w1/wpa_supplicant1/Interfaces/1234",
  2078. "/fi/w1/wpa_supplicant1/Interfaces/1234/Networks/1234" ]:
  2079. try:
  2080. p2p.RemovePersistentGroup(dbus.ObjectPath(p))
  2081. raise Exception("Invalid RemovePersistentGroup accepted")
  2082. except dbus.exceptions.DBusException, e:
  2083. if "InvalidArgs" not in str(e):
  2084. raise Exception("Unexpected error message for invalid RemovePersistentGroup: " + str(e))
  2085. try:
  2086. dev[0].request("P2P_SET disabled 1")
  2087. p2p.Listen(5)
  2088. raise Exception("Invalid Listen accepted")
  2089. except dbus.exceptions.DBusException, e:
  2090. if "UnknownError: Could not start P2P listen" not in str(e):
  2091. raise Exception("Unexpected error message for invalid Listen: " + str(e))
  2092. finally:
  2093. dev[0].request("P2P_SET disabled 0")
  2094. test_obj = bus.get_object(WPAS_DBUS_SERVICE, path, introspect=False)
  2095. test_p2p = dbus.Interface(test_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2096. try:
  2097. test_p2p.Listen("foo")
  2098. raise Exception("Invalid Listen accepted")
  2099. except dbus.exceptions.DBusException, e:
  2100. if "InvalidArgs" not in str(e):
  2101. raise Exception("Unexpected error message for invalid Listen: " + str(e))
  2102. try:
  2103. dev[0].request("P2P_SET disabled 1")
  2104. p2p.ExtendedListen(dbus.Dictionary({}))
  2105. raise Exception("Invalid ExtendedListen accepted")
  2106. except dbus.exceptions.DBusException, e:
  2107. if "UnknownError: failed to initiate a p2p_ext_listen" not in str(e):
  2108. raise Exception("Unexpected error message for invalid ExtendedListen: " + str(e))
  2109. finally:
  2110. dev[0].request("P2P_SET disabled 0")
  2111. try:
  2112. dev[0].request("P2P_SET disabled 1")
  2113. args = { 'duration1': 30000, 'interval1': 102400,
  2114. 'duration2': 20000, 'interval2': 102400 }
  2115. p2p.PresenceRequest(args)
  2116. raise Exception("Invalid PresenceRequest accepted")
  2117. except dbus.exceptions.DBusException, e:
  2118. if "UnknownError: Failed to invoke presence request" not in str(e):
  2119. raise Exception("Unexpected error message for invalid PresenceRequest: " + str(e))
  2120. finally:
  2121. dev[0].request("P2P_SET disabled 0")
  2122. try:
  2123. params = dbus.Dictionary({'frequency': dbus.Int32(-1)})
  2124. p2p.GroupAdd(params)
  2125. raise Exception("Invalid GroupAdd accepted")
  2126. except dbus.exceptions.DBusException, e:
  2127. if "InvalidArgs" not in str(e):
  2128. raise Exception("Unexpected error message for invalid GroupAdd: " + str(e))
  2129. try:
  2130. params = dbus.Dictionary({'persistent_group_object':
  2131. dbus.ObjectPath(path),
  2132. 'frequency': 2412})
  2133. p2p.GroupAdd(params)
  2134. raise Exception("Invalid GroupAdd accepted")
  2135. except dbus.exceptions.DBusException, e:
  2136. if "InvalidArgs" not in str(e):
  2137. raise Exception("Unexpected error message for invalid GroupAdd: " + str(e))
  2138. try:
  2139. p2p.Disconnect()
  2140. raise Exception("Invalid Disconnect accepted")
  2141. except dbus.exceptions.DBusException, e:
  2142. if "UnknownError: failed to disconnect" not in str(e):
  2143. raise Exception("Unexpected error message for invalid Disconnect: " + str(e))
  2144. try:
  2145. dev[0].request("P2P_SET disabled 1")
  2146. p2p.Flush()
  2147. raise Exception("Invalid Flush accepted")
  2148. except dbus.exceptions.DBusException, e:
  2149. if "Error.Failed: P2P is not available for this interface" not in str(e):
  2150. raise Exception("Unexpected error message for invalid Flush: " + str(e))
  2151. finally:
  2152. dev[0].request("P2P_SET disabled 0")
  2153. try:
  2154. dev[0].request("P2P_SET disabled 1")
  2155. args = { 'peer': path,
  2156. 'join': True,
  2157. 'wps_method': 'pbc',
  2158. 'frequency': 2412 }
  2159. pin = p2p.Connect(args)
  2160. raise Exception("Invalid Connect accepted")
  2161. except dbus.exceptions.DBusException, e:
  2162. if "Error.Failed: P2P is not available for this interface" not in str(e):
  2163. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  2164. finally:
  2165. dev[0].request("P2P_SET disabled 0")
  2166. tests = [ { 'frequency': dbus.Int32(-1) },
  2167. { 'wps_method': 'pbc' },
  2168. { 'wps_method': 'foo' } ]
  2169. for args in tests:
  2170. try:
  2171. pin = p2p.Connect(args)
  2172. raise Exception("Invalid Connect accepted")
  2173. except dbus.exceptions.DBusException, e:
  2174. if "InvalidArgs" not in str(e):
  2175. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  2176. try:
  2177. dev[0].request("P2P_SET disabled 1")
  2178. args = { 'peer': path }
  2179. pin = p2p.Invite(args)
  2180. raise Exception("Invalid Invite accepted")
  2181. except dbus.exceptions.DBusException, e:
  2182. if "Error.Failed: P2P is not available for this interface" not in str(e):
  2183. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  2184. finally:
  2185. dev[0].request("P2P_SET disabled 0")
  2186. try:
  2187. args = { 'foo': 'bar' }
  2188. pin = p2p.Invite(args)
  2189. raise Exception("Invalid Invite accepted")
  2190. except dbus.exceptions.DBusException, e:
  2191. if "InvalidArgs" not in str(e):
  2192. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  2193. tests = [ (path, 'display', "InvalidArgs"),
  2194. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2195. 'display',
  2196. "UnknownError: Failed to send provision discovery request"),
  2197. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2198. 'keypad',
  2199. "UnknownError: Failed to send provision discovery request"),
  2200. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2201. 'pbc',
  2202. "UnknownError: Failed to send provision discovery request"),
  2203. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2204. 'pushbutton',
  2205. "UnknownError: Failed to send provision discovery request"),
  2206. (dbus.ObjectPath(path + "/Peers/00112233445566"),
  2207. 'foo', "InvalidArgs") ]
  2208. for (p,method,err) in tests:
  2209. try:
  2210. p2p.ProvisionDiscoveryRequest(p, method)
  2211. raise Exception("Invalid ProvisionDiscoveryRequest accepted")
  2212. except dbus.exceptions.DBusException, e:
  2213. if err not in str(e):
  2214. raise Exception("Unexpected error message for invalid ProvisionDiscoveryRequest: " + str(e))
  2215. try:
  2216. dev[0].request("P2P_SET disabled 1")
  2217. if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Peers",
  2218. dbus_interface=dbus.PROPERTIES_IFACE)
  2219. raise Exception("Invalid Get(Peers) accepted")
  2220. except dbus.exceptions.DBusException, e:
  2221. if "Error.Failed: P2P is not available for this interface" not in str(e):
  2222. raise Exception("Unexpected error message for invalid Get(Peers): " + str(e))
  2223. finally:
  2224. dev[0].request("P2P_SET disabled 0")
  2225. def test_dbus_p2p_oom(dev, apdev):
  2226. """D-Bus P2P operations and OOM"""
  2227. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2228. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2229. with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_entry_get_string_array",
  2230. "Find", "InvalidArgs"):
  2231. p2p.Find(dbus.Dictionary({ 'Foo': [ 'bar' ] }))
  2232. with alloc_fail_dbus(dev[0], 2, "_wpa_dbus_dict_entry_get_string_array",
  2233. "Find", "InvalidArgs"):
  2234. p2p.Find(dbus.Dictionary({ 'Foo': [ 'bar' ] }))
  2235. with alloc_fail_dbus(dev[0], 10, "_wpa_dbus_dict_entry_get_string_array",
  2236. "Find", "InvalidArgs"):
  2237. p2p.Find(dbus.Dictionary({ 'Foo': [ '1','2','3','4','5','6','7','8','9' ] }))
  2238. with alloc_fail_dbus(dev[0], 1, ":=_wpa_dbus_dict_entry_get_binarray",
  2239. "Find", "InvalidArgs"):
  2240. p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123') ] }))
  2241. with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_entry_get_byte_array;_wpa_dbus_dict_entry_get_binarray",
  2242. "Find", "InvalidArgs"):
  2243. p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123') ] }))
  2244. with alloc_fail_dbus(dev[0], 2, "=_wpa_dbus_dict_entry_get_binarray",
  2245. "Find", "InvalidArgs"):
  2246. p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123'),
  2247. dbus.ByteArray('123'),
  2248. dbus.ByteArray('123'),
  2249. dbus.ByteArray('123'),
  2250. dbus.ByteArray('123'),
  2251. dbus.ByteArray('123'),
  2252. dbus.ByteArray('123'),
  2253. dbus.ByteArray('123'),
  2254. dbus.ByteArray('123'),
  2255. dbus.ByteArray('123'),
  2256. dbus.ByteArray('123') ] }))
  2257. with alloc_fail_dbus(dev[0], 1, "wpabuf_alloc_ext_data;_wpa_dbus_dict_entry_get_binarray",
  2258. "Find", "InvalidArgs"):
  2259. p2p.Find(dbus.Dictionary({ 'Foo': [ dbus.ByteArray('123') ] }))
  2260. with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_fill_value_from_variant;wpas_dbus_handler_p2p_find",
  2261. "Find", "InvalidArgs"):
  2262. p2p.Find(dbus.Dictionary({ 'Foo': path }))
  2263. with alloc_fail_dbus(dev[0], 1, "_wpa_dbus_dict_entry_get_byte_array",
  2264. "AddService", "InvalidArgs"):
  2265. args = { 'service_type': 'bonjour',
  2266. 'response': dbus.ByteArray(500*'b') }
  2267. p2p.AddService(args)
  2268. with alloc_fail_dbus(dev[0], 2, "_wpa_dbus_dict_entry_get_byte_array",
  2269. "AddService", "InvalidArgs"):
  2270. p2p.AddService(args)
  2271. def test_dbus_p2p_discovery(dev, apdev):
  2272. """D-Bus P2P discovery"""
  2273. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2274. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2275. addr0 = dev[0].p2p_dev_addr()
  2276. dev[1].request("SET sec_device_type 1-0050F204-2")
  2277. dev[1].request("VENDOR_ELEM_ADD 1 dd0c0050f2041049000411223344")
  2278. dev[1].p2p_listen()
  2279. addr1 = dev[1].p2p_dev_addr()
  2280. a1 = binascii.unhexlify(addr1.replace(':',''))
  2281. wfd_devinfo = "00001c440028"
  2282. dev[2].request("SET wifi_display 1")
  2283. dev[2].request("WFD_SUBELEM_SET 0 0006" + wfd_devinfo)
  2284. wfd = binascii.unhexlify('000006' + wfd_devinfo)
  2285. dev[2].p2p_listen()
  2286. addr2 = dev[2].p2p_dev_addr()
  2287. a2 = binascii.unhexlify(addr2.replace(':',''))
  2288. res = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
  2289. dbus_interface=dbus.PROPERTIES_IFACE)
  2290. if 'Peers' not in res:
  2291. raise Exception("GetAll result missing Peers")
  2292. if len(res['Peers']) != 0:
  2293. raise Exception("Unexpected peer(s) in the list")
  2294. args = {'DiscoveryType': 'social',
  2295. 'RequestedDeviceTypes': [dbus.ByteArray('12345678')],
  2296. 'Timeout': dbus.Int32(1) }
  2297. p2p.Find(dbus.Dictionary(args))
  2298. p2p.StopFind()
  2299. class TestDbusP2p(TestDbus):
  2300. def __init__(self, bus):
  2301. TestDbus.__init__(self, bus)
  2302. self.found = False
  2303. self.found2 = False
  2304. self.lost = False
  2305. self.find_stopped = False
  2306. def __enter__(self):
  2307. gobject.timeout_add(1, self.run_test)
  2308. gobject.timeout_add(15000, self.timeout)
  2309. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2310. "DeviceFound")
  2311. self.add_signal(self.deviceLost, WPAS_DBUS_IFACE_P2PDEVICE,
  2312. "DeviceLost")
  2313. self.add_signal(self.provisionDiscoveryResponseEnterPin,
  2314. WPAS_DBUS_IFACE_P2PDEVICE,
  2315. "ProvisionDiscoveryResponseEnterPin")
  2316. self.add_signal(self.findStopped, WPAS_DBUS_IFACE_P2PDEVICE,
  2317. "FindStopped")
  2318. self.loop.run()
  2319. return self
  2320. def deviceFound(self, path):
  2321. logger.debug("deviceFound: path=%s" % path)
  2322. res = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Peers",
  2323. dbus_interface=dbus.PROPERTIES_IFACE)
  2324. if len(res) < 1:
  2325. raise Exception("Unexpected number of peers")
  2326. if path not in res:
  2327. raise Exception("Mismatch in peer object path")
  2328. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  2329. res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2330. dbus_interface=dbus.PROPERTIES_IFACE,
  2331. byte_arrays=True)
  2332. logger.debug("peer properties: " + str(res))
  2333. if res['DeviceAddress'] == a1:
  2334. if 'SecondaryDeviceTypes' not in res:
  2335. raise Exception("Missing SecondaryDeviceTypes")
  2336. sec = res['SecondaryDeviceTypes']
  2337. if len(sec) < 1:
  2338. raise Exception("Secondary device type missing")
  2339. if "\x00\x01\x00\x50\xF2\x04\x00\x02" not in sec:
  2340. raise Exception("Secondary device type mismatch")
  2341. if 'VendorExtension' not in res:
  2342. raise Exception("Missing VendorExtension")
  2343. vendor = res['VendorExtension']
  2344. if len(vendor) < 1:
  2345. raise Exception("Vendor extension missing")
  2346. if "\x11\x22\x33\x44" not in vendor:
  2347. raise Exception("Secondary device type mismatch")
  2348. self.found = True
  2349. elif res['DeviceAddress'] == a2:
  2350. if 'IEs' not in res:
  2351. raise Exception("IEs missing")
  2352. if res['IEs'] != wfd:
  2353. raise Exception("IEs mismatch")
  2354. self.found2 = True
  2355. else:
  2356. raise Exception("Unexpected peer device address")
  2357. if self.found and self.found2:
  2358. p2p.StopFind()
  2359. p2p.RejectPeer(path)
  2360. p2p.ProvisionDiscoveryRequest(path, 'display')
  2361. def deviceLost(self, path):
  2362. logger.debug("deviceLost: path=%s" % path)
  2363. self.lost = True
  2364. try:
  2365. p2p.RejectPeer(path)
  2366. raise Exception("Invalid RejectPeer accepted")
  2367. except dbus.exceptions.DBusException, e:
  2368. if "UnknownError: Failed to call wpas_p2p_reject" not in str(e):
  2369. raise Exception("Unexpected error message for invalid RejectPeer(): " + str(e))
  2370. self.loop.quit()
  2371. def provisionDiscoveryResponseEnterPin(self, peer_object):
  2372. logger.debug("provisionDiscoveryResponseEnterPin - peer=%s" % peer_object)
  2373. p2p.Flush()
  2374. def findStopped(self):
  2375. logger.debug("findStopped")
  2376. self.find_stopped = True
  2377. def run_test(self, *args):
  2378. logger.debug("run_test")
  2379. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social',
  2380. 'Timeout': dbus.Int32(10)}))
  2381. return False
  2382. def success(self):
  2383. return self.found and self.lost and self.found2 and self.find_stopped
  2384. with TestDbusP2p(bus) as t:
  2385. if not t.success():
  2386. raise Exception("Expected signals not seen")
  2387. dev[1].request("VENDOR_ELEM_REMOVE 1 *")
  2388. dev[1].p2p_stop_find()
  2389. p2p.Listen(1)
  2390. dev[2].p2p_stop_find()
  2391. dev[2].request("P2P_FLUSH")
  2392. if not dev[2].discover_peer(addr0):
  2393. raise Exception("Peer not found")
  2394. p2p.StopFind()
  2395. dev[2].p2p_stop_find()
  2396. try:
  2397. p2p.ExtendedListen(dbus.Dictionary({'foo': 100}))
  2398. raise Exception("Invalid ExtendedListen accepted")
  2399. except dbus.exceptions.DBusException, e:
  2400. if "InvalidArgs" not in str(e):
  2401. raise Exception("Unexpected error message for invalid ExtendedListen(): " + str(e))
  2402. p2p.ExtendedListen(dbus.Dictionary({'period': 100, 'interval': 1000}))
  2403. p2p.ExtendedListen(dbus.Dictionary({}))
  2404. dev[0].global_request("P2P_EXT_LISTEN")
  2405. def test_dbus_p2p_service_discovery(dev, apdev):
  2406. """D-Bus P2P service discovery"""
  2407. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2408. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2409. addr0 = dev[0].p2p_dev_addr()
  2410. addr1 = dev[1].p2p_dev_addr()
  2411. bonjour_query = dbus.ByteArray(binascii.unhexlify('0b5f6166706f766572746370c00c000c01'))
  2412. bonjour_response = dbus.ByteArray(binascii.unhexlify('074578616d706c65c027'))
  2413. args = { 'service_type': 'bonjour',
  2414. 'query': bonjour_query,
  2415. 'response': bonjour_response }
  2416. p2p.AddService(args)
  2417. p2p.FlushService()
  2418. p2p.AddService(args)
  2419. try:
  2420. p2p.DeleteService(args)
  2421. raise Exception("Invalid DeleteService() accepted")
  2422. except dbus.exceptions.DBusException, e:
  2423. if "InvalidArgs" not in str(e):
  2424. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  2425. args = { 'service_type': 'bonjour',
  2426. 'query': bonjour_query }
  2427. p2p.DeleteService(args)
  2428. try:
  2429. p2p.DeleteService(args)
  2430. raise Exception("Invalid DeleteService() accepted")
  2431. except dbus.exceptions.DBusException, e:
  2432. if "InvalidArgs" not in str(e):
  2433. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  2434. args = { 'service_type': 'upnp',
  2435. 'version': 0x10,
  2436. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' }
  2437. p2p.AddService(args)
  2438. p2p.DeleteService(args)
  2439. try:
  2440. p2p.DeleteService(args)
  2441. raise Exception("Invalid DeleteService() accepted")
  2442. except dbus.exceptions.DBusException, e:
  2443. if "InvalidArgs" not in str(e):
  2444. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  2445. tests = [ { 'service_type': 'foo' },
  2446. { 'service_type': 'foo', 'query': bonjour_query },
  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', 'foo': 'bar' } ]
  2457. for args in tests:
  2458. try:
  2459. p2p.DeleteService(args)
  2460. raise Exception("Invalid DeleteService() accepted")
  2461. except dbus.exceptions.DBusException, e:
  2462. if "InvalidArgs" not in str(e):
  2463. raise Exception("Unexpected error message for invalid DeleteService(): " + str(e))
  2464. tests = [ { 'service_type': 'foo' },
  2465. { 'service_type': 'upnp' },
  2466. { 'service_type': 'upnp', 'version': 0x10 },
  2467. { 'service_type': 'upnp',
  2468. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
  2469. { 'version': 0x10,
  2470. 'service': 'uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice' },
  2471. { 'service_type': 'upnp', 'foo': 'bar' },
  2472. { 'service_type': 'bonjour' },
  2473. { 'service_type': 'bonjour', 'query': 'foo' },
  2474. { 'service_type': 'bonjour', 'response': 'foo' },
  2475. { 'service_type': 'bonjour', 'query': bonjour_query },
  2476. { 'service_type': 'bonjour', 'response': bonjour_response },
  2477. { 'service_type': 'bonjour', 'query': dbus.ByteArray(500*'a') },
  2478. { 'service_type': 'bonjour', 'foo': 'bar' } ]
  2479. for args in tests:
  2480. try:
  2481. p2p.AddService(args)
  2482. raise Exception("Invalid AddService() accepted")
  2483. except dbus.exceptions.DBusException, e:
  2484. if "InvalidArgs" not in str(e):
  2485. raise Exception("Unexpected error message for invalid AddService(): " + str(e))
  2486. args = { 'tlv': dbus.ByteArray("\x02\x00\x00\x01") }
  2487. ref = p2p.ServiceDiscoveryRequest(args)
  2488. p2p.ServiceDiscoveryCancelRequest(ref)
  2489. try:
  2490. p2p.ServiceDiscoveryCancelRequest(ref)
  2491. raise Exception("Invalid ServiceDiscoveryCancelRequest() accepted")
  2492. except dbus.exceptions.DBusException, e:
  2493. if "InvalidArgs" not in str(e):
  2494. raise Exception("Unexpected error message for invalid AddService(): " + str(e))
  2495. try:
  2496. p2p.ServiceDiscoveryCancelRequest(dbus.UInt64(0))
  2497. raise Exception("Invalid ServiceDiscoveryCancelRequest() accepted")
  2498. except dbus.exceptions.DBusException, e:
  2499. if "InvalidArgs" not in str(e):
  2500. raise Exception("Unexpected error message for invalid AddService(): " + str(e))
  2501. args = { 'service_type': 'upnp',
  2502. 'version': 0x10,
  2503. 'service': 'ssdp:foo' }
  2504. ref = p2p.ServiceDiscoveryRequest(args)
  2505. p2p.ServiceDiscoveryCancelRequest(ref)
  2506. tests = [ { 'service_type': 'foo' },
  2507. { 'foo': 'bar' },
  2508. { 'tlv': 'foo' },
  2509. { },
  2510. { 'version': 0 },
  2511. { 'service_type': 'upnp',
  2512. 'service': 'ssdp:foo' },
  2513. { 'service_type': 'upnp',
  2514. 'version': 0x10 },
  2515. { 'service_type': 'upnp',
  2516. 'version': 0x10,
  2517. 'service': 'ssdp:foo',
  2518. 'peer_object': dbus.ObjectPath(path + "/Peers") },
  2519. { 'service_type': 'upnp',
  2520. 'version': 0x10,
  2521. 'service': 'ssdp:foo',
  2522. 'peer_object': path + "/Peers" },
  2523. { 'service_type': 'upnp',
  2524. 'version': 0x10,
  2525. 'service': 'ssdp:foo',
  2526. 'peer_object': dbus.ObjectPath(path + "/Peers/00112233445566") } ]
  2527. for args in tests:
  2528. try:
  2529. p2p.ServiceDiscoveryRequest(args)
  2530. raise Exception("Invalid ServiceDiscoveryRequest accepted")
  2531. except dbus.exceptions.DBusException, e:
  2532. if "InvalidArgs" not in str(e):
  2533. raise Exception("Unexpected error message for invalid ServiceDiscoveryRequest(): " + str(e))
  2534. args = { 'foo': 'bar' }
  2535. try:
  2536. p2p.ServiceDiscoveryResponse(dbus.Dictionary(args, signature='sv'))
  2537. raise Exception("Invalid ServiceDiscoveryResponse accepted")
  2538. except dbus.exceptions.DBusException, e:
  2539. if "InvalidArgs" not in str(e):
  2540. raise Exception("Unexpected error message for invalid ServiceDiscoveryResponse(): " + str(e))
  2541. def test_dbus_p2p_service_discovery_query(dev, apdev):
  2542. """D-Bus P2P service discovery query"""
  2543. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2544. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2545. addr0 = dev[0].p2p_dev_addr()
  2546. dev[1].request("P2P_SERVICE_ADD bonjour 0b5f6166706f766572746370c00c000c01 074578616d706c65c027")
  2547. dev[1].p2p_listen()
  2548. addr1 = dev[1].p2p_dev_addr()
  2549. class TestDbusP2p(TestDbus):
  2550. def __init__(self, bus):
  2551. TestDbus.__init__(self, bus)
  2552. self.done = False
  2553. def __enter__(self):
  2554. gobject.timeout_add(1, self.run_test)
  2555. gobject.timeout_add(15000, self.timeout)
  2556. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2557. "DeviceFound")
  2558. self.add_signal(self.serviceDiscoveryResponse,
  2559. WPAS_DBUS_IFACE_P2PDEVICE,
  2560. "ServiceDiscoveryResponse", byte_arrays=True)
  2561. self.loop.run()
  2562. return self
  2563. def deviceFound(self, path):
  2564. logger.debug("deviceFound: path=%s" % path)
  2565. args = { 'peer_object': path,
  2566. 'tlv': dbus.ByteArray("\x02\x00\x00\x01") }
  2567. p2p.ServiceDiscoveryRequest(args)
  2568. def serviceDiscoveryResponse(self, sd_request):
  2569. logger.debug("serviceDiscoveryResponse: sd_request=%s" % str(sd_request))
  2570. self.done = True
  2571. self.loop.quit()
  2572. def run_test(self, *args):
  2573. logger.debug("run_test")
  2574. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social',
  2575. 'Timeout': dbus.Int32(10)}))
  2576. return False
  2577. def success(self):
  2578. return self.done
  2579. with TestDbusP2p(bus) as t:
  2580. if not t.success():
  2581. raise Exception("Expected signals not seen")
  2582. dev[1].p2p_stop_find()
  2583. def test_dbus_p2p_service_discovery_external(dev, apdev):
  2584. """D-Bus P2P service discovery with external response"""
  2585. try:
  2586. _test_dbus_p2p_service_discovery_external(dev, apdev)
  2587. finally:
  2588. dev[0].request("P2P_SERV_DISC_EXTERNAL 0")
  2589. def _test_dbus_p2p_service_discovery_external(dev, apdev):
  2590. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2591. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2592. addr0 = dev[0].p2p_dev_addr()
  2593. addr1 = dev[1].p2p_dev_addr()
  2594. resp = "0300000101"
  2595. dev[1].request("P2P_FLUSH")
  2596. dev[1].request("P2P_SERV_DISC_REQ " + addr0 + " 02000001")
  2597. dev[1].p2p_find(social=True)
  2598. class TestDbusP2p(TestDbus):
  2599. def __init__(self, bus):
  2600. TestDbus.__init__(self, bus)
  2601. self.sd = False
  2602. def __enter__(self):
  2603. gobject.timeout_add(1, self.run_test)
  2604. gobject.timeout_add(15000, self.timeout)
  2605. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2606. "DeviceFound")
  2607. self.add_signal(self.serviceDiscoveryRequest,
  2608. WPAS_DBUS_IFACE_P2PDEVICE,
  2609. "ServiceDiscoveryRequest")
  2610. self.loop.run()
  2611. return self
  2612. def deviceFound(self, path):
  2613. logger.debug("deviceFound: path=%s" % path)
  2614. def serviceDiscoveryRequest(self, sd_request):
  2615. logger.debug("serviceDiscoveryRequest: sd_request=%s" % str(sd_request))
  2616. self.sd = True
  2617. args = { 'peer_object': sd_request['peer_object'],
  2618. 'frequency': sd_request['frequency'],
  2619. 'dialog_token': sd_request['dialog_token'],
  2620. 'tlvs': dbus.ByteArray(binascii.unhexlify(resp)) }
  2621. p2p.ServiceDiscoveryResponse(dbus.Dictionary(args, signature='sv'))
  2622. self.loop.quit()
  2623. def run_test(self, *args):
  2624. logger.debug("run_test")
  2625. p2p.ServiceDiscoveryExternal(1)
  2626. p2p.ServiceUpdate()
  2627. p2p.Listen(15)
  2628. return False
  2629. def success(self):
  2630. return self.sd
  2631. with TestDbusP2p(bus) as t:
  2632. if not t.success():
  2633. raise Exception("Expected signals not seen")
  2634. ev = dev[1].wait_global_event(["P2P-SERV-DISC-RESP"], timeout=5)
  2635. if ev is None:
  2636. raise Exception("Service discovery timed out")
  2637. if addr0 not in ev:
  2638. raise Exception("Unexpected address in SD Response: " + ev)
  2639. if ev.split(' ')[4] != resp:
  2640. raise Exception("Unexpected response data SD Response: " + ev)
  2641. dev[1].p2p_stop_find()
  2642. p2p.StopFind()
  2643. p2p.ServiceDiscoveryExternal(0)
  2644. def test_dbus_p2p_autogo(dev, apdev):
  2645. """D-Bus P2P autonomous GO"""
  2646. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2647. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2648. addr0 = dev[0].p2p_dev_addr()
  2649. class TestDbusP2p(TestDbus):
  2650. def __init__(self, bus):
  2651. TestDbus.__init__(self, bus)
  2652. self.first = True
  2653. self.waiting_end = False
  2654. self.exceptions = False
  2655. self.deauthorized = False
  2656. self.done = False
  2657. def __enter__(self):
  2658. gobject.timeout_add(1, self.run_test)
  2659. gobject.timeout_add(15000, self.timeout)
  2660. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2661. "DeviceFound")
  2662. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2663. "GroupStarted")
  2664. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2665. "GroupFinished")
  2666. self.add_signal(self.persistentGroupAdded,
  2667. WPAS_DBUS_IFACE_P2PDEVICE,
  2668. "PersistentGroupAdded")
  2669. self.add_signal(self.persistentGroupRemoved,
  2670. WPAS_DBUS_IFACE_P2PDEVICE,
  2671. "PersistentGroupRemoved")
  2672. self.add_signal(self.provisionDiscoveryRequestDisplayPin,
  2673. WPAS_DBUS_IFACE_P2PDEVICE,
  2674. "ProvisionDiscoveryRequestDisplayPin")
  2675. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  2676. "StaAuthorized")
  2677. self.add_signal(self.staDeauthorized, WPAS_DBUS_IFACE,
  2678. "StaDeauthorized")
  2679. self.loop.run()
  2680. return self
  2681. def groupStarted(self, properties):
  2682. logger.debug("groupStarted: " + str(properties))
  2683. self.group = properties['group_object']
  2684. self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  2685. properties['interface_object'])
  2686. role = self.g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Role",
  2687. dbus_interface=dbus.PROPERTIES_IFACE)
  2688. if role != "GO":
  2689. self.exceptions = True
  2690. raise Exception("Unexpected role reported: " + role)
  2691. group = self.g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Group",
  2692. dbus_interface=dbus.PROPERTIES_IFACE)
  2693. if group != properties['group_object']:
  2694. self.exceptions = True
  2695. raise Exception("Unexpected Group reported: " + str(group))
  2696. go = self.g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PeerGO",
  2697. dbus_interface=dbus.PROPERTIES_IFACE)
  2698. if go != '/':
  2699. self.exceptions = True
  2700. raise Exception("Unexpected PeerGO value: " + str(go))
  2701. if self.first:
  2702. self.first = False
  2703. logger.info("Remove persistent group instance")
  2704. group_p2p = dbus.Interface(self.g_if_obj,
  2705. WPAS_DBUS_IFACE_P2PDEVICE)
  2706. group_p2p.Disconnect()
  2707. else:
  2708. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2709. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 join")
  2710. def groupFinished(self, properties):
  2711. logger.debug("groupFinished: " + str(properties))
  2712. if self.waiting_end:
  2713. logger.info("Remove persistent group")
  2714. p2p.RemovePersistentGroup(self.persistent)
  2715. else:
  2716. logger.info("Re-start persistent group")
  2717. params = dbus.Dictionary({'persistent_group_object':
  2718. self.persistent,
  2719. 'frequency': 2412})
  2720. p2p.GroupAdd(params)
  2721. def persistentGroupAdded(self, path, properties):
  2722. logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
  2723. self.persistent = path
  2724. def persistentGroupRemoved(self, path):
  2725. logger.debug("persistentGroupRemoved: %s" % path)
  2726. self.done = True
  2727. self.loop.quit()
  2728. def deviceFound(self, path):
  2729. logger.debug("deviceFound: path=%s" % path)
  2730. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  2731. self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2732. dbus_interface=dbus.PROPERTIES_IFACE,
  2733. byte_arrays=True)
  2734. logger.debug('peer properties: ' + str(self.peer))
  2735. def provisionDiscoveryRequestDisplayPin(self, peer_object, pin):
  2736. logger.debug("provisionDiscoveryRequestDisplayPin - peer=%s pin=%s" % (peer_object, pin))
  2737. self.peer_path = peer_object
  2738. peer = binascii.unhexlify(peer_object.split('/')[-1])
  2739. addr = ""
  2740. for p in peer:
  2741. if len(addr) > 0:
  2742. addr += ':'
  2743. addr += '%02x' % ord(p)
  2744. params = { 'Role': 'registrar',
  2745. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  2746. 'Bssid': self.peer['DeviceAddress'],
  2747. 'Type': 'pin' }
  2748. wps = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_WPS)
  2749. try:
  2750. wps.Start(params)
  2751. self.exceptions = True
  2752. raise Exception("Invalid WPS.Start() accepted")
  2753. except dbus.exceptions.DBusException, e:
  2754. if "InvalidArgs" not in str(e):
  2755. self.exceptions = True
  2756. raise Exception("Unexpected error message: " + str(e))
  2757. params = { 'Role': 'registrar',
  2758. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  2759. 'Type': 'pin',
  2760. 'Pin': '12345670' }
  2761. logger.info("Authorize peer to connect to the group")
  2762. wps.Start(params)
  2763. def staAuthorized(self, name):
  2764. logger.debug("staAuthorized: " + name)
  2765. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, self.peer_path)
  2766. res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2767. dbus_interface=dbus.PROPERTIES_IFACE,
  2768. byte_arrays=True)
  2769. logger.debug("Peer properties: " + str(res))
  2770. if 'Groups' not in res or len(res['Groups']) != 1:
  2771. self.exceptions = True
  2772. raise Exception("Unexpected number of peer Groups entries")
  2773. if res['Groups'][0] != self.group:
  2774. self.exceptions = True
  2775. raise Exception("Unexpected peer Groups[0] value")
  2776. g_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group)
  2777. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  2778. dbus_interface=dbus.PROPERTIES_IFACE,
  2779. byte_arrays=True)
  2780. logger.debug("Group properties: " + str(res))
  2781. if 'Members' not in res or len(res['Members']) != 1:
  2782. self.exceptions = True
  2783. raise Exception("Unexpected number of group members")
  2784. ext = dbus.ByteArray("\x11\x22\x33\x44")
  2785. # Earlier implementation of this interface was a bit strange. The
  2786. # property is defined to have aay signature and that is what the
  2787. # getter returned. However, the setter expected there to be a
  2788. # dictionary with 'WPSVendorExtensions' as the key surrounding these
  2789. # values.. The current implementations maintains support for that
  2790. # for backwards compability reasons. Verify that encoding first.
  2791. vals = dbus.Dictionary({ 'WPSVendorExtensions': [ ext ]},
  2792. signature='sv')
  2793. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
  2794. dbus_interface=dbus.PROPERTIES_IFACE)
  2795. res = g_obj.Get(WPAS_DBUS_GROUP, 'WPSVendorExtensions',
  2796. dbus_interface=dbus.PROPERTIES_IFACE,
  2797. byte_arrays=True)
  2798. if len(res) != 1:
  2799. self.exceptions = True
  2800. raise Exception("Unexpected number of vendor extensions")
  2801. if res[0] != ext:
  2802. self.exceptions = True
  2803. raise Exception("Vendor extension value changed")
  2804. # And now verify that the more appropriate encoding is accepted as
  2805. # well.
  2806. res.append(dbus.ByteArray('\xaa\xbb\xcc\xdd\xee\xff'))
  2807. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
  2808. dbus_interface=dbus.PROPERTIES_IFACE)
  2809. res2 = g_obj.Get(WPAS_DBUS_GROUP, 'WPSVendorExtensions',
  2810. dbus_interface=dbus.PROPERTIES_IFACE,
  2811. byte_arrays=True)
  2812. if len(res) != 2:
  2813. self.exceptions = True
  2814. raise Exception("Unexpected number of vendor extensions")
  2815. if res[0] != res2[0] or res[1] != res2[1]:
  2816. self.exceptions = True
  2817. raise Exception("Vendor extension value changed")
  2818. for i in range(10):
  2819. res.append(dbus.ByteArray('\xaa\xbb'))
  2820. try:
  2821. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
  2822. dbus_interface=dbus.PROPERTIES_IFACE)
  2823. self.exceptions = True
  2824. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  2825. except dbus.exceptions.DBusException, e:
  2826. if "Error.Failed" not in str(e):
  2827. self.exceptions = True
  2828. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  2829. vals = dbus.Dictionary({ 'Foo': [ ext ]}, signature='sv')
  2830. try:
  2831. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
  2832. dbus_interface=dbus.PROPERTIES_IFACE)
  2833. self.exceptions = True
  2834. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  2835. except dbus.exceptions.DBusException, e:
  2836. if "InvalidArgs" not in str(e):
  2837. self.exceptions = True
  2838. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  2839. vals = [ "foo" ]
  2840. try:
  2841. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
  2842. dbus_interface=dbus.PROPERTIES_IFACE)
  2843. self.exceptions = True
  2844. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  2845. except dbus.exceptions.DBusException, e:
  2846. if "Error.Failed" not in str(e):
  2847. self.exceptions = True
  2848. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  2849. vals = [ [ "foo" ] ]
  2850. try:
  2851. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', vals,
  2852. dbus_interface=dbus.PROPERTIES_IFACE)
  2853. self.exceptions = True
  2854. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  2855. except dbus.exceptions.DBusException, e:
  2856. if "Error.Failed" not in str(e):
  2857. self.exceptions = True
  2858. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  2859. p2p.RemoveClient({ 'peer': self.peer_path })
  2860. self.waiting_end = True
  2861. group_p2p = dbus.Interface(self.g_if_obj,
  2862. WPAS_DBUS_IFACE_P2PDEVICE)
  2863. group_p2p.Disconnect()
  2864. def staDeauthorized(self, name):
  2865. logger.debug("staDeauthorized: " + name)
  2866. self.deauthorized = True
  2867. def run_test(self, *args):
  2868. logger.debug("run_test")
  2869. params = dbus.Dictionary({'persistent': True,
  2870. 'frequency': 2412})
  2871. logger.info("Add a persistent group")
  2872. p2p.GroupAdd(params)
  2873. return False
  2874. def success(self):
  2875. return self.done and self.deauthorized and not self.exceptions
  2876. with TestDbusP2p(bus) as t:
  2877. if not t.success():
  2878. raise Exception("Expected signals not seen")
  2879. dev[1].wait_go_ending_session()
  2880. def test_dbus_p2p_autogo_pbc(dev, apdev):
  2881. """D-Bus P2P autonomous GO and PBC"""
  2882. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2883. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2884. addr0 = dev[0].p2p_dev_addr()
  2885. class TestDbusP2p(TestDbus):
  2886. def __init__(self, bus):
  2887. TestDbus.__init__(self, bus)
  2888. self.first = True
  2889. self.waiting_end = False
  2890. self.done = False
  2891. def __enter__(self):
  2892. gobject.timeout_add(1, self.run_test)
  2893. gobject.timeout_add(15000, self.timeout)
  2894. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  2895. "DeviceFound")
  2896. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2897. "GroupStarted")
  2898. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2899. "GroupFinished")
  2900. self.add_signal(self.provisionDiscoveryPBCRequest,
  2901. WPAS_DBUS_IFACE_P2PDEVICE,
  2902. "ProvisionDiscoveryPBCRequest")
  2903. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  2904. "StaAuthorized")
  2905. self.loop.run()
  2906. return self
  2907. def groupStarted(self, properties):
  2908. logger.debug("groupStarted: " + str(properties))
  2909. self.group = properties['group_object']
  2910. self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  2911. properties['interface_object'])
  2912. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2913. dev1.global_request("P2P_CONNECT " + addr0 + " pbc join")
  2914. def groupFinished(self, properties):
  2915. logger.debug("groupFinished: " + str(properties))
  2916. self.done = True
  2917. self.loop.quit()
  2918. def deviceFound(self, path):
  2919. logger.debug("deviceFound: path=%s" % path)
  2920. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  2921. self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  2922. dbus_interface=dbus.PROPERTIES_IFACE,
  2923. byte_arrays=True)
  2924. logger.debug('peer properties: ' + str(self.peer))
  2925. def provisionDiscoveryPBCRequest(self, peer_object):
  2926. logger.debug("provisionDiscoveryPBCRequest - peer=%s" % peer_object)
  2927. self.peer_path = peer_object
  2928. peer = binascii.unhexlify(peer_object.split('/')[-1])
  2929. addr = ""
  2930. for p in peer:
  2931. if len(addr) > 0:
  2932. addr += ':'
  2933. addr += '%02x' % ord(p)
  2934. params = { 'Role': 'registrar',
  2935. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  2936. 'Type': 'pbc' }
  2937. logger.info("Authorize peer to connect to the group")
  2938. wps = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_WPS)
  2939. wps.Start(params)
  2940. def staAuthorized(self, name):
  2941. logger.debug("staAuthorized: " + name)
  2942. group_p2p = dbus.Interface(self.g_if_obj,
  2943. WPAS_DBUS_IFACE_P2PDEVICE)
  2944. group_p2p.Disconnect()
  2945. def run_test(self, *args):
  2946. logger.debug("run_test")
  2947. params = dbus.Dictionary({'frequency': 2412})
  2948. p2p.GroupAdd(params)
  2949. return False
  2950. def success(self):
  2951. return self.done
  2952. with TestDbusP2p(bus) as t:
  2953. if not t.success():
  2954. raise Exception("Expected signals not seen")
  2955. dev[1].wait_go_ending_session()
  2956. dev[1].flush_scan_cache()
  2957. def test_dbus_p2p_autogo_legacy(dev, apdev):
  2958. """D-Bus P2P autonomous GO and legacy STA"""
  2959. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  2960. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2961. addr0 = dev[0].p2p_dev_addr()
  2962. class TestDbusP2p(TestDbus):
  2963. def __init__(self, bus):
  2964. TestDbus.__init__(self, bus)
  2965. self.done = False
  2966. def __enter__(self):
  2967. gobject.timeout_add(1, self.run_test)
  2968. gobject.timeout_add(15000, self.timeout)
  2969. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  2970. "GroupStarted")
  2971. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  2972. "GroupFinished")
  2973. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  2974. "StaAuthorized")
  2975. self.loop.run()
  2976. return self
  2977. def groupStarted(self, properties):
  2978. logger.debug("groupStarted: " + str(properties))
  2979. g_obj = bus.get_object(WPAS_DBUS_SERVICE,
  2980. properties['group_object'])
  2981. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  2982. dbus_interface=dbus.PROPERTIES_IFACE,
  2983. byte_arrays=True)
  2984. bssid = ':'.join([binascii.hexlify(l) for l in res['BSSID']])
  2985. pin = '12345670'
  2986. params = { 'Role': 'enrollee',
  2987. 'Type': 'pin',
  2988. 'Pin': pin }
  2989. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  2990. properties['interface_object'])
  2991. wps = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_WPS)
  2992. wps.Start(params)
  2993. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  2994. dev1.scan_for_bss(bssid, freq=2412)
  2995. dev1.request("WPS_PIN " + bssid + " " + pin)
  2996. self.group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  2997. def groupFinished(self, properties):
  2998. logger.debug("groupFinished: " + str(properties))
  2999. self.done = True
  3000. self.loop.quit()
  3001. def staAuthorized(self, name):
  3002. logger.debug("staAuthorized: " + name)
  3003. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3004. dev1.request("DISCONNECT")
  3005. self.group_p2p.Disconnect()
  3006. def run_test(self, *args):
  3007. logger.debug("run_test")
  3008. params = dbus.Dictionary({'frequency': 2412})
  3009. p2p.GroupAdd(params)
  3010. return False
  3011. def success(self):
  3012. return self.done
  3013. with TestDbusP2p(bus) as t:
  3014. if not t.success():
  3015. raise Exception("Expected signals not seen")
  3016. def test_dbus_p2p_join(dev, apdev):
  3017. """D-Bus P2P join an autonomous GO"""
  3018. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3019. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3020. addr1 = dev[1].p2p_dev_addr()
  3021. addr2 = dev[2].p2p_dev_addr()
  3022. dev[1].p2p_start_go(freq=2412)
  3023. dev1_group_ifname = dev[1].group_ifname
  3024. dev[2].p2p_listen()
  3025. class TestDbusP2p(TestDbus):
  3026. def __init__(self, bus):
  3027. TestDbus.__init__(self, bus)
  3028. self.done = False
  3029. self.peer = None
  3030. self.go = None
  3031. def __enter__(self):
  3032. gobject.timeout_add(1, self.run_test)
  3033. gobject.timeout_add(15000, self.timeout)
  3034. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3035. "DeviceFound")
  3036. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3037. "GroupStarted")
  3038. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3039. "GroupFinished")
  3040. self.add_signal(self.invitationResult, WPAS_DBUS_IFACE_P2PDEVICE,
  3041. "InvitationResult")
  3042. self.loop.run()
  3043. return self
  3044. def deviceFound(self, path):
  3045. logger.debug("deviceFound: path=%s" % path)
  3046. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  3047. res = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  3048. dbus_interface=dbus.PROPERTIES_IFACE,
  3049. byte_arrays=True)
  3050. logger.debug('peer properties: ' + str(res))
  3051. if addr2.replace(':','') in path:
  3052. self.peer = path
  3053. elif addr1.replace(':','') in path:
  3054. self.go = path
  3055. if self.peer and self.go:
  3056. logger.info("Join the group")
  3057. p2p.StopFind()
  3058. args = { 'peer': self.go,
  3059. 'join': True,
  3060. 'wps_method': 'pin',
  3061. 'frequency': 2412 }
  3062. pin = p2p.Connect(args)
  3063. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3064. dev1.group_ifname = dev1_group_ifname
  3065. dev1.group_request("WPS_PIN any " + pin)
  3066. def groupStarted(self, properties):
  3067. logger.debug("groupStarted: " + str(properties))
  3068. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3069. properties['interface_object'])
  3070. role = g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Role",
  3071. dbus_interface=dbus.PROPERTIES_IFACE)
  3072. if role != "client":
  3073. raise Exception("Unexpected role reported: " + role)
  3074. group = g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "Group",
  3075. dbus_interface=dbus.PROPERTIES_IFACE)
  3076. if group != properties['group_object']:
  3077. raise Exception("Unexpected Group reported: " + str(group))
  3078. go = g_if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PeerGO",
  3079. dbus_interface=dbus.PROPERTIES_IFACE)
  3080. if go != self.go:
  3081. raise Exception("Unexpected PeerGO value: " + str(go))
  3082. g_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3083. properties['group_object'])
  3084. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  3085. dbus_interface=dbus.PROPERTIES_IFACE,
  3086. byte_arrays=True)
  3087. logger.debug("Group properties: " + str(res))
  3088. ext = dbus.ByteArray("\x11\x22\x33\x44")
  3089. try:
  3090. # Set(WPSVendorExtensions) not allowed for P2P Client
  3091. g_obj.Set(WPAS_DBUS_GROUP, 'WPSVendorExtensions', res,
  3092. dbus_interface=dbus.PROPERTIES_IFACE)
  3093. raise Exception("Invalid Set(WPSVendorExtensions) accepted")
  3094. except dbus.exceptions.DBusException, e:
  3095. if "Error.Failed: Failed to set property" not in str(e):
  3096. raise Exception("Unexpected error message for invalid Set(WPSVendorExtensions): " + str(e))
  3097. group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3098. args = { 'duration1': 30000, 'interval1': 102400,
  3099. 'duration2': 20000, 'interval2': 102400 }
  3100. group_p2p.PresenceRequest(args)
  3101. args = { 'peer': self.peer }
  3102. group_p2p.Invite(args)
  3103. def groupFinished(self, properties):
  3104. logger.debug("groupFinished: " + str(properties))
  3105. self.done = True
  3106. self.loop.quit()
  3107. def invitationResult(self, result):
  3108. logger.debug("invitationResult: " + str(result))
  3109. if result['status'] != 1:
  3110. raise Exception("Unexpected invitation result: " + str(result))
  3111. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3112. dev1.group_ifname = dev1_group_ifname
  3113. dev1.remove_group()
  3114. def run_test(self, *args):
  3115. logger.debug("run_test")
  3116. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  3117. return False
  3118. def success(self):
  3119. return self.done
  3120. with TestDbusP2p(bus) as t:
  3121. if not t.success():
  3122. raise Exception("Expected signals not seen")
  3123. dev[2].p2p_stop_find()
  3124. def test_dbus_p2p_config(dev, apdev):
  3125. """D-Bus Get/Set P2PDeviceConfig"""
  3126. try:
  3127. _test_dbus_p2p_config(dev, apdev)
  3128. finally:
  3129. dev[0].request("P2P_SET ssid_postfix ")
  3130. def _test_dbus_p2p_config(dev, apdev):
  3131. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3132. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3133. res = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3134. dbus_interface=dbus.PROPERTIES_IFACE,
  3135. byte_arrays=True)
  3136. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig", res,
  3137. dbus_interface=dbus.PROPERTIES_IFACE)
  3138. res2 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3139. dbus_interface=dbus.PROPERTIES_IFACE,
  3140. byte_arrays=True)
  3141. if len(res) != len(res2):
  3142. raise Exception("Different number of parameters")
  3143. for k in res:
  3144. if res[k] != res2[k]:
  3145. raise Exception("Parameter %s value changes" % k)
  3146. changes = { 'SsidPostfix': 'foo',
  3147. 'VendorExtension': [ dbus.ByteArray('\x11\x22\x33\x44') ],
  3148. 'SecondaryDeviceTypes': [ dbus.ByteArray('\x11\x22\x33\x44\x55\x66\x77\x88') ]}
  3149. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3150. dbus.Dictionary(changes, signature='sv'),
  3151. dbus_interface=dbus.PROPERTIES_IFACE)
  3152. res2 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3153. dbus_interface=dbus.PROPERTIES_IFACE,
  3154. byte_arrays=True)
  3155. logger.debug("P2PDeviceConfig: " + str(res2))
  3156. if 'VendorExtension' not in res2 or len(res2['VendorExtension']) != 1:
  3157. raise Exception("VendorExtension does not match")
  3158. if 'SecondaryDeviceTypes' not in res2 or len(res2['SecondaryDeviceTypes']) != 1:
  3159. raise Exception("SecondaryDeviceType does not match")
  3160. changes = { 'SsidPostfix': '',
  3161. 'VendorExtension': dbus.Array([], signature="ay"),
  3162. 'SecondaryDeviceTypes': dbus.Array([], signature="ay") }
  3163. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3164. dbus.Dictionary(changes, signature='sv'),
  3165. dbus_interface=dbus.PROPERTIES_IFACE)
  3166. res3 = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3167. dbus_interface=dbus.PROPERTIES_IFACE,
  3168. byte_arrays=True)
  3169. logger.debug("P2PDeviceConfig: " + str(res3))
  3170. if 'VendorExtension' in res3:
  3171. raise Exception("VendorExtension not removed")
  3172. if 'SecondaryDeviceTypes' in res3:
  3173. raise Exception("SecondaryDeviceType not removed")
  3174. try:
  3175. dev[0].request("P2P_SET disabled 1")
  3176. if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3177. dbus_interface=dbus.PROPERTIES_IFACE,
  3178. byte_arrays=True)
  3179. raise Exception("Invalid Get(P2PDeviceConfig) accepted")
  3180. except dbus.exceptions.DBusException, e:
  3181. if "Error.Failed: P2P is not available for this interface" not in str(e):
  3182. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  3183. finally:
  3184. dev[0].request("P2P_SET disabled 0")
  3185. try:
  3186. dev[0].request("P2P_SET disabled 1")
  3187. changes = { 'SsidPostfix': 'foo' }
  3188. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3189. dbus.Dictionary(changes, signature='sv'),
  3190. dbus_interface=dbus.PROPERTIES_IFACE)
  3191. raise Exception("Invalid Set(P2PDeviceConfig) accepted")
  3192. except dbus.exceptions.DBusException, e:
  3193. if "Error.Failed: P2P is not available for this interface" not in str(e):
  3194. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  3195. finally:
  3196. dev[0].request("P2P_SET disabled 0")
  3197. tests = [ { 'DeviceName': 123 },
  3198. { 'SsidPostfix': 123 },
  3199. { 'Foo': 'Bar' } ]
  3200. for changes in tests:
  3201. try:
  3202. if_obj.Set(WPAS_DBUS_IFACE_P2PDEVICE, "P2PDeviceConfig",
  3203. dbus.Dictionary(changes, signature='sv'),
  3204. dbus_interface=dbus.PROPERTIES_IFACE)
  3205. raise Exception("Invalid Set(P2PDeviceConfig) accepted")
  3206. except dbus.exceptions.DBusException, e:
  3207. if "InvalidArgs" not in str(e):
  3208. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  3209. def test_dbus_p2p_persistent(dev, apdev):
  3210. """D-Bus P2P persistent group"""
  3211. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3212. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3213. class TestDbusP2p(TestDbus):
  3214. def __init__(self, bus):
  3215. TestDbus.__init__(self, bus)
  3216. def __enter__(self):
  3217. gobject.timeout_add(1, self.run_test)
  3218. gobject.timeout_add(15000, self.timeout)
  3219. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3220. "GroupStarted")
  3221. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3222. "GroupFinished")
  3223. self.add_signal(self.persistentGroupAdded,
  3224. WPAS_DBUS_IFACE_P2PDEVICE,
  3225. "PersistentGroupAdded")
  3226. self.loop.run()
  3227. return self
  3228. def groupStarted(self, properties):
  3229. logger.debug("groupStarted: " + str(properties))
  3230. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3231. properties['interface_object'])
  3232. group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3233. group_p2p.Disconnect()
  3234. def groupFinished(self, properties):
  3235. logger.debug("groupFinished: " + str(properties))
  3236. self.loop.quit()
  3237. def persistentGroupAdded(self, path, properties):
  3238. logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
  3239. self.persistent = path
  3240. def run_test(self, *args):
  3241. logger.debug("run_test")
  3242. params = dbus.Dictionary({'persistent': True,
  3243. 'frequency': 2412})
  3244. logger.info("Add a persistent group")
  3245. p2p.GroupAdd(params)
  3246. return False
  3247. def success(self):
  3248. return True
  3249. with TestDbusP2p(bus) as t:
  3250. if not t.success():
  3251. raise Exception("Expected signals not seen")
  3252. persistent = t.persistent
  3253. p_obj = bus.get_object(WPAS_DBUS_SERVICE, persistent)
  3254. res = p_obj.Get(WPAS_DBUS_PERSISTENT_GROUP, "Properties",
  3255. dbus_interface=dbus.PROPERTIES_IFACE, byte_arrays=True)
  3256. logger.info("Persistent group Properties: " + str(res))
  3257. vals = dbus.Dictionary({ 'ssid': 'DIRECT-foo' }, signature='sv')
  3258. p_obj.Set(WPAS_DBUS_PERSISTENT_GROUP, "Properties", vals,
  3259. dbus_interface=dbus.PROPERTIES_IFACE)
  3260. res2 = p_obj.Get(WPAS_DBUS_PERSISTENT_GROUP, "Properties",
  3261. dbus_interface=dbus.PROPERTIES_IFACE)
  3262. if len(res) != len(res2):
  3263. raise Exception("Different number of parameters")
  3264. for k in res:
  3265. if k != 'ssid' and res[k] != res2[k]:
  3266. raise Exception("Parameter %s value changes" % k)
  3267. if res2['ssid'] != '"DIRECT-foo"':
  3268. raise Exception("Unexpected ssid")
  3269. args = dbus.Dictionary({ 'ssid': 'DIRECT-testing',
  3270. 'psk': '1234567890' }, signature='sv')
  3271. group = p2p.AddPersistentGroup(args)
  3272. groups = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PersistentGroups",
  3273. dbus_interface=dbus.PROPERTIES_IFACE)
  3274. if len(groups) != 2:
  3275. raise Exception("Unexpected number of persistent groups: " + str(groups))
  3276. p2p.RemoveAllPersistentGroups()
  3277. groups = if_obj.Get(WPAS_DBUS_IFACE_P2PDEVICE, "PersistentGroups",
  3278. dbus_interface=dbus.PROPERTIES_IFACE)
  3279. if len(groups) != 0:
  3280. raise Exception("Unexpected number of persistent groups: " + str(groups))
  3281. try:
  3282. p2p.RemovePersistentGroup(persistent)
  3283. raise Exception("Invalid RemovePersistentGroup accepted")
  3284. except dbus.exceptions.DBusException, e:
  3285. if "NetworkUnknown: There is no such persistent group" not in str(e):
  3286. raise Exception("Unexpected error message for invalid RemovePersistentGroup: " + str(e))
  3287. def test_dbus_p2p_reinvoke_persistent(dev, apdev):
  3288. """D-Bus P2P reinvoke persistent group"""
  3289. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3290. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3291. addr0 = dev[0].p2p_dev_addr()
  3292. class TestDbusP2p(TestDbus):
  3293. def __init__(self, bus):
  3294. TestDbus.__init__(self, bus)
  3295. self.first = True
  3296. self.waiting_end = False
  3297. self.done = False
  3298. self.invited = False
  3299. def __enter__(self):
  3300. gobject.timeout_add(1, self.run_test)
  3301. gobject.timeout_add(15000, self.timeout)
  3302. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3303. "DeviceFound")
  3304. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3305. "GroupStarted")
  3306. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3307. "GroupFinished")
  3308. self.add_signal(self.persistentGroupAdded,
  3309. WPAS_DBUS_IFACE_P2PDEVICE,
  3310. "PersistentGroupAdded")
  3311. self.add_signal(self.provisionDiscoveryRequestDisplayPin,
  3312. WPAS_DBUS_IFACE_P2PDEVICE,
  3313. "ProvisionDiscoveryRequestDisplayPin")
  3314. self.add_signal(self.staAuthorized, WPAS_DBUS_IFACE,
  3315. "StaAuthorized")
  3316. self.loop.run()
  3317. return self
  3318. def groupStarted(self, properties):
  3319. logger.debug("groupStarted: " + str(properties))
  3320. self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3321. properties['interface_object'])
  3322. if not self.invited:
  3323. g_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3324. properties['group_object'])
  3325. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  3326. dbus_interface=dbus.PROPERTIES_IFACE,
  3327. byte_arrays=True)
  3328. bssid = ':'.join([binascii.hexlify(l) for l in res['BSSID']])
  3329. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3330. dev1.scan_for_bss(bssid, freq=2412)
  3331. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 join")
  3332. def groupFinished(self, properties):
  3333. logger.debug("groupFinished: " + str(properties))
  3334. if self.invited:
  3335. self.done = True
  3336. self.loop.quit()
  3337. else:
  3338. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3339. dev1.global_request("SET persistent_reconnect 1")
  3340. dev1.p2p_listen()
  3341. args = { 'persistent_group_object': dbus.ObjectPath(path),
  3342. 'peer': self.peer_path }
  3343. try:
  3344. pin = p2p.Invite(args)
  3345. raise Exception("Invalid Invite accepted")
  3346. except dbus.exceptions.DBusException, e:
  3347. if "InvalidArgs" not in str(e):
  3348. raise Exception("Unexpected error message for invalid Invite: " + str(e))
  3349. args = { 'persistent_group_object': self.persistent,
  3350. 'peer': self.peer_path }
  3351. pin = p2p.Invite(args)
  3352. self.invited = True
  3353. self.sta_group_ev = dev1.wait_global_event(["P2P-GROUP-STARTED"],
  3354. timeout=15)
  3355. if self.sta_group_ev is None:
  3356. raise Exception("P2P-GROUP-STARTED event not seen")
  3357. def persistentGroupAdded(self, path, properties):
  3358. logger.debug("persistentGroupAdded: %s %s" % (path, str(properties)))
  3359. self.persistent = path
  3360. def deviceFound(self, path):
  3361. logger.debug("deviceFound: path=%s" % path)
  3362. peer_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
  3363. self.peer = peer_obj.GetAll(WPAS_DBUS_P2P_PEER,
  3364. dbus_interface=dbus.PROPERTIES_IFACE,
  3365. byte_arrays=True)
  3366. def provisionDiscoveryRequestDisplayPin(self, peer_object, pin):
  3367. logger.debug("provisionDiscoveryRequestDisplayPin - peer=%s pin=%s" % (peer_object, pin))
  3368. self.peer_path = peer_object
  3369. peer = binascii.unhexlify(peer_object.split('/')[-1])
  3370. addr = ""
  3371. for p in peer:
  3372. if len(addr) > 0:
  3373. addr += ':'
  3374. addr += '%02x' % ord(p)
  3375. params = { 'Role': 'registrar',
  3376. 'P2PDeviceAddress': self.peer['DeviceAddress'],
  3377. 'Bssid': self.peer['DeviceAddress'],
  3378. 'Type': 'pin',
  3379. 'Pin': '12345670' }
  3380. logger.info("Authorize peer to connect to the group")
  3381. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3382. wps = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_WPS)
  3383. wps.Start(params)
  3384. self.sta_group_ev = dev1.wait_global_event(["P2P-GROUP-STARTED"],
  3385. timeout=15)
  3386. if self.sta_group_ev is None:
  3387. raise Exception("P2P-GROUP-STARTED event not seen")
  3388. def staAuthorized(self, name):
  3389. logger.debug("staAuthorized: " + name)
  3390. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3391. dev1.group_form_result(self.sta_group_ev)
  3392. dev1.remove_group()
  3393. ev = dev1.wait_global_event(["P2P-GROUP-REMOVED"], timeout=10)
  3394. if ev is None:
  3395. raise Exception("Group removal timed out")
  3396. group_p2p = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3397. group_p2p.Disconnect()
  3398. def run_test(self, *args):
  3399. logger.debug("run_test")
  3400. params = dbus.Dictionary({'persistent': True,
  3401. 'frequency': 2412})
  3402. logger.info("Add a persistent group")
  3403. p2p.GroupAdd(params)
  3404. return False
  3405. def success(self):
  3406. return self.done
  3407. with TestDbusP2p(bus) as t:
  3408. if not t.success():
  3409. raise Exception("Expected signals not seen")
  3410. def test_dbus_p2p_go_neg_rx(dev, apdev):
  3411. """D-Bus P2P GO Negotiation receive"""
  3412. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3413. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3414. addr0 = dev[0].p2p_dev_addr()
  3415. class TestDbusP2p(TestDbus):
  3416. def __init__(self, bus):
  3417. TestDbus.__init__(self, bus)
  3418. self.done = False
  3419. def __enter__(self):
  3420. gobject.timeout_add(1, self.run_test)
  3421. gobject.timeout_add(15000, self.timeout)
  3422. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3423. "DeviceFound")
  3424. self.add_signal(self.goNegotiationRequest,
  3425. WPAS_DBUS_IFACE_P2PDEVICE,
  3426. "GONegotiationRequest",
  3427. byte_arrays=True)
  3428. self.add_signal(self.goNegotiationSuccess,
  3429. WPAS_DBUS_IFACE_P2PDEVICE,
  3430. "GONegotiationSuccess",
  3431. byte_arrays=True)
  3432. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3433. "GroupStarted")
  3434. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3435. "GroupFinished")
  3436. self.loop.run()
  3437. return self
  3438. def deviceFound(self, path):
  3439. logger.debug("deviceFound: path=%s" % path)
  3440. def goNegotiationRequest(self, path, dev_passwd_id, go_intent=0):
  3441. logger.debug("goNegotiationRequest: path=%s dev_passwd_id=%d go_intent=%d" % (path, dev_passwd_id, go_intent))
  3442. if dev_passwd_id != 1:
  3443. raise Exception("Unexpected dev_passwd_id=%d" % dev_passwd_id)
  3444. args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
  3445. 'go_intent': 15, 'persistent': False, 'frequency': 5175 }
  3446. try:
  3447. p2p.Connect(args)
  3448. raise Exception("Invalid Connect accepted")
  3449. except dbus.exceptions.DBusException, e:
  3450. if "ConnectChannelUnsupported" not in str(e):
  3451. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  3452. args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
  3453. 'go_intent': 15, 'persistent': False }
  3454. p2p.Connect(args)
  3455. def goNegotiationSuccess(self, properties):
  3456. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3457. def groupStarted(self, properties):
  3458. logger.debug("groupStarted: " + str(properties))
  3459. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3460. properties['interface_object'])
  3461. group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3462. group_p2p.Disconnect()
  3463. def groupFinished(self, properties):
  3464. logger.debug("groupFinished: " + str(properties))
  3465. self.done = True
  3466. self.loop.quit()
  3467. def run_test(self, *args):
  3468. logger.debug("run_test")
  3469. p2p.Listen(10)
  3470. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3471. if not dev1.discover_peer(addr0):
  3472. raise Exception("Peer not found")
  3473. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 enter")
  3474. return False
  3475. def success(self):
  3476. return self.done
  3477. with TestDbusP2p(bus) as t:
  3478. if not t.success():
  3479. raise Exception("Expected signals not seen")
  3480. def test_dbus_p2p_go_neg_auth(dev, apdev):
  3481. """D-Bus P2P GO Negotiation authorized"""
  3482. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3483. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3484. addr0 = dev[0].p2p_dev_addr()
  3485. dev[1].p2p_listen()
  3486. class TestDbusP2p(TestDbus):
  3487. def __init__(self, bus):
  3488. TestDbus.__init__(self, bus)
  3489. self.done = False
  3490. self.peer_joined = False
  3491. self.peer_disconnected = False
  3492. def __enter__(self):
  3493. gobject.timeout_add(1, self.run_test)
  3494. gobject.timeout_add(15000, self.timeout)
  3495. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3496. "DeviceFound")
  3497. self.add_signal(self.goNegotiationSuccess,
  3498. WPAS_DBUS_IFACE_P2PDEVICE,
  3499. "GONegotiationSuccess",
  3500. byte_arrays=True)
  3501. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3502. "GroupStarted")
  3503. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3504. "GroupFinished")
  3505. self.add_signal(self.staDeauthorized, WPAS_DBUS_IFACE,
  3506. "StaDeauthorized")
  3507. self.add_signal(self.peerJoined, WPAS_DBUS_GROUP,
  3508. "PeerJoined")
  3509. self.add_signal(self.peerDisconnected, WPAS_DBUS_GROUP,
  3510. "PeerDisconnected")
  3511. self.loop.run()
  3512. return self
  3513. def deviceFound(self, path):
  3514. logger.debug("deviceFound: path=%s" % path)
  3515. args = { 'peer': path, 'wps_method': 'keypad',
  3516. 'go_intent': 15, 'authorize_only': True }
  3517. try:
  3518. p2p.Connect(args)
  3519. raise Exception("Invalid Connect accepted")
  3520. except dbus.exceptions.DBusException, e:
  3521. if "InvalidArgs" not in str(e):
  3522. raise Exception("Unexpected error message for invalid Connect: " + str(e))
  3523. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  3524. 'go_intent': 15, 'authorize_only': True }
  3525. p2p.Connect(args)
  3526. p2p.Listen(10)
  3527. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3528. if not dev1.discover_peer(addr0):
  3529. raise Exception("Peer not found")
  3530. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=0")
  3531. ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
  3532. if ev is None:
  3533. raise Exception("Group formation timed out")
  3534. self.sta_group_ev = ev
  3535. def goNegotiationSuccess(self, properties):
  3536. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3537. def groupStarted(self, properties):
  3538. logger.debug("groupStarted: " + str(properties))
  3539. self.g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3540. properties['interface_object'])
  3541. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3542. dev1.group_form_result(self.sta_group_ev)
  3543. dev1.remove_group()
  3544. def staDeauthorized(self, name):
  3545. logger.debug("staDeuthorized: " + name)
  3546. group_p2p = dbus.Interface(self.g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3547. group_p2p.Disconnect()
  3548. def peerJoined(self, peer):
  3549. logger.debug("peerJoined: " + peer)
  3550. self.peer_joined = True
  3551. def peerDisconnected(self, peer):
  3552. logger.debug("peerDisconnected: " + peer)
  3553. self.peer_disconnected = True
  3554. def groupFinished(self, properties):
  3555. logger.debug("groupFinished: " + str(properties))
  3556. self.done = True
  3557. self.loop.quit()
  3558. def run_test(self, *args):
  3559. logger.debug("run_test")
  3560. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  3561. return False
  3562. def success(self):
  3563. return self.done and self.peer_joined and self.peer_disconnected
  3564. with TestDbusP2p(bus) as t:
  3565. if not t.success():
  3566. raise Exception("Expected signals not seen")
  3567. def test_dbus_p2p_go_neg_init(dev, apdev):
  3568. """D-Bus P2P GO Negotiation initiation"""
  3569. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3570. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3571. addr0 = dev[0].p2p_dev_addr()
  3572. dev[1].p2p_listen()
  3573. class TestDbusP2p(TestDbus):
  3574. def __init__(self, bus):
  3575. TestDbus.__init__(self, bus)
  3576. self.done = False
  3577. self.peer_group_added = False
  3578. self.peer_group_removed = False
  3579. def __enter__(self):
  3580. gobject.timeout_add(1, self.run_test)
  3581. gobject.timeout_add(15000, self.timeout)
  3582. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3583. "DeviceFound")
  3584. self.add_signal(self.goNegotiationSuccess,
  3585. WPAS_DBUS_IFACE_P2PDEVICE,
  3586. "GONegotiationSuccess",
  3587. byte_arrays=True)
  3588. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3589. "GroupStarted")
  3590. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3591. "GroupFinished")
  3592. self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
  3593. "PropertiesChanged")
  3594. self.loop.run()
  3595. return self
  3596. def deviceFound(self, path):
  3597. logger.debug("deviceFound: path=%s" % path)
  3598. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3599. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  3600. 'go_intent': 0 }
  3601. p2p.Connect(args)
  3602. ev = dev1.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
  3603. if ev is None:
  3604. raise Exception("Timeout while waiting for GO Neg Request")
  3605. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=15")
  3606. ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
  3607. if ev is None:
  3608. raise Exception("Group formation timed out")
  3609. self.sta_group_ev = ev
  3610. def goNegotiationSuccess(self, properties):
  3611. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3612. def groupStarted(self, properties):
  3613. logger.debug("groupStarted: " + str(properties))
  3614. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3615. properties['interface_object'])
  3616. group_p2p = dbus.Interface(g_if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3617. group_p2p.Disconnect()
  3618. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3619. dev1.group_form_result(self.sta_group_ev)
  3620. dev1.remove_group()
  3621. def groupFinished(self, properties):
  3622. logger.debug("groupFinished: " + str(properties))
  3623. self.done = True
  3624. def propertiesChanged(self, interface_name, changed_properties,
  3625. invalidated_properties):
  3626. logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
  3627. if interface_name != WPAS_DBUS_P2P_PEER:
  3628. return
  3629. if "Groups" not in changed_properties:
  3630. return
  3631. if len(changed_properties["Groups"]) > 0:
  3632. self.peer_group_added = True
  3633. if len(changed_properties["Groups"]) == 0:
  3634. self.peer_group_removed = True
  3635. self.loop.quit()
  3636. def run_test(self, *args):
  3637. logger.debug("run_test")
  3638. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  3639. return False
  3640. def success(self):
  3641. return self.done and self.peer_group_added and self.peer_group_removed
  3642. with TestDbusP2p(bus) as t:
  3643. if not t.success():
  3644. raise Exception("Expected signals not seen")
  3645. def test_dbus_p2p_group_termination_by_go(dev, apdev):
  3646. """D-Bus P2P group removal on GO terminating the group"""
  3647. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3648. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3649. addr0 = dev[0].p2p_dev_addr()
  3650. dev[1].p2p_listen()
  3651. class TestDbusP2p(TestDbus):
  3652. def __init__(self, bus):
  3653. TestDbus.__init__(self, bus)
  3654. self.done = False
  3655. self.peer_group_added = False
  3656. self.peer_group_removed = False
  3657. def __enter__(self):
  3658. gobject.timeout_add(1, self.run_test)
  3659. gobject.timeout_add(15000, self.timeout)
  3660. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3661. "DeviceFound")
  3662. self.add_signal(self.goNegotiationSuccess,
  3663. WPAS_DBUS_IFACE_P2PDEVICE,
  3664. "GONegotiationSuccess",
  3665. byte_arrays=True)
  3666. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3667. "GroupStarted")
  3668. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3669. "GroupFinished")
  3670. self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
  3671. "PropertiesChanged")
  3672. self.loop.run()
  3673. return self
  3674. def deviceFound(self, path):
  3675. logger.debug("deviceFound: path=%s" % path)
  3676. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3677. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  3678. 'go_intent': 0 }
  3679. p2p.Connect(args)
  3680. ev = dev1.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
  3681. if ev is None:
  3682. raise Exception("Timeout while waiting for GO Neg Request")
  3683. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=15")
  3684. ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
  3685. if ev is None:
  3686. raise Exception("Group formation timed out")
  3687. self.sta_group_ev = ev
  3688. def goNegotiationSuccess(self, properties):
  3689. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3690. def groupStarted(self, properties):
  3691. logger.debug("groupStarted: " + str(properties))
  3692. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3693. properties['interface_object'])
  3694. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3695. dev1.group_form_result(self.sta_group_ev)
  3696. dev1.remove_group()
  3697. def groupFinished(self, properties):
  3698. logger.debug("groupFinished: " + str(properties))
  3699. self.done = True
  3700. def propertiesChanged(self, interface_name, changed_properties,
  3701. invalidated_properties):
  3702. logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
  3703. if interface_name != WPAS_DBUS_P2P_PEER:
  3704. return
  3705. if "Groups" not in changed_properties:
  3706. return
  3707. if len(changed_properties["Groups"]) > 0:
  3708. self.peer_group_added = True
  3709. if len(changed_properties["Groups"]) == 0 and self.peer_group_added:
  3710. self.peer_group_removed = True
  3711. self.loop.quit()
  3712. def run_test(self, *args):
  3713. logger.debug("run_test")
  3714. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  3715. return False
  3716. def success(self):
  3717. return self.done and self.peer_group_added and self.peer_group_removed
  3718. with TestDbusP2p(bus) as t:
  3719. if not t.success():
  3720. raise Exception("Expected signals not seen")
  3721. def test_dbus_p2p_group_idle_timeout(dev, apdev):
  3722. """D-Bus P2P group removal on idle timeout"""
  3723. try:
  3724. dev[0].global_request("SET p2p_group_idle 1")
  3725. _test_dbus_p2p_group_idle_timeout(dev, apdev)
  3726. finally:
  3727. dev[0].global_request("SET p2p_group_idle 0")
  3728. def _test_dbus_p2p_group_idle_timeout(dev, apdev):
  3729. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3730. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3731. addr0 = dev[0].p2p_dev_addr()
  3732. dev[1].p2p_listen()
  3733. class TestDbusP2p(TestDbus):
  3734. def __init__(self, bus):
  3735. TestDbus.__init__(self, bus)
  3736. self.done = False
  3737. self.peer_group_added = False
  3738. self.peer_group_removed = False
  3739. def __enter__(self):
  3740. gobject.timeout_add(1, self.run_test)
  3741. gobject.timeout_add(15000, self.timeout)
  3742. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3743. "DeviceFound")
  3744. self.add_signal(self.goNegotiationSuccess,
  3745. WPAS_DBUS_IFACE_P2PDEVICE,
  3746. "GONegotiationSuccess",
  3747. byte_arrays=True)
  3748. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3749. "GroupStarted")
  3750. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3751. "GroupFinished")
  3752. self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
  3753. "PropertiesChanged")
  3754. self.loop.run()
  3755. return self
  3756. def deviceFound(self, path):
  3757. logger.debug("deviceFound: path=%s" % path)
  3758. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3759. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  3760. 'go_intent': 0 }
  3761. p2p.Connect(args)
  3762. ev = dev1.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
  3763. if ev is None:
  3764. raise Exception("Timeout while waiting for GO Neg Request")
  3765. dev1.global_request("P2P_CONNECT " + addr0 + " 12345670 display go_intent=15")
  3766. ev = dev1.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
  3767. if ev is None:
  3768. raise Exception("Group formation timed out")
  3769. self.sta_group_ev = ev
  3770. def goNegotiationSuccess(self, properties):
  3771. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3772. def groupStarted(self, properties):
  3773. logger.debug("groupStarted: " + str(properties))
  3774. g_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3775. properties['interface_object'])
  3776. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3777. dev1.group_form_result(self.sta_group_ev)
  3778. ifaddr = dev1.group_request("STA-FIRST").splitlines()[0]
  3779. # Force disassociation with different reason code so that the
  3780. # P2P Client using D-Bus does not get normal group termination event
  3781. # from the GO.
  3782. dev1.group_request("DEAUTHENTICATE " + ifaddr + " reason=0 test=0")
  3783. dev1.remove_group()
  3784. def groupFinished(self, properties):
  3785. logger.debug("groupFinished: " + str(properties))
  3786. self.done = True
  3787. def propertiesChanged(self, interface_name, changed_properties,
  3788. invalidated_properties):
  3789. logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
  3790. if interface_name != WPAS_DBUS_P2P_PEER:
  3791. return
  3792. if "Groups" not in changed_properties:
  3793. return
  3794. if len(changed_properties["Groups"]) > 0:
  3795. self.peer_group_added = True
  3796. if len(changed_properties["Groups"]) == 0:
  3797. self.peer_group_removed = True
  3798. self.loop.quit()
  3799. def run_test(self, *args):
  3800. logger.debug("run_test")
  3801. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  3802. return False
  3803. def success(self):
  3804. return self.done and self.peer_group_added and self.peer_group_removed
  3805. with TestDbusP2p(bus) as t:
  3806. if not t.success():
  3807. raise Exception("Expected signals not seen")
  3808. def test_dbus_p2p_wps_failure(dev, apdev):
  3809. """D-Bus P2P WPS failure"""
  3810. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3811. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3812. addr0 = dev[0].p2p_dev_addr()
  3813. class TestDbusP2p(TestDbus):
  3814. def __init__(self, bus):
  3815. TestDbus.__init__(self, bus)
  3816. self.wps_failed = False
  3817. self.formation_failure = False
  3818. def __enter__(self):
  3819. gobject.timeout_add(1, self.run_test)
  3820. gobject.timeout_add(15000, self.timeout)
  3821. self.add_signal(self.goNegotiationRequest,
  3822. WPAS_DBUS_IFACE_P2PDEVICE,
  3823. "GONegotiationRequest",
  3824. byte_arrays=True)
  3825. self.add_signal(self.goNegotiationSuccess,
  3826. WPAS_DBUS_IFACE_P2PDEVICE,
  3827. "GONegotiationSuccess",
  3828. byte_arrays=True)
  3829. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3830. "GroupStarted")
  3831. self.add_signal(self.wpsFailed, WPAS_DBUS_IFACE_P2PDEVICE,
  3832. "WpsFailed")
  3833. self.add_signal(self.groupFormationFailure,
  3834. WPAS_DBUS_IFACE_P2PDEVICE,
  3835. "GroupFormationFailure")
  3836. self.loop.run()
  3837. return self
  3838. def goNegotiationRequest(self, path, dev_passwd_id, go_intent=0):
  3839. logger.debug("goNegotiationRequest: path=%s dev_passwd_id=%d go_intent=%d" % (path, dev_passwd_id, go_intent))
  3840. if dev_passwd_id != 1:
  3841. raise Exception("Unexpected dev_passwd_id=%d" % dev_passwd_id)
  3842. args = { 'peer': path, 'wps_method': 'display', 'pin': '12345670',
  3843. 'go_intent': 15 }
  3844. p2p.Connect(args)
  3845. def goNegotiationSuccess(self, properties):
  3846. logger.debug("goNegotiationSuccess: properties=%s" % str(properties))
  3847. def groupStarted(self, properties):
  3848. logger.debug("groupStarted: " + str(properties))
  3849. raise Exception("Unexpected GroupStarted")
  3850. def wpsFailed(self, name, args):
  3851. logger.debug("wpsFailed - name=%s args=%s" % (name, str(args)))
  3852. self.wps_failed = True
  3853. if self.formation_failure:
  3854. self.loop.quit()
  3855. def groupFormationFailure(self, reason):
  3856. logger.debug("groupFormationFailure - reason=%s" % reason)
  3857. self.formation_failure = True
  3858. if self.wps_failed:
  3859. self.loop.quit()
  3860. def run_test(self, *args):
  3861. logger.debug("run_test")
  3862. p2p.Listen(10)
  3863. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3864. if not dev1.discover_peer(addr0):
  3865. raise Exception("Peer not found")
  3866. dev1.global_request("P2P_CONNECT " + addr0 + " 87654321 enter")
  3867. return False
  3868. def success(self):
  3869. return self.wps_failed and self.formation_failure
  3870. with TestDbusP2p(bus) as t:
  3871. if not t.success():
  3872. raise Exception("Expected signals not seen")
  3873. def test_dbus_p2p_two_groups(dev, apdev):
  3874. """D-Bus P2P with two concurrent groups"""
  3875. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  3876. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  3877. dev[0].request("SET p2p_no_group_iface 0")
  3878. addr0 = dev[0].p2p_dev_addr()
  3879. addr1 = dev[1].p2p_dev_addr()
  3880. addr2 = dev[2].p2p_dev_addr()
  3881. dev[1].p2p_start_go(freq=2412)
  3882. dev1_group_ifname = dev[1].group_ifname
  3883. class TestDbusP2p(TestDbus):
  3884. def __init__(self, bus):
  3885. TestDbus.__init__(self, bus)
  3886. self.done = False
  3887. self.peer = None
  3888. self.go = None
  3889. self.group1 = None
  3890. self.group2 = None
  3891. self.groups_removed = False
  3892. def __enter__(self):
  3893. gobject.timeout_add(1, self.run_test)
  3894. gobject.timeout_add(15000, self.timeout)
  3895. self.add_signal(self.propertiesChanged, dbus.PROPERTIES_IFACE,
  3896. "PropertiesChanged", byte_arrays=True)
  3897. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  3898. "DeviceFound")
  3899. self.add_signal(self.groupStarted, WPAS_DBUS_IFACE_P2PDEVICE,
  3900. "GroupStarted")
  3901. self.add_signal(self.groupFinished, WPAS_DBUS_IFACE_P2PDEVICE,
  3902. "GroupFinished")
  3903. self.add_signal(self.peerJoined, WPAS_DBUS_GROUP,
  3904. "PeerJoined")
  3905. self.loop.run()
  3906. return self
  3907. def propertiesChanged(self, interface_name, changed_properties,
  3908. invalidated_properties):
  3909. logger.debug("propertiesChanged: interface_name=%s changed_properties=%s invalidated_properties=%s" % (interface_name, str(changed_properties), str(invalidated_properties)))
  3910. def deviceFound(self, path):
  3911. logger.debug("deviceFound: path=%s" % path)
  3912. if addr2.replace(':','') in path:
  3913. self.peer = path
  3914. elif addr1.replace(':','') in path:
  3915. self.go = path
  3916. if self.go and not self.group1:
  3917. logger.info("Join the group")
  3918. p2p.StopFind()
  3919. pin = '12345670'
  3920. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  3921. dev1.group_ifname = dev1_group_ifname
  3922. dev1.group_request("WPS_PIN any " + pin)
  3923. args = { 'peer': self.go,
  3924. 'join': True,
  3925. 'wps_method': 'pin',
  3926. 'pin': pin,
  3927. 'frequency': 2412 }
  3928. p2p.Connect(args)
  3929. def groupStarted(self, properties):
  3930. logger.debug("groupStarted: " + str(properties))
  3931. prop = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
  3932. dbus_interface=dbus.PROPERTIES_IFACE)
  3933. logger.debug("p2pdevice properties: " + str(prop))
  3934. g_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3935. properties['group_object'])
  3936. res = g_obj.GetAll(WPAS_DBUS_GROUP,
  3937. dbus_interface=dbus.PROPERTIES_IFACE,
  3938. byte_arrays=True)
  3939. logger.debug("Group properties: " + str(res))
  3940. if not self.group1:
  3941. self.group1 = properties['group_object']
  3942. self.group1iface = properties['interface_object']
  3943. self.g1_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3944. self.group1iface)
  3945. logger.info("Start autonomous GO")
  3946. params = dbus.Dictionary({ 'frequency': 2412 })
  3947. p2p.GroupAdd(params)
  3948. elif not self.group2:
  3949. self.group2 = properties['group_object']
  3950. self.group2iface = properties['interface_object']
  3951. self.g2_if_obj = bus.get_object(WPAS_DBUS_SERVICE,
  3952. self.group2iface)
  3953. self.g2_bssid = res['BSSID']
  3954. if self.group1 and self.group2:
  3955. logger.info("Authorize peer to join the group")
  3956. a2 = binascii.unhexlify(addr2.replace(':',''))
  3957. params = { 'Role': 'enrollee',
  3958. 'P2PDeviceAddress': dbus.ByteArray(a2),
  3959. 'Bssid': dbus.ByteArray(a2),
  3960. 'Type': 'pin',
  3961. 'Pin': '12345670' }
  3962. g_wps = dbus.Interface(self.g2_if_obj, WPAS_DBUS_IFACE_WPS)
  3963. g_wps.Start(params)
  3964. bssid = ':'.join([binascii.hexlify(l) for l in self.g2_bssid])
  3965. dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2')
  3966. dev2.scan_for_bss(bssid, freq=2412)
  3967. dev2.global_request("P2P_CONNECT " + bssid + " 12345670 join freq=2412")
  3968. ev = dev2.wait_global_event(["P2P-GROUP-STARTED"], timeout=15);
  3969. if ev is None:
  3970. raise Exception("Group join timed out")
  3971. self.dev2_group_ev = ev
  3972. def groupFinished(self, properties):
  3973. logger.debug("groupFinished: " + str(properties))
  3974. if self.group1 == properties['group_object']:
  3975. self.group1 = None
  3976. elif self.group2 == properties['group_object']:
  3977. self.group2 = None
  3978. if not self.group1 and not self.group2:
  3979. self.done = True
  3980. self.loop.quit()
  3981. def peerJoined(self, peer):
  3982. logger.debug("peerJoined: " + peer)
  3983. if self.groups_removed:
  3984. return
  3985. self.check_results()
  3986. dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2')
  3987. dev2.group_form_result(self.dev2_group_ev)
  3988. dev2.remove_group()
  3989. logger.info("Disconnect group2")
  3990. group_p2p = dbus.Interface(self.g2_if_obj,
  3991. WPAS_DBUS_IFACE_P2PDEVICE)
  3992. group_p2p.Disconnect()
  3993. logger.info("Disconnect group1")
  3994. group_p2p = dbus.Interface(self.g1_if_obj,
  3995. WPAS_DBUS_IFACE_P2PDEVICE)
  3996. group_p2p.Disconnect()
  3997. self.groups_removed = True
  3998. def check_results(self):
  3999. logger.info("Check results with two concurrent groups in operation")
  4000. g1_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group1)
  4001. res1 = g1_obj.GetAll(WPAS_DBUS_GROUP,
  4002. dbus_interface=dbus.PROPERTIES_IFACE,
  4003. byte_arrays=True)
  4004. g2_obj = bus.get_object(WPAS_DBUS_SERVICE, self.group2)
  4005. res2 = g2_obj.GetAll(WPAS_DBUS_GROUP,
  4006. dbus_interface=dbus.PROPERTIES_IFACE,
  4007. byte_arrays=True)
  4008. logger.info("group1 = " + self.group1)
  4009. logger.debug("Group properties: " + str(res1))
  4010. logger.info("group2 = " + self.group2)
  4011. logger.debug("Group properties: " + str(res2))
  4012. prop = if_obj.GetAll(WPAS_DBUS_IFACE_P2PDEVICE,
  4013. dbus_interface=dbus.PROPERTIES_IFACE)
  4014. logger.debug("p2pdevice properties: " + str(prop))
  4015. if res1['Role'] != 'client':
  4016. raise Exception("Group1 role reported incorrectly: " + res1['Role'])
  4017. if res2['Role'] != 'GO':
  4018. raise Exception("Group2 role reported incorrectly: " + res2['Role'])
  4019. if prop['Role'] != 'device':
  4020. raise Exception("p2pdevice role reported incorrectly: " + prop['Role'])
  4021. if len(res2['Members']) != 1:
  4022. raise Exception("Unexpected Members value for group 2")
  4023. def run_test(self, *args):
  4024. logger.debug("run_test")
  4025. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  4026. return False
  4027. def success(self):
  4028. return self.done
  4029. with TestDbusP2p(bus) as t:
  4030. if not t.success():
  4031. raise Exception("Expected signals not seen")
  4032. dev[1].remove_group()
  4033. def test_dbus_p2p_cancel(dev, apdev):
  4034. """D-Bus P2P Cancel"""
  4035. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4036. p2p = dbus.Interface(if_obj, WPAS_DBUS_IFACE_P2PDEVICE)
  4037. try:
  4038. p2p.Cancel()
  4039. raise Exception("Unexpected p2p.Cancel() success")
  4040. except dbus.exceptions.DBusException, e:
  4041. pass
  4042. addr0 = dev[0].p2p_dev_addr()
  4043. dev[1].p2p_listen()
  4044. class TestDbusP2p(TestDbus):
  4045. def __init__(self, bus):
  4046. TestDbus.__init__(self, bus)
  4047. self.done = False
  4048. def __enter__(self):
  4049. gobject.timeout_add(1, self.run_test)
  4050. gobject.timeout_add(15000, self.timeout)
  4051. self.add_signal(self.deviceFound, WPAS_DBUS_IFACE_P2PDEVICE,
  4052. "DeviceFound")
  4053. self.loop.run()
  4054. return self
  4055. def deviceFound(self, path):
  4056. logger.debug("deviceFound: path=%s" % path)
  4057. args = { 'peer': path, 'wps_method': 'keypad', 'pin': '12345670',
  4058. 'go_intent': 0 }
  4059. p2p.Connect(args)
  4060. p2p.Cancel()
  4061. self.done = True
  4062. self.loop.quit()
  4063. def run_test(self, *args):
  4064. logger.debug("run_test")
  4065. p2p.Find(dbus.Dictionary({'DiscoveryType': 'social'}))
  4066. return False
  4067. def success(self):
  4068. return self.done
  4069. with TestDbusP2p(bus) as t:
  4070. if not t.success():
  4071. raise Exception("Expected signals not seen")
  4072. def test_dbus_introspect(dev, apdev):
  4073. """D-Bus introspection"""
  4074. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4075. res = if_obj.Introspect(WPAS_DBUS_IFACE,
  4076. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  4077. logger.info("Initial Introspect: " + str(res))
  4078. if res is None or "Introspectable" not in res or "GroupStarted" not in res:
  4079. raise Exception("Unexpected initial Introspect response: " + str(res))
  4080. with alloc_fail(dev[0], 1, "wpa_dbus_introspect"):
  4081. res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
  4082. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  4083. logger.info("Introspect: " + str(res2))
  4084. if res2 is not None:
  4085. raise Exception("Unexpected Introspect response")
  4086. with alloc_fail(dev[0], 1, "=add_interface;wpa_dbus_introspect"):
  4087. res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
  4088. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  4089. logger.info("Introspect: " + str(res2))
  4090. if res2 is None:
  4091. raise Exception("No Introspect response")
  4092. if len(res2) >= len(res):
  4093. raise Exception("Unexpected Introspect response")
  4094. with alloc_fail(dev[0], 1, "wpabuf_alloc;add_interface;wpa_dbus_introspect"):
  4095. res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
  4096. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  4097. logger.info("Introspect: " + str(res2))
  4098. if res2 is None:
  4099. raise Exception("No Introspect response")
  4100. if len(res2) >= len(res):
  4101. raise Exception("Unexpected Introspect response")
  4102. with alloc_fail(dev[0], 2, "=add_interface;wpa_dbus_introspect"):
  4103. res2 = if_obj.Introspect(WPAS_DBUS_IFACE,
  4104. dbus_interface=dbus.INTROSPECTABLE_IFACE)
  4105. logger.info("Introspect: " + str(res2))
  4106. if res2 is None:
  4107. raise Exception("No Introspect response")
  4108. if len(res2) >= len(res):
  4109. raise Exception("Unexpected Introspect response")
  4110. def test_dbus_ap(dev, apdev):
  4111. """D-Bus AddNetwork for AP mode"""
  4112. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4113. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  4114. ssid = "test-wpa2-psk"
  4115. passphrase = 'qwertyuiop'
  4116. class TestDbusConnect(TestDbus):
  4117. def __init__(self, bus):
  4118. TestDbus.__init__(self, bus)
  4119. self.started = False
  4120. def __enter__(self):
  4121. gobject.timeout_add(1, self.run_connect)
  4122. gobject.timeout_add(15000, self.timeout)
  4123. self.add_signal(self.networkAdded, WPAS_DBUS_IFACE, "NetworkAdded")
  4124. self.add_signal(self.networkSelected, WPAS_DBUS_IFACE,
  4125. "NetworkSelected")
  4126. self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
  4127. "PropertiesChanged")
  4128. self.loop.run()
  4129. return self
  4130. def networkAdded(self, network, properties):
  4131. logger.debug("networkAdded: %s" % str(network))
  4132. logger.debug(str(properties))
  4133. def networkSelected(self, network):
  4134. logger.debug("networkSelected: %s" % str(network))
  4135. self.network_selected = True
  4136. def propertiesChanged(self, properties):
  4137. logger.debug("propertiesChanged: %s" % str(properties))
  4138. if 'State' in properties and properties['State'] == "completed":
  4139. self.started = True
  4140. self.loop.quit()
  4141. def run_connect(self, *args):
  4142. logger.debug("run_connect")
  4143. args = dbus.Dictionary({ 'ssid': ssid,
  4144. 'key_mgmt': 'WPA-PSK',
  4145. 'psk': passphrase,
  4146. 'mode': 2,
  4147. 'frequency': 2412 },
  4148. signature='sv')
  4149. self.netw = iface.AddNetwork(args)
  4150. iface.SelectNetwork(self.netw)
  4151. return False
  4152. def success(self):
  4153. return self.started
  4154. with TestDbusConnect(bus) as t:
  4155. if not t.success():
  4156. raise Exception("Expected signals not seen")
  4157. dev[1].connect(ssid, psk=passphrase, scan_freq="2412")
  4158. def test_dbus_connect_wpa_eap(dev, apdev):
  4159. """D-Bus AddNetwork and connection with WPA+WPA2-Enterprise AP"""
  4160. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4161. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  4162. ssid = "test-wpa-eap"
  4163. params = hostapd.wpa_eap_params(ssid=ssid)
  4164. params["wpa"] = "3"
  4165. params["rsn_pairwise"] = "CCMP"
  4166. hapd = hostapd.add_ap(apdev[0]['ifname'], params)
  4167. class TestDbusConnect(TestDbus):
  4168. def __init__(self, bus):
  4169. TestDbus.__init__(self, bus)
  4170. self.done = False
  4171. def __enter__(self):
  4172. gobject.timeout_add(1, self.run_connect)
  4173. gobject.timeout_add(15000, self.timeout)
  4174. self.add_signal(self.propertiesChanged, WPAS_DBUS_IFACE,
  4175. "PropertiesChanged")
  4176. self.add_signal(self.eap, WPAS_DBUS_IFACE, "EAP")
  4177. self.loop.run()
  4178. return self
  4179. def propertiesChanged(self, properties):
  4180. logger.debug("propertiesChanged: %s" % str(properties))
  4181. if 'State' in properties and properties['State'] == "completed":
  4182. self.done = True
  4183. self.loop.quit()
  4184. def eap(self, status, parameter):
  4185. logger.debug("EAP: status=%s parameter=%s" % (status, parameter))
  4186. def run_connect(self, *args):
  4187. logger.debug("run_connect")
  4188. args = dbus.Dictionary({ 'ssid': ssid,
  4189. 'key_mgmt': 'WPA-EAP',
  4190. 'eap': 'PEAP',
  4191. 'identity': 'user',
  4192. 'password': 'password',
  4193. 'ca_cert': 'auth_serv/ca.pem',
  4194. 'phase2': 'auth=MSCHAPV2',
  4195. 'scan_freq': 2412 },
  4196. signature='sv')
  4197. self.netw = iface.AddNetwork(args)
  4198. iface.SelectNetwork(self.netw)
  4199. return False
  4200. def success(self):
  4201. return self.done
  4202. with TestDbusConnect(bus) as t:
  4203. if not t.success():
  4204. raise Exception("Expected signals not seen")
  4205. def test_dbus_ap_scan_2_ap_mode_scan(dev, apdev):
  4206. """AP_SCAN 2 AP mode and D-Bus Scan()"""
  4207. try:
  4208. _test_dbus_ap_scan_2_ap_mode_scan(dev, apdev)
  4209. finally:
  4210. dev[0].request("AP_SCAN 1")
  4211. def _test_dbus_ap_scan_2_ap_mode_scan(dev, apdev):
  4212. (bus,wpas_obj,path,if_obj) = prepare_dbus(dev[0])
  4213. iface = dbus.Interface(if_obj, WPAS_DBUS_IFACE)
  4214. if "OK" not in dev[0].request("AP_SCAN 2"):
  4215. raise Exception("Failed to set AP_SCAN 2")
  4216. id = dev[0].add_network()
  4217. dev[0].set_network(id, "mode", "2")
  4218. dev[0].set_network_quoted(id, "ssid", "wpas-ap-open")
  4219. dev[0].set_network(id, "key_mgmt", "NONE")
  4220. dev[0].set_network(id, "frequency", "2412")
  4221. dev[0].set_network(id, "scan_freq", "2412")
  4222. dev[0].set_network(id, "disabled", "0")
  4223. dev[0].select_network(id)
  4224. ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=5)
  4225. if ev is None:
  4226. raise Exception("AP failed to start")
  4227. with fail_test(dev[0], 1, "wpa_driver_nl80211_scan"):
  4228. iface.Scan({'Type': 'active',
  4229. 'AllowRoam': True,
  4230. 'Channels': [(dbus.UInt32(2412), dbus.UInt32(20))]})
  4231. ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED",
  4232. "AP-DISABLED"], timeout=5)
  4233. if ev is None:
  4234. raise Exception("CTRL-EVENT-SCAN-FAILED not seen")
  4235. if "AP-DISABLED" in ev:
  4236. raise Exception("Unexpected AP-DISABLED event")
  4237. if "retry=1" in ev:
  4238. # Wait for the retry to scan happen
  4239. ev = dev[0].wait_event(["CTRL-EVENT-SCAN-FAILED",
  4240. "AP-DISABLED"], timeout=5)
  4241. if ev is None:
  4242. raise Exception("CTRL-EVENT-SCAN-FAILED not seen - retry")
  4243. if "AP-DISABLED" in ev:
  4244. raise Exception("Unexpected AP-DISABLED event - retry")
  4245. dev[1].connect("wpas-ap-open", key_mgmt="NONE", scan_freq="2412")
  4246. dev[1].request("DISCONNECT")
  4247. dev[1].wait_disconnected()
  4248. dev[0].request("DISCONNECT")
  4249. dev[0].wait_disconnected()