notice.go 18 KB

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