dataStore.go 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package psiphon
  20. import (
  21. "bytes"
  22. "context"
  23. "encoding/binary"
  24. "encoding/json"
  25. "fmt"
  26. "io"
  27. "math"
  28. "os"
  29. "strings"
  30. "sync"
  31. "sync/atomic"
  32. "time"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/dsl"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  39. )
  40. var (
  41. datastoreServerEntriesBucket = []byte("serverEntries")
  42. datastoreServerEntryTagsBucket = []byte("serverEntryTags")
  43. datastoreServerEntryTombstoneTagsBucket = []byte("serverEntryTombstoneTags")
  44. datastoreUrlETagsBucket = []byte("urlETags")
  45. datastoreKeyValueBucket = []byte("keyValues")
  46. datastoreRemoteServerListStatsBucket = []byte("remoteServerListStats")
  47. datastoreFailedTunnelStatsBucket = []byte("failedTunnelStats")
  48. datastoreSLOKsBucket = []byte("SLOKs")
  49. datastoreTacticsBucket = []byte("tactics")
  50. datastoreSpeedTestSamplesBucket = []byte("speedTestSamples")
  51. datastoreDialParametersBucket = []byte("dialParameters")
  52. datastoreNetworkReplayParametersBucket = []byte("networkReplayParameters")
  53. datastoreDSLOSLStatesBucket = []byte("dslOSLStates")
  54. datastoreLastConnectedKey = "lastConnected"
  55. datastoreLastServerEntryFilterKey = []byte("lastServerEntryFilter")
  56. datastoreAffinityServerEntryIDKey = []byte("affinityServerEntryID")
  57. datastoreInproxyCommonCompartmentIDsKey = []byte("inproxyCommonCompartmentIDs")
  58. datastorePersistentStatTypeRemoteServerList = string(datastoreRemoteServerListStatsBucket)
  59. datastorePersistentStatTypeFailedTunnel = string(datastoreFailedTunnelStatsBucket)
  60. datastoreCheckServerEntryTagsEndTimeKey = "checkServerEntryTagsEndTime"
  61. datastoreDSLLastUntunneledFetchTimeKey = "dslLastUntunneledDiscoverTime"
  62. datastoreDSLLastTunneledFetchTimeKey = "dslLastTunneledDiscoverTime"
  63. datastoreDSLLastActiveOSLsTimeKey = "dslLastActiveOSLsTime"
  64. datastoreServerEntryFetchGCThreshold = 10
  65. datastoreReferenceCountMutex sync.RWMutex
  66. datastoreReferenceCount int64
  67. datastoreMutex sync.RWMutex
  68. activeDatastoreDB *datastoreDB
  69. disableCheckServerEntryTags atomic.Bool
  70. datastoreLastServerEntryCount atomic.Int64
  71. )
  72. func init() {
  73. datastoreLastServerEntryCount.Store(-1)
  74. }
  75. // OpenDataStore opens and initializes the singleton datastore instance.
  76. //
  77. // Nested Open/CloseDataStore calls are supported: OpenDataStore will succeed
  78. // when called when the datastore is initialized. Every call to OpenDataStore
  79. // must be paired with a corresponding call to CloseDataStore to ensure the
  80. // datastore is closed.
  81. func OpenDataStore(config *Config) error {
  82. return openDataStore(config, true)
  83. }
  84. // OpenDataStoreWithoutRetry performs an OpenDataStore but does not retry or
  85. // reset the datastore file in case of failures. Use
  86. // OpenDataStoreWithoutRetry when the datastore is expected to be locked by
  87. // another process and faster failure is preferred.
  88. func OpenDataStoreWithoutRetry(config *Config) error {
  89. return openDataStore(config, false)
  90. }
  91. func openDataStore(config *Config, retryAndReset bool) error {
  92. // The datastoreReferenceCountMutex/datastoreMutex mutex pair allow for:
  93. //
  94. // _Nested_ OpenDataStore/CloseDataStore calls to not block when a
  95. // datastoreView is in progress (for example, a GetDialParameters call while
  96. // a slow ScanServerEntries is running). In this case the nested
  97. // OpenDataStore/CloseDataStore calls will lock only
  98. // datastoreReferenceCountMutex and not datastoreMutex.
  99. //
  100. // Synchronized access, for OpenDataStore/CloseDataStore, to
  101. // activeDatastoreDB based on a consistent view of datastoreReferenceCount
  102. // via locking first datastoreReferenceCount and then datastoreMutex while
  103. // holding datastoreReferenceCount.
  104. //
  105. // Concurrent access, for datastoreView/datastoreUpdate, to activeDatastoreDB
  106. // via datastoreMutex read locks.
  107. //
  108. // Exclusive access, for OpenDataStore/CloseDataStore, to activeDatastoreDB,
  109. // with no running datastoreView/datastoreUpdate, by aquiring a
  110. // datastoreMutex write lock.
  111. datastoreReferenceCountMutex.Lock()
  112. if datastoreReferenceCount < 0 || datastoreReferenceCount == math.MaxInt64 {
  113. datastoreReferenceCountMutex.Unlock()
  114. return errors.Tracef(
  115. "invalid datastore reference count: %d", datastoreReferenceCount)
  116. }
  117. if datastoreReferenceCount > 0 {
  118. // For this sanity check, we need only the read-only lock; and must use the
  119. // read-only lock to allow concurrent datastoreView calls.
  120. datastoreMutex.RLock()
  121. isNil := activeDatastoreDB == nil
  122. datastoreMutex.RUnlock()
  123. if isNil {
  124. return errors.TraceNew("datastore unexpectedly closed")
  125. }
  126. // Add a reference to the open datastore.
  127. datastoreReferenceCount += 1
  128. datastoreReferenceCountMutex.Unlock()
  129. return nil
  130. }
  131. // Only lock datastoreMutex now that it's necessary.
  132. // datastoreReferenceCountMutex remains locked.
  133. datastoreMutex.Lock()
  134. if activeDatastoreDB != nil {
  135. datastoreMutex.Unlock()
  136. datastoreReferenceCountMutex.Unlock()
  137. return errors.TraceNew("datastore unexpectedly open")
  138. }
  139. // datastoreReferenceCount is 0, so open the datastore.
  140. newDB, err := datastoreOpenDB(
  141. config.GetDataStoreDirectory(), retryAndReset)
  142. if err != nil {
  143. datastoreMutex.Unlock()
  144. datastoreReferenceCountMutex.Unlock()
  145. return errors.Trace(err)
  146. }
  147. datastoreReferenceCount = 1
  148. activeDatastoreDB = newDB
  149. datastoreMutex.Unlock()
  150. datastoreReferenceCountMutex.Unlock()
  151. _ = resetAllPersistentStatsToUnreported()
  152. return nil
  153. }
  154. // CloseDataStore closes the singleton datastore instance, if open.
  155. func CloseDataStore() {
  156. datastoreReferenceCountMutex.Lock()
  157. defer datastoreReferenceCountMutex.Unlock()
  158. if datastoreReferenceCount <= 0 {
  159. NoticeWarning(
  160. "invalid datastore reference count: %d", datastoreReferenceCount)
  161. return
  162. }
  163. datastoreReferenceCount -= 1
  164. if datastoreReferenceCount > 0 {
  165. return
  166. }
  167. // Only lock datastoreMutex now that it's necessary.
  168. // datastoreReferenceCountMutex remains locked.
  169. datastoreMutex.Lock()
  170. defer datastoreMutex.Unlock()
  171. if activeDatastoreDB == nil {
  172. return
  173. }
  174. err := activeDatastoreDB.close()
  175. if err != nil {
  176. NoticeWarning("failed to close datastore: %s", errors.Trace(err))
  177. }
  178. activeDatastoreDB = nil
  179. }
  180. // GetDataStoreMetrics returns a string logging datastore metrics.
  181. func GetDataStoreMetrics() string {
  182. datastoreMutex.RLock()
  183. defer datastoreMutex.RUnlock()
  184. if activeDatastoreDB == nil {
  185. return ""
  186. }
  187. return activeDatastoreDB.getDataStoreMetrics()
  188. }
  189. // datastoreView runs a read-only transaction, making datastore buckets and
  190. // values available to the supplied function.
  191. //
  192. // Bucket value slices are only valid for the duration of the transaction and
  193. // _must_ not be referenced directly outside the transaction.
  194. func datastoreView(fn func(tx *datastoreTx) error) error {
  195. datastoreMutex.RLock()
  196. defer datastoreMutex.RUnlock()
  197. if activeDatastoreDB == nil {
  198. return errors.TraceNew("datastore not open")
  199. }
  200. err := activeDatastoreDB.view(fn)
  201. if err != nil {
  202. err = errors.Trace(err)
  203. }
  204. return err
  205. }
  206. // datastoreUpdate runs a read-write transaction, making datastore buckets and
  207. // values available to the supplied function.
  208. //
  209. // Bucket value slices are only valid for the duration of the transaction and
  210. // _must_ not be referenced directly outside the transaction.
  211. func datastoreUpdate(fn func(tx *datastoreTx) error) error {
  212. datastoreMutex.RLock()
  213. defer datastoreMutex.RUnlock()
  214. if activeDatastoreDB == nil {
  215. return errors.TraceNew("database not open")
  216. }
  217. err := activeDatastoreDB.update(fn)
  218. if err != nil {
  219. err = errors.Trace(err)
  220. }
  221. return err
  222. }
  223. // StoreServerEntry adds the server entry to the datastore.
  224. //
  225. // When a server entry already exists for a given server, it will be
  226. // replaced only if replaceIfExists is set or if the the ConfigurationVersion
  227. // field of the new entry is strictly higher than the existing entry.
  228. //
  229. // If the server entry data is malformed, an alert notice is issued and
  230. // the entry is skipped; no error is returned.
  231. func StoreServerEntry(
  232. serverEntryFields protocol.ServerEntryFields,
  233. replaceIfExists bool) error {
  234. return errors.Trace(
  235. storeServerEntry(serverEntryFields, replaceIfExists, nil))
  236. }
  237. func storeServerEntry(
  238. serverEntryFields protocol.ServerEntryFields,
  239. replaceIfExists bool,
  240. additionalUpdates func(tx *datastoreTx, serverEntryID []byte) error) error {
  241. // TODO: call serverEntryFields.VerifySignature. At this time, we do not do
  242. // this as not all server entries have an individual signature field. All
  243. // StoreServerEntry callers either call VerifySignature or obtain server
  244. // entries from a trusted source (embedded in a signed client, or in a signed
  245. // authenticated package).
  246. // Server entries should already be validated before this point,
  247. // so instead of skipping we fail with an error.
  248. err := protocol.ValidateServerEntryFields(serverEntryFields)
  249. if err != nil {
  250. return errors.Tracef("invalid server entry: %s", err)
  251. }
  252. // BoltDB implementation note:
  253. // For simplicity, we don't maintain indexes on server entry
  254. // region or supported protocols. Instead, we perform full-bucket
  255. // scans with a filter. With a small enough database (thousands or
  256. // even tens of thousand of server entries) and common enough
  257. // values (e.g., many servers support all protocols), performance
  258. // is expected to be acceptable.
  259. err = datastoreUpdate(func(tx *datastoreTx) error {
  260. serverEntries := tx.bucket(datastoreServerEntriesBucket)
  261. serverEntryTags := tx.bucket(datastoreServerEntryTagsBucket)
  262. serverEntryTombstoneTags := tx.bucket(datastoreServerEntryTombstoneTagsBucket)
  263. serverEntryID := []byte(serverEntryFields.GetIPAddress())
  264. // Check not only that the entry exists, but is valid. This
  265. // will replace in the rare case where the data is corrupt.
  266. existingConfigurationVersion := -1
  267. existingData := serverEntries.get(serverEntryID)
  268. if existingData != nil {
  269. var existingServerEntry *protocol.ServerEntry
  270. err := json.Unmarshal(existingData, &existingServerEntry)
  271. if err == nil {
  272. existingConfigurationVersion = existingServerEntry.ConfigurationVersion
  273. }
  274. }
  275. configurationVersion := serverEntryFields.GetConfigurationVersion()
  276. exists := existingConfigurationVersion > -1
  277. newer := exists && existingConfigurationVersion < configurationVersion
  278. update := !exists || replaceIfExists || newer
  279. if !update {
  280. return nil
  281. }
  282. serverEntryTag := serverEntryFields.GetTag()
  283. // Generate a derived tag when the server entry has no tag.
  284. if serverEntryTag == "" {
  285. serverEntryTag = protocol.GenerateServerEntryTag(
  286. serverEntryFields.GetIPAddress(),
  287. serverEntryFields.GetWebServerSecret())
  288. serverEntryFields.SetTag(serverEntryTag)
  289. }
  290. serverEntryTagBytes := []byte(serverEntryTag)
  291. // Ignore the server entry if it was previously pruned and a tombstone is
  292. // set.
  293. //
  294. // This logic is enforced only for embedded server entries, as all other
  295. // sources are considered to be definitive and non-stale. These exceptions
  296. // intentionally allow the scenario where a server is temporarily deleted
  297. // and then restored; in this case, it's desired for pruned server entries
  298. // to be restored.
  299. if serverEntryFields.GetLocalSource() == protocol.SERVER_ENTRY_SOURCE_EMBEDDED {
  300. if serverEntryTombstoneTags.get(serverEntryTagBytes) != nil {
  301. return nil
  302. }
  303. }
  304. data, err := json.Marshal(serverEntryFields)
  305. if err != nil {
  306. return errors.Trace(err)
  307. }
  308. err = serverEntries.put(serverEntryID, data)
  309. if err != nil {
  310. return errors.Trace(err)
  311. }
  312. serverEntryTagRecord, err := setServerEntryTagRecord(
  313. serverEntryID, configurationVersion)
  314. if err != nil {
  315. return errors.Trace(err)
  316. }
  317. err = serverEntryTags.put(serverEntryTagBytes, serverEntryTagRecord)
  318. if err != nil {
  319. return errors.Trace(err)
  320. }
  321. if additionalUpdates != nil {
  322. err = additionalUpdates(tx, serverEntryID)
  323. if err != nil {
  324. return errors.Trace(err)
  325. }
  326. }
  327. NoticeInfo("updated server %s", serverEntryFields.GetDiagnosticID())
  328. return nil
  329. })
  330. if err != nil {
  331. return errors.Trace(err)
  332. }
  333. return nil
  334. }
  335. // StoreServerEntries stores a list of server entries.
  336. // There is an independent transaction for each entry insert/update.
  337. func StoreServerEntries(
  338. config *Config,
  339. serverEntries []protocol.ServerEntryFields,
  340. replaceIfExists bool) error {
  341. for _, serverEntryFields := range serverEntries {
  342. err := StoreServerEntry(serverEntryFields, replaceIfExists)
  343. if err != nil {
  344. return errors.Trace(err)
  345. }
  346. }
  347. return nil
  348. }
  349. // StreamingStoreServerEntries stores a list of server entries. There is an
  350. // independent transaction for each entry insert/update.
  351. // StreamingStoreServerEntries stops early and returns an error if ctx becomes
  352. // done; any server entries stored up to that point are retained.
  353. func StreamingStoreServerEntries(
  354. ctx context.Context,
  355. config *Config,
  356. serverEntries *protocol.StreamingServerEntryDecoder,
  357. replaceIfExists bool) error {
  358. // Note: both StreamingServerEntryDecoder.Next and StoreServerEntry
  359. // allocate temporary memory buffers for hex/JSON decoding/encoding,
  360. // so this isn't true constant-memory streaming (it depends on garbage
  361. // collection).
  362. n := 0
  363. for {
  364. select {
  365. case <-ctx.Done():
  366. return errors.Trace(ctx.Err())
  367. default:
  368. }
  369. serverEntry, err := serverEntries.Next()
  370. if err != nil {
  371. return errors.Trace(err)
  372. }
  373. if serverEntry == nil {
  374. // No more server entries
  375. return nil
  376. }
  377. err = StoreServerEntry(serverEntry, replaceIfExists)
  378. if err != nil {
  379. return errors.Trace(err)
  380. }
  381. n += 1
  382. if n == datastoreServerEntryFetchGCThreshold {
  383. DoGarbageCollection()
  384. n = 0
  385. }
  386. }
  387. }
  388. // ImportEmbeddedServerEntries loads, decodes, and stores a list of server
  389. // entries. If embeddedServerEntryListFilename is not empty,
  390. // embeddedServerEntryList will be ignored and the encoded server entry list
  391. // will be loaded from the specified file. The import process stops early if
  392. // ctx becomes done; any server entries imported up to that point are
  393. // retained.
  394. func ImportEmbeddedServerEntries(
  395. ctx context.Context,
  396. config *Config,
  397. embeddedServerEntryListFilename string,
  398. embeddedServerEntryList string) error {
  399. var reader io.Reader
  400. if embeddedServerEntryListFilename != "" {
  401. file, err := os.Open(embeddedServerEntryListFilename)
  402. if err != nil {
  403. return errors.Trace(err)
  404. }
  405. defer file.Close()
  406. reader = file
  407. } else {
  408. reader = strings.NewReader(embeddedServerEntryList)
  409. }
  410. err := StreamingStoreServerEntries(
  411. ctx,
  412. config,
  413. protocol.NewStreamingServerEntryDecoder(
  414. reader,
  415. common.TruncateTimestampToHour(common.GetCurrentTimestamp()),
  416. protocol.SERVER_ENTRY_SOURCE_EMBEDDED),
  417. false)
  418. if err != nil {
  419. return errors.Trace(err)
  420. }
  421. return nil
  422. }
  423. // PromoteServerEntry sets the server affinity server entry ID to the
  424. // specified server entry IP address.
  425. func PromoteServerEntry(config *Config, ipAddress string) error {
  426. err := datastoreUpdate(func(tx *datastoreTx) error {
  427. serverEntryID := []byte(ipAddress)
  428. // Ensure the corresponding server entry exists before
  429. // setting server affinity.
  430. bucket := tx.bucket(datastoreServerEntriesBucket)
  431. data := bucket.get(serverEntryID)
  432. if data == nil {
  433. NoticeWarning(
  434. "PromoteServerEntry: ignoring unknown server entry: %s",
  435. ipAddress)
  436. return nil
  437. }
  438. bucket = tx.bucket(datastoreKeyValueBucket)
  439. err := bucket.put(datastoreAffinityServerEntryIDKey, serverEntryID)
  440. if err != nil {
  441. return errors.Trace(err)
  442. }
  443. // Store the current server entry filter (e.g, region, etc.) that
  444. // was in use when the entry was promoted. This is used to detect
  445. // when the top ranked server entry was promoted under a different
  446. // filter.
  447. currentFilter, err := makeServerEntryFilterValue(config)
  448. if err != nil {
  449. return errors.Trace(err)
  450. }
  451. err = bucket.put(datastoreLastServerEntryFilterKey, currentFilter)
  452. if err != nil {
  453. return errors.Trace(err)
  454. }
  455. return nil
  456. })
  457. if err != nil {
  458. return errors.Trace(err)
  459. }
  460. return nil
  461. }
  462. // DeleteServerEntryAffinity clears server affinity if set to the specified
  463. // server.
  464. func DeleteServerEntryAffinity(ipAddress string) error {
  465. err := datastoreUpdate(func(tx *datastoreTx) error {
  466. serverEntryID := []byte(ipAddress)
  467. bucket := tx.bucket(datastoreKeyValueBucket)
  468. affinityServerEntryID := bucket.get(datastoreAffinityServerEntryIDKey)
  469. if bytes.Equal(affinityServerEntryID, serverEntryID) {
  470. err := bucket.delete(datastoreAffinityServerEntryIDKey)
  471. if err != nil {
  472. return errors.Trace(err)
  473. }
  474. err = bucket.delete(datastoreLastServerEntryFilterKey)
  475. if err != nil {
  476. return errors.Trace(err)
  477. }
  478. }
  479. return nil
  480. })
  481. if err != nil {
  482. return errors.Trace(err)
  483. }
  484. return nil
  485. }
  486. // GetLastServerEntryCount returns a generalized number of server entries in
  487. // the datastore recorded by the last ServerEntryIterator New/Reset call.
  488. // Similar to last_connected and persistent stats timestamps, the count is
  489. // rounded to avoid a potentially unique client fingerprint. The return value
  490. // is -1 if no count has been recorded.
  491. func GetLastServerEntryCount() int {
  492. return roundServerEntryCount(int(datastoreLastServerEntryCount.Load()))
  493. }
  494. func roundServerEntryCount(count int) int {
  495. if count <= 0 {
  496. // Return -1 (no count) and 0 (no server entries) as-is.
  497. return count
  498. }
  499. n := protocol.ServerEntryCountRoundingIncrement
  500. // Round up to the nearest ServerEntryCountRoundingIncrement.
  501. return ((count + (n - 1)) / n) * n
  502. }
  503. func makeServerEntryFilterValue(config *Config) ([]byte, error) {
  504. // Currently, only a change of EgressRegion will "break" server affinity.
  505. // If the tunnel protocol filter changes, any existing affinity server
  506. // either passes the new filter, or it will be skipped anyway.
  507. return []byte(config.EgressRegion), nil
  508. }
  509. func hasServerEntryFilterChanged(config *Config) (bool, error) {
  510. currentFilter, err := makeServerEntryFilterValue(config)
  511. if err != nil {
  512. return false, errors.Trace(err)
  513. }
  514. changed := false
  515. err = datastoreView(func(tx *datastoreTx) error {
  516. bucket := tx.bucket(datastoreKeyValueBucket)
  517. previousFilter := bucket.get(datastoreLastServerEntryFilterKey)
  518. // When not found, previousFilter will be nil; ensures this
  519. // results in "changed", even if currentFilter is len(0).
  520. if previousFilter == nil ||
  521. !bytes.Equal(previousFilter, currentFilter) {
  522. changed = true
  523. }
  524. return nil
  525. })
  526. if err != nil {
  527. return false, errors.Trace(err)
  528. }
  529. return changed, nil
  530. }
  531. // ServerEntryIterator is used to iterate over
  532. // stored server entries in rank order.
  533. type ServerEntryIterator struct {
  534. config *Config
  535. applyServerAffinity bool
  536. serverEntryIDs [][]byte
  537. serverEntryIndex int
  538. isTacticsServerEntryIterator bool
  539. isTargetServerEntryIterator bool
  540. isPruneServerEntryIterator bool
  541. hasNextTargetServerEntry bool
  542. targetServerEntry *protocol.ServerEntry
  543. updateMoveToFrontMetrics bool
  544. }
  545. // NewServerEntryIterator creates a new ServerEntryIterator.
  546. //
  547. // The boolean return value indicates whether to treat the first server(s)
  548. // as affinity servers or not. When the server entry selection filter changes
  549. // such as from a specific region to any region, or when there was no previous
  550. // filter/iterator, the the first server(s) are arbitrary and should not be
  551. // given affinity treatment.
  552. //
  553. // NewServerEntryIterator and any returned ServerEntryIterator are not
  554. // designed for concurrent use as not all related datastore operations are
  555. // performed in a single transaction.
  556. func NewServerEntryIterator(config *Config) (bool, *ServerEntryIterator, error) {
  557. // When configured, this target server entry is the only candidate
  558. if config.TargetServerEntry != "" {
  559. return newTargetServerEntryIterator(config, false)
  560. }
  561. filterChanged, err := hasServerEntryFilterChanged(config)
  562. if err != nil {
  563. return false, nil, errors.Trace(err)
  564. }
  565. applyServerAffinity := !filterChanged
  566. iterator := &ServerEntryIterator{
  567. config: config,
  568. applyServerAffinity: applyServerAffinity,
  569. updateMoveToFrontMetrics: true,
  570. }
  571. err = iterator.reset(true)
  572. if err != nil {
  573. return false, nil, errors.Trace(err)
  574. }
  575. return applyServerAffinity, iterator, nil
  576. }
  577. func NewTacticsServerEntryIterator(config *Config) (*ServerEntryIterator, error) {
  578. // When configured, this target server entry is the only candidate
  579. if config.TargetServerEntry != "" {
  580. _, iterator, err := newTargetServerEntryIterator(config, true)
  581. return iterator, err
  582. }
  583. iterator := &ServerEntryIterator{
  584. config: config,
  585. isTacticsServerEntryIterator: true,
  586. }
  587. err := iterator.reset(true)
  588. if err != nil {
  589. return nil, errors.Trace(err)
  590. }
  591. return iterator, nil
  592. }
  593. func NewPruneServerEntryIterator(config *Config) (*ServerEntryIterator, error) {
  594. // There is no TargetServerEntry case when pruning.
  595. iterator := &ServerEntryIterator{
  596. config: config,
  597. isPruneServerEntryIterator: true,
  598. }
  599. err := iterator.reset(true)
  600. if err != nil {
  601. return nil, errors.Trace(err)
  602. }
  603. return iterator, nil
  604. }
  605. // newTargetServerEntryIterator is a helper for initializing the TargetServerEntry case
  606. func newTargetServerEntryIterator(config *Config, isTactics bool) (bool, *ServerEntryIterator, error) {
  607. serverEntry, err := protocol.DecodeServerEntry(
  608. config.TargetServerEntry, config.loadTimestamp, protocol.SERVER_ENTRY_SOURCE_TARGET)
  609. if err != nil {
  610. return false, nil, errors.Trace(err)
  611. }
  612. if serverEntry.Tag == "" {
  613. serverEntry.Tag = protocol.GenerateServerEntryTag(
  614. serverEntry.IpAddress, serverEntry.WebServerSecret)
  615. }
  616. if isTactics {
  617. if len(serverEntry.GetSupportedTacticsProtocols()) == 0 {
  618. return false, nil, errors.TraceNew("TargetServerEntry does not support tactics protocols")
  619. }
  620. } else {
  621. if config.EgressRegion != "" && serverEntry.Region != config.EgressRegion {
  622. return false, nil, errors.TraceNew("TargetServerEntry does not support EgressRegion")
  623. }
  624. p := config.GetParameters().Get()
  625. limitTunnelProtocols := p.TunnelProtocols(parameters.LimitTunnelProtocols)
  626. limitTunnelDialPortNumbers := protocol.TunnelProtocolPortLists(
  627. p.TunnelProtocolPortLists(parameters.LimitTunnelDialPortNumbers))
  628. limitQUICVersions := p.QUICVersions(parameters.LimitQUICVersions)
  629. if len(limitTunnelProtocols) > 0 {
  630. // At the ServerEntryIterator level, only limitTunnelProtocols is applied;
  631. // excludeIntensive and excludeInproxt are handled higher up.
  632. if len(serverEntry.GetSupportedProtocols(
  633. conditionallyEnabledComponents{},
  634. config.UseUpstreamProxy(),
  635. limitTunnelProtocols,
  636. limitTunnelDialPortNumbers,
  637. limitQUICVersions,
  638. false)) == 0 {
  639. return false, nil, errors.Tracef(
  640. "TargetServerEntry does not support LimitTunnelProtocols: %v", limitTunnelProtocols)
  641. }
  642. }
  643. }
  644. iterator := &ServerEntryIterator{
  645. isTacticsServerEntryIterator: isTactics,
  646. isTargetServerEntryIterator: true,
  647. hasNextTargetServerEntry: true,
  648. targetServerEntry: serverEntry,
  649. updateMoveToFrontMetrics: !isTactics,
  650. }
  651. err = iterator.reset(true)
  652. if err != nil {
  653. return false, nil, errors.Trace(err)
  654. }
  655. NoticeInfo("using TargetServerEntry: %s", serverEntry.GetDiagnosticID())
  656. return false, iterator, nil
  657. }
  658. // Reset a NewServerEntryIterator to the start of its cycle. The next
  659. // call to Next will return the first server entry.
  660. func (iterator *ServerEntryIterator) Reset() error {
  661. return iterator.reset(false)
  662. }
  663. func (iterator *ServerEntryIterator) reset(isInitialRound bool) error {
  664. iterator.Close()
  665. if iterator.isTargetServerEntryIterator {
  666. iterator.hasNextTargetServerEntry = true
  667. // Provide the GetLastServerEntryCount implementation. See comment below.
  668. count := 0
  669. err := getBucketKeys(datastoreServerEntriesBucket, func(_ []byte) { count += 1 })
  670. if err != nil {
  671. return errors.Trace(err)
  672. }
  673. datastoreLastServerEntryCount.Store(int64(count))
  674. return nil
  675. }
  676. // Support stand-alone GetTactics operation. See TacticsStorer for more
  677. // details.
  678. if iterator.isTacticsServerEntryIterator {
  679. err := OpenDataStoreWithoutRetry(iterator.config)
  680. if err != nil {
  681. return errors.Trace(err)
  682. }
  683. defer CloseDataStore()
  684. }
  685. // BoltDB implementation note:
  686. // We don't keep a transaction open for the duration of the iterator
  687. // because this would expose the following semantics to consumer code:
  688. //
  689. // Read-only transactions and read-write transactions ... generally
  690. // shouldn't be opened simultaneously in the same goroutine. This can
  691. // cause a deadlock as the read-write transaction needs to periodically
  692. // re-map the data file but it cannot do so while a read-only
  693. // transaction is open.
  694. // (https://github.com/boltdb/bolt)
  695. //
  696. // So the underlying serverEntriesBucket could change after the serverEntryIDs
  697. // list is built.
  698. var serverEntryIDs [][]byte
  699. movedToFront := 0
  700. err := datastoreView(func(tx *datastoreTx) error {
  701. bucket := tx.bucket(datastoreKeyValueBucket)
  702. serverEntryIDs = make([][]byte, 0)
  703. shuffleHead := 0
  704. // The prune case, isPruneServerEntryIterator, skips all
  705. // move-to-front operations and uses a pure random shuffle in order
  706. // to uniformly select server entries to prune check. There may be a
  707. // benefit to inverting the move and move affinity and potential
  708. // replay servers to the _back_ if they're less likely to be pruned;
  709. // however, the replay logic here doesn't check the replay TTL and
  710. // even potential replay servers might be pruned.
  711. var affinityServerEntryID []byte
  712. // In the first round only, move any server affinity candiate to the
  713. // very first position.
  714. if !iterator.isPruneServerEntryIterator &&
  715. isInitialRound &&
  716. iterator.applyServerAffinity {
  717. affinityServerEntryID = bucket.get(datastoreAffinityServerEntryIDKey)
  718. if affinityServerEntryID != nil {
  719. serverEntryIDs = append(serverEntryIDs, append([]byte(nil), affinityServerEntryID...))
  720. shuffleHead = 1
  721. }
  722. }
  723. bucket = tx.bucket(datastoreServerEntriesBucket)
  724. cursor := bucket.cursor()
  725. for key := cursor.firstKey(); key != nil; key = cursor.nextKey() {
  726. if affinityServerEntryID != nil {
  727. if bytes.Equal(affinityServerEntryID, key) {
  728. continue
  729. }
  730. }
  731. serverEntryIDs = append(serverEntryIDs, append([]byte(nil), key...))
  732. }
  733. cursor.close()
  734. // Provide the GetLastServerEntryCount implementation. This snapshot
  735. // of the number of server entries in the datastore is used for
  736. // metrics; a snapshot is recorded here to avoid the overhead of
  737. // datastore scans or operations when the metric is logged.
  738. datastoreLastServerEntryCount.Store(int64(len(serverEntryIDs)))
  739. // Randomly shuffle the entire list of server IDs, excluding the
  740. // server affinity candidate.
  741. for i := len(serverEntryIDs) - 1; i > shuffleHead-1; i-- {
  742. j := prng.Intn(i+1-shuffleHead) + shuffleHead
  743. serverEntryIDs[i], serverEntryIDs[j] = serverEntryIDs[j], serverEntryIDs[i]
  744. }
  745. // In the first round, or with some probability, move _potential_ replay
  746. // candidates to the front of the list (excepting the server affinity slot,
  747. // if any). This move is post-shuffle so the order is still randomized. To
  748. // save the memory overhead of unmarshaling all dial parameters, this
  749. // operation just moves any server with a dial parameter record to the
  750. // front. Whether the dial parameter remains valid for replay -- TTL,
  751. // tactics/config unchanged, etc. --- is checked later.
  752. //
  753. // TODO: move only up to parameters.ReplayCandidateCount to front?
  754. // The DSLPendingPrioritizeDial case also implicitly assumes that mere
  755. // existence of dial parameters will move server entries to the front
  756. // of the list. See MakeDialParameters and doDSLFetch for more
  757. // details about the DSLPendingPrioritizeDial scheme.
  758. //
  759. // Limitation: the move-to-front could be balanced beween
  760. // DSLPendingPrioritizeDial and regular replay cases, however that
  761. // would require unmarshaling all dial parameters, which we are avoiding.
  762. p := iterator.config.GetParameters().Get()
  763. replayCandidateCount := p.Int(parameters.ReplayCandidateCount)
  764. moveToFrontProbability := p.Float(parameters.ReplayLaterRoundMoveToFrontProbability)
  765. maxMoveToFront := p.Int(parameters.ServerEntryIteratorMaxMoveToFront)
  766. p.Close()
  767. if !iterator.isPruneServerEntryIterator &&
  768. (isInitialRound || prng.FlipWeightedCoin(moveToFrontProbability)) &&
  769. replayCandidateCount != 0 &&
  770. maxMoveToFront != 0 {
  771. networkID := []byte(iterator.config.GetNetworkID())
  772. dialParamsBucket := tx.bucket(datastoreDialParametersBucket)
  773. i := shuffleHead
  774. j := len(serverEntryIDs) - 1
  775. for {
  776. if maxMoveToFront >= 0 && movedToFront >= maxMoveToFront {
  777. break
  778. }
  779. for ; i < j; i++ {
  780. key := makeDialParametersKey(serverEntryIDs[i], networkID)
  781. if dialParamsBucket.get(key) == nil {
  782. break
  783. }
  784. }
  785. for ; i < j; j-- {
  786. key := makeDialParametersKey(serverEntryIDs[j], networkID)
  787. if dialParamsBucket.get(key) != nil {
  788. break
  789. }
  790. }
  791. if i < j {
  792. serverEntryIDs[i], serverEntryIDs[j] = serverEntryIDs[j], serverEntryIDs[i]
  793. movedToFront += 1
  794. i++
  795. j--
  796. } else {
  797. break
  798. }
  799. }
  800. }
  801. return nil
  802. })
  803. if err != nil {
  804. return errors.Trace(err)
  805. }
  806. iterator.serverEntryIDs = serverEntryIDs
  807. iterator.serverEntryIndex = 0
  808. if iterator.updateMoveToFrontMetrics {
  809. updater := iterator.config.GetServerEntryIterationMetricsUpdater()
  810. if updater != nil {
  811. updater(movedToFront)
  812. }
  813. }
  814. return nil
  815. }
  816. // Close cleans up resources associated with a ServerEntryIterator.
  817. func (iterator *ServerEntryIterator) Close() {
  818. iterator.serverEntryIDs = nil
  819. iterator.serverEntryIndex = 0
  820. }
  821. // Next returns the next server entry, by rank, for a ServerEntryIterator.
  822. // Returns nil with no error when there is no next item.
  823. func (iterator *ServerEntryIterator) Next() (*protocol.ServerEntry, error) {
  824. var serverEntry *protocol.ServerEntry
  825. var err error
  826. defer func() {
  827. if err != nil {
  828. iterator.Close()
  829. }
  830. }()
  831. if iterator.isTargetServerEntryIterator {
  832. if iterator.hasNextTargetServerEntry {
  833. iterator.hasNextTargetServerEntry = false
  834. return MakeCompatibleServerEntry(iterator.targetServerEntry), nil
  835. }
  836. return nil, nil
  837. }
  838. // Support stand-alone GetTactics operation. See TacticsStorer for more
  839. // details.
  840. if iterator.isTacticsServerEntryIterator {
  841. err := OpenDataStoreWithoutRetry(iterator.config)
  842. if err != nil {
  843. return nil, errors.Trace(err)
  844. }
  845. defer CloseDataStore()
  846. }
  847. // There are no region/protocol indexes for the server entries bucket.
  848. // Loop until we have the next server entry that matches the iterator
  849. // filter requirements.
  850. for {
  851. if iterator.serverEntryIndex >= len(iterator.serverEntryIDs) {
  852. // There is no next item
  853. return nil, nil
  854. }
  855. serverEntryID := iterator.serverEntryIDs[iterator.serverEntryIndex]
  856. iterator.serverEntryIndex += 1
  857. serverEntry = nil
  858. doDeleteServerEntry := false
  859. err = datastoreView(func(tx *datastoreTx) error {
  860. serverEntries := tx.bucket(datastoreServerEntriesBucket)
  861. value := serverEntries.get(serverEntryID)
  862. if value == nil {
  863. return nil
  864. }
  865. // When the server entry has a signature and the signature verification
  866. // public key is configured, perform a signature verification, which will
  867. // detect data corruption of most server entry fields. When the check
  868. // fails, the server entry is deleted and skipped and iteration continues.
  869. //
  870. // This prevents wasteful, time-consuming dials in cases where the server
  871. // entry is intact except for a bit flip in the obfuscation key, for
  872. // example. A delete is triggered also in the case where the server entry
  873. // record fails to unmarshal.
  874. if iterator.config.ServerEntrySignaturePublicKey != "" {
  875. var serverEntryFields protocol.ServerEntryFields
  876. err = json.Unmarshal(value, &serverEntryFields)
  877. if err != nil {
  878. doDeleteServerEntry = true
  879. NoticeWarning(
  880. "ServerEntryIterator.Next: unmarshal failed: %s",
  881. errors.Trace(err))
  882. // Do not stop iterating.
  883. return nil
  884. }
  885. if serverEntryFields.HasSignature() {
  886. err = serverEntryFields.VerifySignature(
  887. iterator.config.ServerEntrySignaturePublicKey)
  888. if err != nil {
  889. doDeleteServerEntry = true
  890. NoticeWarning(
  891. "ServerEntryIterator.Next: verify signature failed: %s",
  892. errors.Trace(err))
  893. // Do not stop iterating.
  894. return nil
  895. }
  896. }
  897. }
  898. // Must unmarshal here as slice is only valid within transaction.
  899. err = json.Unmarshal(value, &serverEntry)
  900. if err != nil {
  901. serverEntry = nil
  902. doDeleteServerEntry = true
  903. NoticeWarning(
  904. "ServerEntryIterator.Next: unmarshal failed: %s",
  905. errors.Trace(err))
  906. // Do not stop iterating.
  907. return nil
  908. }
  909. return nil
  910. })
  911. if err != nil {
  912. return nil, errors.Trace(err)
  913. }
  914. if doDeleteServerEntry {
  915. err := deleteServerEntry(iterator.config, serverEntryID)
  916. if err != nil {
  917. NoticeWarning(
  918. "ServerEntryIterator.Next: deleteServerEntry failed: %s",
  919. errors.Trace(err))
  920. }
  921. continue
  922. }
  923. if serverEntry == nil {
  924. // In case of data corruption or a bug causing this condition,
  925. // do not stop iterating.
  926. NoticeWarning("ServerEntryIterator.Next: unexpected missing server entry")
  927. continue
  928. }
  929. // Generate a derived server entry tag for server entries with no tag. Store
  930. // back the updated server entry so that (a) the tag doesn't need to be
  931. // regenerated; (b) the server entry can be looked up by tag (currently used
  932. // in the status request prune case).
  933. //
  934. // This is a distinct transaction so as to avoid the overhead of regular
  935. // write transactions in the iterator; once tags have been stored back, most
  936. // iterator transactions will remain read-only.
  937. if serverEntry.Tag == "" {
  938. serverEntry.Tag = protocol.GenerateServerEntryTag(
  939. serverEntry.IpAddress, serverEntry.WebServerSecret)
  940. err = datastoreUpdate(func(tx *datastoreTx) error {
  941. serverEntries := tx.bucket(datastoreServerEntriesBucket)
  942. serverEntryTags := tx.bucket(datastoreServerEntryTagsBucket)
  943. // We must reload and store back the server entry _fields_ to preserve any
  944. // currently unrecognized fields, for future compatibility.
  945. value := serverEntries.get(serverEntryID)
  946. if value == nil {
  947. return nil
  948. }
  949. var serverEntryFields protocol.ServerEntryFields
  950. err := json.Unmarshal(value, &serverEntryFields)
  951. if err != nil {
  952. return errors.Trace(err)
  953. }
  954. // As there is minor race condition between loading/checking serverEntry
  955. // and reloading/modifying serverEntryFields, this transaction references
  956. // only the freshly loaded fields when checking and setting the tag.
  957. serverEntryTag := serverEntryFields.GetTag()
  958. if serverEntryTag != "" {
  959. return nil
  960. }
  961. serverEntryTag = protocol.GenerateServerEntryTag(
  962. serverEntryFields.GetIPAddress(),
  963. serverEntryFields.GetWebServerSecret())
  964. serverEntryFields.SetTag(serverEntryTag)
  965. jsonServerEntryFields, err := json.Marshal(serverEntryFields)
  966. if err != nil {
  967. return errors.Trace(err)
  968. }
  969. err = serverEntries.put(serverEntryID, jsonServerEntryFields)
  970. if err != nil {
  971. return errors.Trace(err)
  972. }
  973. serverEntryTagRecord, err := setServerEntryTagRecord(
  974. []byte(serverEntryTag),
  975. serverEntryFields.GetConfigurationVersion())
  976. if err != nil {
  977. return errors.Trace(err)
  978. }
  979. err = serverEntryTags.put([]byte(serverEntryTag), serverEntryTagRecord)
  980. if err != nil {
  981. return errors.Trace(err)
  982. }
  983. return nil
  984. })
  985. if err != nil {
  986. // Do not stop.
  987. NoticeWarning(
  988. "ServerEntryIterator.Next: update server entry failed: %s",
  989. errors.Trace(err))
  990. }
  991. }
  992. if iterator.serverEntryIndex%datastoreServerEntryFetchGCThreshold == 0 {
  993. DoGarbageCollection()
  994. }
  995. // Check filter requirements
  996. if iterator.isPruneServerEntryIterator {
  997. // No region filter for the prune case.
  998. break
  999. } else if iterator.isTacticsServerEntryIterator {
  1000. // Tactics doesn't filter by egress region.
  1001. if len(serverEntry.GetSupportedTacticsProtocols()) > 0 {
  1002. break
  1003. }
  1004. } else {
  1005. if iterator.config.EgressRegion == "" ||
  1006. serverEntry.Region == iterator.config.EgressRegion {
  1007. break
  1008. }
  1009. }
  1010. }
  1011. return MakeCompatibleServerEntry(serverEntry), nil
  1012. }
  1013. // MakeCompatibleServerEntry provides backwards compatibility with old server entries
  1014. // which have a single meekFrontingDomain and not a meekFrontingAddresses array.
  1015. // By copying this one meekFrontingDomain into meekFrontingAddresses, this client effectively
  1016. // uses that single value as legacy clients do.
  1017. func MakeCompatibleServerEntry(serverEntry *protocol.ServerEntry) *protocol.ServerEntry {
  1018. if len(serverEntry.MeekFrontingAddresses) == 0 && serverEntry.MeekFrontingDomain != "" {
  1019. serverEntry.MeekFrontingAddresses =
  1020. append(serverEntry.MeekFrontingAddresses, serverEntry.MeekFrontingDomain)
  1021. }
  1022. return serverEntry
  1023. }
  1024. // PruneServerEntry deletes the server entry, along with associated data,
  1025. // corresponding to the specified server entry tag. Pruning is subject to an
  1026. // age check. In the case of an error, a notice is emitted.
  1027. func PruneServerEntry(config *Config, serverEntryTag string) bool {
  1028. pruned, err := pruneServerEntry(config, serverEntryTag)
  1029. if err != nil {
  1030. NoticeWarning(
  1031. "PruneServerEntry failed: %s: %s",
  1032. serverEntryTag, errors.Trace(err))
  1033. return false
  1034. }
  1035. if pruned {
  1036. NoticePruneServerEntry(serverEntryTag)
  1037. }
  1038. return pruned
  1039. }
  1040. func pruneServerEntry(config *Config, serverEntryTag string) (bool, error) {
  1041. minimumAgeForPruning := config.GetParameters().Get().Duration(
  1042. parameters.ServerEntryMinimumAgeForPruning)
  1043. pruned := false
  1044. err := datastoreUpdate(func(tx *datastoreTx) error {
  1045. serverEntries := tx.bucket(datastoreServerEntriesBucket)
  1046. serverEntryTags := tx.bucket(datastoreServerEntryTagsBucket)
  1047. serverEntryTombstoneTags := tx.bucket(datastoreServerEntryTombstoneTagsBucket)
  1048. keyValues := tx.bucket(datastoreKeyValueBucket)
  1049. dialParameters := tx.bucket(datastoreDialParametersBucket)
  1050. serverEntryTagBytes := []byte(serverEntryTag)
  1051. serverEntryTagRecord := serverEntryTags.get(serverEntryTagBytes)
  1052. if serverEntryTagRecord == nil {
  1053. return errors.TraceNew("server entry tag not found")
  1054. }
  1055. serverEntryID, _, err := getServerEntryTagRecord(serverEntryTagRecord)
  1056. if err != nil {
  1057. return errors.Trace(err)
  1058. }
  1059. serverEntryJson := serverEntries.get(serverEntryID)
  1060. if serverEntryJson == nil {
  1061. return errors.TraceNew("server entry not found")
  1062. }
  1063. var serverEntry *protocol.ServerEntry
  1064. err = json.Unmarshal(serverEntryJson, &serverEntry)
  1065. if err != nil {
  1066. return errors.Trace(err)
  1067. }
  1068. // Only prune sufficiently old server entries. This mitigates the case where
  1069. // stale data in psiphond will incorrectly identify brand new servers as
  1070. // being invalid/deleted.
  1071. serverEntryLocalTimestamp, err := time.Parse(time.RFC3339, serverEntry.LocalTimestamp)
  1072. if err != nil {
  1073. return errors.Trace(err)
  1074. }
  1075. if serverEntryLocalTimestamp.Add(minimumAgeForPruning).After(time.Now()) {
  1076. return nil
  1077. }
  1078. // Handle the server IP recycle case where multiple serverEntryTags records
  1079. // refer to the same server IP. Only delete the server entry record when its
  1080. // tag matches the pruned tag. Otherwise, the server entry record is
  1081. // associated with another tag. The pruned tag is still deleted.
  1082. doDeleteServerEntry := (serverEntry.Tag == serverEntryTag)
  1083. err = serverEntryTags.delete(serverEntryTagBytes)
  1084. if err != nil {
  1085. return errors.Trace(err)
  1086. }
  1087. if doDeleteServerEntry {
  1088. err = deleteServerEntryHelper(
  1089. config,
  1090. serverEntryID,
  1091. serverEntries,
  1092. keyValues,
  1093. dialParameters)
  1094. if err != nil {
  1095. return errors.Trace(err)
  1096. }
  1097. }
  1098. // Tombstones prevent reimporting pruned server entries. Tombstone
  1099. // identifiers are tags, which are derived from the web server secret in
  1100. // addition to the server IP, so tombstones will not clobber recycled server
  1101. // IPs as long as new web server secrets are generated in the recycle case.
  1102. //
  1103. // Tombstones are set only for embedded server entries, as all other sources
  1104. // are expected to provide valid server entries; this also provides a fail-
  1105. // safe mechanism to restore pruned server entries through all non-embedded
  1106. // sources.
  1107. if serverEntry.LocalSource == protocol.SERVER_ENTRY_SOURCE_EMBEDDED {
  1108. err = serverEntryTombstoneTags.put(serverEntryTagBytes, []byte{1})
  1109. if err != nil {
  1110. return errors.Trace(err)
  1111. }
  1112. }
  1113. pruned = true
  1114. return nil
  1115. })
  1116. return pruned, errors.Trace(err)
  1117. }
  1118. // DeleteServerEntry deletes the specified server entry and associated data.
  1119. func DeleteServerEntry(config *Config, ipAddress string) {
  1120. serverEntryID := []byte(ipAddress)
  1121. // For notices, we cannot assume we have a valid server entry tag value to
  1122. // log, as DeleteServerEntry is called when a server entry fails to unmarshal
  1123. // or fails signature verification.
  1124. err := deleteServerEntry(config, serverEntryID)
  1125. if err != nil {
  1126. NoticeWarning("DeleteServerEntry failed: %s", errors.Trace(err))
  1127. return
  1128. }
  1129. NoticeInfo("Server entry deleted")
  1130. }
  1131. func deleteServerEntry(config *Config, serverEntryID []byte) error {
  1132. return datastoreUpdate(func(tx *datastoreTx) error {
  1133. serverEntries := tx.bucket(datastoreServerEntriesBucket)
  1134. serverEntryTags := tx.bucket(datastoreServerEntryTagsBucket)
  1135. keyValues := tx.bucket(datastoreKeyValueBucket)
  1136. dialParameters := tx.bucket(datastoreDialParametersBucket)
  1137. err := deleteServerEntryHelper(
  1138. config,
  1139. serverEntryID,
  1140. serverEntries,
  1141. keyValues,
  1142. dialParameters)
  1143. if err != nil {
  1144. return errors.Trace(err)
  1145. }
  1146. // Remove any tags pointing to the deleted server entry.
  1147. var deleteKeys [][]byte
  1148. cursor := serverEntryTags.cursor()
  1149. for key, value := cursor.first(); key != nil; key, value = cursor.next() {
  1150. if bytes.Equal(value, serverEntryID) {
  1151. deleteKeys = append(deleteKeys, key)
  1152. }
  1153. }
  1154. cursor.close()
  1155. // Mutate bucket only after cursor is closed.
  1156. //
  1157. // TODO: expose boltdb Cursor.Delete to allow for safe mutation
  1158. // within cursor loop.
  1159. for _, deleteKey := range deleteKeys {
  1160. err := serverEntryTags.delete(deleteKey)
  1161. if err != nil {
  1162. return errors.Trace(err)
  1163. }
  1164. }
  1165. return nil
  1166. })
  1167. }
  1168. func deleteServerEntryHelper(
  1169. config *Config,
  1170. serverEntryID []byte,
  1171. serverEntries *datastoreBucket,
  1172. keyValues *datastoreBucket,
  1173. dialParameters *datastoreBucket) error {
  1174. err := serverEntries.delete(serverEntryID)
  1175. if err != nil {
  1176. return errors.Trace(err)
  1177. }
  1178. affinityServerEntryID := keyValues.get(datastoreAffinityServerEntryIDKey)
  1179. if bytes.Equal(affinityServerEntryID, serverEntryID) {
  1180. err = keyValues.delete(datastoreAffinityServerEntryIDKey)
  1181. if err != nil {
  1182. return errors.Trace(err)
  1183. }
  1184. err = keyValues.delete(datastoreLastServerEntryFilterKey)
  1185. if err != nil {
  1186. return errors.Trace(err)
  1187. }
  1188. }
  1189. // Each dial parameters key has serverID as a prefix; see
  1190. // makeDialParametersKey. There may be multiple keys with the
  1191. // serverEntryID prefix; they will be grouped together, so the loop can
  1192. // exit as soon as a previously found prefix is no longer found.
  1193. foundFirstMatch := false
  1194. // TODO: expose boltdb Seek functionality to skip to first matching record.
  1195. var deleteKeys [][]byte
  1196. cursor := dialParameters.cursor()
  1197. for key, _ := cursor.first(); key != nil; key, _ = cursor.next() {
  1198. if bytes.HasPrefix(key, serverEntryID) {
  1199. foundFirstMatch = true
  1200. deleteKeys = append(deleteKeys, key)
  1201. } else if foundFirstMatch {
  1202. break
  1203. }
  1204. }
  1205. cursor.close()
  1206. // Mutate bucket only after cursor is closed.
  1207. //
  1208. // TODO: expose boltdb Cursor.Delete to allow for safe mutation
  1209. // within cursor loop.
  1210. for _, deleteKey := range deleteKeys {
  1211. err := dialParameters.delete(deleteKey)
  1212. if err != nil {
  1213. return errors.Trace(err)
  1214. }
  1215. }
  1216. return nil
  1217. }
  1218. // ScanServerEntries iterates over all stored server entries, unmarshals each,
  1219. // and passes it to callback for processing. If callback returns false, the
  1220. // iteration is cancelled and an error is returned.
  1221. //
  1222. // ScanServerEntries may be slow to execute, particularly for older devices
  1223. // and/or very large server lists. Callers should avoid blocking on
  1224. // ScanServerEntries where possible; and use the cancel option to interrupt
  1225. // scans that are no longer required.
  1226. func ScanServerEntries(callback func(*protocol.ServerEntry) bool) error {
  1227. // TODO: this operation can be sped up (by a factor of ~2x, in one test
  1228. // scenario) by using a faster JSON implementation
  1229. // (https://github.com/json-iterator/go) and increasing
  1230. // datastoreServerEntryFetchGCThreshold.
  1231. //
  1232. // json-iterator increases the binary code size significantly, which affects
  1233. // memory limit accounting on some platforms, so it's not clear we can use it
  1234. // universally. Similarly, tuning datastoreServerEntryFetchGCThreshold has a
  1235. // memory limit tradeoff.
  1236. //
  1237. // Since ScanServerEntries is now called asynchronously and doesn't block
  1238. // establishment at all, we can tolerate its slower performance. Other
  1239. // bulk-JSON operations such as [Streaming]StoreServerEntries also benefit
  1240. // from using a faster JSON implementation, but the relative performance
  1241. // increase is far smaller as import times are dominated by data store write
  1242. // transaction overhead. Other operations such as ServerEntryIterator
  1243. // amortize the cost of JSON unmarshalling over many other operations.
  1244. err := datastoreView(func(tx *datastoreTx) error {
  1245. bucket := tx.bucket(datastoreServerEntriesBucket)
  1246. cursor := bucket.cursor()
  1247. n := 0
  1248. for key, value := cursor.first(); key != nil; key, value = cursor.next() {
  1249. var serverEntry *protocol.ServerEntry
  1250. err := json.Unmarshal(value, &serverEntry)
  1251. if err != nil {
  1252. // In case of data corruption or a bug causing this condition,
  1253. // do not stop iterating.
  1254. NoticeWarning("ScanServerEntries: %s", errors.Trace(err))
  1255. continue
  1256. }
  1257. if !callback(serverEntry) {
  1258. cursor.close()
  1259. return errors.TraceNew("scan cancelled")
  1260. }
  1261. n += 1
  1262. if n == datastoreServerEntryFetchGCThreshold {
  1263. DoGarbageCollection()
  1264. n = 0
  1265. }
  1266. }
  1267. cursor.close()
  1268. return nil
  1269. })
  1270. if err != nil {
  1271. return errors.Trace(err)
  1272. }
  1273. return nil
  1274. }
  1275. // HasServerEntries returns a bool indicating if the data store contains at
  1276. // least one server entry. This is a faster operation than CountServerEntries.
  1277. // On failure, HasServerEntries returns false.
  1278. func HasServerEntries() bool {
  1279. hasServerEntries := false
  1280. err := datastoreView(func(tx *datastoreTx) error {
  1281. bucket := tx.bucket(datastoreServerEntriesBucket)
  1282. cursor := bucket.cursor()
  1283. key, _ := cursor.first()
  1284. hasServerEntries = (key != nil)
  1285. cursor.close()
  1286. return nil
  1287. })
  1288. if err != nil {
  1289. NoticeWarning("HasServerEntries failed: %s", errors.Trace(err))
  1290. return false
  1291. }
  1292. return hasServerEntries
  1293. }
  1294. // CountServerEntries returns a count of stored server entries. On failure,
  1295. // CountServerEntries returns 0.
  1296. func CountServerEntries() int {
  1297. count := 0
  1298. err := datastoreView(func(tx *datastoreTx) error {
  1299. bucket := tx.bucket(datastoreServerEntriesBucket)
  1300. cursor := bucket.cursor()
  1301. for key, _ := cursor.first(); key != nil; key, _ = cursor.next() {
  1302. count += 1
  1303. }
  1304. cursor.close()
  1305. return nil
  1306. })
  1307. if err != nil {
  1308. NoticeWarning("CountServerEntries failed: %s", err)
  1309. return 0
  1310. }
  1311. return count
  1312. }
  1313. // SetUrlETag stores an ETag for the specfied URL.
  1314. // Note: input URL is treated as a string, and is not
  1315. // encoded or decoded or otherwise canonicalized.
  1316. func SetUrlETag(url, etag string) error {
  1317. err := datastoreUpdate(func(tx *datastoreTx) error {
  1318. bucket := tx.bucket(datastoreUrlETagsBucket)
  1319. err := bucket.put([]byte(url), []byte(etag))
  1320. if err != nil {
  1321. return errors.Trace(err)
  1322. }
  1323. return nil
  1324. })
  1325. if err != nil {
  1326. return errors.Trace(err)
  1327. }
  1328. return nil
  1329. }
  1330. // GetUrlETag retrieves a previously stored an ETag for the
  1331. // specfied URL. If not found, it returns an empty string value.
  1332. func GetUrlETag(url string) (string, error) {
  1333. var etag string
  1334. err := datastoreView(func(tx *datastoreTx) error {
  1335. bucket := tx.bucket(datastoreUrlETagsBucket)
  1336. etag = string(bucket.get([]byte(url)))
  1337. return nil
  1338. })
  1339. if err != nil {
  1340. return "", errors.Trace(err)
  1341. }
  1342. return etag, nil
  1343. }
  1344. // SetKeyValue stores a key/value pair.
  1345. func SetKeyValue(key, value string) error {
  1346. err := datastoreUpdate(func(tx *datastoreTx) error {
  1347. bucket := tx.bucket(datastoreKeyValueBucket)
  1348. err := bucket.put([]byte(key), []byte(value))
  1349. if err != nil {
  1350. return errors.Trace(err)
  1351. }
  1352. return nil
  1353. })
  1354. if err != nil {
  1355. return errors.Trace(err)
  1356. }
  1357. return nil
  1358. }
  1359. // GetKeyValue retrieves the value for a given key. If not found,
  1360. // it returns an empty string value.
  1361. func GetKeyValue(key string) (string, error) {
  1362. var value string
  1363. err := datastoreView(func(tx *datastoreTx) error {
  1364. bucket := tx.bucket(datastoreKeyValueBucket)
  1365. value = string(bucket.get([]byte(key)))
  1366. return nil
  1367. })
  1368. if err != nil {
  1369. return "", errors.Trace(err)
  1370. }
  1371. return value, nil
  1372. }
  1373. // Persistent stat records in the persistentStatStateUnreported
  1374. // state are available for take out.
  1375. //
  1376. // Records in the persistentStatStateReporting have been taken
  1377. // out and are pending either deletion (for a successful request)
  1378. // or change to StateUnreported (for a failed request).
  1379. //
  1380. // All persistent stat records are reverted to StateUnreported
  1381. // when the datastore is initialized at start up.
  1382. var persistentStatStateUnreported = []byte("0")
  1383. var persistentStatStateReporting = []byte("1")
  1384. var persistentStatTypes = []string{
  1385. datastorePersistentStatTypeRemoteServerList,
  1386. datastorePersistentStatTypeFailedTunnel,
  1387. }
  1388. // StorePersistentStat adds a new persistent stat record, which
  1389. // is set to StateUnreported and is an immediate candidate for
  1390. // reporting.
  1391. //
  1392. // The stat is a JSON byte array containing fields as
  1393. // required by the Psiphon server API. It's assumed that the
  1394. // JSON value contains enough unique information for the value to
  1395. // function as a key in the key/value datastore.
  1396. //
  1397. // Only up to PersistentStatsMaxStoreRecords are stored. Once this
  1398. // limit is reached, new records are discarded.
  1399. func StorePersistentStat(config *Config, statType string, stat []byte) error {
  1400. if !common.Contains(persistentStatTypes, statType) {
  1401. return errors.Tracef("invalid persistent stat type: %s", statType)
  1402. }
  1403. maxStoreRecords := config.GetParameters().Get().Int(
  1404. parameters.PersistentStatsMaxStoreRecords)
  1405. err := datastoreUpdate(func(tx *datastoreTx) error {
  1406. bucket := tx.bucket([]byte(statType))
  1407. count := 0
  1408. cursor := bucket.cursor()
  1409. for key, _ := cursor.first(); key != nil; key, _ = cursor.next() {
  1410. count++
  1411. }
  1412. cursor.close()
  1413. // TODO: assuming newer metrics are more useful, replace oldest record
  1414. // instead of discarding?
  1415. if count >= maxStoreRecords {
  1416. // Silently discard.
  1417. return nil
  1418. }
  1419. err := bucket.put(stat, persistentStatStateUnreported)
  1420. if err != nil {
  1421. return errors.Trace(err)
  1422. }
  1423. return nil
  1424. })
  1425. if err != nil {
  1426. return errors.Trace(err)
  1427. }
  1428. return nil
  1429. }
  1430. // CountUnreportedPersistentStats returns the number of persistent
  1431. // stat records in StateUnreported.
  1432. func CountUnreportedPersistentStats() int {
  1433. unreported := 0
  1434. err := datastoreView(func(tx *datastoreTx) error {
  1435. for _, statType := range persistentStatTypes {
  1436. bucket := tx.bucket([]byte(statType))
  1437. cursor := bucket.cursor()
  1438. for key, value := cursor.first(); key != nil; key, value = cursor.next() {
  1439. if bytes.Equal(value, persistentStatStateUnreported) {
  1440. unreported++
  1441. }
  1442. }
  1443. cursor.close()
  1444. }
  1445. return nil
  1446. })
  1447. if err != nil {
  1448. NoticeWarning("CountUnreportedPersistentStats failed: %s", err)
  1449. return 0
  1450. }
  1451. return unreported
  1452. }
  1453. // TakeOutUnreportedPersistentStats returns persistent stats records that are
  1454. // in StateUnreported. At least one record, if present, will be returned and
  1455. // then additional records up to PersistentStatsMaxSendBytes. The records are
  1456. // set to StateReporting. If the records are successfully reported, clear them
  1457. // with ClearReportedPersistentStats. If the records are not successfully
  1458. // reported, restore them with PutBackUnreportedPersistentStats.
  1459. func TakeOutUnreportedPersistentStats(
  1460. config *Config,
  1461. adjustMaxSendBytes int) (map[string][][]byte, int, error) {
  1462. // TODO: add a failsafe like disableCheckServerEntryTags, to avoid repeatedly resending
  1463. // persistent stats in the case of a local error? Also consider just dropping persistent stats
  1464. // which fail to send due to a network disconnection, rather than invoking
  1465. // PutBackUnreportedPersistentStats -- especially if it's likely that the server received the
  1466. // stats and the disconnection occurs just before the request is acknowledged.
  1467. stats := make(map[string][][]byte)
  1468. maxSendBytes := config.GetParameters().Get().Int(
  1469. parameters.PersistentStatsMaxSendBytes)
  1470. maxSendBytes -= adjustMaxSendBytes
  1471. sendBytes := 0
  1472. err := datastoreUpdate(func(tx *datastoreTx) error {
  1473. for _, statType := range persistentStatTypes {
  1474. bucket := tx.bucket([]byte(statType))
  1475. var deleteKeys [][]byte
  1476. cursor := bucket.cursor()
  1477. for key, value := cursor.first(); key != nil; key, value = cursor.next() {
  1478. // Perform a test JSON unmarshaling. In case of data corruption or a bug,
  1479. // attempt to delete and skip the record.
  1480. var jsonData interface{}
  1481. err := json.Unmarshal(key, &jsonData)
  1482. if err != nil {
  1483. NoticeWarning(
  1484. "Invalid key in TakeOutUnreportedPersistentStats: %s: %s",
  1485. string(key), err)
  1486. deleteKeys = append(deleteKeys, key)
  1487. continue
  1488. }
  1489. if bytes.Equal(value, persistentStatStateUnreported) {
  1490. // Must make a copy as slice is only valid within transaction.
  1491. data := make([]byte, len(key))
  1492. copy(data, key)
  1493. if stats[statType] == nil {
  1494. stats[statType] = make([][]byte, 0)
  1495. }
  1496. stats[statType] = append(stats[statType], data)
  1497. sendBytes += len(data)
  1498. if sendBytes >= maxSendBytes {
  1499. break
  1500. }
  1501. }
  1502. }
  1503. cursor.close()
  1504. // Mutate bucket only after cursor is closed.
  1505. for _, deleteKey := range deleteKeys {
  1506. _ = bucket.delete(deleteKey)
  1507. }
  1508. for _, key := range stats[statType] {
  1509. err := bucket.put(key, persistentStatStateReporting)
  1510. if err != nil {
  1511. return errors.Trace(err)
  1512. }
  1513. }
  1514. }
  1515. return nil
  1516. })
  1517. if err != nil {
  1518. return nil, 0, errors.Trace(err)
  1519. }
  1520. return stats, sendBytes, nil
  1521. }
  1522. // PutBackUnreportedPersistentStats restores a list of persistent
  1523. // stat records to StateUnreported.
  1524. func PutBackUnreportedPersistentStats(stats map[string][][]byte) error {
  1525. err := datastoreUpdate(func(tx *datastoreTx) error {
  1526. for _, statType := range persistentStatTypes {
  1527. bucket := tx.bucket([]byte(statType))
  1528. for _, key := range stats[statType] {
  1529. err := bucket.put(key, persistentStatStateUnreported)
  1530. if err != nil {
  1531. return errors.Trace(err)
  1532. }
  1533. }
  1534. }
  1535. return nil
  1536. })
  1537. if err != nil {
  1538. return errors.Trace(err)
  1539. }
  1540. return nil
  1541. }
  1542. // ClearReportedPersistentStats deletes a list of persistent
  1543. // stat records that were successfully reported.
  1544. func ClearReportedPersistentStats(stats map[string][][]byte) error {
  1545. err := datastoreUpdate(func(tx *datastoreTx) error {
  1546. for _, statType := range persistentStatTypes {
  1547. bucket := tx.bucket([]byte(statType))
  1548. for _, key := range stats[statType] {
  1549. err := bucket.delete(key)
  1550. if err != nil {
  1551. return err
  1552. }
  1553. }
  1554. }
  1555. return nil
  1556. })
  1557. if err != nil {
  1558. return errors.Trace(err)
  1559. }
  1560. return nil
  1561. }
  1562. // resetAllPersistentStatsToUnreported sets all persistent stat
  1563. // records to StateUnreported. This reset is called when the
  1564. // datastore is initialized at start up, as we do not know if
  1565. // persistent records in StateReporting were reported or not.
  1566. func resetAllPersistentStatsToUnreported() error {
  1567. err := datastoreUpdate(func(tx *datastoreTx) error {
  1568. for _, statType := range persistentStatTypes {
  1569. bucket := tx.bucket([]byte(statType))
  1570. resetKeys := make([][]byte, 0)
  1571. cursor := bucket.cursor()
  1572. for key := cursor.firstKey(); key != nil; key = cursor.nextKey() {
  1573. resetKeys = append(resetKeys, key)
  1574. }
  1575. cursor.close()
  1576. // TODO: data mutation is done outside cursor. Is this
  1577. // strictly necessary in this case? As is, this means
  1578. // all stats need to be loaded into memory at once.
  1579. // https://godoc.org/github.com/boltdb/bolt#Cursor
  1580. for _, key := range resetKeys {
  1581. err := bucket.put(key, persistentStatStateUnreported)
  1582. if err != nil {
  1583. return errors.Trace(err)
  1584. }
  1585. }
  1586. }
  1587. return nil
  1588. })
  1589. if err != nil {
  1590. return errors.Trace(err)
  1591. }
  1592. return nil
  1593. }
  1594. // IsCheckServerEntryTagsDue indicates that a new prune check is due, based on
  1595. // the time of the previous check ending.
  1596. func IsCheckServerEntryTagsDue(config *Config) bool {
  1597. // disableCheckServerEntryTags is a failsafe, enabled in error cases below
  1598. // and in UpdateCheckServerEntryTagsEndTime to prevent constantly
  1599. // resending prune check payloads if the scheduling mechanism fails.
  1600. if disableCheckServerEntryTags.Load() {
  1601. return false
  1602. }
  1603. // Whether the next check is due is based on time elapsed since the time
  1604. // of the previous check ending, with the elapsed time set in tactics.
  1605. // The previous end time, rather the next due time, is stored, to allow
  1606. // changes to this tactic to have immediate effect.
  1607. p := config.GetParameters().Get()
  1608. enabled := p.Bool(parameters.CheckServerEntryTagsEnabled)
  1609. checkPeriod := p.Duration(parameters.CheckServerEntryTagsPeriod)
  1610. p.Close()
  1611. if !enabled {
  1612. return false
  1613. }
  1614. lastEndTime, err := getTimeKeyValue(datastoreCheckServerEntryTagsEndTimeKey)
  1615. if err != nil {
  1616. NoticeWarning("IsCheckServerEntryTagsDue getTimeKeyValue failed: %s", errors.Trace(err))
  1617. disableCheckServerEntryTags.Store(true)
  1618. return false
  1619. }
  1620. return lastEndTime.IsZero() || time.Now().After(lastEndTime.Add(checkPeriod))
  1621. }
  1622. // UpdateCheckServerEntryTagsEndTime should be called after a prune check is
  1623. // complete. The end time is set, extending the time until the next check,
  1624. // unless there's a sufficiently high ratio of pruned servers from the last
  1625. // check.
  1626. func UpdateCheckServerEntryTagsEndTime(config *Config, checkCount int, pruneCount int) {
  1627. p := config.GetParameters().Get()
  1628. ratio := p.Float(parameters.CheckServerEntryTagsRepeatRatio)
  1629. minimum := p.Int(parameters.CheckServerEntryTagsRepeatMinimum)
  1630. p.Close()
  1631. // When there's a sufficiently high ratio of pruned/checked from
  1632. // the _previous_ check operation, don't mark the check as ended. This
  1633. // will result in the next status request performing another check. It's
  1634. // assumed that the ratio will decrease over the course of repeated
  1635. // checks as more server entries are pruned, and random selection for
  1636. // checking will include fewer and fewer invalid server entry tags.
  1637. //
  1638. // The rate of repeated checking is also limited by the status request
  1639. // schedule, where PsiphonAPIStatusRequestPeriodMin/Max defaults to 5-10
  1640. // minutes.
  1641. if pruneCount >= minimum && ratio > 0 && float64(pruneCount)/float64(checkCount) >= ratio {
  1642. NoticeInfo("UpdateCheckServerEntryTagsEndTime: %d/%d: repeat", pruneCount, checkCount)
  1643. return
  1644. }
  1645. err := setTimeKeyValue(datastoreCheckServerEntryTagsEndTimeKey, time.Now())
  1646. if err != nil {
  1647. NoticeWarning("UpdateCheckServerEntryTagsEndTime setTimeKeyValue failed: %s", errors.Trace(err))
  1648. disableCheckServerEntryTags.Store(true)
  1649. return
  1650. }
  1651. NoticeInfo("UpdateCheckServerEntryTagsEndTime: %d/%d: done", pruneCount, checkCount)
  1652. }
  1653. // GetCheckServerEntryTags returns a random selection of server entry tags to
  1654. // be checked for pruning. An empty list is returned if a check is not yet
  1655. // due.
  1656. func GetCheckServerEntryTags(config *Config) ([]string, int, error) {
  1657. if disableCheckServerEntryTags.Load() {
  1658. return nil, 0, nil
  1659. }
  1660. if !IsCheckServerEntryTagsDue(config) {
  1661. return nil, 0, nil
  1662. }
  1663. // maxSendBytes is intended to limit the request memory overhead and
  1664. // network size. maxWorkTime ensures that slow devices -- with datastore
  1665. // operations and JSON unmarshaling particularly slow -- will launch a
  1666. // request in a timely fashion.
  1667. p := config.GetParameters().Get()
  1668. maxSendBytes := p.Int(parameters.CheckServerEntryTagsMaxSendBytes)
  1669. maxWorkTime := p.Duration(parameters.CheckServerEntryTagsMaxWorkTime)
  1670. minimumAgeForPruning := p.Duration(parameters.ServerEntryMinimumAgeForPruning)
  1671. p.Close()
  1672. iterator, err := NewPruneServerEntryIterator(config)
  1673. if err != nil {
  1674. return nil, 0, errors.Trace(err)
  1675. }
  1676. var checkTags []string
  1677. bytes := 0
  1678. startWork := time.Now()
  1679. for {
  1680. serverEntry, err := iterator.Next()
  1681. if err != nil {
  1682. return nil, 0, errors.Trace(err)
  1683. }
  1684. if serverEntry == nil {
  1685. break
  1686. }
  1687. // Skip checking the server entry if PruneServerEntry won't prune it
  1688. // anyway, due to ServerEntryMinimumAgeForPruning.
  1689. serverEntryLocalTimestamp, err := time.Parse(time.RFC3339, serverEntry.LocalTimestamp)
  1690. if err != nil {
  1691. return nil, 0, errors.Trace(err)
  1692. }
  1693. if serverEntryLocalTimestamp.Add(minimumAgeForPruning).After(time.Now()) {
  1694. continue
  1695. }
  1696. // Server entries with replay records are not skipped. It's possible that replay records are
  1697. // retained, due to ReplayRetainFailedProbability, even if the server entry is no longer
  1698. // valid. Inspecting replay would also require an additional JSON unmarshal of the
  1699. // DialParameters, in order to check the replay TTL.
  1700. //
  1701. // A potential future enhancement could be to add and check a new index that tracks how
  1702. // recently a server entry connection got as far as completing the SSH handshake, which
  1703. // verifies the Psiphon server running at that server entry network address. This would
  1704. // exclude from prune checking all recently known-valid servers regardless of whether they
  1705. // ultimately pass the liveness test, establish a tunnel, or reach the replay data transfer
  1706. // targets.
  1707. checkTags = append(checkTags, serverEntry.Tag)
  1708. // Approximate the size of the JSON encoding of the string array,
  1709. // including quotes and commas.
  1710. bytes += len(serverEntry.Tag) + 3
  1711. if bytes >= maxSendBytes || (maxWorkTime > 0 && time.Since(startWork) > maxWorkTime) {
  1712. break
  1713. }
  1714. }
  1715. return checkTags, bytes, nil
  1716. }
  1717. // CountSLOKs returns the total number of SLOK records.
  1718. func CountSLOKs() int {
  1719. count := 0
  1720. err := datastoreView(func(tx *datastoreTx) error {
  1721. bucket := tx.bucket(datastoreSLOKsBucket)
  1722. cursor := bucket.cursor()
  1723. for key := cursor.firstKey(); key != nil; key = cursor.nextKey() {
  1724. count++
  1725. }
  1726. cursor.close()
  1727. return nil
  1728. })
  1729. if err != nil {
  1730. NoticeWarning("CountSLOKs failed: %s", err)
  1731. return 0
  1732. }
  1733. return count
  1734. }
  1735. // DeleteSLOKs deletes all SLOK records.
  1736. func DeleteSLOKs() error {
  1737. err := datastoreUpdate(func(tx *datastoreTx) error {
  1738. return tx.clearBucket(datastoreSLOKsBucket)
  1739. })
  1740. if err != nil {
  1741. return errors.Trace(err)
  1742. }
  1743. return nil
  1744. }
  1745. // SetSLOK stores a SLOK key, referenced by its ID. The bool
  1746. // return value indicates whether the SLOK was already stored.
  1747. func SetSLOK(id, slok []byte) (bool, error) {
  1748. var duplicate bool
  1749. err := datastoreUpdate(func(tx *datastoreTx) error {
  1750. bucket := tx.bucket(datastoreSLOKsBucket)
  1751. duplicate = bucket.get(id) != nil
  1752. err := bucket.put(id, slok)
  1753. if err != nil {
  1754. return errors.Trace(err)
  1755. }
  1756. return nil
  1757. })
  1758. if err != nil {
  1759. return false, errors.Trace(err)
  1760. }
  1761. return duplicate, nil
  1762. }
  1763. // GetSLOK returns a SLOK key for the specified ID. The return
  1764. // value is nil if the SLOK is not found.
  1765. func GetSLOK(id []byte) ([]byte, error) {
  1766. var slok []byte
  1767. err := datastoreView(func(tx *datastoreTx) error {
  1768. bucket := tx.bucket(datastoreSLOKsBucket)
  1769. value := bucket.get(id)
  1770. if value != nil {
  1771. // Must make a copy as slice is only valid within transaction.
  1772. slok = make([]byte, len(value))
  1773. copy(slok, value)
  1774. }
  1775. return nil
  1776. })
  1777. if err != nil {
  1778. return nil, errors.Trace(err)
  1779. }
  1780. return slok, nil
  1781. }
  1782. func makeDialParametersKey(serverIPAddress, networkID []byte) []byte {
  1783. // TODO: structured key?
  1784. return append(append([]byte(nil), serverIPAddress...), networkID...)
  1785. }
  1786. // SetDialParameters stores dial parameters associated with the specified
  1787. // server/network ID.
  1788. func SetDialParameters(serverIPAddress, networkID string, dialParams *DialParameters) error {
  1789. key := makeDialParametersKey([]byte(serverIPAddress), []byte(networkID))
  1790. data, err := json.Marshal(dialParams)
  1791. if err != nil {
  1792. return errors.Trace(err)
  1793. }
  1794. return setBucketValue(datastoreDialParametersBucket, key, data)
  1795. }
  1796. // GetDialParameters fetches any dial parameters associated with the specified
  1797. // server/network ID. Returns nil, nil when no record is found.
  1798. func GetDialParameters(
  1799. config *Config, serverIPAddress, networkID string) (*DialParameters, error) {
  1800. // Support stand-alone GetTactics operation. See TacticsStorer for more
  1801. // details.
  1802. err := OpenDataStoreWithoutRetry(config)
  1803. if err != nil {
  1804. return nil, errors.Trace(err)
  1805. }
  1806. defer CloseDataStore()
  1807. key := makeDialParametersKey([]byte(serverIPAddress), []byte(networkID))
  1808. var dialParams *DialParameters
  1809. err = getBucketValue(
  1810. datastoreDialParametersBucket,
  1811. key,
  1812. func(value []byte) error {
  1813. if value == nil {
  1814. return nil
  1815. }
  1816. // Note: unlike with server entries, this record is not deleted when the
  1817. // unmarshal fails, as the caller should proceed with the dial without dial
  1818. // parameters; and when when the dial succeeds, new dial parameters will be
  1819. // written over this record.
  1820. err := json.Unmarshal(value, &dialParams)
  1821. if err != nil {
  1822. return errors.Trace(err)
  1823. }
  1824. return nil
  1825. })
  1826. if err != nil {
  1827. return nil, errors.Trace(err)
  1828. }
  1829. return dialParams, nil
  1830. }
  1831. // DeleteDialParameters clears any dial parameters associated with the
  1832. // specified server/network ID.
  1833. func DeleteDialParameters(serverIPAddress, networkID string) error {
  1834. key := makeDialParametersKey([]byte(serverIPAddress), []byte(networkID))
  1835. return deleteBucketValue(datastoreDialParametersBucket, key)
  1836. }
  1837. // TacticsStorer implements tactics.Storer.
  1838. //
  1839. // Each TacticsStorer datastore operation is wrapped with
  1840. // OpenDataStoreWithoutRetry/CloseDataStore, which enables a limited degree of
  1841. // multiprocess datastore synchronization:
  1842. //
  1843. // One process runs a Controller. Another process runs a stand-alone operation
  1844. // which accesses tactics via GetTactics. For example, SendFeedback.
  1845. //
  1846. // When the Controller is running, it holds an exclusive lock on the datastore
  1847. // and TacticsStorer operations in GetTactics in another process will fail.
  1848. // The stand-alone operation should proceed without tactics. In many cases,
  1849. // this is acceptable since any stand-alone operation network traffic will be
  1850. // tunneled.
  1851. //
  1852. // When the Controller is not running, the TacticsStorer operations in
  1853. // GetTactics in another process will succeed, with no operation holding a
  1854. // datastore lock for longer than the handful of milliseconds required to
  1855. // perform a single datastore operation.
  1856. //
  1857. // If the Controller is started while the stand-alone operation is in
  1858. // progress, the Controller start will not be blocked for long by the brief
  1859. // TacticsStorer datastore locks; the bolt Open call, in particular, has a 1
  1860. // second lock aquisition timeout and OpenDataStore will retry when the
  1861. // datastore file is locked.
  1862. //
  1863. // In this scheme, no attempt is made to detect interleaving datastore writes;
  1864. // that is, if a different process writes tactics in between GetTactics calls
  1865. // to GetTacticsRecord and then SetTacticsRecord. This is because all tactics
  1866. // writes are considered fresh and valid.
  1867. //
  1868. // Using OpenDataStoreWithoutRetry ensures that the GetTactics attempt in the
  1869. // non-Controller operation will quickly fail if the datastore is locked.
  1870. type TacticsStorer struct {
  1871. config *Config
  1872. }
  1873. func (t *TacticsStorer) SetTacticsRecord(networkID string, record []byte) error {
  1874. err := OpenDataStoreWithoutRetry(t.config)
  1875. if err != nil {
  1876. return errors.Trace(err)
  1877. }
  1878. defer CloseDataStore()
  1879. err = setBucketValue(datastoreTacticsBucket, []byte(networkID), record)
  1880. if err != nil {
  1881. return errors.Trace(err)
  1882. }
  1883. return nil
  1884. }
  1885. func (t *TacticsStorer) GetTacticsRecord(networkID string) ([]byte, error) {
  1886. err := OpenDataStoreWithoutRetry(t.config)
  1887. if err != nil {
  1888. return nil, errors.Trace(err)
  1889. }
  1890. defer CloseDataStore()
  1891. value, err := copyBucketValue(datastoreTacticsBucket, []byte(networkID))
  1892. if err != nil {
  1893. return nil, errors.Trace(err)
  1894. }
  1895. return value, nil
  1896. }
  1897. func (t *TacticsStorer) SetSpeedTestSamplesRecord(networkID string, record []byte) error {
  1898. err := OpenDataStoreWithoutRetry(t.config)
  1899. if err != nil {
  1900. return errors.Trace(err)
  1901. }
  1902. defer CloseDataStore()
  1903. err = setBucketValue(datastoreSpeedTestSamplesBucket, []byte(networkID), record)
  1904. if err != nil {
  1905. return errors.Trace(err)
  1906. }
  1907. return nil
  1908. }
  1909. func (t *TacticsStorer) GetSpeedTestSamplesRecord(networkID string) ([]byte, error) {
  1910. err := OpenDataStoreWithoutRetry(t.config)
  1911. if err != nil {
  1912. return nil, errors.Trace(err)
  1913. }
  1914. defer CloseDataStore()
  1915. value, err := copyBucketValue(datastoreSpeedTestSamplesBucket, []byte(networkID))
  1916. if err != nil {
  1917. return nil, errors.Trace(err)
  1918. }
  1919. return value, nil
  1920. }
  1921. // GetTacticsStorer creates a TacticsStorer.
  1922. func GetTacticsStorer(config *Config) *TacticsStorer {
  1923. return &TacticsStorer{config: config}
  1924. }
  1925. // GetAffinityServerEntryAndDialParameters fetches the current affinity server
  1926. // entry value and any corresponding dial parameters for the specified network
  1927. // ID. An error is returned when no affinity server is available. The
  1928. // DialParameter output may be nil when a server entry is found but has no
  1929. // dial parameters.
  1930. func GetAffinityServerEntryAndDialParameters(
  1931. networkID string) (protocol.ServerEntryFields, *DialParameters, error) {
  1932. var serverEntryFields protocol.ServerEntryFields
  1933. var dialParams *DialParameters
  1934. err := datastoreView(func(tx *datastoreTx) error {
  1935. keyValues := tx.bucket(datastoreKeyValueBucket)
  1936. serverEntries := tx.bucket(datastoreServerEntriesBucket)
  1937. dialParameters := tx.bucket(datastoreDialParametersBucket)
  1938. affinityServerEntryID := keyValues.get(datastoreAffinityServerEntryIDKey)
  1939. if affinityServerEntryID == nil {
  1940. return errors.TraceNew("no affinity server available")
  1941. }
  1942. serverEntryRecord := serverEntries.get(affinityServerEntryID)
  1943. if serverEntryRecord == nil {
  1944. return errors.TraceNew("affinity server entry not found")
  1945. }
  1946. err := json.Unmarshal(
  1947. serverEntryRecord,
  1948. &serverEntryFields)
  1949. if err != nil {
  1950. return errors.Trace(err)
  1951. }
  1952. dialParamsKey := makeDialParametersKey(
  1953. []byte(serverEntryFields.GetIPAddress()),
  1954. []byte(networkID))
  1955. dialParamsRecord := dialParameters.get(dialParamsKey)
  1956. if dialParamsRecord != nil {
  1957. err := json.Unmarshal(dialParamsRecord, &dialParams)
  1958. if err != nil {
  1959. return errors.Trace(err)
  1960. }
  1961. }
  1962. return nil
  1963. })
  1964. if err != nil {
  1965. return nil, nil, errors.Trace(err)
  1966. }
  1967. return serverEntryFields, dialParams, nil
  1968. }
  1969. // GetSignedServerEntryFields loads, from the datastore, the raw JSON server
  1970. // entry fields for the specified server entry.
  1971. //
  1972. // The protocol.ServerEntryFields returned by GetSignedServerEntryFields will
  1973. // include all fields required to verify the server entry signature,
  1974. // including new fields added after the current client version, which do not
  1975. // get unmarshaled into protocol.ServerEntry.
  1976. func GetSignedServerEntryFields(ipAddress string) (protocol.ServerEntryFields, error) {
  1977. var serverEntryFields protocol.ServerEntryFields
  1978. err := datastoreView(func(tx *datastoreTx) error {
  1979. serverEntries := tx.bucket(datastoreServerEntriesBucket)
  1980. key := []byte(ipAddress)
  1981. serverEntryRecord := serverEntries.get(key)
  1982. if serverEntryRecord == nil {
  1983. return errors.TraceNew("server entry not found")
  1984. }
  1985. err := json.Unmarshal(
  1986. serverEntryRecord,
  1987. &serverEntryFields)
  1988. if err != nil {
  1989. return errors.Trace(err)
  1990. }
  1991. return nil
  1992. })
  1993. if err != nil {
  1994. return nil, errors.Trace(err)
  1995. }
  1996. err = serverEntryFields.ToSignedFields()
  1997. if err != nil {
  1998. return nil, errors.Trace(err)
  1999. }
  2000. return serverEntryFields, nil
  2001. }
  2002. // StoreInproxyCommonCompartmentIDs stores a list of in-proxy common
  2003. // compartment IDs. Clients obtain common compartment IDs from tactics;
  2004. // persisting the IDs enables a scheme whereby existing clients may continue
  2005. // to use common compartment IDs, and access the related in-proxy proxy
  2006. // matches, even after the compartment IDs are de-listed from tactics.
  2007. //
  2008. // The caller is responsible for merging new and existing compartment IDs into
  2009. // the input list, and trimming the length of the list appropriately.
  2010. func StoreInproxyCommonCompartmentIDs(compartmentIDs []string) error {
  2011. value, err := json.Marshal(compartmentIDs)
  2012. if err != nil {
  2013. return errors.Trace(err)
  2014. }
  2015. err = setBucketValue(
  2016. datastoreKeyValueBucket,
  2017. datastoreInproxyCommonCompartmentIDsKey,
  2018. value)
  2019. return errors.Trace(err)
  2020. }
  2021. // LoadInproxyCommonCompartmentIDs returns the list of known, persisted
  2022. // in-proxy common compartment IDs. LoadInproxyCommonCompartmentIDs will
  2023. // return nil, nil when there is no stored list.
  2024. func LoadInproxyCommonCompartmentIDs() ([]string, error) {
  2025. var compartmentIDs []string
  2026. err := getBucketValue(
  2027. datastoreKeyValueBucket,
  2028. datastoreInproxyCommonCompartmentIDsKey,
  2029. func(value []byte) error {
  2030. if value == nil {
  2031. return nil
  2032. }
  2033. // Note: unlike with server entries, this record is not deleted
  2034. // when the unmarshal fails, as the caller should proceed with
  2035. // any common compartment IDs available with tactics; and
  2036. // subsequently call StoreInproxyCommonCompartmentIDs, writing
  2037. // over this record.
  2038. err := json.Unmarshal(value, &compartmentIDs)
  2039. if err != nil {
  2040. return errors.Trace(err)
  2041. }
  2042. return nil
  2043. })
  2044. if err != nil {
  2045. return nil, errors.Trace(err)
  2046. }
  2047. return compartmentIDs, nil
  2048. }
  2049. // makeNetworkReplayParametersKey creates a unique key for the replay
  2050. // parameters which reflects the network ID context; the replay data type, R;
  2051. // and the replay ID, which uniquely identifies the object that is replayed
  2052. // (for example, am in-proxy broker public key, uniquely identifying a
  2053. // broker).
  2054. func makeNetworkReplayParametersKey[R any](networkID, replayID string) []byte {
  2055. // A pointer to an R is used instead of stack (or heap) allocating a full
  2056. // R object. As a result, the %T will include a '*' prefix, and this is
  2057. // removed by the [1:].
  2058. //
  2059. // Fields are delimited using 0 bytes, which aren't expected to occur in
  2060. // the field string values.
  2061. var t *R
  2062. key := append(append([]byte(nil), []byte(networkID)...), 0)
  2063. key = append(append(key, []byte(fmt.Sprintf("%T", t)[1:])...), 0)
  2064. key = append(key, []byte(replayID)...)
  2065. return key
  2066. }
  2067. // SetNetworkReplayParameters stores replay parameters associated with the
  2068. // specified context and object.
  2069. //
  2070. // Limitation: unlike server dial parameters, the datastore does not prune
  2071. // replay records.
  2072. func SetNetworkReplayParameters[R any](networkID, replayID string, replayParams *R) error {
  2073. key := makeNetworkReplayParametersKey[R](networkID, replayID)
  2074. data, err := json.Marshal(replayParams)
  2075. if err != nil {
  2076. return errors.Trace(err)
  2077. }
  2078. return setBucketValue(datastoreNetworkReplayParametersBucket, key, data)
  2079. }
  2080. // SelectCandidateWithNetworkReplayParameters takes a list of candidate
  2081. // objects and selects one. The candidates are considered in the specified
  2082. // order. The first candidate with a valid replay record is returned, along
  2083. // with its replay parameters.
  2084. //
  2085. // The caller provides isValidReplay which should indicate if replay
  2086. // parameters remain valid; the caller should check for expiry and changes to
  2087. // the underlhying tactics.
  2088. //
  2089. // When no candidates with valid replay parameters are found,
  2090. // SelectCandidateWithNetworkReplayParameters returns the first candidate and
  2091. // nil replay parameters.
  2092. //
  2093. // When selectFirstCandidate is specified,
  2094. // SelectCandidateWithNetworkReplayParameters will check for valid replay
  2095. // parameters for the first candidate only, and then select the first
  2096. // candidate.
  2097. func SelectCandidateWithNetworkReplayParameters[C, R any](
  2098. networkID string,
  2099. selectFirstCandidate bool,
  2100. candidates []*C,
  2101. getReplayID func(*C) string,
  2102. isValidReplay func(*C, *R) bool) (*C, *R, error) {
  2103. if len(candidates) < 1 {
  2104. return nil, nil, errors.TraceNew("no candidates")
  2105. }
  2106. candidate := candidates[0]
  2107. var replay *R
  2108. err := datastoreUpdate(func(tx *datastoreTx) error {
  2109. bucket := tx.bucket(datastoreNetworkReplayParametersBucket)
  2110. for _, c := range candidates {
  2111. key := makeNetworkReplayParametersKey[R](networkID, getReplayID(c))
  2112. value := bucket.get(key)
  2113. if value == nil {
  2114. continue
  2115. }
  2116. var r *R
  2117. err := json.Unmarshal(value, &r)
  2118. if err != nil {
  2119. // Delete the record. This avoids continually checking it.
  2120. // Note that the deletes performed here won't prune records
  2121. // for old candidates which are no longer passed in to
  2122. // SelectCandidateWithNetworkReplayParameters.
  2123. NoticeWarning(
  2124. "SelectCandidateWithNetworkReplayParameters: unmarshal failed: %s",
  2125. errors.Trace(err))
  2126. _ = bucket.delete(key)
  2127. continue
  2128. }
  2129. if isValidReplay(c, r) {
  2130. candidate = c
  2131. replay = r
  2132. return nil
  2133. } else if selectFirstCandidate {
  2134. return nil
  2135. } else {
  2136. // Delete the record if it's no longer valid due to expiry or
  2137. // tactics changes. This avoids continually checking it.
  2138. _ = bucket.delete(key)
  2139. continue
  2140. }
  2141. }
  2142. // No valid replay parameters were found, so candidates[0] and a nil
  2143. // replay will be returned.
  2144. return nil
  2145. })
  2146. if err != nil {
  2147. return nil, nil, errors.Trace(err)
  2148. }
  2149. return candidate, replay, nil
  2150. }
  2151. // DeleteNetworkReplayParameters deletes the replay record associated with the
  2152. // specified context and object.
  2153. func DeleteNetworkReplayParameters[R any](networkID, replayID string) error {
  2154. key := makeNetworkReplayParametersKey[R](networkID, replayID)
  2155. return deleteBucketValue(datastoreNetworkReplayParametersBucket, key)
  2156. }
  2157. // DSLGetLastUntunneledFetchTime returns the timestamp of the last
  2158. // successfully completed untunneled DSL fetch.
  2159. func DSLGetLastUntunneledFetchTime() (time.Time, error) {
  2160. value, err := getTimeKeyValue(datastoreDSLLastUntunneledFetchTimeKey)
  2161. return value, errors.Trace(err)
  2162. }
  2163. // DSLSetLastUntunneledFetchTime sets the timestamp of the most recent
  2164. // successfully completed untunneled DSL fetch.
  2165. func DSLSetLastUntunneledFetchTime(time time.Time) error {
  2166. err := setTimeKeyValue(datastoreDSLLastUntunneledFetchTimeKey, time)
  2167. return errors.Trace(err)
  2168. }
  2169. // DSLGetLastUntunneledFetchTime returns the timestamp of the last
  2170. // successfully completed tunneled DSL fetch.
  2171. func DSLGetLastTunneledFetchTime() (time.Time, error) {
  2172. value, err := getTimeKeyValue(datastoreDSLLastTunneledFetchTimeKey)
  2173. return value, errors.Trace(err)
  2174. }
  2175. // DSLSetLastTunneledFetchTime sets the timestamp of the most recent
  2176. // successfully completed untunneled DSL fetch.
  2177. func DSLSetLastTunneledFetchTime(time time.Time) error {
  2178. err := setTimeKeyValue(datastoreDSLLastTunneledFetchTimeKey, time)
  2179. return errors.Trace(err)
  2180. }
  2181. // dslLookupServerEntry returns the server entry ID for the specified server
  2182. // entry tag version when there's locally stored server entry for that tag
  2183. // and with the specified version. Otherwise, it returns nil.
  2184. func dslLookupServerEntry(
  2185. tx *datastoreTx,
  2186. tag dsl.ServerEntryTag,
  2187. version int) ([]byte, error) {
  2188. serverEntryTags := tx.bucket(datastoreServerEntryTagsBucket)
  2189. serverEntryTagRecord := serverEntryTags.get(tag)
  2190. if serverEntryTagRecord == nil {
  2191. return nil, nil
  2192. }
  2193. serverEntryID, configurationVersion, err := getServerEntryTagRecord(
  2194. serverEntryTagRecord)
  2195. if err != nil {
  2196. return nil, errors.Trace(err)
  2197. }
  2198. if configurationVersion != version {
  2199. return nil, nil
  2200. }
  2201. return serverEntryID, nil
  2202. }
  2203. // dslPrioritizeDialServerEntry will create a DSLPendingPrioritizeDialTimestamp
  2204. // placeholder dial parameters for the specified server entry, unless a dial
  2205. // params already exists. Any existing dial param isn't unmarshaled and
  2206. // inspected -- even if it's a replay past its TTL, the existence of the
  2207. // record already suffices to move the server entry to the front in a server
  2208. // entry iterator shuffle.
  2209. //
  2210. // See MakeDialParameters for more details about the DSLPendingPrioritizeDial
  2211. // scheme.
  2212. func dslPrioritizeDialServerEntry(
  2213. tx *datastoreTx,
  2214. networkID string,
  2215. serverEntryID []byte) error {
  2216. dialParamsBucket := tx.bucket(datastoreDialParametersBucket)
  2217. key := makeDialParametersKey(serverEntryID, []byte(networkID))
  2218. if dialParamsBucket.get(key) != nil {
  2219. return nil
  2220. }
  2221. dialParams := &DialParameters{
  2222. DSLPendingPrioritizeDialTimestamp: time.Now(),
  2223. }
  2224. record, err := json.Marshal(dialParams)
  2225. if err != nil {
  2226. return errors.Trace(err)
  2227. }
  2228. err = dialParamsBucket.put(key, record)
  2229. if err != nil {
  2230. return errors.Trace(err)
  2231. }
  2232. return nil
  2233. }
  2234. // DSLHasServerEntry returns whether the datastore contains the server entry
  2235. // with the specified tag and version. DSLHasServerEntry uses a fast lookup
  2236. // which avoids unmarshaling server entries.
  2237. func DSLHasServerEntry(
  2238. tag dsl.ServerEntryTag,
  2239. version int,
  2240. prioritizeDial bool,
  2241. networkID string) bool {
  2242. hasServerEntry := false
  2243. var err error
  2244. if !prioritizeDial {
  2245. // Use a more concurrency-friendly view transaction when
  2246. // prioritizeDial is false and there's no possibility of a datastore
  2247. // update.
  2248. err = datastoreView(func(tx *datastoreTx) error {
  2249. serverEntryID, err := dslLookupServerEntry(tx, tag, version)
  2250. if err != nil {
  2251. return errors.Trace(err)
  2252. }
  2253. hasServerEntry = (serverEntryID != nil)
  2254. return nil
  2255. })
  2256. } else {
  2257. err = datastoreUpdate(func(tx *datastoreTx) error {
  2258. serverEntryID, err := dslLookupServerEntry(tx, tag, version)
  2259. if err != nil {
  2260. return errors.Trace(err)
  2261. }
  2262. hasServerEntry = (serverEntryID != nil)
  2263. // If the local datastore contains a server entry for the
  2264. // specified tag, but the version doesn't match, the
  2265. // prioritization will be skipped. In this case, the updated
  2266. // server entry will most likely be downloaded and
  2267. // DSLStoreServerEntry will apply the prioritization.
  2268. if hasServerEntry {
  2269. err := dslPrioritizeDialServerEntry(tx, networkID, serverEntryID)
  2270. if err != nil {
  2271. return errors.Trace(err)
  2272. }
  2273. }
  2274. return nil
  2275. })
  2276. }
  2277. if err != nil {
  2278. NoticeWarning("DSLHasServerEntry failed: %s", errors.Trace(err))
  2279. return false
  2280. }
  2281. return hasServerEntry
  2282. }
  2283. // DSLStoreServerEntry adds the server entry to the datastore using
  2284. // StoreServerEntry and populating LocalSource and LocalTimestamp.
  2285. func DSLStoreServerEntry(
  2286. serverEntrySignaturePublicKey string,
  2287. packedServerEntryFields protocol.PackedServerEntryFields,
  2288. source string,
  2289. prioritizeDial bool,
  2290. networkID string) error {
  2291. serverEntryFields, err := protocol.DecodePackedServerEntryFields(packedServerEntryFields)
  2292. if err != nil {
  2293. return errors.Trace(err)
  2294. }
  2295. err = serverEntryFields.VerifySignature(serverEntrySignaturePublicKey)
  2296. if err != nil {
  2297. return errors.Trace(err)
  2298. }
  2299. // See protocol.DecodeServerEntryFields and ImportEmbeddedServerEntries
  2300. // for other code paths that populate SetLocalSource and SetLocalTimestamp.
  2301. serverEntryFields.SetLocalSource(source)
  2302. serverEntryFields.SetLocalTimestamp(common.TruncateTimestampToHour(common.GetCurrentTimestamp()))
  2303. err = protocol.ValidateServerEntryFields(serverEntryFields)
  2304. if err != nil {
  2305. return errors.Trace(err)
  2306. }
  2307. var additionalUpdates func(tx *datastoreTx, serverEntryID []byte) error
  2308. if prioritizeDial {
  2309. additionalUpdates = func(tx *datastoreTx, serverEntryID []byte) error {
  2310. err := dslPrioritizeDialServerEntry(tx, networkID, serverEntryID)
  2311. if err != nil {
  2312. return errors.Trace(err)
  2313. }
  2314. return nil
  2315. }
  2316. }
  2317. err = storeServerEntry(serverEntryFields, true, additionalUpdates)
  2318. if err != nil {
  2319. return errors.Trace(err)
  2320. }
  2321. return nil
  2322. }
  2323. // DSLGetLastActiveOSLsTime returns the timestamp of the last
  2324. // successfully completed active OSL check.
  2325. func DSLGetLastActiveOSLsTime() (time.Time, error) {
  2326. value, err := getTimeKeyValue(datastoreDSLLastActiveOSLsTimeKey)
  2327. return value, errors.Trace(err)
  2328. }
  2329. // DSLSetLastActiveOSLsTime sets the timestamp of the most recent
  2330. // successfully completed active OSL check.
  2331. func DSLSetLastActiveOSLsTime(time time.Time) error {
  2332. err := setTimeKeyValue(datastoreDSLLastActiveOSLsTimeKey, time)
  2333. return errors.Trace(err)
  2334. }
  2335. // DSLKnownOSLIDs returns the set of known OSL IDs retrieved from the active
  2336. // OSL DSL request.
  2337. func DSLKnownOSLIDs() ([]dsl.OSLID, error) {
  2338. IDs := []dsl.OSLID{}
  2339. err := getBucketKeys(datastoreDSLOSLStatesBucket, func(key []byte) {
  2340. // Must make a copy as slice is only valid within transaction.
  2341. IDs = append(IDs, append([]byte(nil), key...))
  2342. })
  2343. if err != nil {
  2344. return nil, errors.Trace(err)
  2345. }
  2346. return IDs, nil
  2347. }
  2348. // DSLGetOSLState gets the current OSL state associated with an active OSL. A
  2349. // nil state is returned when no state is found for the specified ID. See
  2350. // dsl.Fetcher for more details on OSL states.
  2351. func DSLGetOSLState(ID dsl.OSLID) ([]byte, error) {
  2352. state, err := copyBucketValue(datastoreDSLOSLStatesBucket, ID)
  2353. if err != nil {
  2354. return nil, errors.Trace(err)
  2355. }
  2356. return state, nil
  2357. }
  2358. // DSLStoreOSLState sets the OSL state associated with an active OSL.
  2359. func DSLStoreOSLState(ID dsl.OSLID, state []byte) error {
  2360. err := setBucketValue(datastoreDSLOSLStatesBucket, ID, state)
  2361. return errors.Trace(err)
  2362. }
  2363. // DSLDeleteOSLState deletes the specified OSL state.
  2364. func DSLDeleteOSLState(ID dsl.OSLID) error {
  2365. err := deleteBucketValue(datastoreDSLOSLStatesBucket, ID)
  2366. return errors.Trace(err)
  2367. }
  2368. func setTimeKeyValue(key string, timevalue time.Time) error {
  2369. err := SetKeyValue(key, timevalue.Format(time.RFC3339))
  2370. return errors.Trace(err)
  2371. }
  2372. func getTimeKeyValue(key string) (time.Time, error) {
  2373. value, err := GetKeyValue(key)
  2374. if err != nil {
  2375. return time.Time{}, errors.Trace(err)
  2376. }
  2377. if value == "" {
  2378. return time.Time{}, nil
  2379. }
  2380. timeValue, err := time.Parse(time.RFC3339, value)
  2381. if err != nil {
  2382. return time.Time{}, errors.Trace(err)
  2383. }
  2384. return timeValue, nil
  2385. }
  2386. func setBucketValue(bucket, key, value []byte) error {
  2387. err := datastoreUpdate(func(tx *datastoreTx) error {
  2388. bucket := tx.bucket(bucket)
  2389. err := bucket.put(key, value)
  2390. if err != nil {
  2391. return errors.Trace(err)
  2392. }
  2393. return nil
  2394. })
  2395. if err != nil {
  2396. return errors.Trace(err)
  2397. }
  2398. return nil
  2399. }
  2400. func getBucketValue(bucket, key []byte, valueCallback func([]byte) error) error {
  2401. err := datastoreView(func(tx *datastoreTx) error {
  2402. bucket := tx.bucket(bucket)
  2403. value := bucket.get(key)
  2404. return valueCallback(value)
  2405. })
  2406. if err != nil {
  2407. return errors.Trace(err)
  2408. }
  2409. return nil
  2410. }
  2411. func deleteBucketValue(bucket, key []byte) error {
  2412. err := datastoreUpdate(func(tx *datastoreTx) error {
  2413. bucket := tx.bucket(bucket)
  2414. return bucket.delete(key)
  2415. })
  2416. if err != nil {
  2417. return errors.Trace(err)
  2418. }
  2419. return nil
  2420. }
  2421. func copyBucketValue(bucket, key []byte) ([]byte, error) {
  2422. var valueCopy []byte
  2423. err := getBucketValue(bucket, key, func(value []byte) error {
  2424. if value != nil {
  2425. // Must make a copy as slice is only valid within transaction.
  2426. valueCopy = make([]byte, len(value))
  2427. copy(valueCopy, value)
  2428. }
  2429. return nil
  2430. })
  2431. return valueCopy, err
  2432. }
  2433. func getBucketKeys(bucket []byte, keyCallback func([]byte)) error {
  2434. err := datastoreView(func(tx *datastoreTx) error {
  2435. bucket := tx.bucket(bucket)
  2436. cursor := bucket.cursor()
  2437. for key := cursor.firstKey(); key != nil; key = cursor.nextKey() {
  2438. keyCallback(key)
  2439. }
  2440. cursor.close()
  2441. return nil
  2442. })
  2443. if err != nil {
  2444. return errors.Trace(err)
  2445. }
  2446. return nil
  2447. }
  2448. func setServerEntryTagRecord(
  2449. serverEntryID []byte, configurationVersion int) ([]byte, error) {
  2450. var delimiter = [1]byte{0}
  2451. if bytes.Contains(serverEntryID, delimiter[:]) {
  2452. // Not expected, since serverEntryID is an IP address string.
  2453. return nil, errors.TraceNew("invalid serverEntryID")
  2454. }
  2455. if configurationVersion < 0 || configurationVersion >= math.MaxInt32 {
  2456. return nil, errors.TraceNew("invalid configurationVersion")
  2457. }
  2458. var version [4]byte
  2459. binary.LittleEndian.PutUint32(version[:], uint32(configurationVersion))
  2460. return append(append(serverEntryID, delimiter[:]...), version[:]...), nil
  2461. }
  2462. func getServerEntryTagRecord(
  2463. record []byte) ([]byte, int, error) {
  2464. var delimiter = [1]byte{0}
  2465. i := bytes.Index(record, delimiter[:])
  2466. if i == -1 {
  2467. // Backwards compatibility: assume version 0
  2468. return record, 0, nil
  2469. }
  2470. i += 1
  2471. if len(record)-i != 4 {
  2472. return nil, 0, errors.TraceNew("invalid configurationVersion")
  2473. }
  2474. configurationVersion := binary.LittleEndian.Uint32(record[i:])
  2475. return record[:i-1], int(configurationVersion), nil
  2476. }