notice.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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/json"
  23. "fmt"
  24. "io"
  25. "log"
  26. "os"
  27. "sort"
  28. "strings"
  29. "sync"
  30. "sync/atomic"
  31. "time"
  32. )
  33. var noticeLoggerMutex sync.Mutex
  34. var noticeLogger = log.New(os.Stderr, "", 0)
  35. var noticeLogDiagnostics = int32(0)
  36. // SetEmitDiagnosticNotices toggles whether diagnostic notices
  37. // are emitted. Diagnostic notices contain potentially sensitive
  38. // circumvention network information; only enable this in environments
  39. // where notices are handled securely (for example, don't include these
  40. // notices in log files which users could post to public forums).
  41. func SetEmitDiagnosticNotices(enable bool) {
  42. if enable {
  43. atomic.StoreInt32(&noticeLogDiagnostics, 1)
  44. } else {
  45. atomic.StoreInt32(&noticeLogDiagnostics, 0)
  46. }
  47. }
  48. // GetEmitDiagnoticNotices returns the current state
  49. // of emitting diagnostic notices.
  50. func GetEmitDiagnoticNotices() bool {
  51. return atomic.LoadInt32(&noticeLogDiagnostics) == 1
  52. }
  53. // SetNoticeOutput sets a target writer to receive notices. By default,
  54. // notices are written to stderr.
  55. //
  56. // Notices are encoded in JSON. Here's an example:
  57. //
  58. // {"data":{"message":"shutdown operate tunnel"},"noticeType":"Info","showUser":false,"timestamp":"2015-01-28T17:35:13Z"}
  59. //
  60. // All notices have the following fields:
  61. // - "noticeType": the type of notice, which indicates the meaning of the notice along with what's in the data payload.
  62. // - "data": additional structured data payload. For example, the "ListeningSocksProxyPort" notice type has a "port" integer
  63. // data in its payload.
  64. // - "showUser": whether the information should be displayed to the user. For example, this flag is set for "SocksProxyPortInUse"
  65. // as the user should be informed that their configured choice of listening port could not be used. Core clients should
  66. // anticipate that the core will add additional "showUser"=true notices in the future and emit at least the raw notice.
  67. // - "timestamp": UTC timezone, RFC3339 format timestamp for notice event
  68. //
  69. // See the Notice* functions for details on each notice meaning and payload.
  70. //
  71. func SetNoticeOutput(output io.Writer) {
  72. noticeLoggerMutex.Lock()
  73. defer noticeLoggerMutex.Unlock()
  74. noticeLogger = log.New(output, "", 0)
  75. }
  76. const (
  77. noticeIsDiagnostic = 1
  78. noticeShowUser = 2
  79. )
  80. // outputNotice encodes a notice in JSON and writes it to the output writer.
  81. func outputNotice(noticeType string, noticeFlags uint32, args ...interface{}) {
  82. if (noticeFlags&noticeIsDiagnostic != 0) && !GetEmitDiagnoticNotices() {
  83. return
  84. }
  85. obj := make(map[string]interface{})
  86. noticeData := make(map[string]interface{})
  87. obj["noticeType"] = noticeType
  88. obj["showUser"] = (noticeFlags&noticeShowUser != 0)
  89. obj["data"] = noticeData
  90. obj["timestamp"] = time.Now().UTC().Format(time.RFC3339)
  91. for i := 0; i < len(args)-1; i += 2 {
  92. name, ok := args[i].(string)
  93. value := args[i+1]
  94. if ok {
  95. noticeData[name] = value
  96. }
  97. }
  98. encodedJson, err := json.Marshal(obj)
  99. var output string
  100. if err == nil {
  101. output = string(encodedJson)
  102. } else {
  103. output = fmt.Sprintf("{\"Alert\":{\"message\":\"%s\"}}", ContextError(err))
  104. }
  105. noticeLoggerMutex.Lock()
  106. defer noticeLoggerMutex.Unlock()
  107. noticeLogger.Print(output)
  108. }
  109. // NoticeInfo is an informational message
  110. func NoticeInfo(format string, args ...interface{}) {
  111. outputNotice("Info", noticeIsDiagnostic, "message", fmt.Sprintf(format, args...))
  112. }
  113. // NoticeAlert is an alert message; typically a recoverable error condition
  114. func NoticeAlert(format string, args ...interface{}) {
  115. outputNotice("Alert", noticeIsDiagnostic, "message", fmt.Sprintf(format, args...))
  116. }
  117. // NoticeError is an error message; typically an unrecoverable error condition
  118. func NoticeError(format string, args ...interface{}) {
  119. outputNotice("Error", noticeIsDiagnostic, "message", fmt.Sprintf(format, args...))
  120. }
  121. // NoticeCandidateServers is how many possible servers are available for the selected region and protocol
  122. func NoticeCandidateServers(region, protocol string, count int) {
  123. outputNotice("CandidateServers", 0, "region", region, "protocol", protocol, "count", count)
  124. }
  125. // NoticeAvailableEgressRegions is what regions are available for egress from.
  126. // Consecutive reports of the same list of regions are suppressed.
  127. func NoticeAvailableEgressRegions(regions []string) {
  128. sortedRegions := append([]string(nil), regions...)
  129. sort.Strings(sortedRegions)
  130. repetitionMessage := strings.Join(sortedRegions, "")
  131. outputRepetitiveNotice(
  132. "AvailableEgressRegions", repetitionMessage, 0,
  133. "AvailableEgressRegions", 0, "regions", sortedRegions)
  134. }
  135. // NoticeConnectingServer is details on a connection attempt
  136. func NoticeConnectingServer(ipAddress, region, protocol, directTCPDialAddress string, meekConfig *MeekConfig) {
  137. if meekConfig == nil {
  138. outputNotice("ConnectingServer", noticeIsDiagnostic,
  139. "ipAddress", ipAddress,
  140. "region", region,
  141. "protocol", protocol,
  142. "directTCPDialAddress", directTCPDialAddress)
  143. } else {
  144. outputNotice("ConnectingServer", noticeIsDiagnostic,
  145. "ipAddress", ipAddress,
  146. "region", region,
  147. "protocol", protocol,
  148. "meekDialAddress", meekConfig.DialAddress,
  149. "meekUseHTTPS", meekConfig.UseHTTPS,
  150. "meekSNIServerName", meekConfig.SNIServerName,
  151. "meekHostHeader", meekConfig.HostHeader,
  152. "meekTransformedHostName", meekConfig.TransformedHostName)
  153. }
  154. }
  155. // NoticeActiveTunnel is a successful connection that is used as an active tunnel for port forwarding
  156. func NoticeActiveTunnel(ipAddress, protocol string) {
  157. outputNotice("ActiveTunnel", noticeIsDiagnostic, "ipAddress", ipAddress, "protocol", protocol)
  158. }
  159. // NoticeSocksProxyPortInUse is a failure to use the configured LocalSocksProxyPort
  160. func NoticeSocksProxyPortInUse(port int) {
  161. outputNotice("SocksProxyPortInUse", noticeShowUser, "port", port)
  162. }
  163. // NoticeListeningSocksProxyPort is the selected port for the listening local SOCKS proxy
  164. func NoticeListeningSocksProxyPort(port int) {
  165. outputNotice("ListeningSocksProxyPort", 0, "port", port)
  166. }
  167. // NoticeSocksProxyPortInUse is a failure to use the configured LocalHttpProxyPort
  168. func NoticeHttpProxyPortInUse(port int) {
  169. outputNotice("HttpProxyPortInUse", noticeShowUser, "port", port)
  170. }
  171. // NoticeListeningSocksProxyPort is the selected port for the listening local HTTP proxy
  172. func NoticeListeningHttpProxyPort(port int) {
  173. outputNotice("ListeningHttpProxyPort", 0, "port", port)
  174. }
  175. // NoticeClientUpgradeAvailable is an available client upgrade, as per the handshake. The
  176. // client should download and install an upgrade.
  177. func NoticeClientUpgradeAvailable(version string) {
  178. outputNotice("ClientUpgradeAvailable", 0, "version", version)
  179. }
  180. // NoticeClientIsLatestVersion reports that an upgrade check was made and the client
  181. // is already the latest version. availableVersion is the version available for download,
  182. // if known.
  183. func NoticeClientIsLatestVersion(availableVersion string) {
  184. outputNotice("ClientIsLatestVersion", 0, "availableVersion", availableVersion)
  185. }
  186. // NoticeHomepage is a sponsor homepage, as per the handshake. The client
  187. // should display the sponsor's homepage.
  188. func NoticeHomepage(url string) {
  189. outputNotice("Homepage", 0, "url", url)
  190. }
  191. // NoticeClientVerificationRequired indicates that client verification is required, as
  192. // indicated by the handshake. The client should submit a client verification payload.
  193. // Empty nonce is allowed, if ttlSeconds is 0 the client should not send verification
  194. // payload to the server. If resetCache is set the client must always perform a new
  195. // verification and update its cache
  196. func NoticeClientVerificationRequired(nonce string, ttlSeconds int, resetCache bool) {
  197. outputNotice("ClientVerificationRequired", 0, "nonce", nonce, "ttlSeconds", ttlSeconds, "resetCache", resetCache)
  198. }
  199. // NoticeClientRegion is the client's region, as determined by the server and
  200. // reported to the client in the handshake.
  201. func NoticeClientRegion(region string) {
  202. outputNotice("ClientRegion", 0, "region", region)
  203. }
  204. // NoticeTunnels is how many active tunnels are available. The client should use this to
  205. // determine connecting/unexpected disconnect state transitions. When count is 0, the core is
  206. // disconnected; when count > 1, the core is connected.
  207. func NoticeTunnels(count int) {
  208. outputNotice("Tunnels", 0, "count", count)
  209. }
  210. // NoticeSessionId is the session ID used across all tunnels established by the controller.
  211. func NoticeSessionId(sessionId string) {
  212. outputNotice("SessionId", noticeIsDiagnostic, "sessionId", sessionId)
  213. }
  214. func NoticeImpairedProtocolClassification(impairedProtocolClassification map[string]int) {
  215. outputNotice("ImpairedProtocolClassification", noticeIsDiagnostic,
  216. "classification", impairedProtocolClassification)
  217. }
  218. // NoticeUntunneled indicates than an address has been classified as untunneled and is being
  219. // accessed directly.
  220. //
  221. // Note: "address" should remain private; this notice should only be used for alerting
  222. // users, not for diagnostics logs.
  223. //
  224. func NoticeUntunneled(address string) {
  225. outputNotice("Untunneled", noticeShowUser, "address", address)
  226. }
  227. // NoticeSplitTunnelRegion reports that split tunnel is on for the given region.
  228. func NoticeSplitTunnelRegion(region string) {
  229. outputNotice("SplitTunnelRegion", noticeShowUser, "region", region)
  230. }
  231. // NoticeUpstreamProxyError reports an error when connecting to an upstream proxy. The
  232. // user may have input, for example, an incorrect address or incorrect credentials.
  233. func NoticeUpstreamProxyError(err error) {
  234. outputNotice("UpstreamProxyError", noticeShowUser, "message", err.Error())
  235. }
  236. // NoticeClientUpgradeDownloadedBytes reports client upgrade download progress.
  237. func NoticeClientUpgradeDownloadedBytes(bytes int64) {
  238. outputNotice("ClientUpgradeDownloadedBytes", noticeIsDiagnostic, "bytes", bytes)
  239. }
  240. // NoticeClientUpgradeDownloaded indicates that a client upgrade download
  241. // is complete and available at the destination specified.
  242. func NoticeClientUpgradeDownloaded(filename string) {
  243. outputNotice("ClientUpgradeDownloaded", 0, "filename", filename)
  244. }
  245. // NoticeBytesTransferred reports how many tunneled bytes have been
  246. // transferred since the last NoticeBytesTransferred, for the tunnel
  247. // to the server at ipAddress.
  248. func NoticeBytesTransferred(ipAddress string, sent, received int64) {
  249. if GetEmitDiagnoticNotices() {
  250. outputNotice("BytesTransferred", noticeIsDiagnostic, "ipAddress", ipAddress, "sent", sent, "received", received)
  251. } else {
  252. // This case keeps the EmitBytesTransferred and EmitDiagnosticNotices config options independent
  253. outputNotice("BytesTransferred", 0, "sent", sent, "received", received)
  254. }
  255. }
  256. // NoticeTotalBytesTransferred reports how many tunneled bytes have been
  257. // transferred in total up to this point, for the tunnel to the server
  258. // at ipAddress.
  259. func NoticeTotalBytesTransferred(ipAddress string, sent, received int64) {
  260. if GetEmitDiagnoticNotices() {
  261. outputNotice("TotalBytesTransferred", noticeIsDiagnostic, "ipAddress", ipAddress, "sent", sent, "received", received)
  262. } else {
  263. // This case keeps the EmitBytesTransferred and EmitDiagnosticNotices config options independent
  264. outputNotice("TotalBytesTransferred", 0, "sent", sent, "received", received)
  265. }
  266. }
  267. // NoticeLocalProxyError reports a local proxy error message. Repetitive
  268. // errors for a given proxy type are suppressed.
  269. func NoticeLocalProxyError(proxyType string, err error) {
  270. // For repeats, only consider the base error message, which is
  271. // the root error that repeats (the full error often contains
  272. // different specific values, e.g., local port numbers, but
  273. // the same repeating root).
  274. // Assumes error format of ContextError.
  275. repetitionMessage := err.Error()
  276. index := strings.LastIndex(repetitionMessage, ": ")
  277. if index != -1 {
  278. repetitionMessage = repetitionMessage[index+2:]
  279. }
  280. outputRepetitiveNotice(
  281. "LocalProxyError"+proxyType, repetitionMessage, 1,
  282. "LocalProxyError", noticeIsDiagnostic, "message", err.Error())
  283. }
  284. // NoticeConnectedTunnelDialStats reports extra network details for tunnel connections that required extra configuration.
  285. func NoticeConnectedTunnelDialStats(ipAddress string, tunnelDialStats *TunnelDialStats) {
  286. outputNotice("ConnectedTunnelDialStats", noticeIsDiagnostic,
  287. "ipAddress", ipAddress,
  288. "upstreamProxyType", tunnelDialStats.UpstreamProxyType,
  289. "upstreamProxyCustomHeaderNames", strings.Join(tunnelDialStats.UpstreamProxyCustomHeaderNames, ","),
  290. "meekDialAddress", tunnelDialStats.MeekDialAddress,
  291. "meekDialAddress", tunnelDialStats.MeekDialAddress,
  292. "meekResolvedIPAddress", tunnelDialStats.MeekResolvedIPAddress,
  293. "meekSNIServerName", tunnelDialStats.MeekSNIServerName,
  294. "meekHostHeader", tunnelDialStats.MeekHostHeader,
  295. "meekTransformedHostName", tunnelDialStats.MeekTransformedHostName)
  296. }
  297. // NoticeBuildInfo reports build version info.
  298. func NoticeBuildInfo(buildDate, buildRepo, buildRev, goVersion, gomobileVersion string) {
  299. outputNotice("BuildInfo", 0,
  300. "buildDate", buildDate,
  301. "buildRepo", buildRepo,
  302. "buildRev", buildRev,
  303. "goVersion", goVersion,
  304. "gomobileVersion", gomobileVersion)
  305. }
  306. // NoticeExiting indicates that tunnel-core is exiting imminently.
  307. func NoticeExiting() {
  308. outputNotice("Exiting", 0)
  309. }
  310. // NoticeRemoteServerListDownloadedBytes reports remote server list download progress.
  311. func NoticeRemoteServerListDownloadedBytes(bytes int64) {
  312. outputNotice("RemoteServerListDownloadedBytes", noticeIsDiagnostic, "bytes", bytes)
  313. }
  314. // NoticeRemoteServerListDownloaded indicates that a remote server list download
  315. // completed successfully.
  316. func NoticeRemoteServerListDownloaded(filename string) {
  317. outputNotice("RemoteServerListDownloaded", noticeIsDiagnostic, "filename", filename)
  318. }
  319. func NoticeClientVerificationRequestCompleted(ipAddress string) {
  320. outputNotice("NoticeClientVerificationRequestCompleted", noticeIsDiagnostic, "ipAddress", ipAddress)
  321. }
  322. type repetitiveNoticeState struct {
  323. message string
  324. repeats int
  325. }
  326. var repetitiveNoticeMutex sync.Mutex
  327. var repetitiveNoticeStates = make(map[string]*repetitiveNoticeState)
  328. // outputRepetitiveNotice conditionally outputs a notice. Used for noticies which
  329. // often repeat in noisy bursts. For a repeat limit of N, the notice is emitted
  330. // with a "repeats" count on consecutive repeats up to the limit and then suppressed
  331. // until the repetitionMessage differs.
  332. func outputRepetitiveNotice(
  333. repetitionKey, repetitionMessage string, repeatLimit int,
  334. noticeType string, noticeFlags uint32, args ...interface{}) {
  335. repetitiveNoticeMutex.Lock()
  336. defer repetitiveNoticeMutex.Unlock()
  337. state, ok := repetitiveNoticeStates[repetitionKey]
  338. if !ok {
  339. state = new(repetitiveNoticeState)
  340. repetitiveNoticeStates[repetitionKey] = state
  341. }
  342. emit := true
  343. if repetitionMessage != state.message {
  344. state.message = repetitionMessage
  345. state.repeats = 0
  346. } else {
  347. state.repeats += 1
  348. if state.repeats > repeatLimit {
  349. emit = false
  350. }
  351. }
  352. if emit {
  353. if state.repeats > 0 {
  354. args = append(args, "repeats", state.repeats)
  355. }
  356. outputNotice(noticeType, noticeFlags, args...)
  357. }
  358. }
  359. type noticeObject struct {
  360. NoticeType string `json:"noticeType"`
  361. Data json.RawMessage `json:"data"`
  362. Timestamp string `json:"timestamp"`
  363. }
  364. // GetNotice receives a JSON encoded object and attempts to parse it as a Notice.
  365. // The type is returned as a string and the payload as a generic map.
  366. func GetNotice(notice []byte) (
  367. noticeType string, payload map[string]interface{}, err error) {
  368. var object noticeObject
  369. err = json.Unmarshal(notice, &object)
  370. if err != nil {
  371. return "", nil, err
  372. }
  373. var objectPayload interface{}
  374. err = json.Unmarshal(object.Data, &objectPayload)
  375. if err != nil {
  376. return "", nil, err
  377. }
  378. return object.NoticeType, objectPayload.(map[string]interface{}), nil
  379. }
  380. // NoticeReceiver consumes a notice input stream and invokes a callback function
  381. // for each discrete JSON notice object byte sequence.
  382. type NoticeReceiver struct {
  383. mutex sync.Mutex
  384. buffer []byte
  385. callback func([]byte)
  386. }
  387. // NewNoticeReceiver initializes a new NoticeReceiver
  388. func NewNoticeReceiver(callback func([]byte)) *NoticeReceiver {
  389. return &NoticeReceiver{callback: callback}
  390. }
  391. // Write implements io.Writer.
  392. func (receiver *NoticeReceiver) Write(p []byte) (n int, err error) {
  393. receiver.mutex.Lock()
  394. defer receiver.mutex.Unlock()
  395. receiver.buffer = append(receiver.buffer, p...)
  396. index := bytes.Index(receiver.buffer, []byte("\n"))
  397. if index == -1 {
  398. return len(p), nil
  399. }
  400. notice := receiver.buffer[:index]
  401. receiver.buffer = receiver.buffer[index+1:]
  402. receiver.callback(notice)
  403. return len(p), nil
  404. }
  405. // NewNoticeConsoleRewriter consumes JSON-format notice input and parses each
  406. // notice and rewrites in a more human-readable format more suitable for
  407. // console output. The data payload field is left as JSON.
  408. func NewNoticeConsoleRewriter(writer io.Writer) *NoticeReceiver {
  409. return NewNoticeReceiver(func(notice []byte) {
  410. var object noticeObject
  411. _ = json.Unmarshal(notice, &object)
  412. fmt.Fprintf(
  413. writer,
  414. "%s %s %s\n",
  415. object.Timestamp,
  416. object.NoticeType,
  417. string(object.Data))
  418. })
  419. }