test_dbus.py 205 KB

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