test_dbus.py 232 KB

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