test_dbus.py 218 KB

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