notice.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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 bythe handshake. The client should submit a client verification payload.
  193. func NoticeClientVerificationRequired() {
  194. outputNotice("ClientVerificationRequired", 0)
  195. }
  196. // NoticeClientRegion is the client's region, as determined by the server and
  197. // reported to the client in the handshake.
  198. func NoticeClientRegion(region string) {
  199. outputNotice("ClientRegion", 0, "region", region)
  200. }
  201. // NoticeTunnels is how many active tunnels are available. The client should use this to
  202. // determine connecting/unexpected disconnect state transitions. When count is 0, the core is
  203. // disconnected; when count > 1, the core is connected.
  204. func NoticeTunnels(count int) {
  205. outputNotice("Tunnels", 0, "count", count)
  206. }
  207. // NoticeSessionId is the session ID used across all tunnels established by the controller.
  208. func NoticeSessionId(sessionId string) {
  209. outputNotice("SessionId", noticeIsDiagnostic, "sessionId", sessionId)
  210. }
  211. func NoticeImpairedProtocolClassification(impairedProtocolClassification map[string]int) {
  212. outputNotice("ImpairedProtocolClassification", noticeIsDiagnostic,
  213. "classification", impairedProtocolClassification)
  214. }
  215. // NoticeUntunneled indicates than an address has been classified as untunneled and is being
  216. // accessed directly.
  217. //
  218. // Note: "address" should remain private; this notice should only be used for alerting
  219. // users, not for diagnostics logs.
  220. //
  221. func NoticeUntunneled(address string) {
  222. outputNotice("Untunneled", noticeShowUser, "address", address)
  223. }
  224. // NoticeSplitTunnelRegion reports that split tunnel is on for the given region.
  225. func NoticeSplitTunnelRegion(region string) {
  226. outputNotice("SplitTunnelRegion", noticeShowUser, "region", region)
  227. }
  228. // NoticeUpstreamProxyError reports an error when connecting to an upstream proxy. The
  229. // user may have input, for example, an incorrect address or incorrect credentials.
  230. func NoticeUpstreamProxyError(err error) {
  231. outputNotice("UpstreamProxyError", noticeShowUser, "message", err.Error())
  232. }
  233. // NoticeClientUpgradeDownloadedBytes reports client upgrade download progress.
  234. func NoticeClientUpgradeDownloadedBytes(bytes int64) {
  235. outputNotice("ClientUpgradeDownloadedBytes", noticeIsDiagnostic, "bytes", bytes)
  236. }
  237. // NoticeClientUpgradeDownloaded indicates that a client upgrade download
  238. // is complete and available at the destination specified.
  239. func NoticeClientUpgradeDownloaded(filename string) {
  240. outputNotice("ClientUpgradeDownloaded", 0, "filename", filename)
  241. }
  242. // NoticeBytesTransferred reports how many tunneled bytes have been
  243. // transferred since the last NoticeBytesTransferred, for the tunnel
  244. // to the server at ipAddress.
  245. func NoticeBytesTransferred(ipAddress string, sent, received int64) {
  246. if GetEmitDiagnoticNotices() {
  247. outputNotice("BytesTransferred", noticeIsDiagnostic, "ipAddress", ipAddress, "sent", sent, "received", received)
  248. } else {
  249. // This case keeps the EmitBytesTransferred and EmitDiagnosticNotices config options independent
  250. outputNotice("BytesTransferred", 0, "sent", sent, "received", received)
  251. }
  252. }
  253. // NoticeTotalBytesTransferred reports how many tunneled bytes have been
  254. // transferred in total up to this point, for the tunnel to the server
  255. // at ipAddress.
  256. func NoticeTotalBytesTransferred(ipAddress string, sent, received int64) {
  257. if GetEmitDiagnoticNotices() {
  258. outputNotice("TotalBytesTransferred", noticeIsDiagnostic, "ipAddress", ipAddress, "sent", sent, "received", received)
  259. } else {
  260. // This case keeps the EmitBytesTransferred and EmitDiagnosticNotices config options independent
  261. outputNotice("TotalBytesTransferred", 0, "sent", sent, "received", received)
  262. }
  263. }
  264. // NoticeLocalProxyError reports a local proxy error message. Repetitive
  265. // errors for a given proxy type are suppressed.
  266. func NoticeLocalProxyError(proxyType string, err error) {
  267. // For repeats, only consider the base error message, which is
  268. // the root error that repeats (the full error often contains
  269. // different specific values, e.g., local port numbers, but
  270. // the same repeating root).
  271. // Assumes error format of ContextError.
  272. repetitionMessage := err.Error()
  273. index := strings.LastIndex(repetitionMessage, ": ")
  274. if index != -1 {
  275. repetitionMessage = repetitionMessage[index+2:]
  276. }
  277. outputRepetitiveNotice(
  278. "LocalProxyError"+proxyType, repetitionMessage, 1,
  279. "LocalProxyError", noticeIsDiagnostic, "message", err.Error())
  280. }
  281. // NoticeConnectedMeekStats reports extra network details for a meek tunnel connection.
  282. func NoticeConnectedMeekStats(ipAddress string, meekStats *MeekStats) {
  283. outputNotice("ConnectedMeekStats", noticeIsDiagnostic,
  284. "ipAddress", ipAddress,
  285. "dialAddress", meekStats.DialAddress,
  286. "resolvedIPAddress", meekStats.ResolvedIPAddress,
  287. "sniServerName", meekStats.SNIServerName,
  288. "hostHeader", meekStats.HostHeader,
  289. "transformedHostName", meekStats.TransformedHostName)
  290. }
  291. // NoticeBuildInfo reports build version info.
  292. func NoticeBuildInfo(buildDate, buildRepo, buildRev, goVersion, gomobileVersion string) {
  293. outputNotice("BuildInfo", 0,
  294. "buildDate", buildDate,
  295. "buildRepo", buildRepo,
  296. "buildRev", buildRev,
  297. "goVersion", goVersion,
  298. "gomobileVersion", gomobileVersion)
  299. }
  300. // NoticeExiting indicates that tunnel-core is exiting imminently.
  301. func NoticeExiting() {
  302. outputNotice("Exiting", 0)
  303. }
  304. // NoticeRemoteServerListDownloadedBytes reports remote server list download progress.
  305. func NoticeRemoteServerListDownloadedBytes(bytes int64) {
  306. outputNotice("RemoteServerListDownloadedBytes", noticeIsDiagnostic, "bytes", bytes)
  307. }
  308. // NoticeRemoteServerListDownloaded indicates that a remote server list download
  309. // completed successfully.
  310. func NoticeRemoteServerListDownloaded(filename string) {
  311. outputNotice("RemoteServerListDownloaded", noticeIsDiagnostic, "filename", filename)
  312. }
  313. func NoticeClientVerificationRequestCompleted(ipAddress string) {
  314. outputNotice("NoticeClientVerificationRequestCompleted", noticeIsDiagnostic, "ipAddress", ipAddress)
  315. }
  316. type repetitiveNoticeState struct {
  317. message string
  318. repeats int
  319. }
  320. var repetitiveNoticeMutex sync.Mutex
  321. var repetitiveNoticeStates = make(map[string]*repetitiveNoticeState)
  322. // outputRepetitiveNotice conditionally outputs a notice. Used for noticies which
  323. // often repeat in noisy bursts. For a repeat limit of N, the notice is emitted
  324. // with a "repeats" count on consecutive repeats up to the limit and then suppressed
  325. // until the repetitionMessage differs.
  326. func outputRepetitiveNotice(
  327. repetitionKey, repetitionMessage string, repeatLimit int,
  328. noticeType string, noticeFlags uint32, args ...interface{}) {
  329. repetitiveNoticeMutex.Lock()
  330. defer repetitiveNoticeMutex.Unlock()
  331. state, ok := repetitiveNoticeStates[repetitionKey]
  332. if !ok {
  333. state = new(repetitiveNoticeState)
  334. repetitiveNoticeStates[repetitionKey] = state
  335. }
  336. emit := true
  337. if repetitionMessage != state.message {
  338. state.message = repetitionMessage
  339. state.repeats = 0
  340. } else {
  341. state.repeats += 1
  342. if state.repeats > repeatLimit {
  343. emit = false
  344. }
  345. }
  346. if emit {
  347. if state.repeats > 0 {
  348. args = append(args, "repeats", state.repeats)
  349. }
  350. outputNotice(noticeType, noticeFlags, args...)
  351. }
  352. }
  353. type noticeObject struct {
  354. NoticeType string `json:"noticeType"`
  355. Data json.RawMessage `json:"data"`
  356. Timestamp string `json:"timestamp"`
  357. }
  358. // GetNotice receives a JSON encoded object and attempts to parse it as a Notice.
  359. // The type is returned as a string and the payload as a generic map.
  360. func GetNotice(notice []byte) (
  361. noticeType string, payload map[string]interface{}, err error) {
  362. var object noticeObject
  363. err = json.Unmarshal(notice, &object)
  364. if err != nil {
  365. return "", nil, err
  366. }
  367. var objectPayload interface{}
  368. err = json.Unmarshal(object.Data, &objectPayload)
  369. if err != nil {
  370. return "", nil, err
  371. }
  372. return object.NoticeType, objectPayload.(map[string]interface{}), nil
  373. }
  374. // NoticeReceiver consumes a notice input stream and invokes a callback function
  375. // for each discrete JSON notice object byte sequence.
  376. type NoticeReceiver struct {
  377. mutex sync.Mutex
  378. buffer []byte
  379. callback func([]byte)
  380. }
  381. // NewNoticeReceiver initializes a new NoticeReceiver
  382. func NewNoticeReceiver(callback func([]byte)) *NoticeReceiver {
  383. return &NoticeReceiver{callback: callback}
  384. }
  385. // Write implements io.Writer.
  386. func (receiver *NoticeReceiver) Write(p []byte) (n int, err error) {
  387. receiver.mutex.Lock()
  388. defer receiver.mutex.Unlock()
  389. receiver.buffer = append(receiver.buffer, p...)
  390. index := bytes.Index(receiver.buffer, []byte("\n"))
  391. if index == -1 {
  392. return len(p), nil
  393. }
  394. notice := receiver.buffer[:index]
  395. receiver.buffer = receiver.buffer[index+1:]
  396. receiver.callback(notice)
  397. return len(p), nil
  398. }
  399. // NewNoticeConsoleRewriter consumes JSON-format notice input and parses each
  400. // notice and rewrites in a more human-readable format more suitable for
  401. // console output. The data payload field is left as JSON.
  402. func NewNoticeConsoleRewriter(writer io.Writer) *NoticeReceiver {
  403. return NewNoticeReceiver(func(notice []byte) {
  404. var object noticeObject
  405. _ = json.Unmarshal(notice, &object)
  406. fmt.Fprintf(
  407. writer,
  408. "%s %s %s\n",
  409. object.Timestamp,
  410. object.NoticeType,
  411. string(object.Data))
  412. })
  413. }