serverApi.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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. "encoding/base64"
  23. "encoding/hex"
  24. "encoding/json"
  25. "errors"
  26. "fmt"
  27. "io"
  28. "io/ioutil"
  29. "net"
  30. "net/http"
  31. "strconv"
  32. "sync/atomic"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/transferstats"
  34. )
  35. // ServerContext is a utility struct which holds all of the data associated
  36. // with a Psiphon server connection. In addition to the established tunnel, this
  37. // includes data associated with Psiphon API requests and a persistent http
  38. // client configured to make tunneled Psiphon API requests.
  39. type ServerContext struct {
  40. sessionId string
  41. tunnelNumber int64
  42. baseRequestUrl string
  43. psiphonHttpsClient *http.Client
  44. statsRegexps *transferstats.Regexps
  45. clientRegion string
  46. clientUpgradeVersion string
  47. serverHandshakeTimestamp string
  48. }
  49. // nextTunnelNumber is a monotonically increasing number assigned to each
  50. // successive tunnel connection. The sessionId and tunnelNumber together
  51. // form a globally unique identifier for tunnels, which is used for
  52. // stats. Note that the number is increasing but not necessarily
  53. // consecutive for each active tunnel in session.
  54. var nextTunnelNumber int64
  55. // MakeSessionId creates a new session ID. The same session ID is used across
  56. // multi-tunnel controller runs, where each tunnel has its own ServerContext
  57. // instance.
  58. // In server-side stats, we now consider a "session" to be the lifetime of the
  59. // Controller (e.g., the user's commanded start and stop) and we measure this
  60. // duration as well as the duration of each tunnel within the session.
  61. func MakeSessionId() (sessionId string, err error) {
  62. randomId, err := MakeSecureRandomBytes(PSIPHON_API_CLIENT_SESSION_ID_LENGTH)
  63. if err != nil {
  64. return "", ContextError(err)
  65. }
  66. return hex.EncodeToString(randomId), nil
  67. }
  68. // NewServerContext makes the tunnelled handshake request to the Psiphon server
  69. // and returns a ServerContext struct for use with subsequent Psiphon server API
  70. // requests (e.g., periodic connected and status requests).
  71. func NewServerContext(tunnel *Tunnel, sessionId string) (*ServerContext, error) {
  72. psiphonHttpsClient, err := makePsiphonHttpsClient(tunnel)
  73. if err != nil {
  74. return nil, ContextError(err)
  75. }
  76. serverContext := &ServerContext{
  77. sessionId: sessionId,
  78. tunnelNumber: atomic.AddInt64(&nextTunnelNumber, 1),
  79. baseRequestUrl: makeBaseRequestUrl(tunnel, "", sessionId),
  80. psiphonHttpsClient: psiphonHttpsClient,
  81. }
  82. err = serverContext.doHandshakeRequest()
  83. if err != nil {
  84. return nil, ContextError(err)
  85. }
  86. return serverContext, nil
  87. }
  88. // doHandshakeRequest performs the handshake API request. The handshake
  89. // returns upgrade info, newly discovered server entries -- which are
  90. // stored -- and sponsor info (home pages, stat regexes).
  91. func (serverContext *ServerContext) doHandshakeRequest() error {
  92. extraParams := make([]*ExtraParam, 0)
  93. serverEntryIpAddresses, err := GetServerEntryIpAddresses()
  94. if err != nil {
  95. return ContextError(err)
  96. }
  97. // Submit a list of known servers -- this will be used for
  98. // discovery statistics.
  99. for _, ipAddress := range serverEntryIpAddresses {
  100. extraParams = append(extraParams, &ExtraParam{"known_server", ipAddress})
  101. }
  102. url := buildRequestUrl(serverContext.baseRequestUrl, "handshake", extraParams...)
  103. responseBody, err := serverContext.doGetRequest(url)
  104. if err != nil {
  105. return ContextError(err)
  106. }
  107. // Skip legacy format lines and just parse the JSON config line
  108. configLinePrefix := []byte("Config: ")
  109. var configLine []byte
  110. for _, line := range bytes.Split(responseBody, []byte("\n")) {
  111. if bytes.HasPrefix(line, configLinePrefix) {
  112. configLine = line[len(configLinePrefix):]
  113. break
  114. }
  115. }
  116. if len(configLine) == 0 {
  117. return ContextError(errors.New("no config line found"))
  118. }
  119. // Note:
  120. // - 'preemptive_reconnect_lifetime_milliseconds' is currently unused
  121. // - 'ssh_session_id' is ignored; client session ID is used instead
  122. var handshakeConfig struct {
  123. Homepages []string `json:"homepages"`
  124. UpgradeClientVersion string `json:"upgrade_client_version"`
  125. PageViewRegexes []map[string]string `json:"page_view_regexes"`
  126. HttpsRequestRegexes []map[string]string `json:"https_request_regexes"`
  127. EncodedServerList []string `json:"encoded_server_list"`
  128. ClientRegion string `json:"client_region"`
  129. ServerTimestamp string `json:"server_timestamp"`
  130. }
  131. err = json.Unmarshal(configLine, &handshakeConfig)
  132. if err != nil {
  133. return ContextError(err)
  134. }
  135. serverContext.clientRegion = handshakeConfig.ClientRegion
  136. NoticeClientRegion(serverContext.clientRegion)
  137. var decodedServerEntries []*ServerEntry
  138. // Store discovered server entries
  139. for _, encodedServerEntry := range handshakeConfig.EncodedServerList {
  140. serverEntry, err := DecodeServerEntry(encodedServerEntry)
  141. if err != nil {
  142. return ContextError(err)
  143. }
  144. err = ValidateServerEntry(serverEntry)
  145. if err != nil {
  146. // Skip this entry and continue with the next one
  147. continue
  148. }
  149. decodedServerEntries = append(decodedServerEntries, serverEntry)
  150. }
  151. // The reason we are storing the entire array of server entries at once rather
  152. // than one at a time is that some desirable side-effects get triggered by
  153. // StoreServerEntries that don't get triggered by StoreServerEntry.
  154. err = StoreServerEntries(decodedServerEntries, true)
  155. if err != nil {
  156. return ContextError(err)
  157. }
  158. // TODO: formally communicate the sponsor and upgrade info to an
  159. // outer client via some control interface.
  160. for _, homepage := range handshakeConfig.Homepages {
  161. NoticeHomepage(homepage)
  162. }
  163. serverContext.clientUpgradeVersion = handshakeConfig.UpgradeClientVersion
  164. if handshakeConfig.UpgradeClientVersion != "" {
  165. NoticeClientUpgradeAvailable(handshakeConfig.UpgradeClientVersion)
  166. }
  167. var regexpsNotices []string
  168. serverContext.statsRegexps, regexpsNotices = transferstats.MakeRegexps(
  169. handshakeConfig.PageViewRegexes,
  170. handshakeConfig.HttpsRequestRegexes)
  171. for _, notice := range regexpsNotices {
  172. NoticeAlert(notice)
  173. }
  174. serverContext.serverHandshakeTimestamp = handshakeConfig.ServerTimestamp
  175. return nil
  176. }
  177. // DoConnectedRequest performs the connected API request. This request is
  178. // used for statistics. The server returns a last_connected token for
  179. // the client to store and send next time it connects. This token is
  180. // a timestamp (using the server clock, and should be rounded to the
  181. // nearest hour) which is used to determine when a connection represents
  182. // a unique user for a time period.
  183. func (serverContext *ServerContext) DoConnectedRequest() error {
  184. const DATA_STORE_LAST_CONNECTED_KEY = "lastConnected"
  185. lastConnected, err := GetKeyValue(DATA_STORE_LAST_CONNECTED_KEY)
  186. if err != nil {
  187. return ContextError(err)
  188. }
  189. if lastConnected == "" {
  190. lastConnected = "None"
  191. }
  192. url := buildRequestUrl(
  193. serverContext.baseRequestUrl,
  194. "connected",
  195. &ExtraParam{"session_id", serverContext.sessionId},
  196. &ExtraParam{"last_connected", lastConnected})
  197. responseBody, err := serverContext.doGetRequest(url)
  198. if err != nil {
  199. return ContextError(err)
  200. }
  201. var response struct {
  202. ConnectedTimestamp string `json:"connected_timestamp"`
  203. }
  204. err = json.Unmarshal(responseBody, &response)
  205. if err != nil {
  206. return ContextError(err)
  207. }
  208. err = SetKeyValue(DATA_STORE_LAST_CONNECTED_KEY, response.ConnectedTimestamp)
  209. if err != nil {
  210. return ContextError(err)
  211. }
  212. return nil
  213. }
  214. // StatsRegexps gets the Regexps used for the statistics for this tunnel.
  215. func (serverContext *ServerContext) StatsRegexps() *transferstats.Regexps {
  216. return serverContext.statsRegexps
  217. }
  218. // DoStatusRequest makes a /status request to the server, sending session stats.
  219. func (serverContext *ServerContext) DoStatusRequest(tunnel *Tunnel) error {
  220. url := makeStatusRequestUrl(serverContext.sessionId, serverContext.baseRequestUrl, true)
  221. payload, payloadInfo, err := makeStatusRequestPayload(tunnel.serverEntry.IpAddress)
  222. if err != nil {
  223. return ContextError(err)
  224. }
  225. err = serverContext.doPostRequest(url, "application/json", bytes.NewReader(payload))
  226. if err != nil {
  227. // Resend the transfer stats and tunnel stats later
  228. // Note: potential duplicate reports if the server received and processed
  229. // the request but the client failed to receive the response.
  230. putBackStatusRequestPayload(payloadInfo)
  231. return ContextError(err)
  232. }
  233. confirmStatusRequestPayload(payloadInfo)
  234. return nil
  235. }
  236. func makeStatusRequestUrl(sessionId, baseRequestUrl string, isTunneled bool) string {
  237. // Add a random amount of padding to help prevent stats updates from being
  238. // a predictable size (which often happens when the connection is quiet).
  239. padding := MakeSecureRandomPadding(0, PSIPHON_API_STATUS_REQUEST_PADDING_MAX_BYTES)
  240. // Legacy clients set "connected" to "0" when disconnecting, and this value
  241. // is used to calculate session duration estimates. This is now superseded
  242. // by explicit tunnel stats duration reporting.
  243. // The legacy method of reconstructing session durations is not compatible
  244. // with this client's connected request retries and asynchronous final
  245. // status request attempts. So we simply set this "connected" flag to reflect
  246. // whether the request is sent tunneled or not.
  247. connected := "1"
  248. if !isTunneled {
  249. connected = "0"
  250. }
  251. return buildRequestUrl(
  252. baseRequestUrl,
  253. "status",
  254. &ExtraParam{"session_id", sessionId},
  255. &ExtraParam{"connected", connected},
  256. // TODO: base64 encoding of padding means the padding
  257. // size is not exactly [0, PADDING_MAX_BYTES]
  258. &ExtraParam{"padding", base64.StdEncoding.EncodeToString(padding)})
  259. }
  260. // statusRequestPayloadInfo is a temporary structure for data used to
  261. // either "clear" or "put back" status request payload data depending
  262. // on whether or not the request succeeded.
  263. type statusRequestPayloadInfo struct {
  264. serverId string
  265. transferStats *transferstats.AccumulatedStats
  266. tunnelStats [][]byte
  267. }
  268. func makeStatusRequestPayload(
  269. serverId string) ([]byte, *statusRequestPayloadInfo, error) {
  270. transferStats := transferstats.TakeOutStatsForServer(serverId)
  271. tunnelStats, err := TakeOutUnreportedTunnelStats(
  272. PSIPHON_API_TUNNEL_STATS_MAX_COUNT)
  273. if err != nil {
  274. NoticeAlert(
  275. "TakeOutUnreportedTunnelStats failed: %s", ContextError(err))
  276. tunnelStats = nil
  277. // Proceed with transferStats only
  278. }
  279. payloadInfo := &statusRequestPayloadInfo{
  280. serverId, transferStats, tunnelStats}
  281. payload := make(map[string]interface{})
  282. hostBytes, bytesTransferred := transferStats.GetStatsForStatusRequest()
  283. payload["host_bytes"] = hostBytes
  284. payload["bytes_transferred"] = bytesTransferred
  285. // We're not recording these fields, but the server requires them.
  286. payload["page_views"] = make([]string, 0)
  287. payload["https_requests"] = make([]string, 0)
  288. // Tunnel stats records are already in JSON format
  289. jsonTunnelStats := make([]json.RawMessage, len(tunnelStats))
  290. for i, tunnelStatsRecord := range tunnelStats {
  291. jsonTunnelStats[i] = json.RawMessage(tunnelStatsRecord)
  292. }
  293. payload["tunnel_stats"] = jsonTunnelStats
  294. jsonPayload, err := json.Marshal(payload)
  295. if err != nil {
  296. // Send the transfer stats and tunnel stats later
  297. putBackStatusRequestPayload(payloadInfo)
  298. return nil, nil, ContextError(err)
  299. }
  300. return jsonPayload, payloadInfo, nil
  301. }
  302. func putBackStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  303. transferstats.PutBackStatsForServer(
  304. payloadInfo.serverId, payloadInfo.transferStats)
  305. err := PutBackUnreportedTunnelStats(payloadInfo.tunnelStats)
  306. if err != nil {
  307. // These tunnel stats records won't be resent under after a
  308. // datastore re-initialization.
  309. NoticeAlert(
  310. "PutBackUnreportedTunnelStats failed: %s", ContextError(err))
  311. }
  312. }
  313. func confirmStatusRequestPayload(payloadInfo *statusRequestPayloadInfo) {
  314. err := ClearReportedTunnelStats(payloadInfo.tunnelStats)
  315. if err != nil {
  316. // These tunnel stats records may be resent.
  317. NoticeAlert(
  318. "ClearReportedTunnelStats failed: %s", ContextError(err))
  319. }
  320. }
  321. // TryUntunneledStatusRequest makes direct connections to the specified
  322. // server (if supported) in an attempt to send useful bytes transferred
  323. // and tunnel duration stats after a tunnel has alreay failed.
  324. // The tunnel is assumed to be closed, but its config, protocol, and
  325. // context values must still be valid.
  326. // TryUntunneledStatusRequest emits notices detailing failed attempts.
  327. func TryUntunneledStatusRequest(tunnel *Tunnel, isShutdown bool) error {
  328. for _, port := range tunnel.serverEntry.GetDirectWebRequestPorts() {
  329. err := doUntunneledStatusRequest(tunnel, port, isShutdown)
  330. if err == nil {
  331. return nil
  332. }
  333. NoticeAlert("doUntunneledStatusRequest failed for %s:%s: %s",
  334. tunnel.serverEntry.IpAddress, port, err)
  335. }
  336. return errors.New("all attempts failed")
  337. }
  338. // doUntunneledStatusRequest attempts an untunneled stratus request.
  339. func doUntunneledStatusRequest(
  340. tunnel *Tunnel, port string, isShutdown bool) error {
  341. url := makeStatusRequestUrl(
  342. tunnel.serverContext.sessionId,
  343. makeBaseRequestUrl(tunnel, port, tunnel.serverContext.sessionId),
  344. false)
  345. certificate, err := DecodeCertificate(tunnel.serverEntry.WebServerCertificate)
  346. if err != nil {
  347. return ContextError(err)
  348. }
  349. timeout := PSIPHON_API_SERVER_TIMEOUT
  350. if isShutdown {
  351. timeout = PSIPHON_API_SHUTDOWN_SERVER_TIMEOUT
  352. }
  353. httpClient, requestUrl, err := MakeUntunneledHttpsClient(
  354. tunnel.untunneledDialConfig,
  355. certificate,
  356. url,
  357. timeout)
  358. if err != nil {
  359. return ContextError(err)
  360. }
  361. payload, payloadInfo, err := makeStatusRequestPayload(tunnel.serverEntry.IpAddress)
  362. if err != nil {
  363. return ContextError(err)
  364. }
  365. bodyType := "application/json"
  366. body := bytes.NewReader(payload)
  367. response, err := httpClient.Post(requestUrl, bodyType, body)
  368. if err == nil && response.StatusCode != http.StatusOK {
  369. response.Body.Close()
  370. err = fmt.Errorf("HTTP POST request failed with response code: %d", response.StatusCode)
  371. }
  372. if err != nil {
  373. // Resend the transfer stats and tunnel stats later
  374. // Note: potential duplicate reports if the server received and processed
  375. // the request but the client failed to receive the response.
  376. putBackStatusRequestPayload(payloadInfo)
  377. // Trim this error since it may include long URLs
  378. return ContextError(TrimError(err))
  379. }
  380. confirmStatusRequestPayload(payloadInfo)
  381. response.Body.Close()
  382. return nil
  383. }
  384. // RecordTunnelStats records a tunnel duration and bytes
  385. // sent and received for subsequent reporting and quality
  386. // analysis.
  387. //
  388. // Tunnel durations are precisely measured client-side
  389. // and reported in status requests. As the duration is
  390. // not determined until the tunnel is closed, tunnel
  391. // stats records are stored in the persistent datastore
  392. // and reported via subsequent status requests sent to any
  393. // Psiphon server.
  394. //
  395. // Since the status request that reports a tunnel stats
  396. // record is not necessarily handled by the same server, the
  397. // tunnel stats records include the original server ID.
  398. //
  399. // Other fields that may change between tunnel stats recording
  400. // and reporting include client geo data, propagation channel,
  401. // sponsor ID, client version. These are not stored in the
  402. // datastore (client region, in particular, since that would
  403. // create an on-disk record of user location).
  404. // TODO: the server could encrypt, with a nonce and key unknown to
  405. // the client, a blob containing this data; return it in the
  406. // handshake response; and the client could store and later report
  407. // this blob with its tunnel stats records.
  408. //
  409. // Multiple "status" requests may be in flight at once (due
  410. // to multi-tunnel, asynchronous final status retry, and
  411. // aggressive status requests for pre-registered tunnels),
  412. // To avoid duplicate reporting, tunnel stats records are
  413. // "taken-out" by a status request and then "put back" in
  414. // case the request fails.
  415. //
  416. // Note: since tunnel stats records have a globally unique
  417. // identifier (sessionId + tunnelNumber), we could tolerate
  418. // duplicate reporting and filter our duplicates on the
  419. // server-side. Permitting duplicate reporting could increase
  420. // the velocity of reporting (for example, both the asynchronous
  421. // untunneled final status requests and the post-connected
  422. // immediate startus requests could try to report the same tunnel
  423. // stats).
  424. // Duplicate reporting may also occur when a server receives and
  425. // processes a status request but the client fails to receive
  426. // the response.
  427. func RecordTunnelStats(
  428. sessionId string,
  429. tunnelNumber int64,
  430. tunnelServerIpAddress string,
  431. serverHandshakeTimestamp, duration string,
  432. totalBytesSent, totalBytesReceived int64) error {
  433. tunnelStats := struct {
  434. SessionId string `json:"session_id"`
  435. TunnelNumber int64 `json:"tunnel_number"`
  436. TunnelServerIpAddress string `json:"tunnel_server_ip_address"`
  437. ServerHandshakeTimestamp string `json:"server_handshake_timestamp"`
  438. Duration string `json:"duration"`
  439. TotalBytesSent int64 `json:"total_bytes_sent"`
  440. TotalBytesReceived int64 `json:"total_bytes_received"`
  441. }{
  442. sessionId,
  443. tunnelNumber,
  444. tunnelServerIpAddress,
  445. serverHandshakeTimestamp,
  446. duration,
  447. totalBytesSent,
  448. totalBytesReceived,
  449. }
  450. tunnelStatsJson, err := json.Marshal(tunnelStats)
  451. if err != nil {
  452. return ContextError(err)
  453. }
  454. return StoreTunnelStats(tunnelStatsJson)
  455. }
  456. // doGetRequest makes a tunneled HTTPS request and returns the response body.
  457. func (serverContext *ServerContext) doGetRequest(
  458. requestUrl string) (responseBody []byte, err error) {
  459. response, err := serverContext.psiphonHttpsClient.Get(requestUrl)
  460. if err == nil && response.StatusCode != http.StatusOK {
  461. response.Body.Close()
  462. err = fmt.Errorf("HTTP GET request failed with response code: %d", response.StatusCode)
  463. }
  464. if err != nil {
  465. // Trim this error since it may include long URLs
  466. return nil, ContextError(TrimError(err))
  467. }
  468. defer response.Body.Close()
  469. body, err := ioutil.ReadAll(response.Body)
  470. if err != nil {
  471. return nil, ContextError(err)
  472. }
  473. return body, nil
  474. }
  475. // doPostRequest makes a tunneled HTTPS POST request.
  476. func (serverContext *ServerContext) doPostRequest(
  477. requestUrl string, bodyType string, body io.Reader) (err error) {
  478. response, err := serverContext.psiphonHttpsClient.Post(requestUrl, bodyType, body)
  479. if err == nil && response.StatusCode != http.StatusOK {
  480. response.Body.Close()
  481. err = fmt.Errorf("HTTP POST request failed with response code: %d", response.StatusCode)
  482. }
  483. if err != nil {
  484. // Trim this error since it may include long URLs
  485. return ContextError(TrimError(err))
  486. }
  487. response.Body.Close()
  488. return nil
  489. }
  490. // makeBaseRequestUrl makes a URL containing all the common parameters
  491. // that are included with Psiphon API requests. These common parameters
  492. // are used for statistics.
  493. func makeBaseRequestUrl(tunnel *Tunnel, port, sessionId string) string {
  494. var requestUrl bytes.Buffer
  495. if port == "" {
  496. port = tunnel.serverEntry.WebServerPort
  497. }
  498. // Note: don't prefix with HTTPS scheme, see comment in doGetRequest.
  499. // e.g., don't do this: requestUrl.WriteString("https://")
  500. requestUrl.WriteString("http://")
  501. requestUrl.WriteString(tunnel.serverEntry.IpAddress)
  502. requestUrl.WriteString(":")
  503. requestUrl.WriteString(port)
  504. requestUrl.WriteString("/")
  505. // Placeholder for the path component of a request
  506. requestUrl.WriteString("%s")
  507. requestUrl.WriteString("?client_session_id=")
  508. requestUrl.WriteString(sessionId)
  509. requestUrl.WriteString("&server_secret=")
  510. requestUrl.WriteString(tunnel.serverEntry.WebServerSecret)
  511. requestUrl.WriteString("&propagation_channel_id=")
  512. requestUrl.WriteString(tunnel.config.PropagationChannelId)
  513. requestUrl.WriteString("&sponsor_id=")
  514. requestUrl.WriteString(tunnel.config.SponsorId)
  515. requestUrl.WriteString("&client_version=")
  516. requestUrl.WriteString(tunnel.config.ClientVersion)
  517. // TODO: client_tunnel_core_version
  518. requestUrl.WriteString("&relay_protocol=")
  519. requestUrl.WriteString(tunnel.protocol)
  520. requestUrl.WriteString("&client_platform=")
  521. requestUrl.WriteString(tunnel.config.ClientPlatform)
  522. requestUrl.WriteString("&tunnel_whole_device=")
  523. requestUrl.WriteString(strconv.Itoa(tunnel.config.TunnelWholeDevice))
  524. return requestUrl.String()
  525. }
  526. type ExtraParam struct{ name, value string }
  527. // buildRequestUrl makes a URL for an API request. The URL includes the
  528. // base request URL and any extra parameters for the specific request.
  529. func buildRequestUrl(baseRequestUrl, path string, extraParams ...*ExtraParam) string {
  530. var requestUrl bytes.Buffer
  531. requestUrl.WriteString(fmt.Sprintf(baseRequestUrl, path))
  532. for _, extraParam := range extraParams {
  533. requestUrl.WriteString("&")
  534. requestUrl.WriteString(extraParam.name)
  535. requestUrl.WriteString("=")
  536. requestUrl.WriteString(extraParam.value)
  537. }
  538. return requestUrl.String()
  539. }
  540. // makeHttpsClient creates a Psiphon HTTPS client that tunnels requests and which validates
  541. // the web server using the Psiphon server entry web server certificate.
  542. // This is not a general purpose HTTPS client.
  543. // As the custom dialer makes an explicit TLS connection, URLs submitted to the returned
  544. // http.Client should use the "http://" scheme. Otherwise http.Transport will try to do another TLS
  545. // handshake inside the explicit TLS session.
  546. func makePsiphonHttpsClient(tunnel *Tunnel) (httpsClient *http.Client, err error) {
  547. certificate, err := DecodeCertificate(tunnel.serverEntry.WebServerCertificate)
  548. if err != nil {
  549. return nil, ContextError(err)
  550. }
  551. tunneledDialer := func(_, addr string) (conn net.Conn, err error) {
  552. return tunnel.sshClient.Dial("tcp", addr)
  553. }
  554. dialer := NewCustomTLSDialer(
  555. &CustomTLSConfig{
  556. Dial: tunneledDialer,
  557. Timeout: PSIPHON_API_SERVER_TIMEOUT,
  558. VerifyLegacyCertificate: certificate,
  559. })
  560. transport := &http.Transport{
  561. Dial: dialer,
  562. ResponseHeaderTimeout: PSIPHON_API_SERVER_TIMEOUT,
  563. }
  564. return &http.Client{
  565. Transport: transport,
  566. Timeout: PSIPHON_API_SERVER_TIMEOUT,
  567. }, nil
  568. }