test_dbus.py 204 KB

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