notice.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  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. func noticeServerDialStats(noticeType, ipAddress, region, protocol string, tunnelDialStats *TunnelDialStats) {
  154. args := []interface{}{
  155. "ipAddress", ipAddress,
  156. "region", region,
  157. "protocol", protocol,
  158. }
  159. if tunnelDialStats.SelectedSSHClientVersion {
  160. args = append(args, "SSHClientVersion", tunnelDialStats.SSHClientVersion)
  161. }
  162. if tunnelDialStats.UpstreamProxyType != "" {
  163. args = append(args, "upstreamProxyType", tunnelDialStats.UpstreamProxyType)
  164. }
  165. if tunnelDialStats.UpstreamProxyCustomHeaderNames != nil {
  166. args = append(args, "upstreamProxyCustomHeaderNames", strings.Join(tunnelDialStats.UpstreamProxyCustomHeaderNames, ","))
  167. }
  168. if tunnelDialStats.MeekDialAddress != "" {
  169. args = append(args, "meekDialAddress", tunnelDialStats.MeekDialAddress)
  170. }
  171. if tunnelDialStats.MeekResolvedIPAddress != "" {
  172. args = append(args, "meekResolvedIPAddress", tunnelDialStats.MeekResolvedIPAddress)
  173. }
  174. if tunnelDialStats.MeekSNIServerName != "" {
  175. args = append(args, "meekSNIServerName", tunnelDialStats.MeekSNIServerName)
  176. }
  177. if tunnelDialStats.MeekHostHeader != "" {
  178. args = append(args, "meekHostHeader", tunnelDialStats.MeekHostHeader)
  179. }
  180. // MeekTransformedHostName is meaningful when meek is used, which is when MeekDialAddress != ""
  181. if tunnelDialStats.MeekDialAddress != "" {
  182. args = append(args, "meekTransformedHostName", tunnelDialStats.MeekTransformedHostName)
  183. }
  184. if tunnelDialStats.SelectedUserAgent {
  185. args = append(args, "userAgent", tunnelDialStats.UserAgent)
  186. }
  187. if tunnelDialStats.SelectedTLSProfile {
  188. args = append(args, "TLSProfile", tunnelDialStats.TLSProfile)
  189. }
  190. outputNotice(
  191. noticeType,
  192. noticeIsDiagnostic,
  193. args...)
  194. }
  195. // NoticeConnectingServer reports parameters and details for a single connection attempt
  196. func NoticeConnectingServer(ipAddress, region, protocol string, tunnelDialStats *TunnelDialStats) {
  197. noticeServerDialStats("ConnectingServer", ipAddress, region, protocol, tunnelDialStats)
  198. }
  199. // NoticeConnectedServer reports parameters and details for a single successful connection
  200. func NoticeConnectedServer(ipAddress, region, protocol string, tunnelDialStats *TunnelDialStats) {
  201. noticeServerDialStats("ConnectedServer", ipAddress, region, protocol, tunnelDialStats)
  202. }
  203. // NoticeActiveTunnel is a successful connection that is used as an active tunnel for port forwarding
  204. func NoticeActiveTunnel(ipAddress, protocol string, isTCS bool) {
  205. outputNotice("ActiveTunnel", noticeIsDiagnostic, "ipAddress", ipAddress, "protocol", protocol, "isTCS", isTCS)
  206. }
  207. // NoticeSocksProxyPortInUse is a failure to use the configured LocalSocksProxyPort
  208. func NoticeSocksProxyPortInUse(port int) {
  209. outputNotice("SocksProxyPortInUse", noticeShowUser, "port", port)
  210. }
  211. // NoticeListeningSocksProxyPort is the selected port for the listening local SOCKS proxy
  212. func NoticeListeningSocksProxyPort(port int) {
  213. outputNotice("ListeningSocksProxyPort", 0, "port", port)
  214. }
  215. // NoticeSocksProxyPortInUse is a failure to use the configured LocalHttpProxyPort
  216. func NoticeHttpProxyPortInUse(port int) {
  217. outputNotice("HttpProxyPortInUse", noticeShowUser, "port", port)
  218. }
  219. // NoticeListeningSocksProxyPort is the selected port for the listening local HTTP proxy
  220. func NoticeListeningHttpProxyPort(port int) {
  221. outputNotice("ListeningHttpProxyPort", 0, "port", port)
  222. }
  223. // NoticeClientUpgradeAvailable is an available client upgrade, as per the handshake. The
  224. // client should download and install an upgrade.
  225. func NoticeClientUpgradeAvailable(version string) {
  226. outputNotice("ClientUpgradeAvailable", 0, "version", version)
  227. }
  228. // NoticeClientIsLatestVersion reports that an upgrade check was made and the client
  229. // is already the latest version. availableVersion is the version available for download,
  230. // if known.
  231. func NoticeClientIsLatestVersion(availableVersion string) {
  232. outputNotice("ClientIsLatestVersion", 0, "availableVersion", availableVersion)
  233. }
  234. // NoticeHomepage is a sponsor homepage, as per the handshake. The client
  235. // should display the sponsor's homepage.
  236. func NoticeHomepage(url string) {
  237. outputNotice("Homepage", 0, "url", url)
  238. }
  239. // NoticeClientVerificationRequired indicates that client verification is required, as
  240. // indicated by the handshake. The client should submit a client verification payload.
  241. // Empty nonce is allowed, if ttlSeconds is 0 the client should not send verification
  242. // payload to the server. If resetCache is set the client must always perform a new
  243. // verification and update its cache
  244. func NoticeClientVerificationRequired(nonce string, ttlSeconds int, resetCache bool) {
  245. outputNotice("ClientVerificationRequired", 0, "nonce", nonce, "ttlSeconds", ttlSeconds, "resetCache", resetCache)
  246. }
  247. // NoticeClientRegion is the client's region, as determined by the server and
  248. // reported to the client in the handshake.
  249. func NoticeClientRegion(region string) {
  250. outputNotice("ClientRegion", 0, "region", region)
  251. }
  252. // NoticeTunnels is how many active tunnels are available. The client should use this to
  253. // determine connecting/unexpected disconnect state transitions. When count is 0, the core is
  254. // disconnected; when count > 1, the core is connected.
  255. func NoticeTunnels(count int) {
  256. outputNotice("Tunnels", 0, "count", count)
  257. }
  258. // NoticeSessionId is the session ID used across all tunnels established by the controller.
  259. func NoticeSessionId(sessionId string) {
  260. outputNotice("SessionId", noticeIsDiagnostic, "sessionId", sessionId)
  261. }
  262. func NoticeImpairedProtocolClassification(impairedProtocolClassification map[string]int) {
  263. outputNotice("ImpairedProtocolClassification", noticeIsDiagnostic,
  264. "classification", impairedProtocolClassification)
  265. }
  266. // NoticeUntunneled indicates than an address has been classified as untunneled and is being
  267. // accessed directly.
  268. //
  269. // Note: "address" should remain private; this notice should only be used for alerting
  270. // users, not for diagnostics logs.
  271. //
  272. func NoticeUntunneled(address string) {
  273. outputNotice("Untunneled", noticeShowUser, "address", address)
  274. }
  275. // NoticeSplitTunnelRegion reports that split tunnel is on for the given region.
  276. func NoticeSplitTunnelRegion(region string) {
  277. outputNotice("SplitTunnelRegion", noticeShowUser, "region", region)
  278. }
  279. // NoticeUpstreamProxyError reports an error when connecting to an upstream proxy. The
  280. // user may have input, for example, an incorrect address or incorrect credentials.
  281. func NoticeUpstreamProxyError(err error) {
  282. outputNotice("UpstreamProxyError", noticeShowUser, "message", err.Error())
  283. }
  284. // NoticeClientUpgradeDownloadedBytes reports client upgrade download progress.
  285. func NoticeClientUpgradeDownloadedBytes(bytes int64) {
  286. outputNotice("ClientUpgradeDownloadedBytes", noticeIsDiagnostic, "bytes", bytes)
  287. }
  288. // NoticeClientUpgradeDownloaded indicates that a client upgrade download
  289. // is complete and available at the destination specified.
  290. func NoticeClientUpgradeDownloaded(filename string) {
  291. outputNotice("ClientUpgradeDownloaded", 0, "filename", filename)
  292. }
  293. // NoticeBytesTransferred reports how many tunneled bytes have been
  294. // transferred since the last NoticeBytesTransferred, for the tunnel
  295. // to the server at ipAddress.
  296. func NoticeBytesTransferred(ipAddress string, sent, received int64) {
  297. if GetEmitDiagnoticNotices() {
  298. outputNotice("BytesTransferred", noticeIsDiagnostic, "ipAddress", ipAddress, "sent", sent, "received", received)
  299. } else {
  300. // This case keeps the EmitBytesTransferred and EmitDiagnosticNotices config options independent
  301. outputNotice("BytesTransferred", 0, "sent", sent, "received", received)
  302. }
  303. }
  304. // NoticeTotalBytesTransferred reports how many tunneled bytes have been
  305. // transferred in total up to this point, for the tunnel to the server
  306. // at ipAddress.
  307. func NoticeTotalBytesTransferred(ipAddress string, sent, received int64) {
  308. if GetEmitDiagnoticNotices() {
  309. outputNotice("TotalBytesTransferred", noticeIsDiagnostic, "ipAddress", ipAddress, "sent", sent, "received", received)
  310. } else {
  311. // This case keeps the EmitBytesTransferred and EmitDiagnosticNotices config options independent
  312. outputNotice("TotalBytesTransferred", 0, "sent", sent, "received", received)
  313. }
  314. }
  315. // NoticeLocalProxyError reports a local proxy error message. Repetitive
  316. // errors for a given proxy type are suppressed.
  317. func NoticeLocalProxyError(proxyType string, err error) {
  318. // For repeats, only consider the base error message, which is
  319. // the root error that repeats (the full error often contains
  320. // different specific values, e.g., local port numbers, but
  321. // the same repeating root).
  322. // Assumes error format of common.ContextError.
  323. repetitionMessage := err.Error()
  324. index := strings.LastIndex(repetitionMessage, ": ")
  325. if index != -1 {
  326. repetitionMessage = repetitionMessage[index+2:]
  327. }
  328. outputRepetitiveNotice(
  329. "LocalProxyError"+proxyType, repetitionMessage, 1,
  330. "LocalProxyError", noticeIsDiagnostic, "message", err.Error())
  331. }
  332. // NoticeBuildInfo reports build version info.
  333. func NoticeBuildInfo() {
  334. outputNotice("BuildInfo", 0, "buildInfo", common.GetBuildInfo())
  335. }
  336. // NoticeExiting indicates that tunnel-core is exiting imminently.
  337. func NoticeExiting() {
  338. outputNotice("Exiting", 0)
  339. }
  340. // NoticeRemoteServerListResourceDownloadedBytes reports remote server list download progress.
  341. func NoticeRemoteServerListResourceDownloadedBytes(url string, bytes int64) {
  342. outputNotice("RemoteServerListResourceDownloadedBytes", noticeIsDiagnostic, "url", url, "bytes", bytes)
  343. }
  344. // NoticeRemoteServerListResourceDownloaded indicates that a remote server list download
  345. // completed successfully.
  346. func NoticeRemoteServerListResourceDownloaded(url string) {
  347. outputNotice("RemoteServerListResourceDownloaded", noticeIsDiagnostic, "url", url)
  348. }
  349. func NoticeClientVerificationRequestCompleted(ipAddress string) {
  350. // TODO: remove "Notice" prefix
  351. outputNotice("NoticeClientVerificationRequestCompleted", noticeIsDiagnostic, "ipAddress", ipAddress)
  352. }
  353. // NoticeSLOKSeeded indicates that the SLOK with the specified ID was received from
  354. // the Psiphon server. The "duplicate" flags indicates whether the SLOK was previously known.
  355. func NoticeSLOKSeeded(slokID string, duplicate bool) {
  356. outputNotice("SLOKSeeded", noticeIsDiagnostic, "slokID", slokID, "duplicate", duplicate)
  357. }
  358. type repetitiveNoticeState struct {
  359. message string
  360. repeats int
  361. }
  362. var repetitiveNoticeMutex sync.Mutex
  363. var repetitiveNoticeStates = make(map[string]*repetitiveNoticeState)
  364. // outputRepetitiveNotice conditionally outputs a notice. Used for noticies which
  365. // often repeat in noisy bursts. For a repeat limit of N, the notice is emitted
  366. // with a "repeats" count on consecutive repeats up to the limit and then suppressed
  367. // until the repetitionMessage differs.
  368. func outputRepetitiveNotice(
  369. repetitionKey, repetitionMessage string, repeatLimit int,
  370. noticeType string, noticeFlags uint32, args ...interface{}) {
  371. repetitiveNoticeMutex.Lock()
  372. defer repetitiveNoticeMutex.Unlock()
  373. state, ok := repetitiveNoticeStates[repetitionKey]
  374. if !ok {
  375. state = new(repetitiveNoticeState)
  376. repetitiveNoticeStates[repetitionKey] = state
  377. }
  378. emit := true
  379. if repetitionMessage != state.message {
  380. state.message = repetitionMessage
  381. state.repeats = 0
  382. } else {
  383. state.repeats += 1
  384. if state.repeats > repeatLimit {
  385. emit = false
  386. }
  387. }
  388. if emit {
  389. if state.repeats > 0 {
  390. args = append(args, "repeats", state.repeats)
  391. }
  392. outputNotice(noticeType, noticeFlags, args...)
  393. }
  394. }
  395. type noticeObject struct {
  396. NoticeType string `json:"noticeType"`
  397. Data json.RawMessage `json:"data"`
  398. Timestamp string `json:"timestamp"`
  399. }
  400. // GetNotice receives a JSON encoded object and attempts to parse it as a Notice.
  401. // The type is returned as a string and the payload as a generic map.
  402. func GetNotice(notice []byte) (
  403. noticeType string, payload map[string]interface{}, err error) {
  404. var object noticeObject
  405. err = json.Unmarshal(notice, &object)
  406. if err != nil {
  407. return "", nil, err
  408. }
  409. var objectPayload interface{}
  410. err = json.Unmarshal(object.Data, &objectPayload)
  411. if err != nil {
  412. return "", nil, err
  413. }
  414. return object.NoticeType, objectPayload.(map[string]interface{}), nil
  415. }
  416. // NoticeReceiver consumes a notice input stream and invokes a callback function
  417. // for each discrete JSON notice object byte sequence.
  418. type NoticeReceiver struct {
  419. mutex sync.Mutex
  420. buffer []byte
  421. callback func([]byte)
  422. }
  423. // NewNoticeReceiver initializes a new NoticeReceiver
  424. func NewNoticeReceiver(callback func([]byte)) *NoticeReceiver {
  425. return &NoticeReceiver{callback: callback}
  426. }
  427. // Write implements io.Writer.
  428. func (receiver *NoticeReceiver) Write(p []byte) (n int, err error) {
  429. receiver.mutex.Lock()
  430. defer receiver.mutex.Unlock()
  431. receiver.buffer = append(receiver.buffer, p...)
  432. index := bytes.Index(receiver.buffer, []byte("\n"))
  433. if index == -1 {
  434. return len(p), nil
  435. }
  436. notice := receiver.buffer[:index]
  437. receiver.buffer = receiver.buffer[index+1:]
  438. receiver.callback(notice)
  439. return len(p), nil
  440. }
  441. // NewNoticeConsoleRewriter consumes JSON-format notice input and parses each
  442. // notice and rewrites in a more human-readable format more suitable for
  443. // console output. The data payload field is left as JSON.
  444. func NewNoticeConsoleRewriter(writer io.Writer) *NoticeReceiver {
  445. return NewNoticeReceiver(func(notice []byte) {
  446. var object noticeObject
  447. _ = json.Unmarshal(notice, &object)
  448. fmt.Fprintf(
  449. writer,
  450. "%s %s %s\n",
  451. object.Timestamp,
  452. object.NoticeType,
  453. string(object.Data))
  454. })
  455. }
  456. // NoticeWriter implements io.Writer and emits the contents of Write() calls
  457. // as Notices. This is to transform logger messages, if they can be redirected
  458. // to an io.Writer, to notices.
  459. type NoticeWriter struct {
  460. noticeType string
  461. }
  462. // NewNoticeWriter initializes a new NoticeWriter
  463. func NewNoticeWriter(noticeType string) *NoticeWriter {
  464. return &NoticeWriter{noticeType: noticeType}
  465. }
  466. // Write implements io.Writer.
  467. func (writer *NoticeWriter) Write(p []byte) (n int, err error) {
  468. outputNotice(writer.noticeType, noticeIsDiagnostic, "message", string(p))
  469. return len(p), nil
  470. }
  471. // NoticeCommonLogger maps the common.Logger interface to the notice facility.
  472. // This is used to make the notice facility available to other packages that
  473. // don't import the "psiphon" package.
  474. func NoticeCommonLogger() common.Logger {
  475. return &commonLogger{}
  476. }
  477. type commonLogger struct {
  478. }
  479. func (logger *commonLogger) WithContext() common.LogContext {
  480. return &commonLogContext{
  481. context: common.GetParentContext(),
  482. }
  483. }
  484. func (logger *commonLogger) WithContextFields(fields common.LogFields) common.LogContext {
  485. return &commonLogContext{
  486. context: common.GetParentContext(),
  487. fields: fields,
  488. }
  489. }
  490. func (logger *commonLogger) LogMetric(metric string, fields common.LogFields) {
  491. outputNotice(
  492. metric,
  493. noticeIsDiagnostic,
  494. listCommonFields(fields)...)
  495. }
  496. func listCommonFields(fields common.LogFields) []interface{} {
  497. fieldList := make([]interface{}, 0)
  498. for name, value := range fields {
  499. var formattedValue string
  500. if err, ok := value.(error); ok {
  501. formattedValue = err.Error()
  502. } else {
  503. formattedValue = fmt.Sprintf("%#v", value)
  504. }
  505. fieldList = append(fieldList, name, formattedValue)
  506. }
  507. return fieldList
  508. }
  509. type commonLogContext struct {
  510. context string
  511. fields common.LogFields
  512. }
  513. func (context *commonLogContext) outputNotice(
  514. noticeType string, args ...interface{}) {
  515. outputNotice(
  516. noticeType,
  517. noticeIsDiagnostic,
  518. append(
  519. []interface{}{
  520. "message", fmt.Sprint(args...),
  521. "context", context.context},
  522. listCommonFields(context.fields)...)...)
  523. }
  524. func (context *commonLogContext) Debug(args ...interface{}) {
  525. // Ignored.
  526. }
  527. func (context *commonLogContext) Info(args ...interface{}) {
  528. context.outputNotice("Info", args)
  529. }
  530. func (context *commonLogContext) Warning(args ...interface{}) {
  531. context.outputNotice("Alert", args)
  532. }
  533. func (context *commonLogContext) Error(args ...interface{}) {
  534. context.outputNotice("Error", args)
  535. }