Rod Hynes 8 лет назад
Родитель
Сommit
49eae87f49
39 измененных файлов с 132 добавлено и 133 удалено
  1. 2 1
      MobileLibrary/psi/psi.go
  2. 1 1
      psiphon/TCPConn.go
  3. 3 3
      psiphon/common/buildinfo.go
  4. 2 2
      psiphon/common/net.go
  5. 1 1
      psiphon/common/networkInterface.go
  6. 2 2
      psiphon/common/obfuscatedSshConn.go
  7. 3 3
      psiphon/common/osl/osl.go
  8. 1 1
      psiphon/common/osl/osl_test.go
  9. 1 1
      psiphon/common/osl/paver/main.go
  10. 2 2
      psiphon/common/protocol/serverEntry_test.go
  11. 2 2
      psiphon/common/subnet.go
  12. 1 1
      psiphon/common/throttled.go
  13. 11 11
      psiphon/config_test.go
  14. 2 2
      psiphon/controller.go
  15. 1 1
      psiphon/controller_test.go
  16. 2 2
      psiphon/dataStore.go
  17. 2 2
      psiphon/feedback.go
  18. 9 9
      psiphon/meekConn.go
  19. 1 1
      psiphon/net.go
  20. 3 3
      psiphon/notice.go
  21. 1 1
      psiphon/remoteServerList_test.go
  22. 29 30
      psiphon/server/api.go
  23. 4 4
      psiphon/server/config.go
  24. 1 1
      psiphon/server/dns.go
  25. 4 4
      psiphon/server/meek.go
  26. 6 6
      psiphon/server/psinet/psinet.go
  27. 1 1
      psiphon/server/server_test.go
  28. 1 1
      psiphon/server/services.go
  29. 1 1
      psiphon/server/trafficRules.go
  30. 8 8
      psiphon/server/tunnelServer.go
  31. 1 1
      psiphon/server/webServer.go
  32. 2 2
      psiphon/serverApi.go
  33. 2 2
      psiphon/transferstats/conn.go
  34. 8 8
      psiphon/tunnel.go
  35. 1 2
      psiphon/upstreamproxy/auth_basic.go
  36. 4 4
      psiphon/upstreamproxy/proxy_http.go
  37. 1 1
      psiphon/upstreamproxy/proxy_socks4.go
  38. 3 3
      psiphon/upstreamproxy/transport_proxy_auth.go
  39. 2 2
      psiphon/upstreamproxy/upstreamproxy.go

+ 2 - 1
MobileLibrary/psi/psi.go

@@ -131,7 +131,8 @@ func Stop() {
 	}
 }
 
-// This is a passthrough to Controller.SetClientVerificationPayloadForActiveTunnels.
+// SetClientVerificationPayload is a passthrough to
+// Controller.SetClientVerificationPayloadForActiveTunnels.
 // Note: should only be called after Start() and before Stop(); otherwise,
 // will silently take no action.
 func SetClientVerificationPayload(clientVerificationPayload string) {

+ 1 - 1
psiphon/TCPConn.go

@@ -101,7 +101,7 @@ func interruptibleTCPDial(addr string, config *DialConfig) (*TCPConn, error) {
 	// Note: since this goroutine may be left running after an interrupt, don't
 	// call Notice() or perform other actions unexpected after a Controller stops.
 	// The lifetime of the goroutine may depend on the host OS TCP connect timeout
-	// when tcpDial, amoung other things, when makes a blocking syscall.Connect()
+	// when tcpDial, among other things, when makes a blocking syscall.Connect()
 	// call.
 	go func() {
 		if config.IPv6Synthesizer != nil {

+ 3 - 3
psiphon/common/buildinfo.go

@@ -51,7 +51,7 @@ var gomobileVersion string
 // Dependencies should be listed as a JSON object like the following (no spaces) {"github.com/Psiphon-Labs/psiphon-tunnel-core":"abcdef","...":"..."}
 var dependencies string
 
-// Capture relevant build information here for use in clients or servers
+// BuildInfo captures relevant build information here for use in clients or servers
 type BuildInfo struct {
 	BuildDate       string          `json:"buildDate"`
 	BuildRepo       string          `json:"buildRepo"`
@@ -61,7 +61,7 @@ type BuildInfo struct {
 	Dependencies    json.RawMessage `json:"dependencies"`
 }
 
-// Convert 'BuildInfo' struct to 'map[string]interface{}'
+// ToMap converts 'BuildInfo' struct to 'map[string]interface{}'
 func (bi *BuildInfo) ToMap() *map[string]interface{} {
 
 	var dependenciesMap map[string]interface{}
@@ -78,7 +78,7 @@ func (bi *BuildInfo) ToMap() *map[string]interface{} {
 	return &buildInfoMap
 }
 
-// Return an instance of the BuildInfo struct
+// GetBuildInfo returns an instance of the BuildInfo struct
 func GetBuildInfo() *BuildInfo {
 	if strings.TrimSpace(dependencies) == "" {
 		dependencies = "{}"

+ 2 - 2
psiphon/common/net.go

@@ -70,7 +70,7 @@ func (conns *Conns) CloseAll() {
 	conns.mutex.Lock()
 	defer conns.mutex.Unlock()
 	conns.isClosed = true
-	for conn, _ := range conns.conns {
+	for conn := range conns.conns {
 		conn.Close()
 	}
 	conns.conns = make(map[net.Conn]bool)
@@ -259,7 +259,7 @@ func (conn *ActivityMonitoredConn) GetActiveDuration() time.Duration {
 	return time.Duration(atomic.LoadInt64(&conn.lastReadActivityTime) - conn.monotonicStartTime)
 }
 
-// GetLastActivityTime returns the arbitrary monotonic time of the last Read.
+// GetLastActivityMonotime returns the arbitrary monotonic time of the last Read.
 func (conn *ActivityMonitoredConn) GetLastActivityMonotime() monotime.Time {
 	return monotime.Time(atomic.LoadInt64(&conn.lastReadActivityTime))
 }

+ 1 - 1
psiphon/common/networkInterface.go

@@ -24,7 +24,7 @@ import (
 	"net"
 )
 
-// GetInterfaceIPAddress takes an interface name, such as "eth0", and returns
+// GetInterfaceIPAddresses takes an interface name, such as "eth0", and returns
 // the first IPv4 and IPv6 addresses associated with it. Either of the IPv4 or
 // IPv6 address may be nil. If neither type of address is found, an error
 // is returned.

+ 2 - 2
psiphon/common/obfuscatedSshConn.go

@@ -125,7 +125,7 @@ func NewObfuscatedSshConn(
 		obfuscator, err = NewServerObfuscator(
 			conn, &ObfuscatorConfig{Keyword: obfuscationKeyword})
 		if err != nil {
-			// TODO: readForver() equivilent
+			// TODO: readForver() equivalent
 			return nil, ContextError(err)
 		}
 		readDeobfuscate = obfuscator.ObfuscateClientToServer
@@ -295,7 +295,7 @@ func (conn *ObfuscatedSshConn) readAndTransform(buffer []byte) (n int, err error
 // http://www.ietf.org/rfc/rfc4253.txt sec 7.3, 12:
 // The payload for SSH_MSG_NEWKEYS is one byte, the packet type, value 21.
 //
-// SSH packet padding values are transformed to achive random, variable length
+// SSH packet padding values are transformed to achieve random, variable length
 // padding during the KEX phase as a partial defense against traffic analysis.
 // (The transformer can do this since only the payload and not the padding of
 // these packets is authenticated in the "exchange hash").

+ 3 - 3
psiphon/common/osl/osl.go

@@ -433,7 +433,7 @@ func (state *ClientSeedState) Resume(
 	state.signalIssueSLOKs = signalIssueSLOKs
 }
 
-// NewClientSeedPortForwardState creates a new client port forward
+// NewClientSeedPortForward creates a new client port forward
 // traffic progress tracker. Port forward progress reported to the
 // ClientSeedPortForward is added to seed state progress for all
 // seed specs containing upstreamIPAddress in their subnets.
@@ -497,7 +497,7 @@ func (state *ClientSeedState) sendIssueSLOKsSignal() {
 	}
 }
 
-// UpdateProgress adds port forward bytes transfered and duration to
+// UpdateProgress adds port forward bytes transferred and duration to
 // all seed spec progresses associated with the port forward.
 // If UpdateProgress is invoked after the SLOK time period has rolled
 // over, any pending seeded SLOKs are issued and all progress is reset.
@@ -783,7 +783,7 @@ type PaveLogInfo struct {
 // epoch to endTime, and a pave file for each OSL. paveServerEntries is
 // a map from hex-encoded OSL IDs to server entries to pave into that OSL.
 // When entries are found, OSL will contain those entries, newline
-// seperated. Otherwise the OSL will still be issued, but be empty.
+// separated. Otherwise the OSL will still be issued, but be empty.
 //
 // As OSLs outside the epoch-endTime range will no longer appear in
 // the registry, Pave is intended to be used to create the full set

+ 1 - 1
psiphon/common/osl/osl_test.go

@@ -376,7 +376,7 @@ func TestOSL(t *testing.T) {
 			pavedRegistries[propagationChannelID] = paveFiles[len(paveFiles)-1].Contents
 
 			pavedOSLFileContents[propagationChannelID] = make(map[string][]byte)
-			for _, paveFile := range paveFiles[0:len(paveFiles)] {
+			for _, paveFile := range paveFiles[0:] {
 				pavedOSLFileContents[propagationChannelID][paveFile.Name] = paveFile.Contents
 			}
 		}

+ 1 - 1
psiphon/common/osl/paver/main.go

@@ -188,7 +188,7 @@ func main() {
 
 	// pave a directory for each propagation channel
 
-	for propagationChannelID, _ := range allPropagationChannelIDs {
+	for propagationChannelID := range allPropagationChannelIDs {
 
 		paveFiles, err := config.Pave(
 			endTime,

+ 2 - 2
psiphon/common/protocol/serverEntry_test.go

@@ -54,7 +54,7 @@ func TestDecodeServerEntryList(t *testing.T) {
 	}
 	for _, serverEntry := range serverEntries {
 		if serverEntry.IpAddress != _EXPECTED_IP_ADDRESS {
-			t.Error("unexpected IP address in decoded server entry: %s", serverEntry.IpAddress)
+			t.Errorf("unexpected IP address in decoded server entry: %s", serverEntry.IpAddress)
 		}
 	}
 }
@@ -86,7 +86,7 @@ func TestStreamingServerEntryDecoder(t *testing.T) {
 	}
 	for _, serverEntry := range serverEntries {
 		if serverEntry.IpAddress != _EXPECTED_IP_ADDRESS {
-			t.Error("unexpected IP address in decoded server entry: %s", serverEntry.IpAddress)
+			t.Errorf("unexpected IP address in decoded server entry: %s", serverEntry.IpAddress)
 		}
 	}
 }

+ 2 - 2
psiphon/common/subnet.go

@@ -53,8 +53,8 @@ func NewSubnetLookup(CIDRs []string) (SubnetLookup, error) {
 	return lookup, nil
 }
 
-// NewSubnetLookup creates a SubnetLookup from text routes data.
-// The input format is expected to be text lines where each line
+// NewSubnetLookupFromRoutes creates a SubnetLookup from text routes
+// data. The input format is expected to be text lines where each line
 // is, e.g., "1.2.3.0\t255.255.255.0\n"
 func NewSubnetLookupFromRoutes(routesData []byte) (SubnetLookup, error) {
 

+ 1 - 1
psiphon/common/throttled.go

@@ -90,7 +90,7 @@ func NewThrottledConn(conn net.Conn, limits RateLimits) *ThrottledConn {
 // other goroutines are calling Read/Write. This function
 // will not block, and the new rate limits will be
 // applied within Read/Write, but not necessarily until
-// some futher I/O at previous rates.
+// some further I/O at previous rates.
 func (conn *ThrottledConn) SetLimits(limits RateLimits) {
 
 	// Using atomic instead of mutex to avoid blocking

+ 11 - 11
psiphon/config_test.go

@@ -177,7 +177,7 @@ func TestDownloadURLs(t *testing.T) {
 		{
 			"missing OnlyAfterAttempts = 0",
 			[]*DownloadURL{
-				&DownloadURL{
+				{
 					URL:               encodedA,
 					OnlyAfterAttempts: 1,
 				},
@@ -190,7 +190,7 @@ func TestDownloadURLs(t *testing.T) {
 		{
 			"single URL, multiple attempts",
 			[]*DownloadURL{
-				&DownloadURL{
+				{
 					URL:               encodedA,
 					OnlyAfterAttempts: 0,
 				},
@@ -203,15 +203,15 @@ func TestDownloadURLs(t *testing.T) {
 		{
 			"multiple URLs, single attempt",
 			[]*DownloadURL{
-				&DownloadURL{
+				{
 					URL:               encodedA,
 					OnlyAfterAttempts: 0,
 				},
-				&DownloadURL{
+				{
 					URL:               encodedB,
 					OnlyAfterAttempts: 1,
 				},
-				&DownloadURL{
+				{
 					URL:               encodedC,
 					OnlyAfterAttempts: 1,
 				},
@@ -224,15 +224,15 @@ func TestDownloadURLs(t *testing.T) {
 		{
 			"multiple URLs, multiple attempts",
 			[]*DownloadURL{
-				&DownloadURL{
+				{
 					URL:               encodedA,
 					OnlyAfterAttempts: 0,
 				},
-				&DownloadURL{
+				{
 					URL:               encodedB,
 					OnlyAfterAttempts: 1,
 				},
-				&DownloadURL{
+				{
 					URL:               encodedC,
 					OnlyAfterAttempts: 1,
 				},
@@ -245,15 +245,15 @@ func TestDownloadURLs(t *testing.T) {
 		{
 			"multiple URLs, multiple attempts",
 			[]*DownloadURL{
-				&DownloadURL{
+				{
 					URL:               encodedA,
 					OnlyAfterAttempts: 0,
 				},
-				&DownloadURL{
+				{
 					URL:               encodedB,
 					OnlyAfterAttempts: 1,
 				},
-				&DownloadURL{
+				{
 					URL:               encodedC,
 					OnlyAfterAttempts: 3,
 				},

+ 2 - 2
psiphon/controller.go

@@ -501,7 +501,7 @@ func (controller *Controller) startOrSignalConnectedReporter() {
 	}
 }
 
-// upgradeDownloader makes periodic attemps to complete a client upgrade
+// upgradeDownloader makes periodic attempts to complete a client upgrade
 // download. DownloadUpgrade() is resumable, so each attempt has potential for
 // getting closer to completion, even in conditions where the download or
 // tunnel is repeatedly interrupted.
@@ -970,7 +970,7 @@ func (controller *Controller) setClientVerificationPayloadForActiveTunnels(
 
 // Dial selects an active tunnel and establishes a port forward
 // connection through the selected tunnel. Failure to connect is considered
-// a port foward failure, for the purpose of monitoring tunnel health.
+// a port forward failure, for the purpose of monitoring tunnel health.
 func (controller *Controller) Dial(
 	remoteAddr string, alwaysTunnel bool, downstreamConn net.Conn) (conn net.Conn, err error) {
 

+ 1 - 1
psiphon/controller_test.go

@@ -1080,7 +1080,7 @@ func initDisruptor() {
 
 const upstreamProxyURL = "http://127.0.0.1:2161"
 
-var upstreamProxyCustomHeaders = map[string][]string{"X-Test-Header-Name": []string{"test-header-value1", "test-header-value2"}}
+var upstreamProxyCustomHeaders = map[string][]string{"X-Test-Header-Name": {"test-header-value1", "test-header-value2"}}
 
 func hasExpectedCustomHeaders(h http.Header) bool {
 	for name, values := range upstreamProxyCustomHeaders {

+ 2 - 2
psiphon/dataStore.go

@@ -736,7 +736,7 @@ func ReportAvailableRegions() {
 	}
 
 	regionList := make([]string, 0, len(regions))
-	for region, _ := range regions {
+	for region := range regions {
 		// Some server entries do not have a region, but it makes no sense to return
 		// an empty string as an "available region".
 		if region != "" {
@@ -910,7 +910,7 @@ var persistentStatTypes = []string{
 	PERSISTENT_STAT_TYPE_TUNNEL,
 }
 
-// StorePersistentStats adds a new persistent stat record, which
+// StorePersistentStat adds a new persistent stat record, which
 // is set to StateUnreported and is an immediate candidate for
 // reporting.
 //

+ 2 - 2
psiphon/feedback.go

@@ -187,7 +187,7 @@ func uploadFeedback(config *DialConfig, feedbackData []byte, url, userAgent stri
 
 // Pad src to the next block boundary with PKCS7 padding
 // (https://tools.ietf.org/html/rfc5652#section-6.3).
-func AddPKCS7Padding(src []byte, blockSize int) []byte {
+func addPKCS7Padding(src []byte, blockSize int) []byte {
 	paddingLen := blockSize - (len(src) % blockSize)
 	padding := bytes.Repeat([]byte{byte(paddingLen)}, paddingLen)
 	return append(src, padding...)
@@ -197,7 +197,7 @@ func AddPKCS7Padding(src []byte, blockSize int) []byte {
 func encryptAESCBC(plaintext []byte) ([]byte, []byte, []byte, error) {
 	// CBC mode works on blocks so plaintexts need to be padded to the
 	// next whole block (https://tools.ietf.org/html/rfc5246#section-6.2.3.2).
-	plaintext = AddPKCS7Padding(plaintext, aes.BlockSize)
+	plaintext = addPKCS7Padding(plaintext, aes.BlockSize)
 
 	ciphertext := make([]byte, len(plaintext))
 	iv, err := common.MakeSecureRandomBytes(aes.BlockSize)

+ 9 - 9
psiphon/meekConn.go

@@ -436,27 +436,27 @@ func (meek *MeekConn) Write(buffer []byte) (n int, err error) {
 	return n, err
 }
 
-// Stub implementation of net.Conn.LocalAddr
+// LocalAddr is a stub implementation of net.Conn.LocalAddr
 func (meek *MeekConn) LocalAddr() net.Addr {
 	return nil
 }
 
-// Stub implementation of net.Conn.RemoteAddr
+// RemoteAddr is a stub implementation of net.Conn.RemoteAddr
 func (meek *MeekConn) RemoteAddr() net.Addr {
 	return nil
 }
 
-// Stub implementation of net.Conn.SetDeadline
+// SetDeadline is a stub implementation of net.Conn.SetDeadline
 func (meek *MeekConn) SetDeadline(t time.Time) error {
 	return common.ContextError(errors.New("not supported"))
 }
 
-// Stub implementation of net.Conn.SetReadDeadline
+// SetReadDeadline is a stub implementation of net.Conn.SetReadDeadline
 func (meek *MeekConn) SetReadDeadline(t time.Time) error {
 	return common.ContextError(errors.New("not supported"))
 }
 
-// Stub implementation of net.Conn.SetWriteDeadline
+// SetWriteDeadline is a stub implementation of net.Conn.SetWriteDeadline
 func (meek *MeekConn) SetWriteDeadline(t time.Time) error {
 	return common.ContextError(errors.New("not supported"))
 }
@@ -612,7 +612,7 @@ func (meek *MeekConn) roundTrip(sendPayload []byte) (int64, error) {
 	//
 	// 4. While reading the response payload. The client will omit its
 	//    request payload when retrying, as the server has already
-	//    acknowleged it. The client will also indicate to the server
+	//    acknowledged it. The client will also indicate to the server
 	//    the amount of response payload already received, and the
 	//    server will skip resending the indicated amount of response
 	//    payload.
@@ -622,7 +622,7 @@ func (meek *MeekConn) roundTrip(sendPayload []byte) (int64, error) {
 
 	retries := uint(0)
 	retryDeadline := monotime.Now().Add(MEEK_ROUND_TRIP_RETRY_DEADLINE)
-	serverAcknowlegedRequestPayload := false
+	serverAcknowledgedRequestPayload := false
 	receivedPayloadSize := int64(0)
 
 	for try := 0; ; try++ {
@@ -631,7 +631,7 @@ func (meek *MeekConn) roundTrip(sendPayload []byte) (int64, error) {
 		// partial server response.
 
 		var sendPayloadReader io.Reader
-		if !serverAcknowlegedRequestPayload {
+		if !serverAcknowledgedRequestPayload {
 			sendPayloadReader = bytes.NewReader(sendPayload)
 		}
 
@@ -693,7 +693,7 @@ func (meek *MeekConn) roundTrip(sendPayload []byte) (int64, error) {
 
 			// Received the response status code, so the server
 			// must have received the request payload.
-			serverAcknowlegedRequestPayload = true
+			serverAcknowledgedRequestPayload = true
 
 			readPayloadSize, err := meek.readPayload(response.Body)
 			response.Body.Close()

+ 1 - 1
psiphon/net.go

@@ -384,7 +384,7 @@ func MakeDownloadHttpClient(
 	return httpClient, requestUrl, nil
 }
 
-// ResumeDownload is a resuable helper that downloads requestUrl via the
+// ResumeDownload is a reusable helper that downloads requestUrl via the
 // httpClient, storing the result in downloadFilename when the download is
 // complete. Intermediate, partial downloads state is stored in
 // downloadFilename.part and downloadFilename.part.etag.

+ 3 - 3
psiphon/notice.go

@@ -114,7 +114,7 @@ func outputNotice(noticeType string, noticeFlags uint32, args ...interface{}) {
 		output = string(encodedJson)
 	} else {
 		// Try to emit a properly formatted Alert notice that the outer client can
-		// report. One scenario where this is useful is if the preceeding Marshal
+		// report. One scenario where this is useful is if the preceding Marshal
 		// fails due to bad data in the args. This has happened for a json.RawMessage
 		// field.
 		obj := make(map[string]interface{})
@@ -247,12 +247,12 @@ func NoticeListeningSocksProxyPort(port int) {
 	outputNotice("ListeningSocksProxyPort", 0, "port", port)
 }
 
-// NoticeSocksProxyPortInUse is a failure to use the configured LocalHttpProxyPort
+// NoticeHttpProxyPortInUse is a failure to use the configured LocalHttpProxyPort
 func NoticeHttpProxyPortInUse(port int) {
 	outputNotice("HttpProxyPortInUse", noticeShowUser, "port", port)
 }
 
-// NoticeListeningSocksProxyPort is the selected port for the listening local HTTP proxy
+// NoticeListeningHttpProxyPort is the selected port for the listening local HTTP proxy
 func NoticeListeningHttpProxyPort(port int) {
 	outputNotice("ListeningHttpProxyPort", 0, "port", port)
 }

+ 1 - 1
psiphon/remoteServerList_test.go

@@ -172,7 +172,7 @@ func TestObfuscatedRemoteServerLists(t *testing.T) {
 		signingPublicKey,
 		signingPrivateKey,
 		map[string][]string{
-			oslID: []string{string(encodedServerEntry)},
+			oslID: {string(encodedServerEntry)},
 		},
 		nil)
 	if err != nil {

+ 29 - 30
psiphon/server/api.go

@@ -110,7 +110,7 @@ func dispatchAPIRequestHandler(
 
 	// Before invoking the handlers, enforce some preconditions:
 	//
-	// - A handshake request must preceed any other requests.
+	// - A handshake request must precede any other requests.
 	// - When the handshake results in a traffic rules state where
 	//   the client is immediately exhausted, no requests
 	//   may succeed. This case ensures that blocked clients do
@@ -240,8 +240,8 @@ func handshakeAPIRequestHandler(
 
 var connectedRequestParams = append(
 	[]requestParamSpec{
-		requestParamSpec{"session_id", isHexDigits, 0},
-		requestParamSpec{"last_connected", isLastConnected, 0}},
+		{"session_id", isHexDigits, 0},
+		{"last_connected", isLastConnected, 0}},
 	baseRequestParams...)
 
 // connectedAPIRequestHandler implements the "connected" API request.
@@ -281,8 +281,8 @@ func connectedAPIRequestHandler(
 
 var statusRequestParams = append(
 	[]requestParamSpec{
-		requestParamSpec{"session_id", isHexDigits, 0},
-		requestParamSpec{"connected", isBooleanFlag, 0}},
+		{"session_id", isHexDigits, 0},
+		{"connected", isBooleanFlag, 0}},
 	baseRequestParams...)
 
 // statusAPIRequestHandler implements the "status" API request.
@@ -501,9 +501,8 @@ func clientVerificationAPIRequestHandler(
 			}
 
 			return responsePayload, nil
-		} else {
-			return make([]byte, 0), nil
 		}
+		return make([]byte, 0), nil
 	} else {
 		verificationData, err := getJSONObjectRequestParam(params, "verificationData")
 		if err != nil {
@@ -552,29 +551,29 @@ const (
 // Each param is expected to be a string, unless requestParamArray
 // is specified, in which case an array of string is expected.
 var baseRequestParams = []requestParamSpec{
-	requestParamSpec{"server_secret", isServerSecret, requestParamNotLogged},
-	requestParamSpec{"client_session_id", isHexDigits, requestParamNotLogged},
-	requestParamSpec{"propagation_channel_id", isHexDigits, 0},
-	requestParamSpec{"sponsor_id", isHexDigits, 0},
-	requestParamSpec{"client_version", isIntString, 0},
-	requestParamSpec{"client_platform", isClientPlatform, 0},
-	requestParamSpec{"client_build_rev", isHexDigits, requestParamOptional},
-	requestParamSpec{"relay_protocol", isRelayProtocol, 0},
-	requestParamSpec{"tunnel_whole_device", isBooleanFlag, requestParamOptional},
-	requestParamSpec{"device_region", isRegionCode, requestParamOptional},
-	requestParamSpec{"ssh_client_version", isAnyString, requestParamOptional},
-	requestParamSpec{"upstream_proxy_type", isUpstreamProxyType, requestParamOptional},
-	requestParamSpec{"upstream_proxy_custom_header_names", isAnyString, requestParamOptional | requestParamArray},
-	requestParamSpec{"meek_dial_address", isDialAddress, requestParamOptional},
-	requestParamSpec{"meek_resolved_ip_address", isIPAddress, requestParamOptional},
-	requestParamSpec{"meek_sni_server_name", isDomain, requestParamOptional},
-	requestParamSpec{"meek_host_header", isHostHeader, requestParamOptional},
-	requestParamSpec{"meek_transformed_host_name", isBooleanFlag, requestParamOptional},
-	requestParamSpec{"user_agent", isAnyString, requestParamOptional},
-	requestParamSpec{"tls_profile", isAnyString, requestParamOptional},
-	requestParamSpec{"server_entry_region", isRegionCode, requestParamOptional},
-	requestParamSpec{"server_entry_source", isServerEntrySource, requestParamOptional},
-	requestParamSpec{"server_entry_timestamp", isISO8601Date, requestParamOptional},
+	{"server_secret", isServerSecret, requestParamNotLogged},
+	{"client_session_id", isHexDigits, requestParamNotLogged},
+	{"propagation_channel_id", isHexDigits, 0},
+	{"sponsor_id", isHexDigits, 0},
+	{"client_version", isIntString, 0},
+	{"client_platform", isClientPlatform, 0},
+	{"client_build_rev", isHexDigits, requestParamOptional},
+	{"relay_protocol", isRelayProtocol, 0},
+	{"tunnel_whole_device", isBooleanFlag, requestParamOptional},
+	{"device_region", isRegionCode, requestParamOptional},
+	{"ssh_client_version", isAnyString, requestParamOptional},
+	{"upstream_proxy_type", isUpstreamProxyType, requestParamOptional},
+	{"upstream_proxy_custom_header_names", isAnyString, requestParamOptional | requestParamArray},
+	{"meek_dial_address", isDialAddress, requestParamOptional},
+	{"meek_resolved_ip_address", isIPAddress, requestParamOptional},
+	{"meek_sni_server_name", isDomain, requestParamOptional},
+	{"meek_host_header", isHostHeader, requestParamOptional},
+	{"meek_transformed_host_name", isBooleanFlag, requestParamOptional},
+	{"user_agent", isAnyString, requestParamOptional},
+	{"tls_profile", isAnyString, requestParamOptional},
+	{"server_entry_region", isRegionCode, requestParamOptional},
+	{"server_entry_source", isServerEntrySource, requestParamOptional},
+	{"server_entry_timestamp", isISO8601Date, requestParamOptional},
 }
 
 func validateRequestParams(

+ 4 - 4
psiphon/server/config.go

@@ -75,7 +75,7 @@ type Config struct {
 	// MaxMind database files. When empty, no GeoIP lookups are
 	// performed. Each file is queried, in order, for the
 	// logged fields: country code, city, and ISP. Multiple
-	// file support accomodates the MaxMind distribution where
+	// file support accommodates the MaxMind distribution where
 	// ISP data in a separate file.
 	GeoIPDatabaseFilenames []string
 
@@ -195,7 +195,7 @@ type Config struct {
 	// MeekCachedResponsePoolBufferSize is the size of a fixed-size,
 	// shared buffer used to temporarily extend a private buffer when
 	// MeekCachedResponseBufferSize is insufficient. Shared buffers
-	// allow some clients to sucessfully retry longer response payloads
+	// allow some clients to successfully retry longer response payloads
 	// without allocating large buffers for all clients.
 	// A default of 64K is used when MeekCachedResponsePoolBufferSize
 	// is 0.
@@ -324,7 +324,7 @@ func LoadConfig(configJSON []byte) (*Config, error) {
 		}
 	}
 
-	for tunnelProtocol, _ := range config.TunnelProtocolPorts {
+	for tunnelProtocol := range config.TunnelProtocolPorts {
 		if !common.Contains(protocol.SupportedTunnelProtocols, tunnelProtocol) {
 			return nil, fmt.Errorf("Unsupported tunnel protocol: %s", tunnelProtocol)
 		}
@@ -613,7 +613,7 @@ func GenerateConfig(params *GenerateConfigParams) ([]byte, []byte, []byte, error
 		capabilities = append(capabilities, protocol.CAPABILITY_UNTUNNELED_WEB_API_REQUESTS)
 	}
 
-	for tunnelProtocol, _ := range params.TunnelProtocolPorts {
+	for tunnelProtocol := range params.TunnelProtocolPorts {
 		capabilities = append(capabilities, protocol.GetCapability(tunnelProtocol))
 	}
 

+ 1 - 1
psiphon/server/dns.go

@@ -142,7 +142,7 @@ func (dns *DNSResolver) reloadWhenStale() {
 	// when no write lock is pending). An atomic.CompareAndSwapInt32 is
 	// used to ensure only one goroutine enters Reload() and blocks on
 	// its write lock. Finally, since since ReloadableFile.Reload
-	// checks whether the underlying file has changed _before_ aquiring a
+	// checks whether the underlying file has changed _before_ acquiring a
 	// write lock, we only incur write lock blocking when "/etc/resolv.conf"
 	// has actually changed.
 

+ 4 - 4
psiphon/server/meek.go

@@ -182,7 +182,7 @@ func (server *MeekServer) Run() error {
 	// Notes:
 	// - WriteTimeout may include time awaiting request, as per:
 	//   https://blog.cloudflare.com/the-complete-guide-to-golang-net-http-timeouts
-	// - Legacy meek-server wrapped each client HTTP connection with an explict idle
+	// - Legacy meek-server wrapped each client HTTP connection with an explicit idle
 	//   timeout net.Conn and didn't use http.Server timeouts. We could do the same
 	//   here (use ActivityMonitoredConn) but the stock http.Server timeouts should
 	//   now be sufficient.
@@ -387,7 +387,7 @@ func (server *MeekServer) ServeHTTP(responseWriter http.ResponseWriter, request
 		greaterThanSwapInt64(&session.metricPeakCachedResponseHitSize, int64(responseSize))
 
 		// The client may again fail to receive the payload and may again
-		// retry, so not yet releasing cachedReponse buffers.
+		// retry, so not yet releasing cachedResponse buffers.
 
 	} else {
 
@@ -399,7 +399,7 @@ func (server *MeekServer) ServeHTTP(responseWriter http.ResponseWriter, request
 		// Note: this code depends on an implementation detail of
 		// io.MultiWriter: a Write() to the MultiWriter writes first
 		// to the cache, and then to the response writer. So if the
-		// write to the reponse writer fails, the payload is cached.
+		// write to the response writer fails, the payload is cached.
 		multiWriter := io.MultiWriter(session.cachedResponse, responseWriter)
 
 		// The client expects 206, not 200, whenever it sets a Range header,
@@ -919,7 +919,7 @@ func (conn *meekConn) pumpReads(reader io.Reader) error {
 	// take its checksum before relaying it, the read buffer can
 	// grow to up to 2 x MEEK_MAX_REQUEST_PAYLOAD_LENGTH + 1.
 
-	// +1 allows for an explict check for request payloads that
+	// +1 allows for an explicit check for request payloads that
 	// exceed the maximum permitted length.
 	limitReader := io.LimitReader(reader, MEEK_MAX_REQUEST_PAYLOAD_LENGTH+1)
 	n, err := readBuffer.ReadFrom(limitReader)

+ 6 - 6
psiphon/server/psinet/psinet.go

@@ -17,10 +17,10 @@
  *
  */
 
-// Package psiphon/server/psinet implements psinet database services. The psinet
-// database is a JSON-format file containing information about the Psiphon network,
-// including sponsors, home pages, stats regexes, available upgrades, and other
-// servers for discovery. This package also implements the Psiphon discovery algorithm.
+// Package psinet implements psinet database services. The psinet database is a
+// JSON-format file containing information about the Psiphon network, including
+// sponsors, home pages, stats regexes, available upgrades, and other servers for
+// discovery. This package also implements the Psiphon discovery algorithm.
 package psinet
 
 import (
@@ -262,7 +262,7 @@ func (db *Database) GetHttpsRequestRegexes(sponsorID string) []map[string]string
 
 	sponsor, ok := db.Sponsors[sponsorID]
 	if !ok {
-		sponsor, ok = db.Sponsors[db.DefaultSponsorID]
+		sponsor, _ = db.Sponsors[db.DefaultSponsorID]
 	}
 
 	// If neither sponsorID or DefaultSponsorID were found, sponsor will be the
@@ -297,7 +297,7 @@ func (db *Database) DiscoverServers(discoveryValue int) []string {
 		var end time.Time
 		var err error
 
-		// All servers that are discoverable on this day are eligable for discovery
+		// All servers that are discoverable on this day are eligible for discovery
 		if len(server.DiscoveryDateRange) != 0 {
 			start, err = time.Parse("2006-01-02T15:04:05", server.DiscoveryDateRange[0])
 			if err != nil {

+ 1 - 1
psiphon/server/server_test.go

@@ -679,7 +679,7 @@ func makeTunneledNTPRequestAttempt(
 		udpgwPreambleSize := 11 // see writeUdpgwPreamble
 		buffer := make([]byte, udpgwProtocolMaxMessageSize)
 		packetSize, clientAddr, err := serverUDPConn.ReadFromUDP(
-			buffer[udpgwPreambleSize:len(buffer)])
+			buffer[udpgwPreambleSize:])
 		if err != nil {
 			t.Logf("serverUDPConn.Read for %s failed: %s", destination, err)
 			return

+ 1 - 1
psiphon/server/services.go

@@ -17,7 +17,7 @@
  *
  */
 
-// Package psiphon/server implements the core tunnel functionality of a Psiphon server.
+// Package server implements the core tunnel functionality of a Psiphon server.
 // The main function is RunServices, which runs one or all of a Psiphon API web server,
 // a tunneling SSH server, and an Obfuscated SSH protocol server. The server configuration
 // is created by the GenerateConfig function.

+ 1 - 1
psiphon/server/trafficRules.go

@@ -234,7 +234,7 @@ func (set *TrafficRulesSet) Validate() error {
 
 	for _, filteredRule := range set.FilteredRules {
 
-		for paramName, _ := range filteredRule.Filter.HandshakeParameters {
+		for paramName := range filteredRule.Filter.HandshakeParameters {
 			validParamName := false
 			for _, paramSpec := range baseRequestParams {
 				if paramSpec.name == paramName {

+ 8 - 8
psiphon/server/tunnelServer.go

@@ -214,7 +214,7 @@ func (server *TunnelServer) ResetAllClientOSLConfigs() {
 }
 
 // SetClientHandshakeState sets the handshake state -- that it completed and
-// what paramaters were passed -- in sshClient. This state is used for allowing
+// what parameters were passed -- in sshClient. This state is used for allowing
 // port forwards and for future traffic rule selection. SetClientHandshakeState
 // also triggers an immediate traffic rule re-selection, as the rules selected
 // upon tunnel establishment may no longer apply now that handshake values are
@@ -333,7 +333,7 @@ func (sshServer *sshServer) runListener(
 	listenerTunnelProtocol string) {
 
 	runningProtocols := make([]string, 0)
-	for tunnelProtocol, _ := range sshServer.support.Config.TunnelProtocolPorts {
+	for tunnelProtocol := range sshServer.support.Config.TunnelProtocolPorts {
 		runningProtocols = append(runningProtocols, tunnelProtocol)
 	}
 
@@ -460,7 +460,7 @@ func (sshServer *sshServer) registerEstablishedClient(client *sshClient) bool {
 
 	// In the case of a duplicate client sessionID, the previous client is closed.
 	// - Well-behaved clients generate pick a random sessionID that should be
-	//   unique (won't accidentally conflict) and hard to guess (can't be targetted
+	//   unique (won't accidentally conflict) and hard to guess (can't be targeted
 	//   by a malicious client).
 	// - Clients reuse the same sessionID when a tunnel is unexpectedly disconnected
 	//   and resestablished. In this case, when the same server is selected, this logic
@@ -531,7 +531,7 @@ func (sshServer *sshServer) getLoadStats() (ProtocolStats, RegionStats) {
 	zeroProtocolStats := func() map[string]map[string]int64 {
 		stats := make(map[string]map[string]int64)
 		stats["ALL"] = zeroStats()
-		for tunnelProtocol, _ := range sshServer.support.Config.TunnelProtocolPorts {
+		for tunnelProtocol := range sshServer.support.Config.TunnelProtocolPorts {
 			stats[tunnelProtocol] = zeroStats()
 		}
 		return stats
@@ -981,7 +981,7 @@ func (sshClient *sshClient) passwordCallback(conn ssh.ConnMetadata, password []b
 		// but that's no longer supported.
 		if len(password) == expectedSessionIDLength+expectedSSHPasswordLength {
 			sshPasswordPayload.SessionId = string(password[0:expectedSessionIDLength])
-			sshPasswordPayload.SshPassword = string(password[expectedSSHPasswordLength:len(password)])
+			sshPasswordPayload.SshPassword = string(password[expectedSSHPasswordLength:])
 		} else {
 			return nil, common.ContextError(fmt.Errorf("invalid password payload for %q", conn.User()))
 		}
@@ -1036,7 +1036,7 @@ func (sshClient *sshClient) authLogCallback(conn ssh.ConnMetadata, method string
 		// Note: here we previously logged messages for fail2ban to act on. This is no longer
 		// done as the complexity outweighs the benefits.
 		//
-		// - The SSH credential is not secret -- it's in the server entry. Attackers targetting
+		// - The SSH credential is not secret -- it's in the server entry. Attackers targeting
 		//   the server likely already have the credential. On the other hand, random scanning and
 		//   brute forcing is mitigated with high entropy random passwords, rate limiting
 		//   (implemented on the host via iptables), and limited capabilities (the SSH session can
@@ -1050,7 +1050,7 @@ func (sshClient *sshClient) authLogCallback(conn ssh.ConnMetadata, method string
 		//
 		// Random scanning and brute forcing of port 22 will result in log noise. To mitigate this,
 		// not every authentication failure is logged. A summary log is emitted periodically to
-		// retain some record of this activity in case this is relevent to, e.g., a performance
+		// retain some record of this activity in case this is relevant to, e.g., a performance
 		// investigation.
 
 		atomic.AddInt64(&sshClient.sshServer.authFailedCount, 1)
@@ -2059,7 +2059,7 @@ func (sshClient *sshClient) handleTCPChannel(
 
 	// Dial the remote address.
 	//
-	// Hostname resolution is performed explicitly, as a seperate step, as the target IP
+	// Hostname resolution is performed explicitly, as a separate step, as the target IP
 	// address is used for traffic rules (AllowSubnets) and OSL seed progress.
 	//
 	// Contexts are used for cancellation (via sshClient.runContext, which is cancelled

+ 1 - 1
psiphon/server/webServer.go

@@ -247,7 +247,7 @@ func (webServer *webServer) handshakeHandler(w http.ResponseWriter, r *http.Requ
 		return
 	}
 
-	// The legacy response format is newline seperated, name prefixed values.
+	// The legacy response format is newline separated, name prefixed values.
 	// Within that legacy format, the modern JSON response (containing all the
 	// legacy response values and more) is single value with a "Config:" prefix.
 	// This response uses the legacy format but omits all but the JSON value.

+ 2 - 2
psiphon/serverApi.go

@@ -598,7 +598,7 @@ func (serverContext *ServerContext) doUntunneledStatusRequest(
 // server-side. Permitting duplicate reporting could increase
 // the velocity of reporting (for example, both the asynchronous
 // untunneled final status requests and the post-connected
-// immediate startus requests could try to report the same tunnel
+// immediate status requests could try to report the same tunnel
 // stats).
 // Duplicate reporting may also occur when a server receives and
 // processes a status request but the client fails to receive
@@ -683,7 +683,7 @@ func (serverContext *ServerContext) DoClientVerificationRequest(
 
 		// Empty verification payload signals desire to
 		// query the server for current TTL. This is
-		// indicated to the server by the absense of the
+		// indicated to the server by the absence of the
 		// verificationData field.
 		if verificationPayload != "" {
 			rawMessage := json.RawMessage(verificationPayload)

+ 2 - 2
psiphon/transferstats/conn.go

@@ -17,8 +17,8 @@
  *
  */
 
-// Package stats counts and keeps track of session stats. These are per-domain
-// bytes transferred and total bytes transferred.
+// Package transferstats counts and keeps track of session stats. These are
+// per-domain bytes transferred and total bytes transferred.
 package transferstats
 
 /*

+ 8 - 8
psiphon/tunnel.go

@@ -48,7 +48,7 @@ import (
 // is not set, the connection may be made directly, depending on split tunnel
 // classification, when that feature is supported and active.
 // downstreamConn is an optional parameter which specifies a connection to be
-// explictly closed when the Dialed connection is closed. For instance, this
+// explicitly closed when the Dialed connection is closed. For instance, this
 // is used to close downstreamConn App<->LocalProxy connections when the related
 // LocalProxy<->SshPortForward connections close.
 type Tunneler interface {
@@ -56,7 +56,7 @@ type Tunneler interface {
 	SignalComponentFailure()
 }
 
-// TunnerOwner specifies the interface required by Tunnel to notify its
+// TunnelOwner specifies the interface required by Tunnel to notify its
 // owner when it has failed. The owner may, as in the case of the Controller,
 // remove the tunnel from its list of active tunnels.
 type TunnelOwner interface {
@@ -372,10 +372,10 @@ func (tunnel *Tunnel) SetClientVerificationPayload(clientVerificationPayload str
 	}
 }
 
-// TunneledConn implements net.Conn and wraps a port foward connection.
+// TunneledConn implements net.Conn and wraps a port forward connection.
 // It is used to hook into Read and Write to observe I/O errors and
 // report these errors back to the tunnel monitor as port forward failures.
-// TunneledConn optionally tracks a peer connection to be explictly closed
+// TunneledConn optionally tracks a peer connection to be explicitly closed
 // when the TunneledConn is closed.
 type TunneledConn struct {
 	net.Conn
@@ -723,7 +723,7 @@ func dialSsh(
 	if upstreamProxyType != "" {
 		dialStats.UpstreamProxyType = upstreamProxyType
 		dialStats.UpstreamProxyCustomHeaderNames = make([]string, 0)
-		for name, _ := range dialConfig.CustomHeaders {
+		for name := range dialConfig.CustomHeaders {
 			if selectedUserAgent && name == "User-Agent" {
 				continue
 			}
@@ -968,7 +968,7 @@ func makeRandomPeriod(min, max time.Duration) time.Duration {
 // failed dial or failed read/write. This keep alive has a shorter
 // timeout.
 //
-// Note that port foward failures may be due to non-failure conditions.
+// Note that port forward failures may be due to non-failure conditions.
 // For example, when the user inputs an invalid domain name and
 // resolution is done by the ssh server; or trying to connect to a
 // non-white-listed port; and the error message in these cases is not
@@ -1056,7 +1056,7 @@ func (tunnel *Tunnel) operateTunnel(tunnelOwner TunnelOwner) {
 	signalStatusRequest := make(chan struct{})
 	go func() {
 		defer requestsWaitGroup.Done()
-		for _ = range signalStatusRequest {
+		for range signalStatusRequest {
 			sendStats(tunnel)
 		}
 	}()
@@ -1237,7 +1237,7 @@ func (tunnel *Tunnel) operateTunnel(tunnelOwner TunnelOwner) {
 		// we use the last data received time as the estimated tunnel end time.
 		//
 		// One potential issue with using the last received time is receiving data
-		// after an extended sleep because the device sleep occured with data still in
+		// after an extended sleep because the device sleep occurred with data still in
 		// the OS socket read buffer. This is not expected to happen on Android, as the
 		// OS will wake a process when it has TCP data available to read. (For this reason,
 		// the actual long sleep issue is only with an idle tunnel; in this case the client

+ 1 - 2
psiphon/upstreamproxy/auth_basic.go

@@ -50,9 +50,8 @@ func (a *BasicHttpAuthenticator) Authenticate(req *http.Request, resp *http.Resp
 	if a.state == BASIC_HTTP_AUTH_STATE_CHALLENGE_RECEIVED {
 		a.state = BASIC_HTTP_AUTH_STATE_RESPONSE_GENERATED
 		return a.PreAuthenticate(req)
-	} else {
-		return proxyError(fmt.Errorf("Authorization is not accepted by the proxy server"))
 	}
+	return proxyError(fmt.Errorf("Authorization is not accepted by the proxy server"))
 }
 
 func (a *BasicHttpAuthenticator) IsConnectionBased() bool {

+ 4 - 4
psiphon/upstreamproxy/proxy_http.go

@@ -192,13 +192,13 @@ func (pc *proxyConn) handshake(addr, username, password string) error {
 
 	if resp.StatusCode == 407 {
 		if pc.authState == HTTP_AUTH_STATE_UNCHALLENGED {
-			var auth_err error = nil
-			pc.authenticator, auth_err = NewHttpAuthenticator(resp, username, password)
-			if auth_err != nil {
+			var authErr error
+			pc.authenticator, authErr = NewHttpAuthenticator(resp, username, password)
+			if authErr != nil {
 				pc.httpClientConn.Close()
 				pc.authState = HTTP_AUTH_STATE_FAILURE
 				//Already wrapped in proxyError
-				return auth_err
+				return authErr
 			}
 		}
 

+ 1 - 1
psiphon/upstreamproxy/proxy_socks4.go

@@ -176,7 +176,7 @@ func socks4ErrorToString(code byte) string {
 	case socks4Rejected:
 		return "request rejected or failed"
 	case socks4RejectedIdentdFailed:
-		return "request rejected becasue SOCKS server cannot connect to identd on the client"
+		return "request rejected because SOCKS server cannot connect to identd on the client"
 	case socks4RejectedIdentdMismatch:
 		return "request rejected because the client program and identd report different user-ids"
 	default:

+ 3 - 3
psiphon/upstreamproxy/transport_proxy_auth.go

@@ -95,7 +95,7 @@ func (tr *ProxyAuthTransport) RoundTrip(req *http.Request) (resp *http.Response,
 		return nil, err
 	}
 
-	var ha HttpAuthenticator = nil
+	var ha HttpAuthenticator
 
 	// Clone request early because RoundTrip will destroy request Body
 	// Also add custom headers to the cloned request
@@ -249,8 +249,8 @@ func newTransportConn(c net.Conn, tr *ProxyAuthTransport) *transportConn {
 // If so, the last intercepted request is authenticated against the response
 // in case of connection based auth scheme(i.e. NTLM)
 // All the non-connection based schemes are handled by the ProxyAuthTransport.RoundTrip()
-func (tc *transportConn) Read(p []byte) (n int, read_err error) {
-	n, read_err = tc.Conn.Read(p)
+func (tc *transportConn) Read(p []byte) (n int, readErr error) {
+	n, readErr = tc.Conn.Read(p)
 	if n < HTTP_STAT_LINE_LENGTH {
 		return
 	}

+ 2 - 2
psiphon/upstreamproxy/upstreamproxy.go

@@ -48,8 +48,8 @@ type UpstreamProxyConfig struct {
 	CustomHeaders   http.Header
 }
 
-// UpstreamProxyConfig implements proxy.Dialer interface
-// so we can pass it to proxy.FromURL
+// Dial implements the proxy.Dialer interface, allowing a UpstreamProxyConfig
+// to be passed to proxy.FromURL.
 func (u *UpstreamProxyConfig) Dial(network, addr string) (net.Conn, error) {
 	return u.ForwardDialFunc(network, addr)
 }