serverApi.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  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/base64"
  24. "encoding/hex"
  25. "encoding/json"
  26. "fmt"
  27. "io"
  28. "io/ioutil"
  29. "net"
  30. "net/http"
  31. "net/url"
  32. "strconv"
  33. "strings"
  34. "time"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/buildinfo"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/fragmentor"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  43. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/transferstats"
  44. )
  45. // ServerContext is a utility struct which holds all of the data associated
  46. // with a Psiphon server connection. In addition to the established tunnel, this
  47. // includes data and transport mechanisms for Psiphon API requests. Legacy servers
  48. // offer the Psiphon API through a web service; newer servers offer the Psiphon
  49. // API through SSH requests made directly through the tunnel's SSH client.
  50. type ServerContext struct {
  51. tunnel *Tunnel
  52. psiphonHttpsClient *http.Client
  53. statsRegexps *transferstats.Regexps
  54. clientUpgradeVersion string
  55. serverHandshakeTimestamp string
  56. paddingPRNG *prng.PRNG
  57. }
  58. // MakeSessionId creates a new session ID. The same session ID is used across
  59. // multi-tunnel controller runs, where each tunnel has its own ServerContext
  60. // instance.
  61. // In server-side stats, we now consider a "session" to be the lifetime of the
  62. // Controller (e.g., the user's commanded start and stop) and we measure this
  63. // duration as well as the duration of each tunnel within the session.
  64. func MakeSessionId() (string, error) {
  65. randomId, err := common.MakeSecureRandomBytes(protocol.PSIPHON_API_CLIENT_SESSION_ID_LENGTH)
  66. if err != nil {
  67. return "", errors.Trace(err)
  68. }
  69. return hex.EncodeToString(randomId), nil
  70. }
  71. // NewServerContext makes the tunneled handshake request to the Psiphon server
  72. // and returns a ServerContext struct for use with subsequent Psiphon server API
  73. // requests (e.g., periodic connected and status requests).
  74. func NewServerContext(tunnel *Tunnel) (*ServerContext, error) {
  75. // For legacy servers, set up psiphonHttpsClient for
  76. // accessing the Psiphon API via the web service.
  77. var psiphonHttpsClient *http.Client
  78. if !tunnel.dialParams.ServerEntry.SupportsSSHAPIRequests() ||
  79. tunnel.config.TargetApiProtocol == protocol.PSIPHON_WEB_API_PROTOCOL {
  80. var err error
  81. psiphonHttpsClient, err = makePsiphonHttpsClient(tunnel)
  82. if err != nil {
  83. return nil, errors.Trace(err)
  84. }
  85. }
  86. serverContext := &ServerContext{
  87. tunnel: tunnel,
  88. psiphonHttpsClient: psiphonHttpsClient,
  89. paddingPRNG: prng.NewPRNGWithSeed(tunnel.dialParams.APIRequestPaddingSeed),
  90. }
  91. ignoreRegexps := tunnel.config.GetParameters().Get().Bool(
  92. parameters.IgnoreHandshakeStatsRegexps)
  93. err := serverContext.doHandshakeRequest(ignoreRegexps)
  94. if err != nil {
  95. return nil, errors.Trace(err)
  96. }
  97. return serverContext, nil
  98. }
  99. // doHandshakeRequest performs the "handshake" API request. The handshake
  100. // returns upgrade info, newly discovered server entries -- which are
  101. // stored -- and sponsor info (home pages, stat regexes).
  102. func (serverContext *ServerContext) doHandshakeRequest(
  103. ignoreStatsRegexps bool) error {
  104. params := serverContext.getBaseAPIParameters(baseParametersAll)
  105. // The server will return a signed copy of its own server entry when the
  106. // client specifies this 'missing_server_entry_signature' parameter.
  107. //
  108. // The purpose of this mechanism is to rapidly upgrade client local storage
  109. // from unsigned to signed server entries, and to ensure that the client has
  110. // a signed server entry for its currently connected server as required for
  111. // the client-to-client exchange feature.
  112. //
  113. // The server entry will be included in handshakeResponse.EncodedServerList,
  114. // along side discovery servers.
  115. requestedMissingSignature := false
  116. if !serverContext.tunnel.dialParams.ServerEntry.HasSignature() {
  117. requestedMissingSignature = true
  118. params["missing_server_entry_signature"] =
  119. serverContext.tunnel.dialParams.ServerEntry.Tag
  120. }
  121. doTactics := !serverContext.tunnel.config.DisableTactics
  122. networkID := ""
  123. if doTactics {
  124. // Limitation: it is assumed that the network ID obtained here is the
  125. // one that is active when the handshake request is received by the
  126. // server. However, it is remotely possible to switch networks
  127. // immediately after invoking the GetNetworkID callback and initiating
  128. // the handshake, if the tunnel protocol is meek.
  129. //
  130. // The response handling code below calls GetNetworkID again and ignores
  131. // any tactics payload if the network ID is not the same. While this
  132. // doesn't detect all cases of changing networks, it reduces the already
  133. // narrow window.
  134. networkID = serverContext.tunnel.config.GetNetworkID()
  135. err := tactics.SetTacticsAPIParameters(
  136. GetTacticsStorer(serverContext.tunnel.config),
  137. networkID,
  138. params)
  139. if err != nil {
  140. return errors.Trace(err)
  141. }
  142. }
  143. // When split tunnel mode is enabled, indicate this to the server. When
  144. // indicated, the server will perform split tunnel classifications on TCP
  145. // port forwards and reject, with a distinct response, port forwards which
  146. // the client should connect to directly, untunneled.
  147. if serverContext.tunnel.config.SplitTunnelOwnRegion {
  148. params["split_tunnel"] = "1"
  149. }
  150. // While regular split tunnel mode makes untunneled connections to
  151. // destinations in the client's own country, selected split tunnel mode
  152. // allows the client to specify a list of untunneled countries. Either or
  153. // both modes may be enabled.
  154. if len(serverContext.tunnel.config.SplitTunnelRegions) > 0 {
  155. params["split_tunnel_regions"] = serverContext.tunnel.config.SplitTunnelRegions
  156. }
  157. var response []byte
  158. if serverContext.psiphonHttpsClient == nil {
  159. params[protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS] =
  160. serverContext.tunnel.config.GetAuthorizations()
  161. request, err := serverContext.makeSSHAPIRequestPayload(params)
  162. if err != nil {
  163. return errors.Trace(err)
  164. }
  165. response, err = serverContext.tunnel.SendAPIRequest(
  166. protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME, request)
  167. if err != nil {
  168. return errors.Trace(err)
  169. }
  170. } else {
  171. // Legacy web service API request
  172. responseBody, err := serverContext.doGetRequest(
  173. makeRequestUrl(serverContext.tunnel, "", "handshake", params))
  174. if err != nil {
  175. return errors.Trace(err)
  176. }
  177. // Skip legacy format lines and just parse the JSON config line
  178. configLinePrefix := []byte("Config: ")
  179. for _, line := range bytes.Split(responseBody, []byte("\n")) {
  180. if bytes.HasPrefix(line, configLinePrefix) {
  181. response = line[len(configLinePrefix):]
  182. break
  183. }
  184. }
  185. if len(response) == 0 {
  186. return errors.TraceNew("no config line found")
  187. }
  188. }
  189. // Legacy fields:
  190. // - 'preemptive_reconnect_lifetime_milliseconds' is unused and ignored
  191. // - 'ssh_session_id' is ignored; client session ID is used instead
  192. var handshakeResponse protocol.HandshakeResponse
  193. // Initialize these fields to distinguish between psiphond omitting values in
  194. // the response and the zero value, which means unlimited rate.
  195. handshakeResponse.UpstreamBytesPerSecond = -1
  196. handshakeResponse.DownstreamBytesPerSecond = -1
  197. err := json.Unmarshal(response, &handshakeResponse)
  198. if err != nil {
  199. return errors.Trace(err)
  200. }
  201. if serverContext.tunnel.config.EmitClientAddress {
  202. NoticeClientAddress(handshakeResponse.ClientAddress)
  203. }
  204. NoticeClientRegion(handshakeResponse.ClientRegion)
  205. // Emit a SplitTunnelRegions notice indicating active split tunnel region.
  206. // For SplitTunnelOwnRegion, the handshake ClientRegion is the split
  207. // tunnel region and this region is always listed first.
  208. splitTunnelRegions := []string{}
  209. if serverContext.tunnel.config.SplitTunnelOwnRegion {
  210. splitTunnelRegions = []string{handshakeResponse.ClientRegion}
  211. }
  212. for _, region := range serverContext.tunnel.config.SplitTunnelRegions {
  213. if !serverContext.tunnel.config.SplitTunnelOwnRegion ||
  214. region != handshakeResponse.ClientRegion {
  215. splitTunnelRegions = append(splitTunnelRegions, region)
  216. }
  217. }
  218. if len(splitTunnelRegions) > 0 {
  219. NoticeSplitTunnelRegions(splitTunnelRegions)
  220. }
  221. var serverEntries []protocol.ServerEntryFields
  222. // Store discovered server entries
  223. // We use the server's time, as it's available here, for the server entry
  224. // timestamp since this is more reliable than the client time.
  225. for _, encodedServerEntry := range handshakeResponse.EncodedServerList {
  226. serverEntryFields, err := protocol.DecodeServerEntryFields(
  227. encodedServerEntry,
  228. common.TruncateTimestampToHour(handshakeResponse.ServerTimestamp),
  229. protocol.SERVER_ENTRY_SOURCE_DISCOVERY)
  230. if err != nil {
  231. return errors.Trace(err)
  232. }
  233. // Retain the original timestamp and source in the requestedMissingSignature
  234. // case, as this server entry was not discovered here.
  235. //
  236. // Limitation: there is a transient edge case where
  237. // requestedMissingSignature will be set for a discovery server entry that
  238. // _is_ also discovered here.
  239. if requestedMissingSignature &&
  240. serverEntryFields.GetIPAddress() == serverContext.tunnel.dialParams.ServerEntry.IpAddress {
  241. serverEntryFields.SetLocalTimestamp(serverContext.tunnel.dialParams.ServerEntry.LocalTimestamp)
  242. serverEntryFields.SetLocalSource(serverContext.tunnel.dialParams.ServerEntry.LocalSource)
  243. }
  244. err = protocol.ValidateServerEntryFields(serverEntryFields)
  245. if err != nil {
  246. // Skip this entry and continue with the next one
  247. NoticeWarning("invalid handshake server entry: %s", err)
  248. continue
  249. }
  250. serverEntries = append(serverEntries, serverEntryFields)
  251. }
  252. err = StoreServerEntries(
  253. serverContext.tunnel.config,
  254. serverEntries,
  255. true)
  256. if err != nil {
  257. return errors.Trace(err)
  258. }
  259. NoticeHomepages(handshakeResponse.Homepages)
  260. serverContext.clientUpgradeVersion = handshakeResponse.UpgradeClientVersion
  261. if handshakeResponse.UpgradeClientVersion != "" {
  262. NoticeClientUpgradeAvailable(handshakeResponse.UpgradeClientVersion)
  263. } else {
  264. NoticeClientIsLatestVersion("")
  265. }
  266. if !ignoreStatsRegexps {
  267. // The handshake returns page_view_regexes and https_request_regexes.
  268. // page_view_regexes is obsolete and not used. https_request_regexes, which
  269. // are actually host/domain name regexes, are used for host/domain name
  270. // bytes transferred metrics: tunneled traffic TLS SNI server names and HTTP
  271. // Host header host names are matched against these regexes to select flows
  272. // for bytes transferred counting.
  273. var regexpsNotices []string
  274. serverContext.statsRegexps, regexpsNotices = transferstats.MakeRegexps(
  275. handshakeResponse.HttpsRequestRegexes)
  276. for _, notice := range regexpsNotices {
  277. NoticeWarning(notice)
  278. }
  279. }
  280. diagnosticID := serverContext.tunnel.dialParams.ServerEntry.GetDiagnosticID()
  281. serverContext.serverHandshakeTimestamp = handshakeResponse.ServerTimestamp
  282. NoticeServerTimestamp(diagnosticID, serverContext.serverHandshakeTimestamp)
  283. NoticeActiveAuthorizationIDs(diagnosticID, handshakeResponse.ActiveAuthorizationIDs)
  284. NoticeTrafficRateLimits(
  285. diagnosticID,
  286. handshakeResponse.UpstreamBytesPerSecond,
  287. handshakeResponse.DownstreamBytesPerSecond)
  288. if doTactics && handshakeResponse.TacticsPayload != nil &&
  289. networkID == serverContext.tunnel.config.GetNetworkID() {
  290. var payload *tactics.Payload
  291. err := json.Unmarshal(handshakeResponse.TacticsPayload, &payload)
  292. if err != nil {
  293. return errors.Trace(err)
  294. }
  295. // handshakeResponse.TacticsPayload may be "null", and payload
  296. // will successfully unmarshal as nil. As a result, the previous
  297. // handshakeResponse.TacticsPayload != nil test is insufficient.
  298. if payload != nil {
  299. tacticsRecord, err := tactics.HandleTacticsPayload(
  300. GetTacticsStorer(serverContext.tunnel.config),
  301. networkID,
  302. payload)
  303. if err != nil {
  304. return errors.Trace(err)
  305. }
  306. if tacticsRecord != nil &&
  307. prng.FlipWeightedCoin(tacticsRecord.Tactics.Probability) {
  308. err := serverContext.tunnel.config.SetParameters(
  309. tacticsRecord.Tag, true, tacticsRecord.Tactics.Parameters)
  310. if err != nil {
  311. NoticeInfo("apply handshake tactics failed: %s", err)
  312. }
  313. // The error will be due to invalid tactics values
  314. // from the server. When SetParameters fails, all
  315. // previous tactics values are left in place.
  316. }
  317. }
  318. }
  319. return nil
  320. }
  321. // DoConnectedRequest performs the "connected" API request. This request is
  322. // used for statistics, including unique user counting; reporting the full
  323. // tunnel establishment duration including the handshake request; and updated
  324. // fragmentor metrics.
  325. //
  326. // Users are not assigned identifiers. Instead, daily unique users are
  327. // calculated by having clients submit their last connected timestamp
  328. // (truncated to an hour, as a privacy measure). As client clocks are
  329. // unreliable, the server returns new last_connected values for the client to
  330. // store and send next time it connects.
  331. func (serverContext *ServerContext) DoConnectedRequest() error {
  332. // Limitation: as currently implemented, the last_connected exchange isn't a
  333. // distributed, atomic operation. When clients send the connected request,
  334. // the server may receive the request, count a unique user based on the
  335. // client's last_connected, and then the tunnel fails before the client
  336. // receives the response, so the client will not update its last_connected
  337. // value and submit the same one again, resulting in an inflated unique user
  338. // count.
  339. //
  340. // The SetInFlightConnectedRequest mechanism mitigates one class of connected
  341. // request interruption, a commanded shutdown in the middle of a connected
  342. // request, by allowing some time for the request to complete before
  343. // terminating the tunnel.
  344. //
  345. // TODO: consider extending the connected request protocol with additional
  346. // "acknowledgment" messages so that the server does not commit its unique
  347. // user count until after the client has acknowledged receipt and durable
  348. // storage of the new last_connected value.
  349. requestDone := make(chan struct{})
  350. defer close(requestDone)
  351. if !serverContext.tunnel.SetInFlightConnectedRequest(requestDone) {
  352. return errors.TraceNew("tunnel is closing")
  353. }
  354. defer serverContext.tunnel.SetInFlightConnectedRequest(nil)
  355. params := serverContext.getBaseAPIParameters(
  356. baseParametersOnlyUpstreamFragmentorDialParameters)
  357. lastConnected, err := getLastConnected()
  358. if err != nil {
  359. return errors.Trace(err)
  360. }
  361. params["last_connected"] = lastConnected
  362. // serverContext.tunnel.establishDuration is nanoseconds; report milliseconds
  363. params["establishment_duration"] =
  364. fmt.Sprintf("%d", serverContext.tunnel.establishDuration/time.Millisecond)
  365. var response []byte
  366. if serverContext.psiphonHttpsClient == nil {
  367. request, err := serverContext.makeSSHAPIRequestPayload(params)
  368. if err != nil {
  369. return errors.Trace(err)
  370. }
  371. response, err = serverContext.tunnel.SendAPIRequest(
  372. protocol.PSIPHON_API_CONNECTED_REQUEST_NAME, request)
  373. if err != nil {
  374. return errors.Trace(err)
  375. }
  376. } else {
  377. // Legacy web service API request
  378. response, err = serverContext.doGetRequest(
  379. makeRequestUrl(serverContext.tunnel, "", "connected", params))
  380. if err != nil {
  381. return errors.Trace(err)
  382. }
  383. }
  384. var connectedResponse protocol.ConnectedResponse
  385. err = json.Unmarshal(response, &connectedResponse)
  386. if err != nil {
  387. return errors.Trace(err)
  388. }
  389. err = SetKeyValue(
  390. datastoreLastConnectedKey, connectedResponse.ConnectedTimestamp)
  391. if err != nil {
  392. return errors.Trace(err)
  393. }
  394. return nil
  395. }
  396. func getLastConnected() (string, error) {
  397. lastConnected, err := GetKeyValue(datastoreLastConnectedKey)
  398. if err != nil {
  399. return "", errors.Trace(err)
  400. }
  401. if lastConnected == "" {
  402. lastConnected = "None"
  403. }
  404. return lastConnected, nil
  405. }
  406. // StatsRegexps gets the Regexps used for the statistics for this tunnel.
  407. func (serverContext *ServerContext) StatsRegexps() *transferstats.Regexps {
  408. return serverContext.statsRegexps
  409. }
  410. // DoStatusRequest makes a "status" API request to the server, sending session stats.
  411. func (serverContext *ServerContext) DoStatusRequest(tunnel *Tunnel) error {
  412. params := serverContext.getBaseAPIParameters(baseParametersNoDialParameters)
  413. // Note: ensure putBackStatusRequestPayload is called, to replace
  414. // payload for future attempt, in all failure cases.
  415. statusPayload, statusPayloadInfo, err := makeStatusRequestPayload(
  416. serverContext.tunnel.config,
  417. tunnel.dialParams.ServerEntry.IpAddress)
  418. if err != nil {
  419. return errors.Trace(err)
  420. }
  421. // Skip the request when there's no payload to send.
  422. if len(statusPayload) == 0 {
  423. return nil
  424. }
  425. var response []byte
  426. if serverContext.psiphonHttpsClient == nil {
  427. rawMessage := json.RawMessage(statusPayload)
  428. params["statusData"] = &rawMessage
  429. var request []byte
  430. request, err = serverContext.makeSSHAPIRequestPayload(params)
  431. if err == nil {
  432. response, err = serverContext.tunnel.SendAPIRequest(
  433. protocol.PSIPHON_API_STATUS_REQUEST_NAME, request)
  434. }
  435. } else {
  436. // Legacy web service API request
  437. response, err = serverContext.doPostRequest(
  438. makeRequestUrl(serverContext.tunnel, "", "status", params),
  439. "application/json",
  440. bytes.NewReader(statusPayload))
  441. }
  442. if err != nil {
  443. // Resend the transfer stats and tunnel stats later
  444. // Note: potential duplicate reports if the server received and processed
  445. // the request but the client failed to receive the response.
  446. putBackStatusRequestPayload(statusPayloadInfo)
  447. return errors.Trace(err)
  448. }
  449. confirmStatusRequestPayload(statusPayloadInfo)
  450. var statusResponse protocol.StatusResponse
  451. err = json.Unmarshal(response, &statusResponse)
  452. if err != nil {
  453. return errors.Trace(err)
  454. }
  455. for _, serverEntryTag := range statusResponse.InvalidServerEntryTags {
  456. PruneServerEntry(serverContext.tunnel.config, serverEntryTag)
  457. }
  458. return nil
  459. }
  460. // statusRequestPayloadInfo is a temporary structure for data used to
  461. // either "clear" or "put back" status request payload data depending
  462. // on whether or not the request succeeded.
  463. type statusRequestPayloadInfo struct {
  464. serverId string
  465. transferStats *transferstats.AccumulatedStats
  466. persistentStats map[string][][]byte
  467. }
  468. func makeStatusRequestPayload(
  469. config *Config,
  470. serverId string) ([]byte, *statusRequestPayloadInfo, error) {
  471. transferStats := transferstats.TakeOutStatsForServer(serverId)
  472. hostBytes := transferStats.GetStatsForStatusRequest()
  473. persistentStats, err := TakeOutUnreportedPersistentStats(config)
  474. if err != nil {
  475. NoticeWarning(
  476. "TakeOutUnreportedPersistentStats failed: %s", errors.Trace(err))
  477. persistentStats = nil
  478. // Proceed with transferStats only
  479. }
  480. if len(hostBytes) == 0 && len(persistentStats) == 0 {
  481. // There is no payload to send.
  482. return nil, nil, nil
  483. }
  484. payloadInfo := &statusRequestPayloadInfo{
  485. serverId, transferStats, persistentStats}
  486. payload := make(map[string]interface{})
  487. payload["host_bytes"] = hostBytes
  488. // We're not recording these fields, but legacy servers require them.
  489. payload["bytes_transferred"] = 0
  490. payload["page_views"] = make([]string, 0)
  491. payload["https_requests"] = make([]string, 0)
  492. persistentStatPayloadNames := make(map[string]string)
  493. persistentStatPayloadNames[datastorePersistentStatTypeRemoteServerList] = "remote_server_list_stats"
  494. persistentStatPayloadNames[datastorePersistentStatTypeFailedTunnel] = "failed_tunnel_stats"
  495. for statType, stats := range persistentStats {
  496. // Persistent stats records are already in JSON format
  497. jsonStats := make([]json.RawMessage, len(stats))
  498. for i, stat := range stats {
  499. jsonStats[i] = json.RawMessage(stat)
  500. }
  501. payload[persistentStatPayloadNames[statType]] = jsonStats
  502. }
  503. jsonPayload, err := json.Marshal(payload)
  504. if err != nil {
  505. // Send the transfer stats and tunnel stats later
  506. putBackStatusRequestPayload(payloadInfo)
  507. return nil, nil, errors.Trace(err)
  508. }
  509. return jsonPayload, payloadInfo, nil
  510. }
  511. func putBackStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  512. transferstats.PutBackStatsForServer(
  513. payloadInfo.serverId, payloadInfo.transferStats)
  514. err := PutBackUnreportedPersistentStats(payloadInfo.persistentStats)
  515. if err != nil {
  516. // These persistent stats records won't be resent until after a
  517. // datastore re-initialization.
  518. NoticeWarning(
  519. "PutBackUnreportedPersistentStats failed: %s", errors.Trace(err))
  520. }
  521. }
  522. func confirmStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  523. err := ClearReportedPersistentStats(payloadInfo.persistentStats)
  524. if err != nil {
  525. // These persistent stats records may be resent.
  526. NoticeWarning(
  527. "ClearReportedPersistentStats failed: %s", errors.Trace(err))
  528. }
  529. }
  530. // RecordRemoteServerListStat records a completed common or OSL remote server
  531. // list resource download.
  532. //
  533. // The RSL download event could occur when the client is unable to immediately
  534. // send a status request to a server, so these records are stored in the
  535. // persistent datastore and reported via subsequent status requests sent to
  536. // any Psiphon server.
  537. //
  538. // Note that some common event field values may change between the stat
  539. // recording and reporting, including client geolocation and host_id.
  540. //
  541. // The bytes/duration fields reflect the size and download time for the _last
  542. // chunk only_ in the case of a resumed download. The purpose of these fields
  543. // is to calculate rough data transfer rates. Both bytes and duration are
  544. // included in the log, to allow for filtering out of small transfers which
  545. // may not produce accurate rate numbers.
  546. //
  547. // Multiple "status" requests may be in flight at once (due to multi-tunnel,
  548. // asynchronous final status retry, and aggressive status requests for
  549. // pre-registered tunnels), To avoid duplicate reporting, persistent stats
  550. // records are "taken-out" by a status request and then "put back" in case the
  551. // request fails.
  552. //
  553. // Duplicate reporting may also occur when a server receives and processes a
  554. // status request but the client fails to receive the response.
  555. func RecordRemoteServerListStat(
  556. config *Config,
  557. tunneled bool,
  558. url string,
  559. etag string,
  560. bytes int64,
  561. duration time.Duration,
  562. authenticated bool) error {
  563. if !config.GetParameters().Get().WeightedCoinFlip(
  564. parameters.RecordRemoteServerListPersistentStatsProbability) {
  565. return nil
  566. }
  567. params := make(common.APIParameters)
  568. params["session_id"] = config.SessionID
  569. params["propagation_channel_id"] = config.PropagationChannelId
  570. params["sponsor_id"] = config.GetSponsorID()
  571. params["client_version"] = config.ClientVersion
  572. params["client_platform"] = config.ClientPlatform
  573. params["client_build_rev"] = buildinfo.GetBuildInfo().BuildRev
  574. if config.DeviceRegion != "" {
  575. params["device_region"] = config.DeviceRegion
  576. }
  577. params["client_download_timestamp"] = common.TruncateTimestampToHour(common.GetCurrentTimestamp())
  578. tunneledStr := "0"
  579. if tunneled {
  580. tunneledStr = "1"
  581. }
  582. params["tunneled"] = tunneledStr
  583. params["url"] = url
  584. params["etag"] = etag
  585. params["bytes"] = fmt.Sprintf("%d", bytes)
  586. // duration is nanoseconds; report milliseconds
  587. params["duration"] = fmt.Sprintf("%d", duration/time.Millisecond)
  588. authenticatedStr := "0"
  589. if authenticated {
  590. authenticatedStr = "1"
  591. }
  592. params["authenticated"] = authenticatedStr
  593. remoteServerListStatJson, err := json.Marshal(params)
  594. if err != nil {
  595. return errors.Trace(err)
  596. }
  597. return StorePersistentStat(
  598. config, datastorePersistentStatTypeRemoteServerList, remoteServerListStatJson)
  599. }
  600. // RecordFailedTunnelStat records metrics for a failed tunnel dial, including
  601. // dial parameters and error condition (tunnelErr).
  602. //
  603. // This uses the same reporting facility, with the same caveats, as
  604. // RecordRemoteServerListStat.
  605. func RecordFailedTunnelStat(
  606. config *Config,
  607. dialParams *DialParameters,
  608. livenessTestMetrics *livenessTestMetrics,
  609. bytesUp int64,
  610. bytesDown int64,
  611. tunnelErr error) error {
  612. if !config.GetParameters().Get().WeightedCoinFlip(
  613. parameters.RecordFailedTunnelPersistentStatsProbability) {
  614. return nil
  615. }
  616. lastConnected, err := getLastConnected()
  617. if err != nil {
  618. return errors.Trace(err)
  619. }
  620. params := getBaseAPIParameters(baseParametersAll, config, dialParams)
  621. delete(params, "server_secret")
  622. params["server_entry_tag"] = dialParams.ServerEntry.Tag
  623. params["last_connected"] = lastConnected
  624. params["client_failed_timestamp"] = common.TruncateTimestampToHour(common.GetCurrentTimestamp())
  625. if livenessTestMetrics != nil {
  626. params["liveness_test_upstream_bytes"] = strconv.Itoa(livenessTestMetrics.UpstreamBytes)
  627. params["liveness_test_sent_upstream_bytes"] = strconv.Itoa(livenessTestMetrics.SentUpstreamBytes)
  628. params["liveness_test_downstream_bytes"] = strconv.Itoa(livenessTestMetrics.DownstreamBytes)
  629. params["liveness_test_received_downstream_bytes"] = strconv.Itoa(livenessTestMetrics.ReceivedDownstreamBytes)
  630. }
  631. if bytesUp >= 0 {
  632. params["bytes_up"] = fmt.Sprintf("%d", bytesUp)
  633. }
  634. if bytesDown >= 0 {
  635. params["bytes_down"] = fmt.Sprintf("%d", bytesDown)
  636. }
  637. // Ensure direct server IPs are not exposed in logs. The "net" package, and
  638. // possibly other 3rd party packages, will include destination addresses in
  639. // I/O error messages.
  640. tunnelError := StripIPAddressesString(tunnelErr.Error())
  641. params["tunnel_error"] = tunnelError
  642. failedTunnelStatJson, err := json.Marshal(params)
  643. if err != nil {
  644. return errors.Trace(err)
  645. }
  646. return StorePersistentStat(
  647. config, datastorePersistentStatTypeFailedTunnel, failedTunnelStatJson)
  648. }
  649. // doGetRequest makes a tunneled HTTPS request and returns the response body.
  650. func (serverContext *ServerContext) doGetRequest(
  651. requestUrl string) (responseBody []byte, err error) {
  652. request, err := http.NewRequest("GET", requestUrl, nil)
  653. if err != nil {
  654. return nil, errors.Trace(err)
  655. }
  656. request.Header.Set("User-Agent", MakePsiphonUserAgent(serverContext.tunnel.config))
  657. response, err := serverContext.psiphonHttpsClient.Do(request)
  658. if err == nil && response.StatusCode != http.StatusOK {
  659. response.Body.Close()
  660. err = fmt.Errorf("HTTP GET request failed with response code: %d", response.StatusCode)
  661. }
  662. if err != nil {
  663. // Trim this error since it may include long URLs
  664. return nil, errors.Trace(TrimError(err))
  665. }
  666. defer response.Body.Close()
  667. body, err := ioutil.ReadAll(response.Body)
  668. if err != nil {
  669. return nil, errors.Trace(err)
  670. }
  671. return body, nil
  672. }
  673. // doPostRequest makes a tunneled HTTPS POST request.
  674. func (serverContext *ServerContext) doPostRequest(
  675. requestUrl string, bodyType string, body io.Reader) (responseBody []byte, err error) {
  676. request, err := http.NewRequest("POST", requestUrl, body)
  677. if err != nil {
  678. return nil, errors.Trace(err)
  679. }
  680. request.Header.Set("User-Agent", MakePsiphonUserAgent(serverContext.tunnel.config))
  681. request.Header.Set("Content-Type", bodyType)
  682. response, err := serverContext.psiphonHttpsClient.Do(request)
  683. if err == nil && response.StatusCode != http.StatusOK {
  684. response.Body.Close()
  685. err = fmt.Errorf("HTTP POST request failed with response code: %d", response.StatusCode)
  686. }
  687. if err != nil {
  688. // Trim this error since it may include long URLs
  689. return nil, errors.Trace(TrimError(err))
  690. }
  691. defer response.Body.Close()
  692. responseBody, err = ioutil.ReadAll(response.Body)
  693. if err != nil {
  694. return nil, errors.Trace(err)
  695. }
  696. return responseBody, nil
  697. }
  698. // makeSSHAPIRequestPayload makes a JSON payload for an SSH API request.
  699. func (serverContext *ServerContext) makeSSHAPIRequestPayload(
  700. params common.APIParameters) ([]byte, error) {
  701. jsonPayload, err := json.Marshal(params)
  702. if err != nil {
  703. return nil, errors.Trace(err)
  704. }
  705. return jsonPayload, nil
  706. }
  707. type baseParametersFilter int
  708. const (
  709. baseParametersAll baseParametersFilter = iota
  710. baseParametersOnlyUpstreamFragmentorDialParameters
  711. baseParametersNoDialParameters
  712. )
  713. func (serverContext *ServerContext) getBaseAPIParameters(
  714. filter baseParametersFilter) common.APIParameters {
  715. params := getBaseAPIParameters(
  716. filter,
  717. serverContext.tunnel.config,
  718. serverContext.tunnel.dialParams)
  719. // Add a random amount of padding to defend against API call traffic size
  720. // fingerprints. The "pad_response" field instructs the server to pad its
  721. // response accordingly.
  722. p := serverContext.tunnel.config.GetParameters().Get()
  723. minUpstreamPadding := p.Int(parameters.APIRequestUpstreamPaddingMinBytes)
  724. maxUpstreamPadding := p.Int(parameters.APIRequestUpstreamPaddingMaxBytes)
  725. minDownstreamPadding := p.Int(parameters.APIRequestDownstreamPaddingMinBytes)
  726. maxDownstreamPadding := p.Int(parameters.APIRequestDownstreamPaddingMaxBytes)
  727. if maxUpstreamPadding > 0 {
  728. size := serverContext.paddingPRNG.Range(minUpstreamPadding, maxUpstreamPadding)
  729. params["padding"] = strings.Repeat(" ", size)
  730. }
  731. if maxDownstreamPadding > 0 {
  732. size := serverContext.paddingPRNG.Range(minDownstreamPadding, maxDownstreamPadding)
  733. params["pad_response"] = strconv.Itoa(size)
  734. }
  735. return params
  736. }
  737. // getBaseAPIParameters returns all the common API parameters that are
  738. // included with each Psiphon API request. These common parameters are used
  739. // for metrics.
  740. func getBaseAPIParameters(
  741. filter baseParametersFilter,
  742. config *Config,
  743. dialParams *DialParameters) common.APIParameters {
  744. params := make(common.APIParameters)
  745. params["session_id"] = config.SessionID
  746. params["client_session_id"] = config.SessionID
  747. params["server_secret"] = dialParams.ServerEntry.WebServerSecret
  748. params["propagation_channel_id"] = config.PropagationChannelId
  749. params["sponsor_id"] = config.GetSponsorID()
  750. params["client_version"] = config.ClientVersion
  751. params["client_platform"] = config.ClientPlatform
  752. params["client_features"] = config.clientFeatures
  753. params["client_build_rev"] = buildinfo.GetBuildInfo().BuildRev
  754. // Blank parameters must be omitted.
  755. if config.DeviceRegion != "" {
  756. params["device_region"] = config.DeviceRegion
  757. }
  758. if filter == baseParametersAll {
  759. params["relay_protocol"] = dialParams.TunnelProtocol
  760. params["network_type"] = dialParams.GetNetworkType()
  761. if dialParams.BPFProgramName != "" {
  762. params["client_bpf"] = dialParams.BPFProgramName
  763. }
  764. if dialParams.SelectedSSHClientVersion {
  765. params["ssh_client_version"] = dialParams.SSHClientVersion
  766. }
  767. if dialParams.UpstreamProxyType != "" {
  768. params["upstream_proxy_type"] = dialParams.UpstreamProxyType
  769. }
  770. if dialParams.UpstreamProxyCustomHeaderNames != nil {
  771. params["upstream_proxy_custom_header_names"] = dialParams.UpstreamProxyCustomHeaderNames
  772. }
  773. if dialParams.FrontingProviderID != "" {
  774. params["fronting_provider_id"] = dialParams.FrontingProviderID
  775. }
  776. if dialParams.MeekDialAddress != "" {
  777. params["meek_dial_address"] = dialParams.MeekDialAddress
  778. }
  779. meekResolvedIPAddress := dialParams.MeekResolvedIPAddress.Load().(string)
  780. if meekResolvedIPAddress != "" {
  781. params["meek_resolved_ip_address"] = meekResolvedIPAddress
  782. }
  783. if dialParams.MeekSNIServerName != "" {
  784. params["meek_sni_server_name"] = dialParams.MeekSNIServerName
  785. }
  786. if dialParams.MeekHostHeader != "" {
  787. params["meek_host_header"] = dialParams.MeekHostHeader
  788. }
  789. // MeekTransformedHostName is meaningful when meek is used, which is when
  790. // MeekDialAddress != ""
  791. if dialParams.MeekDialAddress != "" {
  792. transformedHostName := "0"
  793. if dialParams.MeekTransformedHostName {
  794. transformedHostName = "1"
  795. }
  796. params["meek_transformed_host_name"] = transformedHostName
  797. }
  798. if dialParams.SelectedUserAgent {
  799. params["user_agent"] = dialParams.UserAgent
  800. }
  801. if dialParams.SelectedTLSProfile {
  802. params["tls_profile"] = dialParams.TLSProfile
  803. params["tls_version"] = dialParams.GetTLSVersionForMetrics()
  804. }
  805. if dialParams.ServerEntry.Region != "" {
  806. params["server_entry_region"] = dialParams.ServerEntry.Region
  807. }
  808. if dialParams.ServerEntry.LocalSource != "" {
  809. params["server_entry_source"] = dialParams.ServerEntry.LocalSource
  810. }
  811. // As with last_connected, this timestamp stat, which may be a precise
  812. // handshake request server timestamp, is truncated to hour granularity to
  813. // avoid introducing a reconstructable cross-session user trace into server
  814. // logs.
  815. localServerEntryTimestamp := common.TruncateTimestampToHour(
  816. dialParams.ServerEntry.LocalTimestamp)
  817. if localServerEntryTimestamp != "" {
  818. params["server_entry_timestamp"] = localServerEntryTimestamp
  819. }
  820. params[tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME] =
  821. config.GetParameters().Get().Tag()
  822. if dialParams.DialPortNumber != "" {
  823. params["dial_port_number"] = dialParams.DialPortNumber
  824. }
  825. if dialParams.QUICVersion != "" {
  826. params["quic_version"] = dialParams.QUICVersion
  827. }
  828. if dialParams.QUICDialSNIAddress != "" {
  829. params["quic_dial_sni_address"] = dialParams.QUICDialSNIAddress
  830. }
  831. if dialParams.QUICDisablePathMTUDiscovery {
  832. params["quic_disable_client_path_mtu_discovery"] = "1"
  833. }
  834. isReplay := "0"
  835. if dialParams.IsReplay {
  836. isReplay = "1"
  837. }
  838. params["is_replay"] = isReplay
  839. if config.EgressRegion != "" {
  840. params["egress_region"] = config.EgressRegion
  841. }
  842. // dialParams.DialDuration is nanoseconds; report milliseconds
  843. params["dial_duration"] = fmt.Sprintf("%d", dialParams.DialDuration/time.Millisecond)
  844. params["candidate_number"] = strconv.Itoa(dialParams.CandidateNumber)
  845. params["established_tunnels_count"] = strconv.Itoa(dialParams.EstablishedTunnelsCount)
  846. if dialParams.NetworkLatencyMultiplier != 0.0 {
  847. params["network_latency_multiplier"] =
  848. fmt.Sprintf("%f", dialParams.NetworkLatencyMultiplier)
  849. }
  850. if dialParams.ConjureTransport != "" {
  851. params["conjure_transport"] = dialParams.ConjureTransport
  852. }
  853. if dialParams.DialConnMetrics != nil {
  854. metrics := dialParams.DialConnMetrics.GetMetrics()
  855. for name, value := range metrics {
  856. params[name] = fmt.Sprintf("%v", value)
  857. }
  858. }
  859. if dialParams.ObfuscatedSSHConnMetrics != nil {
  860. metrics := dialParams.ObfuscatedSSHConnMetrics.GetMetrics()
  861. for name, value := range metrics {
  862. params[name] = fmt.Sprintf("%v", value)
  863. }
  864. }
  865. } else if filter == baseParametersOnlyUpstreamFragmentorDialParameters {
  866. if dialParams.DialConnMetrics != nil {
  867. names := fragmentor.GetUpstreamMetricsNames()
  868. metrics := dialParams.DialConnMetrics.GetMetrics()
  869. for name, value := range metrics {
  870. if common.Contains(names, name) {
  871. params[name] = fmt.Sprintf("%v", value)
  872. }
  873. }
  874. }
  875. }
  876. return params
  877. }
  878. // makeRequestUrl makes a URL for a web service API request.
  879. func makeRequestUrl(tunnel *Tunnel, port, path string, params common.APIParameters) string {
  880. var requestUrl bytes.Buffer
  881. if port == "" {
  882. port = tunnel.dialParams.ServerEntry.WebServerPort
  883. }
  884. requestUrl.WriteString("https://")
  885. requestUrl.WriteString(tunnel.dialParams.ServerEntry.IpAddress)
  886. requestUrl.WriteString(":")
  887. requestUrl.WriteString(port)
  888. requestUrl.WriteString("/")
  889. requestUrl.WriteString(path)
  890. if len(params) > 0 {
  891. queryParams := url.Values{}
  892. for name, value := range params {
  893. // Note: this logic skips the tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME
  894. // parameter, which has a different type. This parameter is not recognized
  895. // by legacy servers.
  896. switch v := value.(type) {
  897. case string:
  898. queryParams.Set(name, v)
  899. case []string:
  900. // String array param encoded as JSON
  901. jsonValue, err := json.Marshal(v)
  902. if err != nil {
  903. break
  904. }
  905. queryParams.Set(name, string(jsonValue))
  906. }
  907. }
  908. requestUrl.WriteString("?")
  909. requestUrl.WriteString(queryParams.Encode())
  910. }
  911. return requestUrl.String()
  912. }
  913. // makePsiphonHttpsClient creates a Psiphon HTTPS client that tunnels web service API
  914. // requests and which validates the web server using the Psiphon server entry web server
  915. // certificate.
  916. func makePsiphonHttpsClient(tunnel *Tunnel) (httpsClient *http.Client, err error) {
  917. certificate, err := DecodeCertificate(
  918. tunnel.dialParams.ServerEntry.WebServerCertificate)
  919. if err != nil {
  920. return nil, errors.Trace(err)
  921. }
  922. tunneledDialer := func(_ context.Context, _, addr string) (net.Conn, error) {
  923. // This case bypasses tunnel.Dial, to avoid its check that the tunnel is
  924. // already active (it won't be pre-handshake). This bypass won't handle the
  925. // server rejecting the port forward due to split tunnel classification, but
  926. // we know that the server won't classify the web API destination as
  927. // untunneled.
  928. return tunnel.sshClient.Dial("tcp", addr)
  929. }
  930. // Note: as with SSH API requests, there no dial context here. SSH port forward dials
  931. // cannot be interrupted directly. Closing the tunnel will interrupt both the dial and
  932. // the request. While it's possible to add a timeout here, we leave it with no explicit
  933. // timeout which is the same as SSH API requests: if the tunnel has stalled then SSH keep
  934. // alives will cause the tunnel to close.
  935. dialer := NewCustomTLSDialer(
  936. &CustomTLSConfig{
  937. Parameters: tunnel.config.GetParameters(),
  938. Dial: tunneledDialer,
  939. VerifyLegacyCertificate: certificate,
  940. })
  941. transport := &http.Transport{
  942. DialTLS: func(network, addr string) (net.Conn, error) {
  943. return dialer(context.Background(), network, addr)
  944. },
  945. Dial: func(network, addr string) (net.Conn, error) {
  946. return nil, errors.TraceNew("HTTP not supported")
  947. },
  948. }
  949. return &http.Client{
  950. Transport: transport,
  951. }, nil
  952. }
  953. func HandleServerRequest(
  954. tunnelOwner TunnelOwner, tunnel *Tunnel, name string, payload []byte) error {
  955. switch name {
  956. case protocol.PSIPHON_API_OSL_REQUEST_NAME:
  957. return HandleOSLRequest(tunnelOwner, tunnel, payload)
  958. case protocol.PSIPHON_API_ALERT_REQUEST_NAME:
  959. return HandleAlertRequest(tunnelOwner, tunnel, payload)
  960. }
  961. return errors.Tracef("invalid request name: %s", name)
  962. }
  963. func HandleOSLRequest(
  964. tunnelOwner TunnelOwner, tunnel *Tunnel, payload []byte) error {
  965. var oslRequest protocol.OSLRequest
  966. err := json.Unmarshal(payload, &oslRequest)
  967. if err != nil {
  968. return errors.Trace(err)
  969. }
  970. if oslRequest.ClearLocalSLOKs {
  971. DeleteSLOKs()
  972. }
  973. seededNewSLOK := false
  974. for _, slok := range oslRequest.SeedPayload.SLOKs {
  975. duplicate, err := SetSLOK(slok.ID, slok.Key)
  976. if err != nil {
  977. // TODO: return error to trigger retry?
  978. NoticeWarning("SetSLOK failed: %s", errors.Trace(err))
  979. } else if !duplicate {
  980. seededNewSLOK = true
  981. }
  982. if tunnel.config.EmitSLOKs {
  983. NoticeSLOKSeeded(base64.StdEncoding.EncodeToString(slok.ID), duplicate)
  984. }
  985. }
  986. if seededNewSLOK {
  987. tunnelOwner.SignalSeededNewSLOK()
  988. }
  989. return nil
  990. }
  991. func HandleAlertRequest(
  992. tunnelOwner TunnelOwner, tunnel *Tunnel, payload []byte) error {
  993. var alertRequest protocol.AlertRequest
  994. err := json.Unmarshal(payload, &alertRequest)
  995. if err != nil {
  996. return errors.Trace(err)
  997. }
  998. if tunnel.config.EmitServerAlerts {
  999. NoticeServerAlert(alertRequest)
  1000. }
  1001. return nil
  1002. }