cros_network_config.cc 137 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418
  1. // Copyright 2019 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "chromeos/services/network_config/cros_network_config.h"
  5. #include <cmath>
  6. #include <vector>
  7. #include "ash/constants/ash_features.h"
  8. #include "base/containers/contains.h"
  9. #include "base/containers/flat_map.h"
  10. #include "base/guid.h"
  11. #include "base/i18n/time_formatting.h"
  12. #include "base/strings/string_number_conversions.h"
  13. #include "base/strings/string_split.h"
  14. #include "base/strings/string_util.h"
  15. #include "base/strings/utf_string_conversions.h"
  16. #include "chromeos/ash/components/dbus/hermes/hermes_euicc_client.h"
  17. #include "chromeos/ash/components/dbus/hermes/hermes_manager_client.h"
  18. #include "chromeos/ash/components/dbus/shill/shill_manager_client.h"
  19. #include "chromeos/ash/components/network/cellular_esim_profile_handler.h"
  20. #include "chromeos/ash/components/network/cellular_utils.h"
  21. #include "chromeos/ash/components/network/device_state.h"
  22. #include "chromeos/ash/components/network/managed_network_configuration_handler.h"
  23. #include "chromeos/ash/components/network/network_connection_handler.h"
  24. #include "chromeos/ash/components/network/network_device_handler.h"
  25. #include "chromeos/ash/components/network/network_event_log.h"
  26. #include "chromeos/ash/components/network/network_handler.h"
  27. #include "chromeos/ash/components/network/network_metadata_store.h"
  28. #include "chromeos/ash/components/network/network_name_util.h"
  29. #include "chromeos/ash/components/network/network_state.h"
  30. #include "chromeos/ash/components/network/network_state_handler.h"
  31. #include "chromeos/ash/components/network/network_type_pattern.h"
  32. #include "chromeos/ash/components/network/network_util.h"
  33. #include "chromeos/ash/components/network/onc/onc_translation_tables.h"
  34. #include "chromeos/ash/components/network/prohibited_technologies_handler.h"
  35. #include "chromeos/ash/components/network/proxy/ui_proxy_config_service.h"
  36. #include "chromeos/ash/components/sync_wifi/network_eligibility_checker.h"
  37. #include "chromeos/login/login_state/login_state.h"
  38. #include "chromeos/services/network_config/public/cpp/cros_network_config_util.h"
  39. #include "chromeos/services/network_config/public/mojom/cros_network_config.mojom-shared.h"
  40. #include "chromeos/services/network_config/public/mojom/cros_network_config_mojom_traits.h"
  41. #include "components/device_event_log/device_event_log.h"
  42. #include "components/onc/onc_constants.h"
  43. #include "components/user_manager/user_manager.h"
  44. #include "net/base/ip_address.h"
  45. #include "third_party/abseil-cpp/absl/types/optional.h"
  46. #include "third_party/cros_system_api/dbus/service_constants.h"
  47. #include "third_party/cros_system_api/dbus/shill/dbus-constants.h"
  48. using user_manager::UserManager;
  49. namespace chromeos {
  50. namespace network_config {
  51. namespace {
  52. // Error strings from networking_private_api.cc. TODO(1004434): Enumerate
  53. // these in mojo.
  54. const char kErrorAccessToSharedConfig[] = "Error.CannotChangeSharedConfig";
  55. const char kErrorInvalidONCConfiguration[] = "Error.InvalidONCConfiguration";
  56. const char kErrorNetworkUnavailable[] = "Error.NetworkUnavailable";
  57. const char kErrorNotReady[] = "Error.NotReady";
  58. // IKEv2 string from Shill SupportedVPNType property.
  59. const char kIKEv2VPNType[] = "ikev2";
  60. // Default traffic counter reset day.
  61. const int kDefaultResetDay = 1;
  62. std::string ShillToOnc(const std::string& shill_string,
  63. const onc::StringTranslationEntry table[]) {
  64. std::string onc_string;
  65. if (!shill_string.empty())
  66. onc::TranslateStringToONC(table, shill_string, &onc_string);
  67. return onc_string;
  68. }
  69. mojom::NetworkType NetworkPatternToMojo(NetworkTypePattern type) {
  70. if (type.Equals(NetworkTypePattern::Cellular()))
  71. return mojom::NetworkType::kCellular;
  72. if (type.MatchesPattern(NetworkTypePattern::EthernetOrEthernetEAP()))
  73. return mojom::NetworkType::kEthernet;
  74. if (type.Equals(NetworkTypePattern::Tether()))
  75. return mojom::NetworkType::kTether;
  76. if (type.Equals(NetworkTypePattern::VPN()))
  77. return mojom::NetworkType::kVPN;
  78. if (type.Equals(NetworkTypePattern::WiFi()))
  79. return mojom::NetworkType::kWiFi;
  80. NOTREACHED() << "Unsupported network type: " << type.ToDebugString();
  81. return mojom::NetworkType::kAll; // Unsupported
  82. }
  83. mojom::NetworkType ShillTypeToMojo(const std::string& shill_type) {
  84. return NetworkPatternToMojo(NetworkTypePattern::Primitive(shill_type));
  85. }
  86. mojom::NetworkType OncTypeToMojo(const std::string& onc_type) {
  87. return NetworkPatternToMojo(NetworkTypePattern::Primitive(
  88. network_util::TranslateONCTypeToShill(onc_type)));
  89. }
  90. NetworkTypePattern MojoTypeToPattern(mojom::NetworkType type) {
  91. switch (type) {
  92. case mojom::NetworkType::kAll:
  93. return NetworkTypePattern::Default();
  94. case mojom::NetworkType::kCellular:
  95. return NetworkTypePattern::Cellular();
  96. case mojom::NetworkType::kEthernet:
  97. return NetworkTypePattern::Ethernet();
  98. case mojom::NetworkType::kMobile:
  99. return NetworkTypePattern::Mobile();
  100. case mojom::NetworkType::kTether:
  101. return NetworkTypePattern::Tether();
  102. case mojom::NetworkType::kVPN:
  103. return NetworkTypePattern::VPN();
  104. case mojom::NetworkType::kWireless:
  105. return NetworkTypePattern::Wireless();
  106. case mojom::NetworkType::kWiFi:
  107. return NetworkTypePattern::WiFi();
  108. }
  109. NOTREACHED();
  110. return NetworkTypePattern::Default();
  111. }
  112. mojom::IPConfigType OncIPConfigTypeToMojo(const std::string& ip_config_type) {
  113. if (ip_config_type == ::onc::ipconfig::kIPv4)
  114. return mojom::IPConfigType::kIPv4;
  115. if (ip_config_type == ::onc::ipconfig::kIPv6)
  116. return mojom::IPConfigType::kIPv6;
  117. NOTREACHED() << "Unsupported ONC IPConfig type: " << ip_config_type;
  118. return mojom::IPConfigType::kIPv4;
  119. }
  120. std::string MojoIPConfigTypeToOnc(mojom::IPConfigType type) {
  121. switch (type) {
  122. case mojom::IPConfigType::kIPv4:
  123. return ::onc::ipconfig::kIPv4;
  124. case mojom::IPConfigType::kIPv6:
  125. return ::onc::ipconfig::kIPv6;
  126. }
  127. NOTREACHED() << "Unexpeted mojo IPConfig type: " << type;
  128. return ::onc::ipconfig::kIPv4;
  129. }
  130. std::string MojoNetworkTypeToOnc(mojom::NetworkType type) {
  131. switch (type) {
  132. case mojom::NetworkType::kAll:
  133. case mojom::NetworkType::kMobile:
  134. case mojom::NetworkType::kWireless:
  135. break; // Not supported
  136. case mojom::NetworkType::kCellular:
  137. return ::onc::network_type::kCellular;
  138. case mojom::NetworkType::kEthernet:
  139. return ::onc::network_type::kEthernet;
  140. case mojom::NetworkType::kTether:
  141. return ::onc::network_type::kTether;
  142. case mojom::NetworkType::kVPN:
  143. return ::onc::network_type::kVPN;
  144. case mojom::NetworkType::kWiFi:
  145. return ::onc::network_type::kWiFi;
  146. }
  147. NOTREACHED() << "Unsupported mojo to ONC type: " << type;
  148. return std::string();
  149. }
  150. mojom::ConnectionStateType GetMojoConnectionStateType(
  151. const NetworkState* network) {
  152. if (network->IsConnectedState()) {
  153. auto portal_state = network->GetPortalState();
  154. switch (portal_state) {
  155. case NetworkState::PortalState::kUnknown:
  156. return mojom::ConnectionStateType::kConnected;
  157. case NetworkState::PortalState::kOnline:
  158. return mojom::ConnectionStateType::kOnline;
  159. case NetworkState::PortalState::kPortalSuspected:
  160. case NetworkState::PortalState::kPortal:
  161. case NetworkState::PortalState::kProxyAuthRequired:
  162. case NetworkState::PortalState::kNoInternet:
  163. // See PortalState for differentiation of portal states.
  164. return mojom::ConnectionStateType::kPortal;
  165. }
  166. }
  167. if (network->IsConnectingState())
  168. return mojom::ConnectionStateType::kConnecting;
  169. return mojom::ConnectionStateType::kNotConnected;
  170. }
  171. mojom::ConnectionStateType GetConnectionState(const NetworkState* network,
  172. bool technology_enabled) {
  173. // If a network technology is not enabled, always use NotConnected as the
  174. // connection state to avoid any edge cases during device enable/disable.
  175. return technology_enabled ? GetMojoConnectionStateType(network)
  176. : mojom::ConnectionStateType::kNotConnected;
  177. }
  178. std::string MojoSecurityTypeToOnc(mojom::SecurityType security_type) {
  179. switch (security_type) {
  180. case mojom::SecurityType::kNone:
  181. return ::onc::wifi::kSecurityNone;
  182. case mojom::SecurityType::kWep8021x:
  183. return ::onc::wifi::kWEP_8021X;
  184. case mojom::SecurityType::kWepPsk:
  185. return ::onc::wifi::kWEP_PSK;
  186. case mojom::SecurityType::kWpaEap:
  187. return ::onc::wifi::kWPA_EAP;
  188. case mojom::SecurityType::kWpaPsk:
  189. return ::onc::wifi::kWPA_PSK;
  190. }
  191. NOTREACHED() << "Unsupported mojo to ONC type: " << security_type;
  192. return std::string();
  193. }
  194. mojom::VpnType OncVpnTypeToMojo(const std::string& onc_vpn_type) {
  195. if (onc_vpn_type == ::onc::vpn::kIPsec)
  196. return mojom::VpnType::kIKEv2;
  197. if (onc_vpn_type == ::onc::vpn::kTypeL2TP_IPsec)
  198. return mojom::VpnType::kL2TPIPsec;
  199. if (onc_vpn_type == ::onc::vpn::kOpenVPN)
  200. return mojom::VpnType::kOpenVPN;
  201. if (onc_vpn_type == ::onc::vpn::kWireGuard)
  202. return mojom::VpnType::kWireGuard;
  203. if (onc_vpn_type == ::onc::vpn::kThirdPartyVpn)
  204. return mojom::VpnType::kExtension;
  205. if (onc_vpn_type == ::onc::vpn::kArcVpn)
  206. return mojom::VpnType::kArc;
  207. NOTREACHED() << "Unsupported ONC VPN type: " << onc_vpn_type;
  208. return mojom::VpnType::kOpenVPN;
  209. }
  210. std::string MojoVpnTypeToOnc(mojom::VpnType mojo_vpn_type) {
  211. switch (mojo_vpn_type) {
  212. case mojom::VpnType::kIKEv2:
  213. return ::onc::vpn::kIPsec;
  214. case mojom::VpnType::kL2TPIPsec:
  215. return ::onc::vpn::kTypeL2TP_IPsec;
  216. case mojom::VpnType::kOpenVPN:
  217. return ::onc::vpn::kOpenVPN;
  218. case mojom::VpnType::kWireGuard:
  219. return ::onc::vpn::kWireGuard;
  220. case mojom::VpnType::kExtension:
  221. return ::onc::vpn::kThirdPartyVpn;
  222. case mojom::VpnType::kArc:
  223. return ::onc::vpn::kArcVpn;
  224. }
  225. NOTREACHED();
  226. return ::onc::vpn::kOpenVPN;
  227. }
  228. bool GetIsConfiguredByUser(const std::string& network_guid) {
  229. if (!NetworkHandler::IsInitialized())
  230. return false;
  231. NetworkMetadataStore* network_metadata_store =
  232. NetworkHandler::Get()->network_metadata_store();
  233. if (!network_metadata_store)
  234. return false;
  235. return network_metadata_store->GetIsCreatedByUser(network_guid);
  236. }
  237. mojom::DeviceStateType GetMojoDeviceStateType(
  238. NetworkStateHandler::TechnologyState technology_state) {
  239. switch (technology_state) {
  240. case NetworkStateHandler::TECHNOLOGY_UNAVAILABLE:
  241. return mojom::DeviceStateType::kUnavailable;
  242. case NetworkStateHandler::TECHNOLOGY_UNINITIALIZED:
  243. return mojom::DeviceStateType::kUninitialized;
  244. case NetworkStateHandler::TECHNOLOGY_AVAILABLE:
  245. return mojom::DeviceStateType::kDisabled;
  246. case NetworkStateHandler::TECHNOLOGY_DISABLING:
  247. return mojom::DeviceStateType::kDisabling;
  248. case NetworkStateHandler::TECHNOLOGY_ENABLING:
  249. return mojom::DeviceStateType::kEnabling;
  250. case NetworkStateHandler::TECHNOLOGY_ENABLED:
  251. return mojom::DeviceStateType::kEnabled;
  252. case NetworkStateHandler::TECHNOLOGY_PROHIBITED:
  253. return mojom::DeviceStateType::kProhibited;
  254. }
  255. NOTREACHED();
  256. return mojom::DeviceStateType::kUnavailable;
  257. }
  258. mojom::PortalState GetMojoPortalState(
  259. const NetworkState::PortalState portal_state) {
  260. switch (portal_state) {
  261. case NetworkState::PortalState::kUnknown:
  262. return mojom::PortalState::kUnknown;
  263. case NetworkState::PortalState::kOnline:
  264. return mojom::PortalState::kOnline;
  265. case NetworkState::PortalState::kPortalSuspected:
  266. return mojom::PortalState::kPortalSuspected;
  267. case NetworkState::PortalState::kPortal:
  268. return mojom::PortalState::kPortal;
  269. case NetworkState::PortalState::kProxyAuthRequired:
  270. return mojom::PortalState::kProxyAuthRequired;
  271. case NetworkState::PortalState::kNoInternet:
  272. return mojom::PortalState::kNoInternet;
  273. }
  274. NOTREACHED();
  275. return mojom::PortalState::kUnknown;
  276. }
  277. mojom::OncSource GetMojoOncSource(const NetworkState* network) {
  278. ::onc::ONCSource source = network->onc_source();
  279. switch (source) {
  280. case ::onc::ONC_SOURCE_UNKNOWN:
  281. case ::onc::ONC_SOURCE_NONE:
  282. if (!network->IsInProfile())
  283. return mojom::OncSource::kNone;
  284. return network->IsPrivate() ? mojom::OncSource::kUser
  285. : mojom::OncSource::kDevice;
  286. case ::onc::ONC_SOURCE_USER_IMPORT:
  287. return mojom::OncSource::kUser;
  288. case ::onc::ONC_SOURCE_DEVICE_POLICY:
  289. return mojom::OncSource::kDevicePolicy;
  290. case ::onc::ONC_SOURCE_USER_POLICY:
  291. return mojom::OncSource::kUserPolicy;
  292. }
  293. NOTREACHED();
  294. return mojom::OncSource::kNone;
  295. }
  296. const std::string& GetVpnProviderName(
  297. const std::vector<mojom::VpnProviderPtr>& vpn_providers,
  298. const std::string& provider_id) {
  299. for (const mojom::VpnProviderPtr& provider : vpn_providers) {
  300. if (provider->provider_id == provider_id)
  301. return provider->provider_name;
  302. }
  303. return base::EmptyString();
  304. }
  305. bool IsVpnProhibited() {
  306. bool vpn_prohibited = false;
  307. if (NetworkHandler::IsInitialized()) {
  308. std::vector<std::string> prohibited_technologies =
  309. NetworkHandler::Get()
  310. ->prohibited_technologies_handler()
  311. ->GetCurrentlyProhibitedTechnologies();
  312. vpn_prohibited = base::Contains(prohibited_technologies, shill::kTypeVPN);
  313. }
  314. return vpn_prohibited;
  315. }
  316. mojom::DeviceStatePropertiesPtr GetVpnState() {
  317. auto result = mojom::DeviceStateProperties::New();
  318. result->type = mojom::NetworkType::kVPN;
  319. result->device_state = IsVpnProhibited() ? mojom::DeviceStateType::kProhibited
  320. : mojom::DeviceStateType::kEnabled;
  321. return result;
  322. }
  323. mojom::NetworkStatePropertiesPtr NetworkStateToMojo(
  324. NetworkStateHandler* network_state_handler,
  325. CellularESimProfileHandler* cellular_esim_profile_handler,
  326. const std::vector<mojom::VpnProviderPtr>& vpn_providers,
  327. const NetworkState* network) {
  328. mojom::NetworkType type = ShillTypeToMojo(network->type());
  329. if (type == mojom::NetworkType::kAll) {
  330. NET_LOG(ERROR) << "Unexpected network type: " << network->type()
  331. << " GUID: " << network->guid();
  332. return nullptr;
  333. }
  334. auto result = mojom::NetworkStateProperties::New();
  335. result->type = type;
  336. result->connectable = network->connectable();
  337. result->connect_requested = network->connect_requested();
  338. bool technology_enabled = network->Matches(NetworkTypePattern::VPN()) ||
  339. network_state_handler->IsTechnologyEnabled(
  340. NetworkTypePattern::Primitive(network->type()));
  341. result->connection_state = GetConnectionState(network, technology_enabled);
  342. if (!network->GetError().empty())
  343. result->error_state = network->GetError();
  344. result->guid = network->guid();
  345. result->name =
  346. network_name_util::GetNetworkName(cellular_esim_profile_handler, network);
  347. result->portal_state = GetMojoPortalState(network->GetPortalState());
  348. result->priority = network->priority();
  349. result->prohibited_by_policy = network->blocked_by_policy();
  350. result->source = GetMojoOncSource(network);
  351. result->proxy_mode =
  352. NetworkHandler::HasUiProxyConfigService()
  353. ? mojom::ProxyMode(
  354. NetworkHandler::GetUiProxyConfigService()->ProxyModeForNetwork(
  355. network))
  356. : mojom::ProxyMode::kDirect;
  357. switch (type) {
  358. case mojom::NetworkType::kCellular: {
  359. auto cellular = mojom::CellularStateProperties::New();
  360. cellular->iccid = network->iccid();
  361. cellular->eid = network->eid();
  362. cellular->activation_state = network->GetMojoActivationState();
  363. cellular->network_technology = ShillToOnc(network->network_technology(),
  364. onc::kNetworkTechnologyTable);
  365. cellular->roaming = network->IndicateRoaming();
  366. cellular->signal_strength = network->signal_strength();
  367. const DeviceState* cellular_device =
  368. network_state_handler->GetDeviceState(network->device_path());
  369. bool sim_is_primary =
  370. cellular_device && IsSimPrimary(network->iccid(), cellular_device);
  371. cellular->sim_lock_enabled =
  372. sim_is_primary && cellular_device->sim_lock_enabled();
  373. cellular->sim_locked = sim_is_primary && cellular_device->IsSimLocked();
  374. if (sim_is_primary)
  375. cellular->sim_lock_type = cellular_device->sim_lock_type();
  376. result->type_state =
  377. mojom::NetworkTypeStateProperties::NewCellular(std::move(cellular));
  378. break;
  379. }
  380. case mojom::NetworkType::kEthernet: {
  381. auto ethernet = mojom::EthernetStateProperties::New();
  382. ethernet->authentication = network->type() == shill::kTypeEthernetEap
  383. ? mojom::AuthenticationType::k8021x
  384. : mojom::AuthenticationType::kNone;
  385. result->type_state =
  386. mojom::NetworkTypeStateProperties::NewEthernet(std::move(ethernet));
  387. break;
  388. }
  389. case mojom::NetworkType::kTether: {
  390. auto tether = mojom::TetherStateProperties::New();
  391. tether->battery_percentage = network->battery_percentage();
  392. tether->carrier = network->tether_carrier();
  393. tether->has_connected_to_host = network->tether_has_connected_to_host();
  394. tether->signal_strength = network->signal_strength();
  395. result->type_state =
  396. mojom::NetworkTypeStateProperties::NewTether(std::move(tether));
  397. break;
  398. }
  399. case mojom::NetworkType::kVPN: {
  400. auto vpn = mojom::VPNStateProperties::New();
  401. const NetworkState::VpnProviderInfo* vpn_provider =
  402. network->vpn_provider();
  403. if (vpn_provider) {
  404. vpn->type = OncVpnTypeToMojo(
  405. ShillToOnc(vpn_provider->type, onc::kVPNTypeTable));
  406. vpn->provider_id = vpn_provider->id;
  407. vpn->provider_name =
  408. GetVpnProviderName(vpn_providers, vpn_provider->id);
  409. }
  410. result->type_state =
  411. mojom::NetworkTypeStateProperties::NewVpn(std::move(vpn));
  412. break;
  413. }
  414. case mojom::NetworkType::kWiFi: {
  415. auto wifi = mojom::WiFiStateProperties::New();
  416. wifi->bssid = network->bssid();
  417. wifi->frequency = network->frequency();
  418. wifi->hex_ssid = network->GetHexSsid();
  419. wifi->security = network->GetMojoSecurity();
  420. wifi->signal_strength = network->signal_strength();
  421. wifi->ssid = network->name();
  422. wifi->hidden_ssid = network->hidden_ssid();
  423. result->type_state =
  424. mojom::NetworkTypeStateProperties::NewWifi(std::move(wifi));
  425. break;
  426. }
  427. case mojom::NetworkType::kAll:
  428. case mojom::NetworkType::kMobile:
  429. case mojom::NetworkType::kWireless:
  430. NOTREACHED() << "NetworkStateProperties can not be of type: " << type;
  431. break;
  432. }
  433. return result;
  434. }
  435. std::vector<mojom::SIMInfoPtr> CellularSIMInfosToMojo(
  436. const DeviceState* device) {
  437. std::vector<mojom::SIMInfoPtr> sim_info_mojos;
  438. for (const auto& sim_slot : GetSimSlotInfosWithUpdatedEid(device)) {
  439. auto sim_info_mojo = mojom::SIMInfo::New();
  440. sim_info_mojo->slot_id = sim_slot.slot_id;
  441. sim_info_mojo->iccid = sim_slot.iccid;
  442. sim_info_mojo->eid = sim_slot.eid;
  443. sim_info_mojo->is_primary = sim_slot.primary;
  444. sim_info_mojos.push_back(std::move(sim_info_mojo));
  445. }
  446. return sim_info_mojos;
  447. }
  448. bool IsCellularConnecting(NetworkStateHandler* network_state_handler) {
  449. NetworkStateHandler::NetworkStateList cellular_networks;
  450. network_state_handler->GetVisibleNetworkListByType(
  451. NetworkTypePattern::Cellular(), &cellular_networks);
  452. auto iter = std::find_if(cellular_networks.begin(), cellular_networks.end(),
  453. [](const NetworkState* network_state) {
  454. return network_state->IsConnectingState();
  455. });
  456. return iter != cellular_networks.end();
  457. }
  458. mojom::InhibitReason GetInhibitReason(
  459. NetworkStateHandler* network_state_handler,
  460. CellularInhibitor* cellular_inhibitor) {
  461. if (!cellular_inhibitor)
  462. return mojom::InhibitReason::kNotInhibited;
  463. absl::optional<CellularInhibitor::InhibitReason> inhibit_reason =
  464. cellular_inhibitor->GetInhibitReason();
  465. if (!inhibit_reason) {
  466. // For devices with EUICC, the UI should be inhibited when a cellular
  467. // network connection is in progress to prevent additional requests. This is
  468. // due to complexity in switching slots.
  469. if (!chromeos::HermesManagerClient::Get()->GetAvailableEuiccs().empty() &&
  470. IsCellularConnecting(network_state_handler)) {
  471. return mojom::InhibitReason::kConnectingToProfile;
  472. }
  473. return mojom::InhibitReason::kNotInhibited;
  474. }
  475. switch (*inhibit_reason) {
  476. case CellularInhibitor::InhibitReason::kInstallingProfile:
  477. return mojom::InhibitReason::kInstallingProfile;
  478. case CellularInhibitor::InhibitReason::kRenamingProfile:
  479. return mojom::InhibitReason::kRenamingProfile;
  480. case CellularInhibitor::InhibitReason::kRemovingProfile:
  481. return mojom::InhibitReason::kRemovingProfile;
  482. case CellularInhibitor::InhibitReason::kConnectingToProfile:
  483. return mojom::InhibitReason::kConnectingToProfile;
  484. case CellularInhibitor::InhibitReason::kRefreshingProfileList:
  485. return mojom::InhibitReason::kRefreshingProfileList;
  486. case CellularInhibitor::InhibitReason::kResettingEuiccMemory:
  487. return mojom::InhibitReason::kResettingEuiccMemory;
  488. case CellularInhibitor::InhibitReason::kDisablingProfile:
  489. return mojom::InhibitReason::kDisablingProfile;
  490. }
  491. }
  492. mojom::DeviceStatePropertiesPtr DeviceStateToMojo(
  493. const DeviceState* device,
  494. NetworkStateHandler* network_state_handler,
  495. CellularInhibitor* cellular_inhibitor,
  496. mojom::DeviceStateType technology_state) {
  497. mojom::NetworkType type = ShillTypeToMojo(device->type());
  498. if (type == mojom::NetworkType::kAll) {
  499. NET_LOG(ERROR) << "Unexpected device type: " << device->type()
  500. << " path: " << device->path();
  501. return nullptr;
  502. }
  503. auto result = mojom::DeviceStateProperties::New();
  504. result->type = type;
  505. net::IPAddress ipv4_address;
  506. if (ipv4_address.AssignFromIPLiteral(
  507. device->GetIpAddressByType(shill::kTypeIPv4))) {
  508. result->ipv4_address = ipv4_address;
  509. }
  510. net::IPAddress ipv6_address;
  511. if (ipv6_address.AssignFromIPLiteral(
  512. device->GetIpAddressByType(shill::kTypeIPv6))) {
  513. result->ipv6_address = ipv6_address;
  514. }
  515. result->mac_address =
  516. network_util::FormattedMacAddress(device->mac_address());
  517. result->scanning = device->scanning();
  518. result->device_state = technology_state;
  519. result->managed_network_available =
  520. !device->available_managed_network_path().empty();
  521. result->sim_absent = device->IsSimAbsent();
  522. if (device->sim_present()) {
  523. auto sim_lock_status = mojom::SIMLockStatus::New();
  524. sim_lock_status->lock_type = device->sim_lock_type();
  525. sim_lock_status->lock_enabled = device->sim_lock_enabled();
  526. sim_lock_status->retries_left = device->sim_retries_left();
  527. result->sim_lock_status = std::move(sim_lock_status);
  528. }
  529. if (type == mojom::NetworkType::kCellular) {
  530. result->sim_infos = CellularSIMInfosToMojo(device);
  531. result->inhibit_reason =
  532. GetInhibitReason(network_state_handler, cellular_inhibitor);
  533. }
  534. return result;
  535. }
  536. void SetValueIfKeyPresent(const base::Value* dict,
  537. const char* key,
  538. base::Value* out) {
  539. const base::Value* v = dict->FindKey(key);
  540. if (v)
  541. *out = v->Clone();
  542. }
  543. absl::optional<std::string> GetString(const base::Value* dict,
  544. const char* key) {
  545. const base::Value* v = dict->FindKey(key);
  546. if (v && !v->is_string()) {
  547. NET_LOG(ERROR) << "Expected string, found: " << *v;
  548. return absl::nullopt;
  549. }
  550. return v ? absl::make_optional<std::string>(v->GetString()) : absl::nullopt;
  551. }
  552. std::string GetRequiredString(const base::Value* dict, const char* key) {
  553. const base::Value* v = dict->FindKey(key);
  554. if (!v) {
  555. NOTREACHED() << "Required key missing: " << key;
  556. return std::string();
  557. }
  558. if (!v->is_string()) {
  559. NET_LOG(ERROR) << "Expected string, found: " << *v;
  560. return std::string();
  561. }
  562. return v->GetString();
  563. }
  564. bool GetBoolean(const base::Value* dict, const char* key) {
  565. const base::Value* v = dict->FindKey(key);
  566. if (v && !v->is_bool()) {
  567. NET_LOG(ERROR) << "Expected bool, found: " << *v;
  568. return false;
  569. }
  570. return v ? v->GetBool() : false;
  571. }
  572. int32_t GetInt32(const base::Value* dict, const char* key) {
  573. const base::Value* v = dict->FindKey(key);
  574. if (v && !v->is_int()) {
  575. NET_LOG(ERROR) << "Expected int, found: " << *v;
  576. return 0;
  577. }
  578. return v ? v->GetInt() : 0;
  579. }
  580. std::vector<int32_t> GetInt32List(const base::Value* dict, const char* key) {
  581. std::vector<int32_t> result;
  582. const base::Value* v = dict->FindKey(key);
  583. if (v && !v->is_list()) {
  584. NET_LOG(ERROR) << "Expected list, found: " << *v;
  585. return result;
  586. }
  587. if (v) {
  588. for (const base::Value& e : v->GetListDeprecated())
  589. result.push_back(e.GetInt());
  590. }
  591. return result;
  592. }
  593. const base::Value* GetDictionary(const base::Value* dict, const char* key) {
  594. const base::Value* v = dict->FindKey(key);
  595. if (v && !v->is_dict()) {
  596. NET_LOG(ERROR) << "Expected dictionary, found: " << *v;
  597. return nullptr;
  598. }
  599. return v;
  600. }
  601. absl::optional<std::vector<std::string>> GetStringList(const base::Value* dict,
  602. const char* key) {
  603. const base::Value* v = dict->FindKey(key);
  604. if (!v)
  605. return absl::nullopt;
  606. if (!v->is_list()) {
  607. NET_LOG(ERROR) << "Expected list, found: " << *v;
  608. return absl::nullopt;
  609. }
  610. std::vector<std::string> result;
  611. for (const base::Value& e : v->GetListDeprecated())
  612. result.push_back(e.GetString());
  613. return result;
  614. }
  615. void SetString(const char* key,
  616. const absl::optional<std::string>& property,
  617. base::Value* dict) {
  618. if (!property)
  619. return;
  620. dict->SetStringKey(key, *property);
  621. }
  622. void SetStringIfNotEmpty(const char* key,
  623. const absl::optional<std::string>& property,
  624. base::Value* dict) {
  625. if (!property || property->empty())
  626. return;
  627. dict->SetStringKey(key, *property);
  628. }
  629. void SetStringList(const char* key,
  630. const absl::optional<std::vector<std::string>>& property,
  631. base::Value* dict) {
  632. if (!property)
  633. return;
  634. base::Value list(base::Value::Type::LIST);
  635. for (const std::string& s : *property)
  636. list.Append(base::Value(s));
  637. dict->SetKey(key, std::move(list));
  638. }
  639. void SetSubjectAltNameMatch(
  640. const char* key,
  641. const std::vector<mojom::SubjectAltNamePtr>* property,
  642. base::Value* dict) {
  643. base::Value subject_alt_name_list(base::Value::Type::LIST);
  644. for (const auto& ptr : *property) {
  645. std::string type;
  646. switch (ptr->type) {
  647. case mojom::SubjectAltName::Type::kEmail:
  648. type = ::onc::eap_subject_alternative_name_match::kEMAIL;
  649. break;
  650. case mojom::SubjectAltName::Type::kDns:
  651. type = ::onc::eap_subject_alternative_name_match::kDNS;
  652. break;
  653. case mojom::SubjectAltName::Type::kUri:
  654. type = ::onc::eap_subject_alternative_name_match::kURI;
  655. break;
  656. }
  657. base::Value entry(base::Value::Type::DICTIONARY);
  658. entry.SetStringKey(::onc::eap_subject_alternative_name_match::kType, type);
  659. entry.SetStringKey(::onc::eap_subject_alternative_name_match::kValue,
  660. ptr->value);
  661. subject_alt_name_list.Append(std::move(entry));
  662. }
  663. dict->SetKey(key, std::move(subject_alt_name_list));
  664. }
  665. // GetManagedDictionary() returns a ManagedDictionary representing the active
  666. // and policy values for a managed property. The types of |active_value| and
  667. // |policy_value| are expected to match the ONC signature for the property type.
  668. struct ManagedDictionary {
  669. base::Value active_value;
  670. mojom::PolicySource policy_source = mojom::PolicySource::kNone;
  671. base::Value policy_value;
  672. };
  673. ManagedDictionary GetManagedDictionary(const base::Value* onc_dict) {
  674. ManagedDictionary result;
  675. // When available, the active value (i.e. the value from Shill) is used.
  676. SetValueIfKeyPresent(onc_dict, ::onc::kAugmentationActiveSetting,
  677. &result.active_value);
  678. absl::optional<std::string> effective =
  679. GetString(onc_dict, ::onc::kAugmentationEffectiveSetting);
  680. if (!effective)
  681. return result;
  682. // If no active value is set (e.g. the network is not visible), use the
  683. // effective value.
  684. if (result.active_value.is_none())
  685. SetValueIfKeyPresent(onc_dict, effective->c_str(), &result.active_value);
  686. if (result.active_value.is_none()) {
  687. // No active or effective value, return a default dictionary.
  688. return result;
  689. }
  690. // If the effective value is set by an extension, use kActiveExtension.
  691. if (effective == ::onc::kAugmentationActiveExtension) {
  692. result.policy_source = mojom::PolicySource::kActiveExtension;
  693. result.policy_value = result.active_value.Clone();
  694. return result;
  695. }
  696. // Set policy properties based on the effective source and policies.
  697. // NOTE: This does not enforce valid ONC. See onc_merger.cc for details.
  698. const base::Value* user_policy =
  699. onc_dict->FindKey(::onc::kAugmentationUserPolicy);
  700. const base::Value* device_policy =
  701. onc_dict->FindKey(::onc::kAugmentationDevicePolicy);
  702. bool user_enforced = !GetBoolean(onc_dict, ::onc::kAugmentationUserEditable);
  703. bool device_enforced =
  704. !GetBoolean(onc_dict, ::onc::kAugmentationDeviceEditable);
  705. if (effective == ::onc::kAugmentationUserPolicy ||
  706. (user_policy && effective != ::onc::kAugmentationDevicePolicy)) {
  707. // Set the policy source to "User" when:
  708. // * The effective value is set to "UserPolicy" OR
  709. // * A User policy exists and the effective value is not "DevicePolicy",
  710. // i.e. no enforced device policy is overriding a recommended user policy.
  711. result.policy_source = user_enforced
  712. ? mojom::PolicySource::kUserPolicyEnforced
  713. : mojom::PolicySource::kUserPolicyRecommended;
  714. if (user_policy)
  715. result.policy_value = user_policy->Clone();
  716. } else if (effective == ::onc::kAugmentationDevicePolicy || device_policy) {
  717. // Set the policy source to "Device" when:
  718. // * The effective value is set to "DevicePolicy" OR
  719. // * A Device policy exists (since we checked for a user policy first).
  720. result.policy_source = device_enforced
  721. ? mojom::PolicySource::kDevicePolicyEnforced
  722. : mojom::PolicySource::kDevicePolicyRecommended;
  723. if (device_policy)
  724. result.policy_value = device_policy->Clone();
  725. } else if (effective == ::onc::kAugmentationUserSetting ||
  726. effective == ::onc::kAugmentationSharedSetting) {
  727. // User or shared setting, no policy source.
  728. } else {
  729. // Unexpected ONC. No policy source or value will be set.
  730. NET_LOG(ERROR) << "Unexpected ONC property: " << *onc_dict;
  731. }
  732. DCHECK(result.policy_value.is_none() ||
  733. result.policy_value.type() == result.active_value.type());
  734. return result;
  735. }
  736. mojom::ManagedStringPtr GetManagedString(const base::Value* dict,
  737. const char* key) {
  738. const base::Value* v = dict->FindKey(key);
  739. if (!v)
  740. return nullptr;
  741. if (v->is_string()) {
  742. auto result = mojom::ManagedString::New();
  743. result->active_value = v->GetString();
  744. return result;
  745. }
  746. if (v->is_dict()) {
  747. ManagedDictionary managed_dict = GetManagedDictionary(v);
  748. if (!managed_dict.active_value.is_string()) {
  749. NET_LOG(ERROR) << "No active or effective value for: " << key;
  750. return nullptr;
  751. }
  752. auto result = mojom::ManagedString::New();
  753. result->active_value = managed_dict.active_value.GetString();
  754. result->policy_source = managed_dict.policy_source;
  755. if (!managed_dict.policy_value.is_none())
  756. result->policy_value = managed_dict.policy_value.GetString();
  757. return result;
  758. }
  759. NET_LOG(ERROR) << "Expected string or dictionary, found: " << *v;
  760. return nullptr;
  761. }
  762. mojom::ManagedStringPtr GetRequiredManagedString(const base::Value* dict,
  763. const char* key) {
  764. mojom::ManagedStringPtr result = GetManagedString(dict, key);
  765. if (!result) {
  766. // Return an empty string with no policy source.
  767. result = mojom::ManagedString::New();
  768. }
  769. return result;
  770. }
  771. mojom::ManagedStringListPtr GetManagedStringList(const base::Value* dict,
  772. const char* key) {
  773. const base::Value* v = dict->FindKey(key);
  774. if (!v)
  775. return nullptr;
  776. if (v->is_list()) {
  777. auto result = mojom::ManagedStringList::New();
  778. std::vector<std::string> active;
  779. for (const base::Value& e : v->GetListDeprecated())
  780. active.push_back(e.GetString());
  781. result->active_value = std::move(active);
  782. return result;
  783. }
  784. if (v->is_dict()) {
  785. ManagedDictionary managed_dict = GetManagedDictionary(v);
  786. if (!managed_dict.active_value.is_list()) {
  787. NET_LOG(ERROR) << "No active or effective value for: " << key;
  788. return nullptr;
  789. }
  790. auto result = mojom::ManagedStringList::New();
  791. for (const base::Value& e : managed_dict.active_value.GetListDeprecated())
  792. result->active_value.push_back(e.GetString());
  793. result->policy_source = managed_dict.policy_source;
  794. if (!managed_dict.policy_value.is_none()) {
  795. result->policy_value = std::vector<std::string>();
  796. for (const base::Value& e : managed_dict.policy_value.GetListDeprecated())
  797. result->policy_value->push_back(e.GetString());
  798. }
  799. return result;
  800. }
  801. NET_LOG(ERROR) << "Expected list or dictionary, found: " << *v;
  802. return nullptr;
  803. }
  804. mojom::ManagedBooleanPtr GetManagedBoolean(const base::Value* dict,
  805. const char* key) {
  806. const base::Value* v = dict->FindKey(key);
  807. if (!v)
  808. return nullptr;
  809. if (v->is_bool()) {
  810. auto result = mojom::ManagedBoolean::New();
  811. result->active_value = v->GetBool();
  812. return result;
  813. }
  814. if (v->is_dict()) {
  815. ManagedDictionary managed_dict = GetManagedDictionary(v);
  816. if (!managed_dict.active_value.is_bool()) {
  817. NET_LOG(ERROR) << "No active or effective value for: " << key;
  818. return nullptr;
  819. }
  820. auto result = mojom::ManagedBoolean::New();
  821. result->active_value = managed_dict.active_value.GetBool();
  822. result->policy_source = managed_dict.policy_source;
  823. if (!managed_dict.policy_value.is_none())
  824. result->policy_value = managed_dict.policy_value.GetBool();
  825. return result;
  826. }
  827. NET_LOG(ERROR) << "Expected bool or dictionary, found: " << *v;
  828. return nullptr;
  829. }
  830. mojom::ManagedInt32Ptr GetManagedInt32(const base::Value* dict,
  831. const char* key) {
  832. const base::Value* v = dict->FindKey(key);
  833. if (!v)
  834. return nullptr;
  835. if (v->is_int()) {
  836. auto result = mojom::ManagedInt32::New();
  837. result->active_value = v->GetInt();
  838. return result;
  839. }
  840. if (v->is_dict()) {
  841. ManagedDictionary managed_dict = GetManagedDictionary(v);
  842. if (!managed_dict.active_value.is_int()) {
  843. NET_LOG(ERROR) << "No active or effective value for: " << key;
  844. return nullptr;
  845. }
  846. auto result = mojom::ManagedInt32::New();
  847. result->active_value = managed_dict.active_value.GetInt();
  848. result->policy_source = managed_dict.policy_source;
  849. if (!managed_dict.policy_value.is_none())
  850. result->policy_value = managed_dict.policy_value.GetInt();
  851. return result;
  852. }
  853. NET_LOG(ERROR) << "Expected int or dictionary, found: " << *v;
  854. return nullptr;
  855. }
  856. mojom::SubjectAltNamePtr GetSubjectAltName(const base::Value* dict) {
  857. auto san = mojom::SubjectAltName::New();
  858. san->value = GetRequiredString(
  859. dict, ::onc::eap_subject_alternative_name_match::kValue);
  860. std::string type =
  861. GetRequiredString(dict, ::onc::eap_subject_alternative_name_match::kType);
  862. if (type == ::onc::eap_subject_alternative_name_match::kEMAIL) {
  863. san->type = mojom::SubjectAltName::Type::kEmail;
  864. } else if (type == ::onc::eap_subject_alternative_name_match::kDNS) {
  865. san->type = mojom::SubjectAltName::Type::kDns;
  866. } else if (type == ::onc::eap_subject_alternative_name_match::kURI) {
  867. san->type = mojom::SubjectAltName::Type::kUri;
  868. } else {
  869. NET_LOG(ERROR) << "Unknown subject alternative name type " << type;
  870. return nullptr;
  871. }
  872. return san;
  873. }
  874. mojom::ManagedSubjectAltNameMatchListPtr GetManagedSubjectAltNameMatchList(
  875. const base::Value* dict,
  876. const char* key) {
  877. auto result = mojom::ManagedSubjectAltNameMatchList::New();
  878. const base::Value* value = dict->FindKey(key);
  879. if (!value)
  880. return result;
  881. if (value->is_list()) {
  882. std::vector<mojom::SubjectAltNamePtr> active;
  883. for (const base::Value& value : value->GetListDeprecated())
  884. active.push_back(GetSubjectAltName(&value));
  885. result->active_value = std::move(active);
  886. return result;
  887. }
  888. if (value->is_dict()) {
  889. ManagedDictionary managed_dict = GetManagedDictionary(value);
  890. if (!managed_dict.active_value.is_list()) {
  891. NET_LOG(ERROR) << "No active or effective value for WireGuardPeerList";
  892. return result;
  893. }
  894. for (const base::Value& e : managed_dict.active_value.GetListDeprecated())
  895. result->active_value.push_back(GetSubjectAltName(&e));
  896. result->policy_source = managed_dict.policy_source;
  897. if (!managed_dict.policy_value.is_none()) {
  898. result->policy_value = std::vector<mojom::SubjectAltNamePtr>();
  899. for (const base::Value& e : managed_dict.policy_value.GetListDeprecated())
  900. result->policy_value.push_back(GetSubjectAltName(&e));
  901. }
  902. return result;
  903. }
  904. NET_LOG(ERROR) << "Expected list or dictionary, found: " << *value;
  905. return result;
  906. }
  907. mojom::IPConfigPropertiesPtr GetIPConfig(const base::Value* dict) {
  908. auto ip_config = mojom::IPConfigProperties::New();
  909. ip_config->gateway = GetString(dict, ::onc::ipconfig::kGateway);
  910. ip_config->ip_address = GetString(dict, ::onc::ipconfig::kIPAddress);
  911. ip_config->excluded_routes =
  912. GetStringList(dict, ::onc::ipconfig::kExcludedRoutes);
  913. ip_config->included_routes =
  914. GetStringList(dict, ::onc::ipconfig::kIncludedRoutes);
  915. ip_config->name_servers = GetStringList(dict, ::onc::ipconfig::kNameServers);
  916. ip_config->search_domains =
  917. GetStringList(dict, ::onc::ipconfig::kSearchDomains);
  918. ip_config->routing_prefix = GetInt32(dict, ::onc::ipconfig::kRoutingPrefix);
  919. auto type = GetString(dict, ::onc::ipconfig::kType);
  920. if (!type || type->empty()) {
  921. // Shill may omit the IP Config type for VPNs. The type should be IPv4.
  922. ip_config->type = mojom::IPConfigType::kIPv4;
  923. } else {
  924. ip_config->type = OncIPConfigTypeToMojo(*type);
  925. }
  926. ip_config->web_proxy_auto_discovery_url =
  927. GetString(dict, ::onc::ipconfig::kWebProxyAutoDiscoveryUrl);
  928. return ip_config;
  929. }
  930. mojom::ManagedIPConfigPropertiesPtr GetManagedIPConfig(
  931. const base::Value* dict) {
  932. auto ip_config = mojom::ManagedIPConfigProperties::New();
  933. ip_config->gateway = GetManagedString(dict, ::onc::ipconfig::kGateway);
  934. ip_config->ip_address = GetManagedString(dict, ::onc::ipconfig::kIPAddress);
  935. ip_config->name_servers =
  936. GetManagedStringList(dict, ::onc::ipconfig::kNameServers);
  937. ip_config->routing_prefix =
  938. GetManagedInt32(dict, ::onc::ipconfig::kRoutingPrefix);
  939. // The IPConfig type is not actually mutable, so we convert from an optional
  940. // managed string to a required unmanaged type enum.
  941. mojom::ManagedStringPtr managed_type =
  942. GetManagedString(dict, ::onc::ipconfig::kType);
  943. mojom::IPConfigType type =
  944. managed_type ? OncIPConfigTypeToMojo(managed_type->active_value)
  945. : mojom::IPConfigType::kIPv4;
  946. ip_config->type = type;
  947. ip_config->web_proxy_auto_discovery_url =
  948. GetManagedString(dict, ::onc::ipconfig::kWebProxyAutoDiscoveryUrl);
  949. return ip_config;
  950. }
  951. mojom::ManagedProxyLocationPtr GetManagedProxyLocation(const base::Value* dict,
  952. const char* key) {
  953. const base::Value* location_dict = GetDictionary(dict, key);
  954. if (!location_dict)
  955. return nullptr;
  956. auto proxy_location = mojom::ManagedProxyLocation::New();
  957. proxy_location->host =
  958. GetRequiredManagedString(location_dict, ::onc::proxy::kHost);
  959. proxy_location->port = GetManagedInt32(location_dict, ::onc::proxy::kPort);
  960. if (!proxy_location->port) {
  961. NET_LOG(ERROR) << "ProxyLocation: No port: " << *location_dict;
  962. return nullptr;
  963. }
  964. return proxy_location;
  965. }
  966. void SetProxyLocation(const char* key,
  967. const mojom::ProxyLocationPtr& location,
  968. base::Value* dict) {
  969. if (location.is_null())
  970. return;
  971. base::Value location_dict(base::Value::Type::DICTIONARY);
  972. location_dict.SetStringKey(::onc::proxy::kHost, location->host);
  973. location_dict.SetIntKey(::onc::proxy::kPort, location->port);
  974. dict->SetKey(key, std::move(location_dict));
  975. }
  976. mojom::ManagedProxySettingsPtr GetManagedProxySettings(
  977. const base::Value* dict) {
  978. auto proxy_settings = mojom::ManagedProxySettings::New();
  979. proxy_settings->type = GetRequiredManagedString(dict, ::onc::proxy::kType);
  980. const base::Value* manual_dict = GetDictionary(dict, ::onc::proxy::kManual);
  981. if (manual_dict) {
  982. auto manual_proxy_settings = mojom::ManagedManualProxySettings::New();
  983. manual_proxy_settings->http_proxy =
  984. GetManagedProxyLocation(manual_dict, ::onc::proxy::kHttp);
  985. manual_proxy_settings->secure_http_proxy =
  986. GetManagedProxyLocation(manual_dict, ::onc::proxy::kHttps);
  987. manual_proxy_settings->ftp_proxy =
  988. GetManagedProxyLocation(manual_dict, ::onc::proxy::kFtp);
  989. manual_proxy_settings->socks =
  990. GetManagedProxyLocation(manual_dict, ::onc::proxy::kSocks);
  991. proxy_settings->manual = std::move(manual_proxy_settings);
  992. }
  993. proxy_settings->exclude_domains =
  994. GetManagedStringList(dict, ::onc::proxy::kExcludeDomains);
  995. proxy_settings->pac = GetManagedString(dict, ::onc::proxy::kPAC);
  996. return proxy_settings;
  997. }
  998. mojom::ApnPropertiesPtr GetApnProperties(const base::Value* dict) {
  999. auto apn = mojom::ApnProperties::New();
  1000. apn->access_point_name =
  1001. GetRequiredString(dict, ::onc::cellular_apn::kAccessPointName);
  1002. apn->authentication = GetString(dict, ::onc::cellular_apn::kAuthentication);
  1003. apn->language = GetString(dict, ::onc::cellular_apn::kLanguage);
  1004. apn->localized_name = GetString(dict, ::onc::cellular_apn::kLocalizedName);
  1005. apn->name = GetString(dict, ::onc::cellular_apn::kName);
  1006. apn->password = GetString(dict, ::onc::cellular_apn::kPassword);
  1007. apn->username = GetString(dict, ::onc::cellular_apn::kUsername);
  1008. apn->attach = GetString(dict, ::onc::cellular_apn::kAttach);
  1009. return apn;
  1010. }
  1011. mojom::ManagedApnPropertiesPtr GetManagedApnProperties(const base::Value* dict,
  1012. const char* key) {
  1013. const base::Value* apn_dict = dict->FindKey(key);
  1014. if (!apn_dict)
  1015. return nullptr;
  1016. if (!apn_dict->is_dict()) {
  1017. NET_LOG(ERROR) << "Expected dictionary, found: " << *apn_dict;
  1018. return nullptr;
  1019. }
  1020. auto apn = mojom::ManagedApnProperties::New();
  1021. apn->access_point_name =
  1022. GetRequiredManagedString(apn_dict, ::onc::cellular_apn::kAccessPointName);
  1023. CHECK(apn->access_point_name);
  1024. apn->authentication =
  1025. GetManagedString(apn_dict, ::onc::cellular_apn::kAuthentication);
  1026. apn->language = GetManagedString(apn_dict, ::onc::cellular_apn::kLanguage);
  1027. apn->localized_name =
  1028. GetManagedString(apn_dict, ::onc::cellular_apn::kLocalizedName);
  1029. apn->name = GetManagedString(apn_dict, ::onc::cellular_apn::kName);
  1030. apn->password = GetManagedString(apn_dict, ::onc::cellular_apn::kPassword);
  1031. apn->username = GetManagedString(apn_dict, ::onc::cellular_apn::kUsername);
  1032. apn->attach = GetManagedString(apn_dict, ::onc::cellular_apn::kAttach);
  1033. return apn;
  1034. }
  1035. mojom::ManagedApnListPtr GetManagedApnList(const base::Value* value) {
  1036. if (!value)
  1037. return nullptr;
  1038. if (value->is_list()) {
  1039. auto result = mojom::ManagedApnList::New();
  1040. std::vector<mojom::ApnPropertiesPtr> active;
  1041. for (const base::Value& value : value->GetListDeprecated())
  1042. active.push_back(GetApnProperties(&value));
  1043. result->active_value = std::move(active);
  1044. return result;
  1045. } else if (value->is_dict()) {
  1046. ManagedDictionary managed_dict = GetManagedDictionary(value);
  1047. if (!managed_dict.active_value.is_list()) {
  1048. NET_LOG(ERROR) << "No active or effective value for APNList";
  1049. return nullptr;
  1050. }
  1051. auto result = mojom::ManagedApnList::New();
  1052. for (const base::Value& e : managed_dict.active_value.GetListDeprecated())
  1053. result->active_value.push_back(GetApnProperties(&e));
  1054. result->policy_source = managed_dict.policy_source;
  1055. if (!managed_dict.policy_value.is_none()) {
  1056. result->policy_value = std::vector<mojom::ApnPropertiesPtr>();
  1057. for (const base::Value& e : managed_dict.policy_value.GetListDeprecated())
  1058. result->policy_value->push_back(GetApnProperties(&e));
  1059. }
  1060. return result;
  1061. }
  1062. NET_LOG(ERROR) << "Expected list or dictionary, found: " << *value;
  1063. return nullptr;
  1064. }
  1065. std::vector<mojom::FoundNetworkPropertiesPtr> GetFoundNetworksList(
  1066. const base::Value* dict,
  1067. const char* key) {
  1068. std::vector<mojom::FoundNetworkPropertiesPtr> result;
  1069. const base::Value* v = dict->FindKey(key);
  1070. if (!v)
  1071. return result;
  1072. if (!v->is_list()) {
  1073. NET_LOG(ERROR) << "Expected list, found: " << *v;
  1074. return result;
  1075. }
  1076. for (const base::Value& e : v->GetListDeprecated()) {
  1077. auto found_network = mojom::FoundNetworkProperties::New();
  1078. found_network->status =
  1079. GetRequiredString(&e, ::onc::cellular_found_network::kStatus);
  1080. found_network->network_id =
  1081. GetRequiredString(&e, ::onc::cellular_found_network::kNetworkId);
  1082. found_network->technology =
  1083. GetRequiredString(&e, ::onc::cellular_found_network::kTechnology);
  1084. found_network->short_name =
  1085. GetString(&e, ::onc::cellular_found_network::kShortName);
  1086. found_network->long_name =
  1087. GetString(&e, ::onc::cellular_found_network::kLongName);
  1088. result.push_back(std::move(found_network));
  1089. }
  1090. return result;
  1091. }
  1092. mojom::CellularProviderPropertiesPtr GetCellularProviderProperties(
  1093. const base::Value* dict,
  1094. const char* key) {
  1095. const base::Value* provider_dict = dict->FindKey(key);
  1096. if (!provider_dict)
  1097. return nullptr;
  1098. auto provider = mojom::CellularProviderProperties::New();
  1099. provider->name =
  1100. GetRequiredString(provider_dict, ::onc::cellular_provider::kName);
  1101. provider->code =
  1102. GetRequiredString(provider_dict, ::onc::cellular_provider::kCode);
  1103. provider->country =
  1104. GetString(provider_dict, ::onc::cellular_provider::kCountry);
  1105. return provider;
  1106. }
  1107. mojom::ManagedIssuerSubjectPatternPtr GetManagedIssuerSubjectPattern(
  1108. const base::Value* dict,
  1109. const char* key) {
  1110. const base::Value* pattern_dict = dict->FindKey(key);
  1111. if (!pattern_dict)
  1112. return nullptr;
  1113. if (!pattern_dict->is_dict()) {
  1114. NET_LOG(ERROR) << "Expected dictionary, found: " << *pattern_dict;
  1115. return nullptr;
  1116. }
  1117. auto pattern = mojom::ManagedIssuerSubjectPattern::New();
  1118. pattern->common_name =
  1119. GetManagedString(pattern_dict, ::onc::client_cert::kCommonName);
  1120. pattern->locality =
  1121. GetManagedString(pattern_dict, ::onc::client_cert::kLocality);
  1122. pattern->organization =
  1123. GetManagedString(pattern_dict, ::onc::client_cert::kOrganization);
  1124. pattern->organizational_unit =
  1125. GetManagedString(pattern_dict, ::onc::client_cert::kOrganizationalUnit);
  1126. return pattern;
  1127. }
  1128. mojom::ManagedCertificatePatternPtr GetManagedCertificatePattern(
  1129. const base::Value* dict,
  1130. const char* key) {
  1131. const base::Value* pattern_dict = dict->FindKey(key);
  1132. if (!pattern_dict)
  1133. return nullptr;
  1134. if (!pattern_dict->is_dict()) {
  1135. NET_LOG(ERROR) << "Expected dictionary, found: " << *pattern_dict;
  1136. return nullptr;
  1137. }
  1138. auto pattern = mojom::ManagedCertificatePattern::New();
  1139. pattern->enrollment_uri =
  1140. GetManagedStringList(pattern_dict, ::onc::client_cert::kEnrollmentURI);
  1141. pattern->issuer =
  1142. GetManagedIssuerSubjectPattern(pattern_dict, ::onc::client_cert::kIssuer);
  1143. pattern->issuer_ca_ref =
  1144. GetManagedStringList(pattern_dict, ::onc::client_cert::kIssuerCARef);
  1145. pattern->subject = GetManagedIssuerSubjectPattern(
  1146. pattern_dict, ::onc::client_cert::kSubject);
  1147. return pattern;
  1148. }
  1149. mojom::ManagedEAPPropertiesPtr GetManagedEAPProperties(const base::Value* dict,
  1150. const char* key) {
  1151. auto eap = mojom::ManagedEAPProperties::New();
  1152. const base::Value* eap_dict = dict->FindKey(key);
  1153. if (!eap_dict)
  1154. return eap;
  1155. if (!eap_dict->is_dict()) {
  1156. NET_LOG(ERROR) << "Expected dictionary, found: " << *eap_dict;
  1157. return eap;
  1158. }
  1159. eap->anonymous_identity =
  1160. GetManagedString(eap_dict, ::onc::eap::kAnonymousIdentity);
  1161. eap->client_cert_pattern = GetManagedCertificatePattern(
  1162. eap_dict, ::onc::client_cert::kClientCertPattern);
  1163. eap->client_cert_pkcs11_id =
  1164. GetManagedString(eap_dict, ::onc::client_cert::kClientCertPKCS11Id);
  1165. eap->client_cert_provisioning_profile_id = GetManagedString(
  1166. eap_dict, ::onc::client_cert::kClientCertProvisioningProfileId);
  1167. eap->client_cert_ref =
  1168. GetManagedString(eap_dict, ::onc::client_cert::kClientCertRef);
  1169. eap->client_cert_type =
  1170. GetManagedString(eap_dict, ::onc::client_cert::kClientCertType);
  1171. eap->domain_suffix_match =
  1172. GetManagedStringList(eap_dict, ::onc::eap::kDomainSuffixMatch);
  1173. eap->identity = GetManagedString(eap_dict, ::onc::eap::kIdentity);
  1174. eap->inner = GetManagedString(eap_dict, ::onc::eap::kInner);
  1175. eap->outer = GetManagedString(eap_dict, ::onc::eap::kOuter);
  1176. eap->password = GetManagedString(eap_dict, ::onc::eap::kPassword);
  1177. eap->save_credentials =
  1178. GetManagedBoolean(eap_dict, ::onc::eap::kSaveCredentials);
  1179. eap->server_ca_pems =
  1180. GetManagedStringList(eap_dict, ::onc::eap::kServerCAPEMs);
  1181. eap->server_ca_refs =
  1182. GetManagedStringList(eap_dict, ::onc::eap::kServerCARefs);
  1183. eap->subject_alt_name_match = GetManagedSubjectAltNameMatchList(
  1184. eap_dict, ::onc::eap::kSubjectAlternativeNameMatch);
  1185. eap->subject_match = GetManagedString(eap_dict, ::onc::eap::kSubjectMatch);
  1186. eap->tls_version_max = GetManagedString(eap_dict, ::onc::eap::kTLSVersionMax);
  1187. eap->use_proactive_key_caching =
  1188. GetManagedBoolean(eap_dict, ::onc::eap::kUseProactiveKeyCaching);
  1189. eap->use_system_cas = GetManagedBoolean(eap_dict, ::onc::eap::kUseSystemCAs);
  1190. return eap;
  1191. }
  1192. mojom::ManagedIPSecPropertiesPtr GetManagedIPSecProperties(
  1193. const base::Value* dict,
  1194. const char* key) {
  1195. auto ipsec = mojom::ManagedIPSecProperties::New();
  1196. const base::Value* ipsec_dict = dict->FindKey(key);
  1197. if (!ipsec_dict)
  1198. return ipsec;
  1199. if (!ipsec_dict->is_dict()) {
  1200. NET_LOG(ERROR) << "Expected dictionary, found: " << *ipsec_dict;
  1201. return ipsec;
  1202. }
  1203. ipsec->authentication_type =
  1204. GetRequiredManagedString(ipsec_dict, ::onc::ipsec::kAuthenticationType);
  1205. ipsec->client_cert_pattern = GetManagedCertificatePattern(
  1206. ipsec_dict, ::onc::client_cert::kClientCertPattern);
  1207. ipsec->client_cert_pkcs11_id =
  1208. GetManagedString(ipsec_dict, ::onc::client_cert::kClientCertPKCS11Id);
  1209. ipsec->client_cert_provisioning_profile_id = GetManagedString(
  1210. ipsec_dict, ::onc::client_cert::kClientCertProvisioningProfileId);
  1211. ipsec->client_cert_ref =
  1212. GetManagedString(ipsec_dict, ::onc::client_cert::kClientCertRef);
  1213. ipsec->client_cert_type =
  1214. GetManagedString(ipsec_dict, ::onc::client_cert::kClientCertType);
  1215. ipsec->eap = GetManagedEAPProperties(ipsec_dict, ::onc::ipsec::kEAP);
  1216. ipsec->group = GetManagedString(ipsec_dict, ::onc::ipsec::kGroup);
  1217. ipsec->ike_version = GetManagedInt32(ipsec_dict, ::onc::ipsec::kIKEVersion);
  1218. ipsec->psk = GetManagedString(ipsec_dict, ::onc::ipsec::kPSK);
  1219. ipsec->save_credentials =
  1220. GetManagedBoolean(ipsec_dict, ::onc::vpn::kSaveCredentials);
  1221. ipsec->server_ca_pems =
  1222. GetManagedStringList(ipsec_dict, ::onc::ipsec::kServerCAPEMs);
  1223. ipsec->server_ca_refs =
  1224. GetManagedStringList(ipsec_dict, ::onc::ipsec::kServerCARefs);
  1225. ipsec->local_identity =
  1226. GetManagedString(ipsec_dict, ::onc::ipsec::kLocalIdentity);
  1227. ipsec->remote_identity =
  1228. GetManagedString(ipsec_dict, ::onc::ipsec::kRemoteIdentity);
  1229. return ipsec;
  1230. }
  1231. mojom::ManagedL2TPPropertiesPtr GetManagedL2TPProperties(
  1232. const base::Value* dict,
  1233. const char* key) {
  1234. auto l2tp = mojom::ManagedL2TPProperties::New();
  1235. const base::Value* l2tp_dict = dict->FindKey(key);
  1236. if (!l2tp_dict)
  1237. return l2tp;
  1238. if (!l2tp_dict->is_dict()) {
  1239. NET_LOG(ERROR) << "Expected dictionary, found: " << *l2tp_dict;
  1240. return l2tp;
  1241. }
  1242. l2tp->lcp_echo_disabled =
  1243. GetManagedBoolean(l2tp_dict, ::onc::l2tp::kLcpEchoDisabled);
  1244. l2tp->password = GetManagedString(l2tp_dict, ::onc::l2tp::kPassword);
  1245. l2tp->save_credentials =
  1246. GetManagedBoolean(l2tp_dict, ::onc::l2tp::kSaveCredentials);
  1247. l2tp->username = GetManagedString(l2tp_dict, ::onc::l2tp::kUsername);
  1248. return l2tp;
  1249. }
  1250. mojom::ManagedOpenVPNPropertiesPtr GetManagedOpenVPNProperties(
  1251. const base::Value* dict,
  1252. const char* key) {
  1253. auto openvpn = mojom::ManagedOpenVPNProperties::New();
  1254. const base::Value* openvpn_dict = dict->FindKey(key);
  1255. if (!openvpn_dict)
  1256. return openvpn;
  1257. if (!openvpn_dict->is_dict()) {
  1258. NET_LOG(ERROR) << "Expected dictionary, found: " << *openvpn_dict;
  1259. return openvpn;
  1260. }
  1261. openvpn->auth = GetManagedString(openvpn_dict, ::onc::openvpn::kAuth);
  1262. openvpn->auth_retry =
  1263. GetManagedString(openvpn_dict, ::onc::openvpn::kAuthRetry);
  1264. openvpn->auth_no_cache =
  1265. GetManagedBoolean(openvpn_dict, ::onc::openvpn::kAuthNoCache);
  1266. openvpn->cipher = GetManagedString(openvpn_dict, ::onc::openvpn::kCipher);
  1267. openvpn->client_cert_pkcs11_id =
  1268. GetManagedString(openvpn_dict, ::onc::client_cert::kClientCertPKCS11Id);
  1269. openvpn->client_cert_pattern = GetManagedCertificatePattern(
  1270. openvpn_dict, ::onc::client_cert::kClientCertPattern);
  1271. openvpn->client_cert_provisioning_profile_id = GetManagedString(
  1272. openvpn_dict, ::onc::client_cert::kClientCertProvisioningProfileId);
  1273. openvpn->client_cert_ref =
  1274. GetManagedString(openvpn_dict, ::onc::client_cert::kClientCertRef);
  1275. openvpn->client_cert_type =
  1276. GetManagedString(openvpn_dict, ::onc::client_cert::kClientCertType);
  1277. openvpn->compression_algorithm =
  1278. GetManagedString(openvpn_dict, ::onc::openvpn::kCompressionAlgorithm);
  1279. openvpn->extra_hosts =
  1280. GetManagedStringList(openvpn_dict, ::onc::openvpn::kExtraHosts);
  1281. openvpn->ignore_default_route =
  1282. GetManagedBoolean(openvpn_dict, ::onc::openvpn::kIgnoreDefaultRoute);
  1283. openvpn->key_direction =
  1284. GetManagedString(openvpn_dict, ::onc::openvpn::kKeyDirection);
  1285. openvpn->ns_cert_type =
  1286. GetManagedString(openvpn_dict, ::onc::openvpn::kNsCertType);
  1287. openvpn->password = GetManagedString(openvpn_dict, ::onc::openvpn::kPassword);
  1288. openvpn->port = GetManagedInt32(openvpn_dict, ::onc::openvpn::kPort);
  1289. openvpn->proto = GetManagedString(openvpn_dict, ::onc::openvpn::kProto);
  1290. openvpn->push_peer_info =
  1291. GetManagedBoolean(openvpn_dict, ::onc::openvpn::kPushPeerInfo);
  1292. openvpn->remote_cert_eku =
  1293. GetManagedString(openvpn_dict, ::onc::openvpn::kRemoteCertEKU);
  1294. openvpn->remote_cert_ku =
  1295. GetManagedStringList(openvpn_dict, ::onc::openvpn::kRemoteCertKU);
  1296. openvpn->remote_cert_tls =
  1297. GetManagedString(openvpn_dict, ::onc::openvpn::kRemoteCertTLS);
  1298. openvpn->reneg_sec = GetManagedInt32(openvpn_dict, ::onc::openvpn::kRenegSec);
  1299. openvpn->save_credentials =
  1300. GetManagedBoolean(openvpn_dict, ::onc::vpn::kSaveCredentials);
  1301. openvpn->server_ca_pems =
  1302. GetManagedStringList(openvpn_dict, ::onc::openvpn::kServerCAPEMs);
  1303. openvpn->server_ca_refs =
  1304. GetManagedStringList(openvpn_dict, ::onc::openvpn::kServerCARefs);
  1305. openvpn->server_cert_ref =
  1306. GetManagedString(openvpn_dict, ::onc::openvpn::kServerCertRef);
  1307. openvpn->server_poll_timeout =
  1308. GetManagedInt32(openvpn_dict, ::onc::openvpn::kServerPollTimeout);
  1309. openvpn->shaper = GetManagedInt32(openvpn_dict, ::onc::openvpn::kShaper);
  1310. openvpn->static_challenge =
  1311. GetManagedString(openvpn_dict, ::onc::openvpn::kStaticChallenge);
  1312. openvpn->tls_auth_contents =
  1313. GetManagedString(openvpn_dict, ::onc::openvpn::kTLSAuthContents);
  1314. openvpn->tls_remote =
  1315. GetManagedString(openvpn_dict, ::onc::openvpn::kTLSRemote);
  1316. openvpn->tls_version_min =
  1317. GetManagedString(openvpn_dict, ::onc::openvpn::kTLSVersionMin);
  1318. openvpn->user_authentication_type =
  1319. GetManagedString(openvpn_dict, ::onc::openvpn::kUserAuthenticationType);
  1320. openvpn->username = GetManagedString(openvpn_dict, ::onc::vpn::kUsername);
  1321. openvpn->verb = GetManagedString(openvpn_dict, ::onc::openvpn::kVerb);
  1322. openvpn->verify_hash =
  1323. GetManagedString(openvpn_dict, ::onc::openvpn::kVerifyHash);
  1324. const base::Value* verify_x509_dict =
  1325. openvpn_dict->FindKey(::onc::openvpn::kVerifyX509);
  1326. if (verify_x509_dict) {
  1327. auto verify_x509 = mojom::ManagedVerifyX509Properties::New();
  1328. verify_x509->name =
  1329. GetManagedString(verify_x509_dict, ::onc::verify_x509::kName);
  1330. verify_x509->type =
  1331. GetManagedString(verify_x509_dict, ::onc::verify_x509::kType);
  1332. openvpn->verify_x509 = std::move(verify_x509);
  1333. }
  1334. return openvpn;
  1335. }
  1336. mojom::WireGuardPeerPropertiesPtr GetWireGuardPeerProperties(
  1337. const base::Value* dict) {
  1338. auto peer = mojom::WireGuardPeerProperties::New();
  1339. peer->public_key = GetRequiredString(dict, ::onc::wireguard::kPublicKey);
  1340. peer->preshared_key = GetString(dict, ::onc::wireguard::kPresharedKey);
  1341. peer->allowed_ips = GetString(dict, ::onc::wireguard::kAllowedIPs);
  1342. peer->endpoint = GetString(dict, ::onc::wireguard::kEndpoint);
  1343. peer->persistent_keepalive_interval =
  1344. GetInt32(dict, ::onc::wireguard::kPersistentKeepalive);
  1345. return peer;
  1346. }
  1347. mojom::ManagedWireGuardPeerListPtr GetManagedWireGuardPeerList(
  1348. const base::Value* dict,
  1349. const char* key) {
  1350. auto result = mojom::ManagedWireGuardPeerList::New();
  1351. const base::Value* value = dict->FindKey(key);
  1352. if (!value)
  1353. return result;
  1354. if (value->is_list()) {
  1355. std::vector<mojom::WireGuardPeerPropertiesPtr> active;
  1356. for (const base::Value& value : value->GetListDeprecated())
  1357. active.push_back(GetWireGuardPeerProperties(&value));
  1358. result->active_value = std::move(active);
  1359. return result;
  1360. }
  1361. if (value->is_dict()) {
  1362. ManagedDictionary managed_dict = GetManagedDictionary(value);
  1363. if (!managed_dict.active_value.is_list()) {
  1364. NET_LOG(ERROR) << "No active or effective value for WireGuardPeerList";
  1365. return result;
  1366. }
  1367. for (const base::Value& e : managed_dict.active_value.GetListDeprecated())
  1368. result->active_value.push_back(GetWireGuardPeerProperties(&e));
  1369. result->policy_source = managed_dict.policy_source;
  1370. if (!managed_dict.policy_value.is_none()) {
  1371. result->policy_value = std::vector<mojom::WireGuardPeerPropertiesPtr>();
  1372. for (const base::Value& e : managed_dict.policy_value.GetListDeprecated())
  1373. result->policy_value->push_back(GetWireGuardPeerProperties(&e));
  1374. }
  1375. return result;
  1376. }
  1377. NET_LOG(ERROR) << "Expected list or dictionary, found: " << *value;
  1378. return result;
  1379. }
  1380. mojom::ManagedWireGuardPropertiesPtr GetManagedWireGuardProperties(
  1381. const base::Value* dict,
  1382. const char* key) {
  1383. auto wg = mojom::ManagedWireGuardProperties::New();
  1384. const base::Value* wg_dict = dict->FindKey(key);
  1385. if (!wg_dict) {
  1386. NET_LOG(ERROR) << "Missing WireGuard properties element";
  1387. return wg;
  1388. }
  1389. if (!wg_dict->is_dict()) {
  1390. NET_LOG(ERROR) << "Expected dictionary, found: " << *wg_dict;
  1391. return wg;
  1392. }
  1393. wg->private_key = GetManagedString(wg_dict, ::onc::wireguard::kPrivateKey);
  1394. wg->public_key = GetManagedString(wg_dict, ::onc::wireguard::kPublicKey);
  1395. wg->peers = GetManagedWireGuardPeerList(wg_dict, ::onc::wireguard::kPeers);
  1396. return wg;
  1397. }
  1398. mojom::ManagedPropertiesPtr ManagedPropertiesToMojo(
  1399. NetworkStateHandler* network_state_handler,
  1400. CellularESimProfileHandler* cellular_esim_profile_handler,
  1401. const NetworkState* network_state,
  1402. const std::vector<mojom::VpnProviderPtr>& vpn_providers,
  1403. const base::Value* properties) {
  1404. DCHECK(network_state);
  1405. DCHECK(properties);
  1406. absl::optional<std::string> onc_type =
  1407. GetString(properties, ::onc::network_config::kType);
  1408. if (!onc_type) {
  1409. NET_LOG(ERROR) << "Malformed ONC dictionary: missing 'Type'";
  1410. return nullptr;
  1411. }
  1412. mojom::NetworkType type = OncTypeToMojo(*onc_type);
  1413. if (type == mojom::NetworkType::kAll) {
  1414. NET_LOG(ERROR) << "Unexpected network type: " << *onc_type;
  1415. return nullptr;
  1416. }
  1417. auto result = mojom::ManagedProperties::New();
  1418. // |network_state| and |properties| guid should be the same.
  1419. absl::optional<std::string> guid =
  1420. GetString(properties, ::onc::network_config::kGUID);
  1421. if (!guid) {
  1422. NET_LOG(ERROR) << "Malformed ONC dictionary: missing 'GUID'";
  1423. return nullptr;
  1424. }
  1425. DCHECK_EQ(network_state->guid(), *guid);
  1426. result->guid = network_state->guid();
  1427. // Typed properties (compatible with NetworkStateProperties):
  1428. result->connection_state =
  1429. GetConnectionState(network_state, /*technology_enabled=*/true);
  1430. result->source = GetMojoOncSource(network_state);
  1431. result->type = type;
  1432. // Unmanaged properties
  1433. result->connectable =
  1434. GetBoolean(properties, ::onc::network_config::kConnectable);
  1435. result->error_state =
  1436. GetString(properties, ::onc::network_config::kErrorState);
  1437. const base::Value* ip_configs_list =
  1438. properties->FindKey(::onc::network_config::kIPConfigs);
  1439. if (ip_configs_list) {
  1440. std::vector<mojom::IPConfigPropertiesPtr> ip_configs;
  1441. for (const base::Value& ip_config_value :
  1442. ip_configs_list->GetListDeprecated())
  1443. ip_configs.push_back(GetIPConfig(&ip_config_value));
  1444. result->ip_configs = std::move(ip_configs);
  1445. }
  1446. result->portal_state = GetMojoPortalState(network_state->GetPortalState());
  1447. const base::Value* saved_ip_config =
  1448. GetDictionary(properties, ::onc::network_config::kSavedIPConfig);
  1449. if (saved_ip_config)
  1450. result->saved_ip_config = GetIPConfig(saved_ip_config);
  1451. // Managed properties
  1452. result->ip_address_config_type = GetRequiredManagedString(
  1453. properties, ::onc::network_config::kIPAddressConfigType);
  1454. result->metered =
  1455. GetManagedBoolean(properties, ::onc::network_config::kMetered);
  1456. result->name = GetManagedString(properties, ::onc::network_config::kName);
  1457. if (result->name->policy_source == mojom::PolicySource::kNone) {
  1458. absl::optional<std::string> profile_name =
  1459. network_name_util::GetESimProfileName(cellular_esim_profile_handler,
  1460. network_state);
  1461. if (profile_name)
  1462. result->name->active_value = *profile_name;
  1463. }
  1464. result->name_servers_config_type = GetRequiredManagedString(
  1465. properties, ::onc::network_config::kNameServersConfigType);
  1466. result->priority =
  1467. GetManagedInt32(properties, ::onc::network_config::kPriority);
  1468. // Managed dictionaries (not type specific)
  1469. const base::Value* proxy_settings =
  1470. GetDictionary(properties, ::onc::network_config::kProxySettings);
  1471. if (proxy_settings)
  1472. result->proxy_settings = GetManagedProxySettings(proxy_settings);
  1473. const base::Value* static_ip_config =
  1474. GetDictionary(properties, ::onc::network_config::kStaticIPConfig);
  1475. if (static_ip_config)
  1476. result->static_ip_config = GetManagedIPConfig(static_ip_config);
  1477. // Type specific dictionaries
  1478. switch (type) {
  1479. case mojom::NetworkType::kCellular: {
  1480. auto cellular = mojom::ManagedCellularProperties::New();
  1481. cellular->activation_state = network_state->GetMojoActivationState();
  1482. const base::Value* cellular_dict =
  1483. GetDictionary(properties, ::onc::network_config::kCellular);
  1484. if (!cellular_dict) {
  1485. result->type_properties =
  1486. mojom::NetworkTypeManagedProperties::NewCellular(
  1487. std::move(cellular));
  1488. break;
  1489. }
  1490. cellular->auto_connect =
  1491. GetManagedBoolean(cellular_dict, ::onc::cellular::kAutoConnect);
  1492. cellular->selected_apn =
  1493. GetManagedApnProperties(cellular_dict, ::onc::cellular::kAPN);
  1494. cellular->apn_list =
  1495. GetManagedApnList(cellular_dict->FindKey(::onc::cellular::kAPNList));
  1496. cellular->allow_roaming =
  1497. GetManagedBoolean(cellular_dict, ::onc::cellular::kAllowRoaming);
  1498. cellular->esn = GetString(cellular_dict, ::onc::cellular::kESN);
  1499. cellular->family = GetString(cellular_dict, ::onc::cellular::kFamily);
  1500. cellular->firmware_revision =
  1501. GetString(cellular_dict, ::onc::cellular::kFirmwareRevision);
  1502. cellular->found_networks =
  1503. GetFoundNetworksList(cellular_dict, ::onc::cellular::kFoundNetworks);
  1504. cellular->hardware_revision =
  1505. GetString(cellular_dict, ::onc::cellular::kHardwareRevision);
  1506. cellular->home_provider = GetCellularProviderProperties(
  1507. cellular_dict, ::onc::cellular::kHomeProvider);
  1508. cellular->eid = GetString(cellular_dict, ::onc::cellular::kEID);
  1509. cellular->iccid = GetString(cellular_dict, ::onc::cellular::kICCID);
  1510. cellular->imei = GetString(cellular_dict, ::onc::cellular::kIMEI);
  1511. const base::Value* apn_dict =
  1512. GetDictionary(cellular_dict, ::onc::cellular::kLastGoodAPN);
  1513. if (apn_dict)
  1514. cellular->last_good_apn = GetApnProperties(apn_dict);
  1515. cellular->manufacturer =
  1516. GetString(cellular_dict, ::onc::cellular::kManufacturer);
  1517. cellular->mdn = GetString(cellular_dict, ::onc::cellular::kMDN);
  1518. cellular->meid = GetString(cellular_dict, ::onc::cellular::kMEID);
  1519. cellular->min = GetString(cellular_dict, ::onc::cellular::kMIN);
  1520. cellular->model_id = GetString(cellular_dict, ::onc::cellular::kModelID);
  1521. cellular->network_technology =
  1522. GetString(cellular_dict, ::onc::cellular::kNetworkTechnology);
  1523. const base::Value* payment_portal_dict =
  1524. cellular_dict->FindKey(::onc::cellular::kPaymentPortal);
  1525. if (payment_portal_dict) {
  1526. auto payment_portal = mojom::PaymentPortalProperties::New();
  1527. payment_portal->method = GetRequiredString(
  1528. payment_portal_dict, ::onc::cellular_payment_portal::kMethod);
  1529. payment_portal->post_data = GetRequiredString(
  1530. payment_portal_dict, ::onc::cellular_payment_portal::kPostData);
  1531. payment_portal->url = GetString(payment_portal_dict,
  1532. ::onc::cellular_payment_portal::kUrl);
  1533. cellular->payment_portal = std::move(payment_portal);
  1534. }
  1535. cellular->roaming_state =
  1536. GetString(cellular_dict, ::onc::cellular::kRoamingState);
  1537. cellular->serving_operator = GetCellularProviderProperties(
  1538. cellular_dict, ::onc::cellular::kServingOperator);
  1539. cellular->signal_strength =
  1540. GetInt32(cellular_dict, ::onc::cellular::kSignalStrength);
  1541. cellular->support_network_scan =
  1542. GetBoolean(cellular_dict, ::onc::cellular::kSupportNetworkScan);
  1543. const DeviceState* cellular_device =
  1544. network_state_handler->GetDeviceState(network_state->device_path());
  1545. // The cellular device only tracks whether the active SIM is locked. To
  1546. // determine whether |network_state| is locked, we check that the SIM is
  1547. // active by comparing the ICCID to the device's ICCID, then we check that
  1548. // the device is in a locked state.
  1549. cellular->sim_locked = cellular_device &&
  1550. cellular_device->iccid() == cellular->iccid &&
  1551. cellular_device->IsSimLocked();
  1552. result->type_properties =
  1553. mojom::NetworkTypeManagedProperties::NewCellular(std::move(cellular));
  1554. break;
  1555. }
  1556. case mojom::NetworkType::kEthernet: {
  1557. auto ethernet = mojom::ManagedEthernetProperties::New();
  1558. const base::Value* ethernet_dict =
  1559. GetDictionary(properties, ::onc::network_config::kEthernet);
  1560. if (ethernet_dict) {
  1561. ethernet->authentication =
  1562. GetManagedString(ethernet_dict, ::onc::ethernet::kAuthentication);
  1563. ethernet->eap =
  1564. GetManagedEAPProperties(ethernet_dict, ::onc::ethernet::kEAP);
  1565. }
  1566. result->type_properties =
  1567. mojom::NetworkTypeManagedProperties::NewEthernet(std::move(ethernet));
  1568. break;
  1569. }
  1570. case mojom::NetworkType::kTether: {
  1571. // Tether has no managed properties, provide the state properties.
  1572. auto tether = mojom::TetherStateProperties::New();
  1573. tether->battery_percentage = network_state->battery_percentage();
  1574. tether->carrier = network_state->tether_carrier();
  1575. tether->has_connected_to_host =
  1576. network_state->tether_has_connected_to_host();
  1577. tether->signal_strength = network_state->signal_strength();
  1578. result->type_properties =
  1579. mojom::NetworkTypeManagedProperties::NewTether(std::move(tether));
  1580. break;
  1581. }
  1582. case mojom::NetworkType::kVPN: {
  1583. auto vpn = mojom::ManagedVPNProperties::New();
  1584. const base::Value* vpn_dict =
  1585. GetDictionary(properties, ::onc::network_config::kVPN);
  1586. if (!vpn_dict) {
  1587. result->type_properties =
  1588. mojom::NetworkTypeManagedProperties::NewVpn(std::move(vpn));
  1589. break;
  1590. }
  1591. mojom::ManagedStringPtr managed_type =
  1592. GetManagedString(vpn_dict, ::onc::vpn::kType);
  1593. CHECK(managed_type);
  1594. vpn->type = OncVpnTypeToMojo(managed_type->active_value);
  1595. vpn->auto_connect = GetManagedBoolean(vpn_dict, ::onc::vpn::kAutoConnect);
  1596. vpn->host = GetManagedString(vpn_dict, ::onc::vpn::kHost);
  1597. switch (vpn->type) {
  1598. case mojom::VpnType::kIKEv2:
  1599. vpn->ip_sec = GetManagedIPSecProperties(vpn_dict, ::onc::vpn::kIPsec);
  1600. break;
  1601. case mojom::VpnType::kL2TPIPsec:
  1602. vpn->ip_sec = GetManagedIPSecProperties(vpn_dict, ::onc::vpn::kIPsec);
  1603. vpn->l2tp = GetManagedL2TPProperties(vpn_dict, ::onc::vpn::kL2TP);
  1604. break;
  1605. case mojom::VpnType::kOpenVPN:
  1606. vpn->open_vpn =
  1607. GetManagedOpenVPNProperties(vpn_dict, ::onc::vpn::kOpenVPN);
  1608. break;
  1609. case mojom::VpnType::kWireGuard:
  1610. vpn->wireguard =
  1611. GetManagedWireGuardProperties(vpn_dict, ::onc::vpn::kWireGuard);
  1612. break;
  1613. case mojom::VpnType::kExtension:
  1614. case mojom::VpnType::kArc:
  1615. const base::Value* third_party_dict =
  1616. vpn_dict->FindKey(::onc::vpn::kThirdPartyVpn);
  1617. if (third_party_dict) {
  1618. vpn->provider_id = GetManagedString(
  1619. third_party_dict, ::onc::third_party_vpn::kExtensionID);
  1620. absl::optional<std::string> provider_name = GetString(
  1621. third_party_dict, ::onc::third_party_vpn::kProviderName);
  1622. if (provider_name)
  1623. vpn->provider_name = *provider_name;
  1624. if (vpn->provider_id && vpn->provider_name.empty()) {
  1625. vpn->provider_name = GetVpnProviderName(
  1626. vpn_providers, vpn->provider_id->active_value);
  1627. }
  1628. } else {
  1629. // Lookup VPN provider details from the NetworkState.
  1630. const NetworkState::VpnProviderInfo* vpn_provider =
  1631. network_state->vpn_provider();
  1632. if (vpn_provider) {
  1633. vpn->provider_id = mojom::ManagedString::New();
  1634. vpn->provider_id->active_value = vpn_provider->id;
  1635. vpn->provider_name =
  1636. GetVpnProviderName(vpn_providers, vpn_provider->id);
  1637. }
  1638. }
  1639. break;
  1640. }
  1641. result->type_properties =
  1642. mojom::NetworkTypeManagedProperties::NewVpn(std::move(vpn));
  1643. break;
  1644. }
  1645. case mojom::NetworkType::kWiFi: {
  1646. auto wifi = mojom::ManagedWiFiProperties::New();
  1647. wifi->security = network_state->GetMojoSecurity();
  1648. const base::Value* wifi_dict =
  1649. GetDictionary(properties, ::onc::network_config::kWiFi);
  1650. if (!wifi_dict) {
  1651. result->type_properties =
  1652. mojom::NetworkTypeManagedProperties::NewWifi(std::move(wifi));
  1653. break;
  1654. }
  1655. wifi->allow_gateway_arp_polling =
  1656. GetManagedBoolean(wifi_dict, ::onc::wifi::kAllowGatewayARPPolling);
  1657. wifi->auto_connect =
  1658. GetManagedBoolean(wifi_dict, ::onc::wifi::kAutoConnect);
  1659. wifi->bssid = GetString(wifi_dict, ::onc::wifi::kBSSID);
  1660. wifi->eap = GetManagedEAPProperties(wifi_dict, ::onc::wifi::kEAP);
  1661. wifi->frequency = GetInt32(wifi_dict, ::onc::wifi::kFrequency);
  1662. wifi->frequency_list =
  1663. GetInt32List(wifi_dict, ::onc::wifi::kFrequencyList);
  1664. wifi->hex_ssid = GetManagedString(wifi_dict, ::onc::wifi::kHexSSID);
  1665. wifi->hidden_ssid =
  1666. GetManagedBoolean(wifi_dict, ::onc::wifi::kHiddenSSID);
  1667. wifi->passphrase = GetManagedString(wifi_dict, ::onc::wifi::kPassphrase);
  1668. wifi->ssid = GetRequiredManagedString(wifi_dict, ::onc::wifi::kSSID);
  1669. CHECK(wifi->ssid);
  1670. wifi->signal_strength = GetInt32(wifi_dict, ::onc::wifi::kSignalStrength);
  1671. wifi->is_syncable = sync_wifi::IsEligibleForSync(
  1672. result->guid, result->connectable,
  1673. wifi->hidden_ssid ? wifi->hidden_ssid->active_value : false,
  1674. wifi->security, result->source,
  1675. /*log_result=*/false);
  1676. wifi->is_configured_by_active_user = GetIsConfiguredByUser(result->guid);
  1677. result->type_properties =
  1678. mojom::NetworkTypeManagedProperties::NewWifi(std::move(wifi));
  1679. break;
  1680. }
  1681. case mojom::NetworkType::kAll:
  1682. case mojom::NetworkType::kMobile:
  1683. case mojom::NetworkType::kWireless:
  1684. NOTREACHED() << "NetworkStateProperties can not be of type: " << type;
  1685. break;
  1686. }
  1687. // Traffic Counter Properties
  1688. auto traffic_counter_properties = mojom::TrafficCounterProperties::New();
  1689. const base::Value* last_reset_time =
  1690. properties->FindKey(::onc::network_config::kTrafficCounterResetTime);
  1691. if (last_reset_time && last_reset_time->is_double()) {
  1692. traffic_counter_properties->last_reset_time =
  1693. base::Time::FromDeltaSinceWindowsEpoch(
  1694. base::Milliseconds(last_reset_time->GetDouble()));
  1695. traffic_counter_properties->friendly_date =
  1696. base::UTF16ToUTF8(base::TimeFormatFriendlyDate(
  1697. traffic_counter_properties->last_reset_time.value()));
  1698. } else {
  1699. traffic_counter_properties->last_reset_time = absl::nullopt;
  1700. traffic_counter_properties->friendly_date = absl::nullopt;
  1701. }
  1702. const base::Value* auto_reset =
  1703. NetworkHandler::IsInitialized()
  1704. ? NetworkHandler::Get()
  1705. ->network_metadata_store()
  1706. ->GetEnableTrafficCountersAutoReset(result->guid)
  1707. : nullptr;
  1708. traffic_counter_properties->auto_reset =
  1709. auto_reset && auto_reset->is_bool() ? auto_reset->GetBool() : false;
  1710. const base::Value* user_specified_reset_day =
  1711. NetworkHandler::IsInitialized()
  1712. ? NetworkHandler::Get()
  1713. ->network_metadata_store()
  1714. ->GetDayOfTrafficCountersAutoReset(result->guid)
  1715. : nullptr;
  1716. traffic_counter_properties->user_specified_reset_day =
  1717. user_specified_reset_day && user_specified_reset_day->is_int()
  1718. ? user_specified_reset_day->GetInt()
  1719. : kDefaultResetDay;
  1720. result->traffic_counter_properties = std::move(traffic_counter_properties);
  1721. return result;
  1722. }
  1723. bool NetworkTypeCanBeDisabled(mojom::NetworkType type) {
  1724. switch (type) {
  1725. case mojom::NetworkType::kCellular:
  1726. case mojom::NetworkType::kTether:
  1727. case mojom::NetworkType::kWiFi:
  1728. return true;
  1729. case mojom::NetworkType::kAll:
  1730. case mojom::NetworkType::kEthernet:
  1731. case mojom::NetworkType::kMobile:
  1732. case mojom::NetworkType::kVPN:
  1733. case mojom::NetworkType::kWireless:
  1734. return false;
  1735. }
  1736. NOTREACHED();
  1737. return false;
  1738. }
  1739. base::Value GetEAPProperties(const mojom::EAPConfigProperties& eap) {
  1740. base::Value eap_dict(base::Value::Type::DICTIONARY);
  1741. SetString(::onc::eap::kAnonymousIdentity, eap.anonymous_identity, &eap_dict);
  1742. SetString(::onc::client_cert::kClientCertPKCS11Id, eap.client_cert_pkcs11_id,
  1743. &eap_dict);
  1744. SetString(::onc::client_cert::kClientCertType, eap.client_cert_type,
  1745. &eap_dict);
  1746. SetStringList(::onc::eap::kDomainSuffixMatch, eap.domain_suffix_match,
  1747. &eap_dict);
  1748. SetString(::onc::eap::kIdentity, eap.identity, &eap_dict);
  1749. SetString(::onc::eap::kInner, eap.inner, &eap_dict);
  1750. SetString(::onc::eap::kOuter, eap.outer, &eap_dict);
  1751. SetString(::onc::eap::kPassword, eap.password, &eap_dict);
  1752. eap_dict.SetBoolKey(::onc::eap::kSaveCredentials, eap.save_credentials);
  1753. SetStringList(::onc::eap::kServerCAPEMs, eap.server_ca_pems, &eap_dict);
  1754. SetSubjectAltNameMatch(::onc::eap::kSubjectAlternativeNameMatch,
  1755. &eap.subject_alt_name_match, &eap_dict);
  1756. SetString(::onc::eap::kSubjectMatch, eap.subject_match, &eap_dict);
  1757. eap_dict.SetBoolKey(::onc::eap::kUseSystemCAs, eap.use_system_cas);
  1758. return eap_dict;
  1759. }
  1760. std::unique_ptr<base::DictionaryValue> GetOncFromConfigProperties(
  1761. const mojom::ConfigProperties* properties,
  1762. absl::optional<std::string> guid) {
  1763. auto onc = std::make_unique<base::DictionaryValue>();
  1764. // Process |properties->network_type| and set |type|. Configurations have only
  1765. // one type dictionary.
  1766. mojom::NetworkType type = mojom::NetworkType::kAll; // Invalid type
  1767. base::Value type_dict(base::Value::Type::DICTIONARY);
  1768. if (properties->guid && !properties->guid->empty()) {
  1769. if (guid && *guid != *properties->guid) {
  1770. NET_LOG(ERROR) << "GUID does not match: " << *guid
  1771. << " != " << *properties->guid;
  1772. return nullptr;
  1773. }
  1774. SetString(::onc::network_config::kGUID, *properties->guid, onc.get());
  1775. }
  1776. if (properties->type_config->is_cellular()) {
  1777. type = mojom::NetworkType::kCellular;
  1778. const mojom::CellularConfigProperties& cellular =
  1779. *properties->type_config->get_cellular();
  1780. if (cellular.apn) {
  1781. const mojom::ApnProperties& apn = *cellular.apn;
  1782. base::Value apn_dict(base::Value::Type::DICTIONARY);
  1783. apn_dict.SetStringKey(::onc::cellular_apn::kAccessPointName,
  1784. apn.access_point_name);
  1785. SetString(::onc::cellular_apn::kAuthentication, apn.authentication,
  1786. &apn_dict);
  1787. SetString(::onc::cellular_apn::kLanguage, apn.language, &apn_dict);
  1788. SetString(::onc::cellular_apn::kLocalizedName, apn.localized_name,
  1789. &apn_dict);
  1790. SetString(::onc::cellular_apn::kName, apn.name, &apn_dict);
  1791. SetString(::onc::cellular_apn::kPassword, apn.password, &apn_dict);
  1792. SetString(::onc::cellular_apn::kUsername, apn.username, &apn_dict);
  1793. SetString(::onc::cellular_apn::kAttach, apn.attach, &apn_dict);
  1794. type_dict.SetKey(::onc::cellular::kAPN, std::move(apn_dict));
  1795. }
  1796. if (cellular.roaming) {
  1797. type_dict.SetKey(::onc::cellular::kAllowRoaming,
  1798. base::Value(cellular.roaming->allow_roaming));
  1799. }
  1800. } else if (properties->type_config->is_ethernet()) {
  1801. type = mojom::NetworkType::kEthernet;
  1802. const mojom::EthernetConfigProperties& ethernet =
  1803. *properties->type_config->get_ethernet();
  1804. SetString(::onc::ethernet::kAuthentication, ethernet.authentication,
  1805. &type_dict);
  1806. if (ethernet.eap) {
  1807. type_dict.SetKey(::onc::ethernet::kEAP,
  1808. GetEAPProperties(*ethernet.eap.get()));
  1809. }
  1810. } else if (properties->type_config->is_vpn()) {
  1811. type = mojom::NetworkType::kVPN;
  1812. const mojom::VPNConfigProperties& vpn = *properties->type_config->get_vpn();
  1813. SetString(::onc::vpn::kHost, vpn.host, &type_dict);
  1814. if (vpn.ip_sec) {
  1815. const mojom::IPSecConfigProperties& ip_sec = *vpn.ip_sec;
  1816. base::Value ip_sec_dict(base::Value::Type::DICTIONARY);
  1817. SetString(::onc::ipsec::kAuthenticationType, ip_sec.authentication_type,
  1818. &ip_sec_dict);
  1819. SetString(::onc::client_cert::kClientCertPKCS11Id,
  1820. ip_sec.client_cert_pkcs11_id, &ip_sec_dict);
  1821. SetString(::onc::client_cert::kClientCertType, ip_sec.client_cert_type,
  1822. &ip_sec_dict);
  1823. SetString(::onc::ipsec::kGroup, ip_sec.group, &ip_sec_dict);
  1824. ip_sec_dict.SetIntKey(::onc::ipsec::kIKEVersion, ip_sec.ike_version);
  1825. SetString(::onc::ipsec::kPSK, ip_sec.psk, &ip_sec_dict);
  1826. ip_sec_dict.SetBoolKey(::onc::l2tp::kSaveCredentials,
  1827. ip_sec.save_credentials);
  1828. SetStringList(::onc::ipsec::kServerCAPEMs, ip_sec.server_ca_pems,
  1829. &ip_sec_dict);
  1830. SetStringList(::onc::ipsec::kServerCARefs, ip_sec.server_ca_refs,
  1831. &ip_sec_dict);
  1832. SetString(::onc::ipsec::kLocalIdentity, ip_sec.local_identity,
  1833. &ip_sec_dict);
  1834. SetString(::onc::ipsec::kRemoteIdentity, ip_sec.remote_identity,
  1835. &ip_sec_dict);
  1836. if (ip_sec.eap) {
  1837. ip_sec_dict.SetKey(::onc::ipsec::kEAP,
  1838. GetEAPProperties(*ip_sec.eap.get()));
  1839. }
  1840. type_dict.SetKey(::onc::vpn::kIPsec, std::move(ip_sec_dict));
  1841. }
  1842. if (vpn.l2tp) {
  1843. const mojom::L2TPConfigProperties& l2tp = *vpn.l2tp;
  1844. base::Value l2tp_dict(base::Value::Type::DICTIONARY);
  1845. l2tp_dict.SetBoolKey(::onc::l2tp::kLcpEchoDisabled,
  1846. l2tp.lcp_echo_disabled);
  1847. SetString(::onc::l2tp::kPassword, l2tp.password, &l2tp_dict);
  1848. l2tp_dict.SetBoolKey(::onc::l2tp::kSaveCredentials,
  1849. l2tp.save_credentials);
  1850. SetString(::onc::l2tp::kUsername, l2tp.username, &l2tp_dict);
  1851. type_dict.SetKey(::onc::vpn::kL2TP, std::move(l2tp_dict));
  1852. }
  1853. if (vpn.open_vpn) {
  1854. const mojom::OpenVPNConfigProperties& open_vpn = *vpn.open_vpn;
  1855. base::Value open_vpn_dict(base::Value::Type::DICTIONARY);
  1856. SetString(::onc::client_cert::kClientCertPKCS11Id,
  1857. open_vpn.client_cert_pkcs11_id, &open_vpn_dict);
  1858. SetString(::onc::client_cert::kClientCertType, open_vpn.client_cert_type,
  1859. &open_vpn_dict);
  1860. SetStringList(::onc::openvpn::kExtraHosts, open_vpn.extra_hosts,
  1861. &open_vpn_dict);
  1862. SetString(::onc::openvpn::kOTP, open_vpn.otp, &open_vpn_dict);
  1863. SetString(::onc::openvpn::kPassword, open_vpn.password, &open_vpn_dict);
  1864. open_vpn_dict.SetBoolKey(::onc::l2tp::kSaveCredentials,
  1865. open_vpn.save_credentials);
  1866. SetStringList(::onc::openvpn::kServerCAPEMs, open_vpn.server_ca_pems,
  1867. &open_vpn_dict);
  1868. SetStringList(::onc::openvpn::kServerCARefs, open_vpn.server_ca_refs,
  1869. &open_vpn_dict);
  1870. SetString(::onc::vpn::kUsername, open_vpn.username, &open_vpn_dict);
  1871. SetString(::onc::openvpn::kUserAuthenticationType,
  1872. open_vpn.user_authentication_type, &open_vpn_dict);
  1873. type_dict.SetKey(::onc::vpn::kOpenVPN, std::move(open_vpn_dict));
  1874. }
  1875. if (vpn.wireguard) {
  1876. const mojom::WireGuardConfigProperties& wireguard = *vpn.wireguard;
  1877. base::Value wireguard_dict(base::Value::Type::DICTIONARY);
  1878. SetString(::onc::wireguard::kPrivateKey, wireguard.private_key,
  1879. &wireguard_dict);
  1880. base::Value peer_list(base::Value::Type::LIST);
  1881. if (wireguard.peers) {
  1882. for (auto const& peer : *wireguard.peers) {
  1883. base::Value peer_dict(base::Value::Type::DICTIONARY);
  1884. peer_dict.SetStringKey(::onc::wireguard::kPublicKey,
  1885. peer->public_key);
  1886. SetString(::onc::wireguard::kPresharedKey, peer->preshared_key,
  1887. &peer_dict);
  1888. SetString(::onc::wireguard::kEndpoint, peer->endpoint, &peer_dict);
  1889. SetString(::onc::wireguard::kAllowedIPs, peer->allowed_ips,
  1890. &peer_dict);
  1891. if (peer->persistent_keepalive_interval) {
  1892. peer_dict.SetStringKey(
  1893. ::onc::wireguard::kPersistentKeepalive,
  1894. base::NumberToString(peer->persistent_keepalive_interval));
  1895. }
  1896. peer_list.Append(std::move(peer_dict));
  1897. }
  1898. }
  1899. wireguard_dict.SetKey(::onc::wireguard::kPeers, std::move(peer_list));
  1900. wireguard_dict.SetBoolKey(::onc::vpn::kSaveCredentials, true);
  1901. type_dict.SetKey(::onc::vpn::kWireGuard, std::move(wireguard_dict));
  1902. }
  1903. if (vpn.type) {
  1904. SetString(::onc::vpn::kType, MojoVpnTypeToOnc(vpn.type->value),
  1905. &type_dict);
  1906. }
  1907. } else if (properties->type_config->is_wifi()) {
  1908. type = mojom::NetworkType::kWiFi;
  1909. const mojom::WiFiConfigProperties& wifi =
  1910. *properties->type_config->get_wifi();
  1911. SetString(::onc::wifi::kPassphrase, wifi.passphrase, &type_dict);
  1912. SetStringIfNotEmpty(::onc::wifi::kSSID, wifi.ssid, &type_dict);
  1913. SetString(::onc::wifi::kPassphrase, wifi.passphrase, &type_dict);
  1914. switch (wifi.hidden_ssid) {
  1915. case mojom::HiddenSsidMode::kDisabled:
  1916. type_dict.SetBoolKey(::onc::wifi::kHiddenSSID, false);
  1917. break;
  1918. case mojom::HiddenSsidMode::kEnabled:
  1919. type_dict.SetBoolKey(::onc::wifi::kHiddenSSID, true);
  1920. break;
  1921. case mojom::HiddenSsidMode::kAutomatic:
  1922. // This is expressed to the platform by leaving off kHiddenSSID.
  1923. break;
  1924. }
  1925. SetString(::onc::wifi::kSecurity, MojoSecurityTypeToOnc(wifi.security),
  1926. &type_dict);
  1927. if (wifi.eap) {
  1928. type_dict.SetKey(::onc::wifi::kEAP, GetEAPProperties(*wifi.eap.get()));
  1929. }
  1930. }
  1931. std::string onc_type = MojoNetworkTypeToOnc(type);
  1932. if (onc_type.empty()) {
  1933. NET_LOG(ERROR) << "Invalid NetworkConfig properties";
  1934. return nullptr;
  1935. }
  1936. SetString(::onc::network_config::kType, onc_type, onc.get());
  1937. // Process other |properties| members. Order matches the mojo struct.
  1938. if (properties->ip_address_config_type) {
  1939. onc->SetStringKey(::onc::network_config::kIPAddressConfigType,
  1940. *properties->ip_address_config_type);
  1941. }
  1942. if (properties->metered) {
  1943. onc->SetBoolKey(::onc::network_config::kMetered,
  1944. properties->metered->value);
  1945. }
  1946. SetString(::onc::network_config::kName, properties->name, onc.get());
  1947. SetString(::onc::network_config::kNameServersConfigType,
  1948. properties->name_servers_config_type, onc.get());
  1949. if (properties->priority) {
  1950. onc->SetIntKey(::onc::network_config::kPriority,
  1951. properties->priority->value);
  1952. }
  1953. if (properties->proxy_settings) {
  1954. const mojom::ProxySettings& proxy = *properties->proxy_settings;
  1955. base::Value proxy_dict(base::Value::Type::DICTIONARY);
  1956. proxy_dict.SetStringKey(::onc::proxy::kType, proxy.type);
  1957. if (proxy.manual) {
  1958. const mojom::ManualProxySettings& manual = *proxy.manual;
  1959. base::Value manual_dict(base::Value::Type::DICTIONARY);
  1960. SetProxyLocation(::onc::proxy::kHttp, manual.http_proxy, &manual_dict);
  1961. SetProxyLocation(::onc::proxy::kHttps, manual.secure_http_proxy,
  1962. &manual_dict);
  1963. SetProxyLocation(::onc::proxy::kFtp, manual.ftp_proxy, &manual_dict);
  1964. SetProxyLocation(::onc::proxy::kSocks, manual.socks, &manual_dict);
  1965. proxy_dict.SetKey(::onc::proxy::kManual, std::move(manual_dict));
  1966. }
  1967. SetStringList(::onc::proxy::kExcludeDomains, proxy.exclude_domains,
  1968. &proxy_dict);
  1969. SetString(::onc::proxy::kPAC, proxy.pac, &proxy_dict);
  1970. onc->SetKey(::onc::network_config::kProxySettings, std::move(proxy_dict));
  1971. }
  1972. if (properties->static_ip_config) {
  1973. const mojom::IPConfigProperties& ip_config = *properties->static_ip_config;
  1974. base::Value ip_config_dict(base::Value::Type::DICTIONARY);
  1975. SetString(::onc::ipconfig::kGateway, ip_config.gateway, &ip_config_dict);
  1976. SetString(::onc::ipconfig::kIPAddress, ip_config.ip_address,
  1977. &ip_config_dict);
  1978. SetStringList(::onc::ipconfig::kNameServers, ip_config.name_servers,
  1979. &ip_config_dict);
  1980. ip_config_dict.SetIntKey(::onc::ipconfig::kRoutingPrefix,
  1981. ip_config.routing_prefix);
  1982. ip_config_dict.SetStringKey(::onc::ipconfig::kType,
  1983. MojoIPConfigTypeToOnc(ip_config.type));
  1984. SetString(::onc::ipconfig::kWebProxyAutoDiscoveryUrl,
  1985. ip_config.web_proxy_auto_discovery_url, &ip_config_dict);
  1986. onc->SetKey(::onc::network_config::kStaticIPConfig,
  1987. std::move(ip_config_dict));
  1988. }
  1989. if (properties->auto_connect) {
  1990. NetworkTypePattern type_pattern = MojoTypeToPattern(type);
  1991. if (type_pattern.Equals(NetworkTypePattern::Cellular()) ||
  1992. type_pattern.Equals(NetworkTypePattern::VPN()) ||
  1993. type_pattern.Equals(NetworkTypePattern::WiFi())) {
  1994. // Note: All type dicts use the same kAutoConnect key.
  1995. type_dict.SetBoolKey(::onc::wifi::kAutoConnect,
  1996. properties->auto_connect->value);
  1997. }
  1998. }
  1999. if (!type_dict.DictEmpty()) {
  2000. onc->SetKey(onc_type, std::move(type_dict));
  2001. }
  2002. return onc;
  2003. }
  2004. mojom::NetworkCertificatePtr GetMojoCert(
  2005. const NetworkCertificateHandler::Certificate& cert,
  2006. mojom::CertificateType type) {
  2007. auto result = mojom::NetworkCertificate::New();
  2008. result->type = type;
  2009. result->hash = cert.hash;
  2010. result->issued_by = cert.issued_by;
  2011. result->issued_to = cert.issued_to;
  2012. result->available_for_network_auth = cert.available_for_network_auth;
  2013. result->device_wide = cert.device_wide;
  2014. if (type == mojom::CertificateType::kServerCA)
  2015. result->pem_or_id = cert.pem;
  2016. if (type == mojom::CertificateType::kUserCert)
  2017. result->pem_or_id = cert.pkcs11_id;
  2018. return result;
  2019. }
  2020. mojom::TrafficCounterSource ConvertToTrafficCounterSourceEnum(
  2021. const std::string& source) {
  2022. if (source == shill::kTrafficCounterSourceUnknown)
  2023. return mojom::TrafficCounterSource::kUnknown;
  2024. if (source == shill::kTrafficCounterSourceChrome)
  2025. return mojom::TrafficCounterSource::kChrome;
  2026. if (source == shill::kTrafficCounterSourceUser)
  2027. return mojom::TrafficCounterSource::kUser;
  2028. if (source == shill::kTrafficCounterSourceArc)
  2029. return mojom::TrafficCounterSource::kArc;
  2030. if (source == shill::kTrafficCounterSourceCrosvm)
  2031. return mojom::TrafficCounterSource::kCrosvm;
  2032. if (source == shill::kTrafficCounterSourcePluginvm)
  2033. return mojom::TrafficCounterSource::kPluginvm;
  2034. if (source == shill::kTrafficCounterSourceUpdateEngine)
  2035. return mojom::TrafficCounterSource::kUpdateEngine;
  2036. if (source == shill::kTrafficCounterSourceVpn)
  2037. return mojom::TrafficCounterSource::kVpn;
  2038. if (source == shill::kTrafficCounterSourceSystem)
  2039. return mojom::TrafficCounterSource::kSystem;
  2040. NOTREACHED() << "Unknown traffic counter source: " << source;
  2041. return mojom::TrafficCounterSource::kUnknown;
  2042. }
  2043. } // namespace
  2044. CrosNetworkConfig::CrosNetworkConfig()
  2045. : CrosNetworkConfig(
  2046. NetworkHandler::Get()->network_state_handler(),
  2047. NetworkHandler::Get()->network_device_handler(),
  2048. NetworkHandler::Get()->cellular_inhibitor(),
  2049. NetworkHandler::Get()->cellular_esim_profile_handler(),
  2050. NetworkHandler::Get()->managed_network_configuration_handler(),
  2051. NetworkHandler::Get()->network_connection_handler(),
  2052. NetworkHandler::Get()->network_certificate_handler(),
  2053. NetworkHandler::Get()->network_profile_handler()) {}
  2054. CrosNetworkConfig::CrosNetworkConfig(
  2055. NetworkStateHandler* network_state_handler,
  2056. NetworkDeviceHandler* network_device_handler,
  2057. CellularInhibitor* cellular_inhibitor,
  2058. CellularESimProfileHandler* cellular_esim_profile_handler,
  2059. ManagedNetworkConfigurationHandler* network_configuration_handler,
  2060. NetworkConnectionHandler* network_connection_handler,
  2061. NetworkCertificateHandler* network_certificate_handler,
  2062. NetworkProfileHandler* network_profile_handler)
  2063. : network_state_handler_(network_state_handler),
  2064. network_device_handler_(network_device_handler),
  2065. cellular_inhibitor_(cellular_inhibitor),
  2066. cellular_esim_profile_handler_(cellular_esim_profile_handler),
  2067. network_configuration_handler_(network_configuration_handler),
  2068. network_connection_handler_(network_connection_handler),
  2069. network_certificate_handler_(network_certificate_handler),
  2070. network_profile_handler_(network_profile_handler) {
  2071. CHECK(network_state_handler);
  2072. }
  2073. CrosNetworkConfig::~CrosNetworkConfig() {
  2074. if (network_state_handler_ && network_state_handler_->HasObserver(this))
  2075. network_state_handler_->RemoveObserver(this, FROM_HERE);
  2076. if (network_certificate_handler_ &&
  2077. network_certificate_handler_->HasObserver(this)) {
  2078. network_certificate_handler_->RemoveObserver(this);
  2079. }
  2080. if (cellular_inhibitor_ && cellular_inhibitor_->HasObserver(this))
  2081. cellular_inhibitor_->RemoveObserver(this);
  2082. if (network_configuration_handler_ &&
  2083. network_configuration_handler_->HasObserver(this)) {
  2084. network_configuration_handler_->RemoveObserver(this);
  2085. }
  2086. }
  2087. void CrosNetworkConfig::BindReceiver(
  2088. mojo::PendingReceiver<mojom::CrosNetworkConfig> receiver) {
  2089. NET_LOG(EVENT) << "CrosNetworkConfig::BindReceiver()";
  2090. receivers_.Add(this, std::move(receiver));
  2091. }
  2092. void CrosNetworkConfig::AddObserver(
  2093. mojo::PendingRemote<mojom::CrosNetworkConfigObserver> observer) {
  2094. if (!network_state_handler_->HasObserver(this))
  2095. network_state_handler_->AddObserver(this, FROM_HERE);
  2096. if (network_certificate_handler_ &&
  2097. !network_certificate_handler_->HasObserver(this)) {
  2098. network_certificate_handler_->AddObserver(this);
  2099. }
  2100. if (cellular_inhibitor_ && !cellular_inhibitor_->HasObserver(this))
  2101. cellular_inhibitor_->AddObserver(this);
  2102. if (network_configuration_handler_ &&
  2103. !network_configuration_handler_->HasObserver(this)) {
  2104. network_configuration_handler_->AddObserver(this);
  2105. }
  2106. observers_.Add(std::move(observer));
  2107. }
  2108. void CrosNetworkConfig::GetNetworkState(const std::string& guid,
  2109. GetNetworkStateCallback callback) {
  2110. const NetworkState* network =
  2111. network_state_handler_->GetNetworkStateFromGuid(guid);
  2112. if (!network) {
  2113. NET_LOG(ERROR) << "Network not found: " << guid;
  2114. std::move(callback).Run(nullptr);
  2115. return;
  2116. }
  2117. if (network->type() == shill::kTypeEthernetEap) {
  2118. NET_LOG(ERROR) << "EthernetEap not supported for GetNetworkState";
  2119. std::move(callback).Run(nullptr);
  2120. return;
  2121. }
  2122. std::move(callback).Run(NetworkStateToMojo(network_state_handler_,
  2123. cellular_esim_profile_handler_,
  2124. vpn_providers_, network));
  2125. }
  2126. void CrosNetworkConfig::GetNetworkStateList(
  2127. mojom::NetworkFilterPtr filter,
  2128. GetNetworkStateListCallback callback) {
  2129. NetworkStateHandler::NetworkStateList networks;
  2130. NetworkTypePattern pattern = MojoTypeToPattern(filter->network_type);
  2131. switch (filter->filter) {
  2132. case mojom::FilterType::kActive:
  2133. network_state_handler_->GetActiveNetworkListByType(pattern, &networks);
  2134. if (filter->limit > 0 &&
  2135. static_cast<int>(networks.size()) > filter->limit)
  2136. networks.resize(filter->limit);
  2137. break;
  2138. case mojom::FilterType::kVisible:
  2139. network_state_handler_->GetNetworkListByType(
  2140. pattern, /*configured_only=*/false, /*visible_only=*/true,
  2141. filter->limit, &networks);
  2142. break;
  2143. case mojom::FilterType::kConfigured:
  2144. network_state_handler_->GetNetworkListByType(
  2145. pattern, /*configured_only=*/true, /*visible_only=*/false,
  2146. filter->limit, &networks);
  2147. break;
  2148. case mojom::FilterType::kAll:
  2149. network_state_handler_->GetNetworkListByType(
  2150. pattern, /*configured_only=*/false, /*visible_only=*/false,
  2151. filter->limit, &networks);
  2152. break;
  2153. }
  2154. std::vector<mojom::NetworkStatePropertiesPtr> result;
  2155. for (const NetworkState* network : networks) {
  2156. if (network->type() == shill::kTypeEthernetEap) {
  2157. // EthernetEap is used by Shill to store EAP properties and does not
  2158. // represent a separate network service.
  2159. continue;
  2160. }
  2161. mojom::NetworkStatePropertiesPtr mojo_network = NetworkStateToMojo(
  2162. network_state_handler_, cellular_esim_profile_handler_, vpn_providers_,
  2163. network);
  2164. if (mojo_network)
  2165. result.emplace_back(std::move(mojo_network));
  2166. }
  2167. std::move(callback).Run(std::move(result));
  2168. }
  2169. void CrosNetworkConfig::GetDeviceStateList(
  2170. GetDeviceStateListCallback callback) {
  2171. NetworkStateHandler::DeviceStateList devices;
  2172. network_state_handler_->GetDeviceList(&devices);
  2173. std::vector<mojom::DeviceStatePropertiesPtr> result;
  2174. for (const DeviceState* device : devices) {
  2175. mojom::DeviceStateType technology_state =
  2176. GetMojoDeviceStateType(network_state_handler_->GetTechnologyState(
  2177. NetworkTypePattern::Primitive(device->type())));
  2178. if (technology_state == mojom::DeviceStateType::kUnavailable) {
  2179. NET_LOG(ERROR) << "Device state unavailable: " << device->name();
  2180. continue;
  2181. }
  2182. mojom::DeviceStatePropertiesPtr mojo_device = DeviceStateToMojo(
  2183. device, network_state_handler_, cellular_inhibitor_, technology_state);
  2184. if (mojo_device)
  2185. result.emplace_back(std::move(mojo_device));
  2186. }
  2187. // Handle VPN state separately because VPN is not considered a device by shill
  2188. // and thus will not be included in the |devices| list returned by network
  2189. // state handler. In the UI code, it is treated as a "device" for consistency.
  2190. // In the UI code, knowing whether a device is prohibited or not is done by
  2191. // checking |device_state| field of the DeviceStateProperties of the
  2192. // corresponding device. A VPN device state is returned if built-in VPN
  2193. // services are prohibited by policy even if no VPN services exist in order to
  2194. // indicate that adding a VPN is prohibited in the UI.
  2195. if (network_state_handler_->FirstNetworkByType(NetworkTypePattern::VPN()) ||
  2196. IsVpnProhibited()) {
  2197. result.emplace_back(GetVpnState());
  2198. }
  2199. std::move(callback).Run(std::move(result));
  2200. }
  2201. void CrosNetworkConfig::GetManagedProperties(
  2202. const std::string& guid,
  2203. GetManagedPropertiesCallback callback) {
  2204. if (!network_configuration_handler_) {
  2205. NET_LOG(ERROR) << "GetManagedProperties called with no handler";
  2206. std::move(callback).Run(nullptr);
  2207. return;
  2208. }
  2209. const NetworkState* network =
  2210. network_state_handler_->GetNetworkStateFromGuid(guid);
  2211. if (!network) {
  2212. NET_LOG(ERROR) << "Network not found: " << guid;
  2213. std::move(callback).Run(nullptr);
  2214. return;
  2215. }
  2216. network_configuration_handler_->GetManagedProperties(
  2217. chromeos::LoginState::Get()->primary_user_hash(), network->path(),
  2218. base::BindOnce(&CrosNetworkConfig::OnGetManagedProperties,
  2219. weak_factory_.GetWeakPtr(), std::move(callback), guid));
  2220. }
  2221. void CrosNetworkConfig::OnGetManagedProperties(
  2222. GetManagedPropertiesCallback callback,
  2223. std::string guid,
  2224. const std::string& service_path,
  2225. absl::optional<base::Value> properties,
  2226. absl::optional<std::string> error) {
  2227. if (!properties) {
  2228. NET_LOG(ERROR) << "GetManagedProperties failed for: " << guid
  2229. << " Error: " << error.value_or("Failed");
  2230. std::move(callback).Run(nullptr);
  2231. return;
  2232. }
  2233. const NetworkState* network_state =
  2234. network_state_handler_->GetNetworkState(service_path);
  2235. if (!network_state) {
  2236. NET_LOG(ERROR) << "Network not found: " << service_path;
  2237. std::move(callback).Run(nullptr);
  2238. return;
  2239. }
  2240. mojom::ManagedPropertiesPtr managed_properties = ManagedPropertiesToMojo(
  2241. network_state_handler_, cellular_esim_profile_handler_, network_state,
  2242. vpn_providers_, &properties.value());
  2243. if (managed_properties->type == mojom::NetworkType::kCellular) {
  2244. std::vector<mojom::ApnPropertiesPtr> custom_apn_list =
  2245. GetCustomAPNList(guid);
  2246. if (!custom_apn_list.empty()) {
  2247. managed_properties->type_properties->get_cellular()->custom_apn_list =
  2248. std::move(custom_apn_list);
  2249. }
  2250. }
  2251. // For Ethernet networks with no authentication, check for a separate
  2252. // EthernetEAP configuration.
  2253. const NetworkState* eap_state = nullptr;
  2254. if (managed_properties->type == mojom::NetworkType::kEthernet) {
  2255. mojom::ManagedEthernetPropertiesPtr& ethernet =
  2256. managed_properties->type_properties->get_ethernet();
  2257. if (!ethernet->authentication || ethernet->authentication->active_value ==
  2258. ::onc::ethernet::kAuthenticationNone) {
  2259. eap_state = network_state_handler_->GetEAPForEthernet(
  2260. network_state->path(), /*connected_only=*/false);
  2261. }
  2262. }
  2263. if (!eap_state) {
  2264. // No EAP properties, return the managed properties as-is.
  2265. std::move(callback).Run(std::move(managed_properties));
  2266. return;
  2267. }
  2268. // Request the EAP state. On success the EAP state will be applied to
  2269. // |managed_properties| and returned. On failure |managed_properties| will
  2270. // be returned as-is.
  2271. NET_LOG(DEBUG) << "Requesting EAP state for: " + service_path
  2272. << " from: " << eap_state->path();
  2273. network_configuration_handler_->GetManagedProperties(
  2274. chromeos::LoginState::Get()->primary_user_hash(), eap_state->path(),
  2275. base::BindOnce(&CrosNetworkConfig::OnGetManagedPropertiesEap,
  2276. weak_factory_.GetWeakPtr(), std::move(callback),
  2277. std::move(managed_properties)));
  2278. }
  2279. void CrosNetworkConfig::OnGetManagedPropertiesEap(
  2280. GetManagedPropertiesCallback callback,
  2281. mojom::ManagedPropertiesPtr managed_properties,
  2282. const std::string& service_path,
  2283. absl::optional<base::Value> eap_properties,
  2284. absl::optional<std::string> error) {
  2285. if (eap_properties) {
  2286. // Copy the EAP properties to |managed_properties| before sending.
  2287. const base::Value* ethernet_dict =
  2288. eap_properties->FindDictKey(::onc::network_config::kEthernet);
  2289. if (ethernet_dict) {
  2290. auto ethernet = mojom::ManagedEthernetProperties::New();
  2291. ethernet->authentication =
  2292. GetManagedString(ethernet_dict, ::onc::ethernet::kAuthentication);
  2293. ethernet->eap =
  2294. GetManagedEAPProperties(ethernet_dict, ::onc::ethernet::kEAP);
  2295. managed_properties->type_properties =
  2296. mojom::NetworkTypeManagedProperties::NewEthernet(std::move(ethernet));
  2297. }
  2298. }
  2299. std::move(callback).Run(std::move(managed_properties));
  2300. }
  2301. void CrosNetworkConfig::SetProperties(const std::string& guid,
  2302. mojom::ConfigPropertiesPtr properties,
  2303. SetPropertiesCallback callback) {
  2304. if (!network_configuration_handler_) {
  2305. NET_LOG(ERROR) << "SetProperties called with no handler";
  2306. std::move(callback).Run(false, kErrorNotReady);
  2307. return;
  2308. }
  2309. const NetworkState* network =
  2310. network_state_handler_->GetNetworkStateFromGuid(guid);
  2311. if (!network || network->profile_path().empty()) {
  2312. NET_LOG(ERROR) << "SetProperties called with unconfigured network: "
  2313. << guid;
  2314. std::move(callback).Run(false, kErrorNetworkUnavailable);
  2315. return;
  2316. }
  2317. // If EthernetEAP properties exist, and properties.ethernet.eap is provided,
  2318. // apply the configuration to the EthernetEAP service. Currently we only
  2319. // support configuration of EAP properties or other properties (e.g IP
  2320. // Config), not both.
  2321. if (network->type() == shill::kTypeEthernet &&
  2322. properties->type_config->is_ethernet() &&
  2323. properties->type_config->get_ethernet()->eap) {
  2324. const NetworkState* eap_state = network_state_handler_->GetEAPForEthernet(
  2325. network->path(), /*connected_only=*/false);
  2326. if (!eap_state) {
  2327. NET_LOG(ERROR)
  2328. << "SetProperties called with ethernet.eap but no EAP config: "
  2329. << guid;
  2330. std::move(callback).Run(false, kErrorNetworkUnavailable);
  2331. return;
  2332. }
  2333. network = eap_state;
  2334. }
  2335. if (network->type() == shill::kTypeCellular &&
  2336. properties->type_config->is_cellular()) {
  2337. UpdateCustomAPNList(network, properties.get());
  2338. }
  2339. std::unique_ptr<base::DictionaryValue> onc =
  2340. GetOncFromConfigProperties(properties.get(), guid);
  2341. if (!onc) {
  2342. NET_LOG(ERROR) << "Bad ONC Configuration for " << guid;
  2343. std::move(callback).Run(false, kErrorInvalidONCConfiguration);
  2344. return;
  2345. }
  2346. NET_LOG(DEBUG) << "Configuring properties for " << guid << ": " << *onc;
  2347. int callback_id = callback_id_++;
  2348. set_properties_callbacks_[callback_id] = std::move(callback);
  2349. // If the profile path is empty the network is not saved, so we need to call
  2350. // CreateConfiguration(). This can happen for EthernetEAP where a default
  2351. // service is generated by Shill but may not be saved.
  2352. if (network->profile_path().empty()) {
  2353. NET_LOG(USER) << "Configuring properties for " << guid
  2354. << " (no profile entry set)";
  2355. std::string user_id_hash = LoginState::Get()->primary_user_hash();
  2356. network_configuration_handler_->CreateConfiguration(
  2357. user_id_hash, *onc,
  2358. base::BindOnce(&CrosNetworkConfig::SetPropertiesConfigureSuccess,
  2359. weak_factory_.GetWeakPtr(), callback_id),
  2360. base::BindOnce(&CrosNetworkConfig::SetPropertiesFailure,
  2361. weak_factory_.GetWeakPtr(), guid, callback_id));
  2362. return;
  2363. }
  2364. network_configuration_handler_->SetProperties(
  2365. network->path(), *onc,
  2366. base::BindOnce(&CrosNetworkConfig::SetPropertiesSuccess,
  2367. weak_factory_.GetWeakPtr(), callback_id),
  2368. base::BindOnce(&CrosNetworkConfig::SetPropertiesFailure,
  2369. weak_factory_.GetWeakPtr(), guid, callback_id));
  2370. }
  2371. void CrosNetworkConfig::SetPropertiesSuccess(int callback_id) {
  2372. auto iter = set_properties_callbacks_.find(callback_id);
  2373. DCHECK(iter != set_properties_callbacks_.end());
  2374. std::move(iter->second).Run(/*success=*/true, /*message=*/"");
  2375. set_properties_callbacks_.erase(iter);
  2376. }
  2377. void CrosNetworkConfig::SetPropertiesConfigureSuccess(
  2378. int callback_id,
  2379. const std::string& service_path,
  2380. const std::string& guid) {
  2381. auto iter = set_properties_callbacks_.find(callback_id);
  2382. DCHECK(iter != set_properties_callbacks_.end());
  2383. std::move(iter->second).Run(/*success=*/true, /*message=*/"");
  2384. set_properties_callbacks_.erase(iter);
  2385. }
  2386. void CrosNetworkConfig::SetPropertiesFailure(const std::string& guid,
  2387. int callback_id,
  2388. const std::string& error_name) {
  2389. auto iter = set_properties_callbacks_.find(callback_id);
  2390. DCHECK(iter != set_properties_callbacks_.end());
  2391. NET_LOG(ERROR) << "Failed to set network properties: " << guid
  2392. << " Error: " << error_name;
  2393. std::move(iter->second).Run(/*success=*/false, error_name);
  2394. set_properties_callbacks_.erase(iter);
  2395. }
  2396. void CrosNetworkConfig::ConfigureNetwork(mojom::ConfigPropertiesPtr properties,
  2397. bool shared,
  2398. ConfigureNetworkCallback callback) {
  2399. if (!network_configuration_handler_) {
  2400. NET_LOG(ERROR) << "Configure called with no handler";
  2401. std::move(callback).Run(/*guid=*/absl::nullopt, kErrorNotReady);
  2402. return;
  2403. }
  2404. if (!shared && UserManager::Get()->GetPrimaryUser() !=
  2405. UserManager::Get()->GetActiveUser()) {
  2406. NET_LOG(ERROR)
  2407. << "Attempt to set unshared configuration from non primary user";
  2408. std::move(callback).Run(/*guid=*/absl::nullopt, kErrorAccessToSharedConfig);
  2409. return;
  2410. }
  2411. std::unique_ptr<base::DictionaryValue> onc =
  2412. GetOncFromConfigProperties(properties.get(), /*guid=*/absl::nullopt);
  2413. if (!onc) {
  2414. std::move(callback).Run(/*guid=*/absl::nullopt,
  2415. kErrorInvalidONCConfiguration);
  2416. return;
  2417. }
  2418. std::string user_id_hash =
  2419. shared ? "" : LoginState::Get()->primary_user_hash();
  2420. int callback_id = callback_id_++;
  2421. configure_network_callbacks_[callback_id] = std::move(callback);
  2422. network_configuration_handler_->CreateConfiguration(
  2423. user_id_hash, *onc,
  2424. base::BindOnce(&CrosNetworkConfig::ConfigureNetworkSuccess,
  2425. weak_factory_.GetWeakPtr(), callback_id),
  2426. base::BindOnce(&CrosNetworkConfig::ConfigureNetworkFailure,
  2427. weak_factory_.GetWeakPtr(), callback_id));
  2428. }
  2429. void CrosNetworkConfig::ConfigureNetworkSuccess(int callback_id,
  2430. const std::string& service_path,
  2431. const std::string& guid) {
  2432. auto iter = configure_network_callbacks_.find(callback_id);
  2433. DCHECK(iter != configure_network_callbacks_.end());
  2434. std::move(iter->second).Run(guid, /*message=*/"");
  2435. configure_network_callbacks_.erase(iter);
  2436. }
  2437. void CrosNetworkConfig::ConfigureNetworkFailure(int callback_id,
  2438. const std::string& error_name) {
  2439. auto iter = configure_network_callbacks_.find(callback_id);
  2440. DCHECK(iter != configure_network_callbacks_.end());
  2441. DCHECK(iter->second);
  2442. NET_LOG(ERROR) << "Failed to configure network. Error: " << error_name;
  2443. std::move(iter->second).Run(/*guid=*/absl::nullopt, error_name);
  2444. configure_network_callbacks_.erase(iter);
  2445. }
  2446. void CrosNetworkConfig::ForgetNetwork(const std::string& guid,
  2447. ForgetNetworkCallback callback) {
  2448. if (!network_configuration_handler_) {
  2449. NET_LOG(ERROR) << "ForgetNetwork called with no handler";
  2450. std::move(callback).Run(false);
  2451. return;
  2452. }
  2453. const NetworkState* network =
  2454. network_state_handler_->GetNetworkStateFromGuid(guid);
  2455. if (!network || network->profile_path().empty()) {
  2456. NET_LOG(ERROR) << "ForgetNetwork called with unconfigured network: "
  2457. << guid;
  2458. std::move(callback).Run(false);
  2459. return;
  2460. }
  2461. bool allow_forget_shared_config = true;
  2462. ::onc::ONCSource onc_source = ::onc::ONC_SOURCE_UNKNOWN;
  2463. std::string user_id_hash = LoginState::Get()->primary_user_hash();
  2464. if (network_configuration_handler_->FindPolicyByGUID(user_id_hash, guid,
  2465. &onc_source)) {
  2466. if (onc_source == ::onc::ONC_SOURCE_USER_POLICY) {
  2467. // Prevent a policy controlled configuration removal.
  2468. std::move(callback).Run(false);
  2469. return;
  2470. }
  2471. if (onc_source == ::onc::ONC_SOURCE_DEVICE_POLICY)
  2472. allow_forget_shared_config = false;
  2473. }
  2474. int callback_id = callback_id_++;
  2475. forget_network_callbacks_[callback_id] = std::move(callback);
  2476. if (allow_forget_shared_config) {
  2477. network_configuration_handler_->RemoveConfiguration(
  2478. network->path(),
  2479. base::BindOnce(&CrosNetworkConfig::ForgetNetworkSuccess,
  2480. weak_factory_.GetWeakPtr(), callback_id),
  2481. base::BindOnce(&CrosNetworkConfig::ForgetNetworkFailure,
  2482. weak_factory_.GetWeakPtr(), guid, callback_id));
  2483. } else {
  2484. network_configuration_handler_->RemoveConfigurationFromCurrentProfile(
  2485. network->path(),
  2486. base::BindOnce(&CrosNetworkConfig::ForgetNetworkSuccess,
  2487. weak_factory_.GetWeakPtr(), callback_id),
  2488. base::BindOnce(&CrosNetworkConfig::ForgetNetworkFailure,
  2489. weak_factory_.GetWeakPtr(), guid, callback_id));
  2490. }
  2491. }
  2492. void CrosNetworkConfig::ForgetNetworkSuccess(int callback_id) {
  2493. auto iter = forget_network_callbacks_.find(callback_id);
  2494. DCHECK(iter != forget_network_callbacks_.end());
  2495. std::move(iter->second).Run(/*success=*/true);
  2496. forget_network_callbacks_.erase(iter);
  2497. }
  2498. void CrosNetworkConfig::ForgetNetworkFailure(const std::string& guid,
  2499. int callback_id,
  2500. const std::string& error_name) {
  2501. auto iter = forget_network_callbacks_.find(callback_id);
  2502. DCHECK(iter != forget_network_callbacks_.end());
  2503. NET_LOG(ERROR) << "Failed to forget network: " << guid
  2504. << " Error: " << error_name;
  2505. std::move(iter->second).Run(/*success=*/false);
  2506. forget_network_callbacks_.erase(iter);
  2507. }
  2508. void CrosNetworkConfig::SetNetworkTypeEnabledState(
  2509. mojom::NetworkType type,
  2510. bool enabled,
  2511. SetNetworkTypeEnabledStateCallback callback) {
  2512. if (!NetworkTypeCanBeDisabled(type)) {
  2513. std::move(callback).Run(false);
  2514. return;
  2515. }
  2516. NetworkTypePattern pattern = MojoTypeToPattern(type);
  2517. if (!network_state_handler_->IsTechnologyAvailable(pattern)) {
  2518. NET_LOG(ERROR) << "Technology unavailable: " << type;
  2519. std::move(callback).Run(false);
  2520. return;
  2521. }
  2522. if (network_state_handler_->IsTechnologyProhibited(pattern)) {
  2523. NET_LOG(ERROR) << "Technology prohibited: " << type;
  2524. std::move(callback).Run(false);
  2525. return;
  2526. }
  2527. NET_LOG(USER) << __func__ << " " << type << ":" << enabled;
  2528. // Set the technology enabled state and return true. The call to Shill does
  2529. // not have a 'success' callback (and errors are already logged).
  2530. network_state_handler_->SetTechnologyEnabled(
  2531. pattern, enabled, chromeos::network_handler::ErrorCallback());
  2532. std::move(callback).Run(true);
  2533. }
  2534. void CrosNetworkConfig::SetCellularSimState(
  2535. mojom::CellularSimStatePtr sim_state,
  2536. SetCellularSimStateCallback callback) {
  2537. const DeviceState* device_state =
  2538. network_state_handler_->GetDeviceStateByType(
  2539. NetworkTypePattern::Cellular());
  2540. if (!device_state || device_state->IsSimAbsent()) {
  2541. std::move(callback).Run(false);
  2542. return;
  2543. }
  2544. const std::string& lock_type = device_state->sim_lock_type();
  2545. // When unblocking a PUK locked SIM, a new PIN must be provided.
  2546. if (lock_type == shill::kSIMLockPuk && !sim_state->new_pin) {
  2547. NET_LOG(ERROR) << "SetCellularSimState: PUK locked and no pin provided.";
  2548. std::move(callback).Run(false);
  2549. return;
  2550. }
  2551. int callback_id = callback_id_++;
  2552. set_cellular_sim_state_callbacks_[callback_id] = std::move(callback);
  2553. if (lock_type == shill::kSIMLockPuk) {
  2554. // Unblock a PUK locked SIM.
  2555. network_device_handler_->UnblockPin(
  2556. device_state->path(), sim_state->current_pin_or_puk,
  2557. *sim_state->new_pin,
  2558. base::BindOnce(&CrosNetworkConfig::SetCellularSimStateSuccess,
  2559. weak_factory_.GetWeakPtr(), callback_id),
  2560. base::BindOnce(&CrosNetworkConfig::SetCellularSimStateFailure,
  2561. weak_factory_.GetWeakPtr(), callback_id));
  2562. return;
  2563. }
  2564. if (lock_type == shill::kSIMLockPin) {
  2565. // Unlock locked SIM.
  2566. network_device_handler_->EnterPin(
  2567. device_state->path(), sim_state->current_pin_or_puk,
  2568. base::BindOnce(&CrosNetworkConfig::SetCellularSimStateSuccess,
  2569. weak_factory_.GetWeakPtr(), callback_id),
  2570. base::BindOnce(&CrosNetworkConfig::SetCellularSimStateFailure,
  2571. weak_factory_.GetWeakPtr(), callback_id));
  2572. return;
  2573. }
  2574. if (sim_state->new_pin) {
  2575. // Change the SIM PIN.
  2576. network_device_handler_->ChangePin(
  2577. device_state->path(), sim_state->current_pin_or_puk,
  2578. *sim_state->new_pin,
  2579. base::BindOnce(&CrosNetworkConfig::SetCellularSimStateSuccess,
  2580. weak_factory_.GetWeakPtr(), callback_id),
  2581. base::BindOnce(&CrosNetworkConfig::SetCellularSimStateFailure,
  2582. weak_factory_.GetWeakPtr(), callback_id));
  2583. return;
  2584. }
  2585. // Enable or disable SIM locking.
  2586. network_device_handler_->RequirePin(
  2587. device_state->path(), sim_state->require_pin,
  2588. sim_state->current_pin_or_puk,
  2589. base::BindOnce(&CrosNetworkConfig::SetCellularSimStateSuccess,
  2590. weak_factory_.GetWeakPtr(), callback_id),
  2591. base::BindOnce(&CrosNetworkConfig::SetCellularSimStateFailure,
  2592. weak_factory_.GetWeakPtr(), callback_id));
  2593. }
  2594. void CrosNetworkConfig::SetCellularSimStateSuccess(int callback_id) {
  2595. auto iter = set_cellular_sim_state_callbacks_.find(callback_id);
  2596. DCHECK(iter != set_cellular_sim_state_callbacks_.end());
  2597. std::move(iter->second).Run(true);
  2598. set_cellular_sim_state_callbacks_.erase(iter);
  2599. }
  2600. void CrosNetworkConfig::SetCellularSimStateFailure(
  2601. int callback_id,
  2602. const std::string& error_name) {
  2603. auto iter = set_cellular_sim_state_callbacks_.find(callback_id);
  2604. DCHECK(iter != set_cellular_sim_state_callbacks_.end());
  2605. std::move(iter->second).Run(false);
  2606. set_cellular_sim_state_callbacks_.erase(iter);
  2607. }
  2608. void CrosNetworkConfig::SelectCellularMobileNetwork(
  2609. const std::string& guid,
  2610. const std::string& network_id,
  2611. SelectCellularMobileNetworkCallback callback) {
  2612. const DeviceState* device_state = nullptr;
  2613. const NetworkState* network_state =
  2614. network_state_handler_->GetNetworkStateFromGuid(guid);
  2615. if (network_state) {
  2616. device_state =
  2617. network_state_handler_->GetDeviceState(network_state->device_path());
  2618. }
  2619. if (!device_state) {
  2620. std::move(callback).Run(false);
  2621. return;
  2622. }
  2623. int callback_id = callback_id_++;
  2624. select_cellular_mobile_network_callbacks_[callback_id] = std::move(callback);
  2625. network_device_handler_->RegisterCellularNetwork(
  2626. device_state->path(), network_id,
  2627. base::BindOnce(&CrosNetworkConfig::SelectCellularMobileNetworkSuccess,
  2628. weak_factory_.GetWeakPtr(), callback_id),
  2629. base::BindOnce(&CrosNetworkConfig::SelectCellularMobileNetworkFailure,
  2630. weak_factory_.GetWeakPtr(), callback_id));
  2631. }
  2632. void CrosNetworkConfig::SelectCellularMobileNetworkSuccess(int callback_id) {
  2633. auto iter = select_cellular_mobile_network_callbacks_.find(callback_id);
  2634. DCHECK(iter != select_cellular_mobile_network_callbacks_.end());
  2635. std::move(iter->second).Run(true);
  2636. select_cellular_mobile_network_callbacks_.erase(iter);
  2637. }
  2638. void CrosNetworkConfig::SelectCellularMobileNetworkFailure(
  2639. int callback_id,
  2640. const std::string& error_name) {
  2641. auto iter = select_cellular_mobile_network_callbacks_.find(callback_id);
  2642. DCHECK(iter != select_cellular_mobile_network_callbacks_.end());
  2643. std::move(iter->second).Run(false);
  2644. select_cellular_mobile_network_callbacks_.erase(iter);
  2645. }
  2646. void CrosNetworkConfig::UpdateCustomAPNList(
  2647. const NetworkState* network,
  2648. const mojom::ConfigProperties* properties) {
  2649. const mojom::CellularConfigProperties& cellular_config =
  2650. *properties->type_config->get_cellular();
  2651. if (!cellular_config.apn) {
  2652. return;
  2653. }
  2654. const DeviceState* device =
  2655. network_state_handler_->GetDeviceState(network->device_path());
  2656. if (!device) {
  2657. // Unexpected, but see note in NetworkStateToMojo.
  2658. NET_LOG(DEBUG) << "Cellular device is not available for APN list: "
  2659. << network->device_path();
  2660. return;
  2661. }
  2662. // Do not update custom APN list if APN is in device APN list.
  2663. if (device->HasAPN(cellular_config.apn->access_point_name)) {
  2664. return;
  2665. }
  2666. base::Value custom_apn(base::Value::Type::DICTIONARY);
  2667. custom_apn.SetStringKey(::onc::cellular_apn::kAccessPointName,
  2668. cellular_config.apn->access_point_name);
  2669. SetString(::onc::cellular_apn::kName, cellular_config.apn->name, &custom_apn);
  2670. SetString(::onc::cellular_apn::kUsername, cellular_config.apn->username,
  2671. &custom_apn);
  2672. SetString(::onc::cellular_apn::kPassword, cellular_config.apn->password,
  2673. &custom_apn);
  2674. SetString(::onc::cellular_apn::kAuthentication,
  2675. cellular_config.apn->authentication, &custom_apn);
  2676. SetString(::onc::cellular_apn::kLocalizedName,
  2677. cellular_config.apn->localized_name, &custom_apn);
  2678. SetString(::onc::cellular_apn::kLanguage, cellular_config.apn->language,
  2679. &custom_apn);
  2680. SetString(::onc::cellular_apn::kAttach, cellular_config.apn->attach,
  2681. &custom_apn);
  2682. // The UI currently only supports setting a single custom apn.
  2683. base::Value custom_apn_list(base::Value::Type::LIST);
  2684. custom_apn_list.Append(std::move(custom_apn));
  2685. NET_LOG(DEBUG) << "Saving Custom APN entry for " << network->guid();
  2686. NetworkMetadataStore* network_metadata_store =
  2687. NetworkHandler::Get()->network_metadata_store();
  2688. network_metadata_store->SetCustomAPNList(network->guid(),
  2689. std::move(custom_apn_list));
  2690. }
  2691. std::vector<mojom::ApnPropertiesPtr> CrosNetworkConfig::GetCustomAPNList(
  2692. const std::string& guid) {
  2693. NetworkMetadataStore* network_metadata_store =
  2694. NetworkHandler::Get()->network_metadata_store();
  2695. std::vector<mojom::ApnPropertiesPtr> mojo_custom_apns;
  2696. const base::Value* custom_apn_list =
  2697. network_metadata_store->GetCustomAPNList(guid);
  2698. if (!custom_apn_list) {
  2699. return mojo_custom_apns;
  2700. }
  2701. DCHECK(custom_apn_list->is_list());
  2702. for (const auto& apn : custom_apn_list->GetListDeprecated()) {
  2703. DCHECK(apn.is_dict());
  2704. mojom::ApnPropertiesPtr mojo_apn = mojom::ApnProperties::New();
  2705. mojo_apn->access_point_name =
  2706. GetRequiredString(&apn, ::onc::cellular_apn::kAccessPointName);
  2707. mojo_apn->name = GetString(&apn, ::onc::cellular_apn::kName);
  2708. mojo_apn->username = GetString(&apn, ::onc::cellular_apn::kUsername);
  2709. mojo_apn->password = GetString(&apn, ::onc::cellular_apn::kPassword);
  2710. mojo_apn->authentication =
  2711. GetString(&apn, ::onc::cellular_apn::kAuthentication);
  2712. mojo_apn->localized_name =
  2713. GetString(&apn, ::onc::cellular_apn::kLocalizedName);
  2714. mojo_apn->language = GetString(&apn, ::onc::cellular_apn::kLanguage);
  2715. mojo_apn->attach = GetString(&apn, ::onc::cellular_apn::kAttach);
  2716. mojo_custom_apns.push_back(std::move(mojo_apn));
  2717. }
  2718. return mojo_custom_apns;
  2719. }
  2720. void CrosNetworkConfig::RequestNetworkScan(mojom::NetworkType type) {
  2721. network_state_handler_->RequestScan(MojoTypeToPattern(type));
  2722. }
  2723. void CrosNetworkConfig::GetGlobalPolicy(GetGlobalPolicyCallback callback) {
  2724. auto result = mojom::GlobalPolicy::New();
  2725. // Network configuration handler can be nullptr in tests.
  2726. if (!network_configuration_handler_) {
  2727. std::move(callback).Run(std::move(result));
  2728. return;
  2729. }
  2730. // Global network configuration policy values come from the device policy.
  2731. const base::Value* global_policy_dict =
  2732. network_configuration_handler_->GetGlobalConfigFromPolicy(
  2733. /*userhash=*/std::string());
  2734. if (!global_policy_dict) {
  2735. std::move(callback).Run(std::move(result));
  2736. return;
  2737. }
  2738. result->allow_cellular_sim_lock = GetBoolean(
  2739. global_policy_dict, ::onc::global_network_config::kAllowCellularSimLock);
  2740. result->allow_only_policy_cellular_networks = GetBoolean(
  2741. global_policy_dict,
  2742. ::onc::global_network_config::kAllowOnlyPolicyCellularNetworks);
  2743. result->allow_only_policy_networks_to_autoconnect = GetBoolean(
  2744. global_policy_dict,
  2745. ::onc::global_network_config::kAllowOnlyPolicyNetworksToAutoconnect);
  2746. result->allow_only_policy_wifi_networks_to_connect =
  2747. GetBoolean(global_policy_dict,
  2748. ::onc::global_network_config::kAllowOnlyPolicyWiFiToConnect);
  2749. result->allow_only_policy_wifi_networks_to_connect_if_available = GetBoolean(
  2750. global_policy_dict,
  2751. ::onc::global_network_config::kAllowOnlyPolicyWiFiToConnectIfAvailable);
  2752. absl::optional<std::vector<std::string>> blocked_hex_ssids = GetStringList(
  2753. global_policy_dict, ::onc::global_network_config::kBlockedHexSSIDs);
  2754. if (blocked_hex_ssids)
  2755. result->blocked_hex_ssids = std::move(*blocked_hex_ssids);
  2756. std::move(callback).Run(std::move(result));
  2757. }
  2758. void CrosNetworkConfig::StartConnect(const std::string& guid,
  2759. StartConnectCallback callback) {
  2760. std::string service_path = GetServicePathFromGuid(guid);
  2761. if (service_path.empty()) {
  2762. std::move(callback).Run(mojom::StartConnectResult::kInvalidGuid,
  2763. NetworkConnectionHandler::kErrorNotFound);
  2764. return;
  2765. }
  2766. int callback_id = callback_id_++;
  2767. start_connect_callbacks_[callback_id] = std::move(callback);
  2768. network_connection_handler_->ConnectToNetwork(
  2769. service_path,
  2770. base::BindOnce(&CrosNetworkConfig::StartConnectSuccess,
  2771. weak_factory_.GetWeakPtr(), callback_id),
  2772. base::BindOnce(&CrosNetworkConfig::StartConnectFailure,
  2773. weak_factory_.GetWeakPtr(), callback_id),
  2774. true /* check_error_state */, chromeos::ConnectCallbackMode::ON_STARTED);
  2775. }
  2776. void CrosNetworkConfig::StartConnectSuccess(int callback_id) {
  2777. auto iter = start_connect_callbacks_.find(callback_id);
  2778. DCHECK(iter != start_connect_callbacks_.end());
  2779. std::move(iter->second)
  2780. .Run(mojom::StartConnectResult::kSuccess, std::string());
  2781. start_connect_callbacks_.erase(iter);
  2782. }
  2783. void CrosNetworkConfig::StartConnectFailure(int callback_id,
  2784. const std::string& error_name) {
  2785. auto iter = start_connect_callbacks_.find(callback_id);
  2786. DCHECK(iter != start_connect_callbacks_.end());
  2787. mojom::StartConnectResult result;
  2788. if (error_name == NetworkConnectionHandler::kErrorNotFound) {
  2789. result = mojom::StartConnectResult::kInvalidGuid;
  2790. } else if (error_name == NetworkConnectionHandler::kErrorConnected ||
  2791. error_name == NetworkConnectionHandler::kErrorConnecting) {
  2792. result = mojom::StartConnectResult::kInvalidState;
  2793. } else if (error_name == NetworkConnectionHandler::kErrorConnectCanceled) {
  2794. result = mojom::StartConnectResult::kCanceled;
  2795. } else if (error_name == NetworkConnectionHandler::kErrorPassphraseRequired ||
  2796. error_name == NetworkConnectionHandler::kErrorBadPassphrase ||
  2797. error_name ==
  2798. NetworkConnectionHandler::kErrorCertificateRequired ||
  2799. error_name ==
  2800. NetworkConnectionHandler::kErrorConfigurationRequired ||
  2801. error_name ==
  2802. NetworkConnectionHandler::kErrorAuthenticationRequired ||
  2803. error_name == NetworkConnectionHandler::kErrorCertLoadTimeout ||
  2804. error_name == NetworkConnectionHandler::kErrorConfigureFailed) {
  2805. result = mojom::StartConnectResult::kNotConfigured;
  2806. } else if (error_name == NetworkConnectionHandler::kErrorBlockedByPolicy) {
  2807. result = mojom::StartConnectResult::kBlocked;
  2808. } else {
  2809. result = mojom::StartConnectResult::kUnknown;
  2810. }
  2811. std::move(iter->second).Run(result, error_name);
  2812. start_connect_callbacks_.erase(iter);
  2813. }
  2814. void CrosNetworkConfig::StartDisconnect(const std::string& guid,
  2815. StartDisconnectCallback callback) {
  2816. std::string service_path = GetServicePathFromGuid(guid);
  2817. if (service_path.empty()) {
  2818. std::move(callback).Run(false);
  2819. return;
  2820. }
  2821. int callback_id = callback_id_++;
  2822. start_disconnect_callbacks_[callback_id] = std::move(callback);
  2823. network_connection_handler_->DisconnectNetwork(
  2824. service_path,
  2825. base::BindOnce(&CrosNetworkConfig::StartDisconnectSuccess,
  2826. weak_factory_.GetWeakPtr(), callback_id),
  2827. base::BindOnce(&CrosNetworkConfig::StartDisconnectFailure,
  2828. weak_factory_.GetWeakPtr(), callback_id));
  2829. }
  2830. void CrosNetworkConfig::StartDisconnectSuccess(int callback_id) {
  2831. auto iter = start_disconnect_callbacks_.find(callback_id);
  2832. DCHECK(iter != start_disconnect_callbacks_.end());
  2833. std::move(iter->second).Run(true);
  2834. start_disconnect_callbacks_.erase(iter);
  2835. }
  2836. void CrosNetworkConfig::StartDisconnectFailure(int callback_id,
  2837. const std::string& error_name) {
  2838. auto iter = start_disconnect_callbacks_.find(callback_id);
  2839. DCHECK(iter != start_disconnect_callbacks_.end());
  2840. std::move(iter->second).Run(false);
  2841. start_disconnect_callbacks_.erase(iter);
  2842. }
  2843. void CrosNetworkConfig::SetVpnProviders(
  2844. std::vector<mojom::VpnProviderPtr> providers) {
  2845. vpn_providers_ = std::move(providers);
  2846. for (auto& observer : observers_)
  2847. observer->OnVpnProvidersChanged();
  2848. }
  2849. void CrosNetworkConfig::GetVpnProviders(GetVpnProvidersCallback callback) {
  2850. std::move(callback).Run(mojo::Clone(vpn_providers_));
  2851. }
  2852. void CrosNetworkConfig::GetNetworkCertificates(
  2853. GetNetworkCertificatesCallback callback) {
  2854. const std::vector<NetworkCertificateHandler::Certificate>&
  2855. handler_server_cas =
  2856. network_certificate_handler_->server_ca_certificates();
  2857. std::vector<mojom::NetworkCertificatePtr> server_cas;
  2858. for (const auto& cert : handler_server_cas)
  2859. server_cas.push_back(GetMojoCert(cert, mojom::CertificateType::kServerCA));
  2860. std::vector<mojom::NetworkCertificatePtr> user_certs;
  2861. const std::vector<NetworkCertificateHandler::Certificate>&
  2862. handler_user_certs = network_certificate_handler_->client_certificates();
  2863. for (const auto& cert : handler_user_certs)
  2864. user_certs.push_back(GetMojoCert(cert, mojom::CertificateType::kUserCert));
  2865. std::move(callback).Run(std::move(server_cas), std::move(user_certs));
  2866. }
  2867. void CrosNetworkConfig::GetAlwaysOnVpn(GetAlwaysOnVpnCallback callback) {
  2868. const NetworkProfile* profile =
  2869. network_profile_handler_->GetDefaultUserProfile();
  2870. if (!profile) {
  2871. NET_LOG(ERROR) << "GetAlwaysOnVpn: no user profile found";
  2872. // No profile available, ensure the callback gets fired with always-on VPN
  2873. // disabled.
  2874. OnGetAlwaysOnVpn(std::move(callback), shill::kAlwaysOnVpnModeOff,
  2875. std::string());
  2876. return;
  2877. }
  2878. network_profile_handler_->GetAlwaysOnVpnConfiguration(
  2879. profile->path,
  2880. base::BindOnce(&CrosNetworkConfig::OnGetAlwaysOnVpn,
  2881. weak_factory_.GetWeakPtr(), std::move(callback)));
  2882. }
  2883. void CrosNetworkConfig::OnGetAlwaysOnVpn(GetAlwaysOnVpnCallback callback,
  2884. std::string mode,
  2885. std::string service_path) {
  2886. mojom::AlwaysOnVpnMode vpn_mode;
  2887. if (mode == shill::kAlwaysOnVpnModeOff) {
  2888. vpn_mode = mojom::AlwaysOnVpnMode::kOff;
  2889. } else if (mode == shill::kAlwaysOnVpnModeBestEffort) {
  2890. vpn_mode = mojom::AlwaysOnVpnMode::kBestEffort;
  2891. } else if (mode == shill::kAlwaysOnVpnModeStrict) {
  2892. vpn_mode = mojom::AlwaysOnVpnMode::kStrict;
  2893. } else {
  2894. NOTREACHED() << "OnGetAlwaysOnVpn: invalid always-on VPN mode: " << mode;
  2895. vpn_mode = mojom::AlwaysOnVpnMode::kOff;
  2896. }
  2897. std::string guid;
  2898. const NetworkState* network =
  2899. network_state_handler_->GetNetworkState(service_path);
  2900. // |network| is expected to be null when the service has not been set (yet)
  2901. // or has been removed.
  2902. if (network) {
  2903. guid = network->guid();
  2904. }
  2905. mojom::AlwaysOnVpnPropertiesPtr properties =
  2906. mojom::AlwaysOnVpnProperties::New(vpn_mode, guid);
  2907. std::move(callback).Run(std::move(properties));
  2908. }
  2909. void CrosNetworkConfig::SetAlwaysOnVpn(
  2910. mojom::AlwaysOnVpnPropertiesPtr properties) {
  2911. const NetworkProfile* profile =
  2912. network_profile_handler_->GetDefaultUserProfile();
  2913. if (!profile) {
  2914. NET_LOG(ERROR) << "SetAlwaysOnVpn: no user profile found";
  2915. return;
  2916. }
  2917. std::string mode;
  2918. switch (properties->mode) {
  2919. case mojom::AlwaysOnVpnMode::kBestEffort:
  2920. mode = shill::kAlwaysOnVpnModeBestEffort;
  2921. break;
  2922. case mojom::AlwaysOnVpnMode::kStrict:
  2923. mode = shill::kAlwaysOnVpnModeStrict;
  2924. break;
  2925. case mojom::AlwaysOnVpnMode::kOff:
  2926. mode = shill::kAlwaysOnVpnModeOff;
  2927. break;
  2928. default:
  2929. NOTREACHED() << "SetAlwaysOnVpn: invalid mode: " << properties->mode;
  2930. return;
  2931. }
  2932. network_profile_handler_->SetAlwaysOnVpnMode(profile->path, mode);
  2933. if (properties->service_guid.empty()) {
  2934. return;
  2935. }
  2936. std::string service_path = GetServicePathFromGuid(properties->service_guid);
  2937. if (service_path.empty()) {
  2938. return;
  2939. }
  2940. network_profile_handler_->SetAlwaysOnVpnService(profile->path, service_path);
  2941. }
  2942. void CrosNetworkConfig::GetSupportedVpnTypes(
  2943. GetSupportedVpnTypesCallback callback) {
  2944. ShillManagerClient::Get()->GetProperties(
  2945. base::BindOnce(&CrosNetworkConfig::OnGetSupportedVpnTypes,
  2946. weak_factory_.GetWeakPtr(), std::move(callback)));
  2947. }
  2948. void CrosNetworkConfig::OnGetSupportedVpnTypes(
  2949. GetSupportedVpnTypesCallback callback,
  2950. absl::optional<base::Value> properties) {
  2951. std::vector<std::string> result;
  2952. if (!properties) {
  2953. NET_LOG(ERROR) << "GetSupportedVpnTypes: GetProperties failed.";
  2954. std::move(callback).Run(result);
  2955. return;
  2956. }
  2957. const base::Value* value =
  2958. properties->FindKey(shill::kSupportedVPNTypesProperty);
  2959. if (value) {
  2960. result =
  2961. base::SplitString(*value->GetIfString(), ",", base::TRIM_WHITESPACE,
  2962. base::SPLIT_WANT_NONEMPTY);
  2963. }
  2964. if (!base::FeatureList::IsEnabled(ash::features::kEnableIkev2Vpn)) {
  2965. auto iter = std::find(result.begin(), result.end(), kIKEv2VPNType);
  2966. if (iter != result.end()) {
  2967. result.erase(iter);
  2968. }
  2969. }
  2970. std::move(callback).Run(result);
  2971. }
  2972. void CrosNetworkConfig::RequestTrafficCounters(
  2973. const std::string& guid,
  2974. RequestTrafficCountersCallback callback) {
  2975. std::string service_path = GetServicePathFromGuid(guid);
  2976. if (service_path.empty()) {
  2977. NET_LOG(ERROR) << "RequestTrafficCounters: service path for guid " << guid
  2978. << " not found";
  2979. std::move(callback).Run({});
  2980. return;
  2981. }
  2982. network_state_handler_->RequestTrafficCounters(
  2983. service_path,
  2984. base::BindOnce(&CrosNetworkConfig::PopulateTrafficCounters,
  2985. weak_factory_.GetWeakPtr(), std::move(callback)));
  2986. }
  2987. void CrosNetworkConfig::PopulateTrafficCounters(
  2988. RequestTrafficCountersCallback callback,
  2989. absl::optional<base::Value> traffic_counters) {
  2990. if (!traffic_counters || !traffic_counters->is_list() ||
  2991. !traffic_counters->GetListDeprecated().size()) {
  2992. std::move(callback).Run({});
  2993. return;
  2994. }
  2995. std::vector<mojom::TrafficCounterPtr> counters;
  2996. for (const base::Value& tc : traffic_counters->GetListDeprecated()) {
  2997. DCHECK(tc.is_dict());
  2998. const base::Value* source =
  2999. tc.FindKeyOfType("source", base::Value::Type::STRING);
  3000. DCHECK(source);
  3001. // Since rx_bytes may be larger than the maximum value representable by
  3002. // uint32_t, we must check whether it was implicitly converted to a double
  3003. // during D-Bus deserialization.
  3004. uint64_t rx_bytes;
  3005. const base::Value* rb = tc.FindKey("rx_bytes");
  3006. DCHECK(rb);
  3007. if (rb->type() == base::Value::Type::INTEGER) {
  3008. rx_bytes = rb->GetInt();
  3009. } else if (rb->type() == base::Value::Type::DOUBLE) {
  3010. rx_bytes = std::floor(rb->GetDouble());
  3011. } else {
  3012. NOTREACHED();
  3013. }
  3014. // Since tx_bytes may be larger than the maximum value representable by
  3015. // uint32_t, we must check whether it was implicitly converted to a double
  3016. // during D-Bus deserialization.
  3017. uint64_t tx_bytes;
  3018. const base::Value* tb = tc.FindKey("tx_bytes");
  3019. DCHECK(tb);
  3020. if (tb->type() == base::Value::Type::INTEGER) {
  3021. tx_bytes = tb->GetInt();
  3022. } else if (tb->type() == base::Value::Type::DOUBLE) {
  3023. tx_bytes = std::floor(tb->GetDouble());
  3024. } else {
  3025. NOTREACHED();
  3026. }
  3027. counters.push_back(
  3028. mojom::TrafficCounter::New(ConvertToTrafficCounterSourceEnum(
  3029. base::ToLowerASCII(source->GetString())),
  3030. rx_bytes, tx_bytes));
  3031. }
  3032. std::move(callback).Run(std::move(counters));
  3033. }
  3034. void CrosNetworkConfig::ResetTrafficCounters(const std::string& guid) {
  3035. std::string service_path = GetServicePathFromGuid(guid);
  3036. if (service_path.empty()) {
  3037. NET_LOG(ERROR) << "ResetTrafficCounters: service path for guid " << guid
  3038. << " not found";
  3039. return;
  3040. }
  3041. network_state_handler_->ResetTrafficCounters(service_path);
  3042. }
  3043. void CrosNetworkConfig::SetTrafficCountersAutoReset(
  3044. const std::string& guid,
  3045. bool auto_reset,
  3046. mojom::UInt32ValuePtr day,
  3047. SetTrafficCountersAutoResetCallback callback) {
  3048. if (day && !auto_reset) {
  3049. NET_LOG(ERROR) << "Failed to set auto reset day for " << guid
  3050. << ": auto reset must be enabled.";
  3051. std::move(callback).Run(false);
  3052. return;
  3053. }
  3054. if (!day && auto_reset) {
  3055. NET_LOG(ERROR) << "Failed to enable auto reset for " << guid << ": a valid "
  3056. << "day between 1 and 31 (inclusive) must be provided.";
  3057. std::move(callback).Run(false);
  3058. return;
  3059. }
  3060. if (day && (day->value < 1 || day->value > 31)) {
  3061. NET_LOG(ERROR) << "Failed to set auto reset day " << day->value << " for "
  3062. << guid << ": day must be between 1 and 31 (inclusive)";
  3063. std::move(callback).Run(false);
  3064. return;
  3065. }
  3066. NetworkHandler::Get()
  3067. ->network_metadata_store()
  3068. ->SetEnableTrafficCountersAutoReset(guid, auto_reset);
  3069. NetworkHandler::Get()
  3070. ->network_metadata_store()
  3071. ->SetDayOfTrafficCountersAutoReset(
  3072. guid, day ? absl::optional<int>(day->value) : absl::nullopt);
  3073. std::move(callback).Run(true);
  3074. }
  3075. // static
  3076. mojom::TrafficCounterSource CrosNetworkConfig::GetTrafficCounterEnumForTesting(
  3077. const std::string& source) {
  3078. return ConvertToTrafficCounterSourceEnum(source);
  3079. }
  3080. // NetworkStateHandlerObserver
  3081. void CrosNetworkConfig::NetworkListChanged() {
  3082. for (auto& observer : observers_)
  3083. observer->OnNetworkStateListChanged();
  3084. }
  3085. void CrosNetworkConfig::DeviceListChanged() {
  3086. for (auto& observer : observers_)
  3087. observer->OnDeviceStateListChanged();
  3088. }
  3089. void CrosNetworkConfig::ActiveNetworksChanged(
  3090. const std::vector<const NetworkState*>& active_networks) {
  3091. std::vector<mojom::NetworkStatePropertiesPtr> result;
  3092. for (const NetworkState* network : active_networks) {
  3093. mojom::NetworkStatePropertiesPtr mojo_network = NetworkStateToMojo(
  3094. network_state_handler_, cellular_esim_profile_handler_, vpn_providers_,
  3095. network);
  3096. if (mojo_network)
  3097. result.emplace_back(std::move(mojo_network));
  3098. }
  3099. for (auto& observer : observers_)
  3100. observer->OnActiveNetworksChanged(mojo::Clone(result));
  3101. }
  3102. void CrosNetworkConfig::NetworkPropertiesUpdated(const NetworkState* network) {
  3103. if (network->type() == shill::kTypeEthernetEap)
  3104. return;
  3105. mojom::NetworkStatePropertiesPtr mojo_network =
  3106. NetworkStateToMojo(network_state_handler_, cellular_esim_profile_handler_,
  3107. vpn_providers_, network);
  3108. if (!mojo_network)
  3109. return;
  3110. for (auto& observer : observers_)
  3111. observer->OnNetworkStateChanged(mojo_network.Clone());
  3112. }
  3113. void CrosNetworkConfig::DevicePropertiesUpdated(const DeviceState* device) {
  3114. DeviceListChanged();
  3115. }
  3116. void CrosNetworkConfig::ScanCompleted(const DeviceState* device) {
  3117. DeviceListChanged();
  3118. }
  3119. void CrosNetworkConfig::ScanStarted(const DeviceState* device) {
  3120. DeviceListChanged();
  3121. }
  3122. void CrosNetworkConfig::NetworkConnectionStateChanged(
  3123. const NetworkState* network) {
  3124. if (!network->Matches(NetworkTypePattern::Cellular())) {
  3125. return;
  3126. }
  3127. // inhibit_reason device property is dependent on network connection state of
  3128. // cellular networks. Notify device list change so that clients will update
  3129. // with new inhibit reason.
  3130. DeviceListChanged();
  3131. }
  3132. void CrosNetworkConfig::OnShuttingDown() {
  3133. if (network_state_handler_->HasObserver(this))
  3134. network_state_handler_->RemoveObserver(this, FROM_HERE);
  3135. network_state_handler_ = nullptr;
  3136. }
  3137. void CrosNetworkConfig::OnCertificatesChanged() {
  3138. for (auto& observer : observers_)
  3139. observer->OnNetworkCertificatesChanged();
  3140. }
  3141. void CrosNetworkConfig::OnInhibitStateChanged() {
  3142. DeviceListChanged();
  3143. }
  3144. void CrosNetworkConfig::PoliciesApplied(const std::string& userhash) {
  3145. for (auto& observer : observers_)
  3146. observer->OnPoliciesApplied(userhash);
  3147. }
  3148. void CrosNetworkConfig::OnManagedNetworkConfigurationHandlerShuttingDown() {
  3149. if (network_configuration_handler_ &&
  3150. network_configuration_handler_->HasObserver(this)) {
  3151. network_configuration_handler_->RemoveObserver(this);
  3152. }
  3153. network_configuration_handler_ = nullptr;
  3154. }
  3155. const std::string& CrosNetworkConfig::GetServicePathFromGuid(
  3156. const std::string& guid) {
  3157. const chromeos::NetworkState* network =
  3158. network_state_handler_->GetNetworkStateFromGuid(guid);
  3159. return network ? network->path() : base::EmptyString();
  3160. }
  3161. } // namespace network_config
  3162. } // namespace chromeos