test_dbus.py 229 KB

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