notice.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  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. "os"
  26. "sort"
  27. "strings"
  28. "sync"
  29. "sync/atomic"
  30. "time"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/buildinfo"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/stacktrace"
  37. )
  38. type noticeLogger struct {
  39. emitDiagnostics int32
  40. emitNetworkParameters int32
  41. mutex sync.Mutex
  42. writer io.Writer
  43. homepageFilename string
  44. homepageFile *os.File
  45. rotatingFilename string
  46. rotatingOlderFilename string
  47. rotatingFile *os.File
  48. rotatingFileSize int64
  49. rotatingCurrentFileSize int64
  50. rotatingSyncFrequency int
  51. rotatingCurrentNoticeCount int
  52. }
  53. var singletonNoticeLogger = noticeLogger{
  54. writer: os.Stderr,
  55. }
  56. // SetEmitDiagnosticNotices toggles whether diagnostic notices are emitted;
  57. // and whether to include circumvention network parameters in diagnostics.
  58. //
  59. // Diagnostic notices contain potentially sensitive user information; and
  60. // sensitive circumvention network parameters, when enabled. Only enable this
  61. // in environments where notices are handled securely (for example, don't
  62. // include these notices in log files which users could post to public
  63. // forums).
  64. func SetEmitDiagnosticNotices(
  65. emitDiagnostics bool, emitNetworkParameters bool) {
  66. if emitDiagnostics {
  67. atomic.StoreInt32(&singletonNoticeLogger.emitDiagnostics, 1)
  68. } else {
  69. atomic.StoreInt32(&singletonNoticeLogger.emitDiagnostics, 0)
  70. }
  71. if emitNetworkParameters {
  72. atomic.StoreInt32(&singletonNoticeLogger.emitNetworkParameters, 1)
  73. } else {
  74. atomic.StoreInt32(&singletonNoticeLogger.emitNetworkParameters, 0)
  75. }
  76. }
  77. // GetEmitDiagnosticNotices returns the current state
  78. // of emitting diagnostic notices.
  79. func GetEmitDiagnosticNotices() bool {
  80. return atomic.LoadInt32(&singletonNoticeLogger.emitDiagnostics) == 1
  81. }
  82. // GetEmitNetworkParameters returns the current state
  83. // of emitting network parameters.
  84. func GetEmitNetworkParameters() bool {
  85. return atomic.LoadInt32(&singletonNoticeLogger.emitNetworkParameters) == 1
  86. }
  87. // SetNoticeWriter sets a target writer to receive notices. By default,
  88. // notices are written to stderr. Notices are newline delimited.
  89. //
  90. // writer specifies an alternate io.Writer where notices are to be written.
  91. //
  92. // Notices are encoded in JSON. Here's an example:
  93. //
  94. // {"data":{"message":"shutdown operate tunnel"},"noticeType":"Info","timestamp":"2006-01-02T15:04:05.999999999Z07:00"}
  95. //
  96. // All notices have the following fields:
  97. // - "noticeType": the type of notice, which indicates the meaning of the notice along with what's in the data payload.
  98. // - "data": additional structured data payload. For example, the "ListeningSocksProxyPort" notice type has a "port" integer
  99. // data in its payload.
  100. // - "timestamp": UTC timezone, RFC3339Milli format timestamp for notice event
  101. //
  102. // See the Notice* functions for details on each notice meaning and payload.
  103. func SetNoticeWriter(writer io.Writer) {
  104. singletonNoticeLogger.mutex.Lock()
  105. defer singletonNoticeLogger.mutex.Unlock()
  106. singletonNoticeLogger.writer = writer
  107. }
  108. // setNoticeFiles configures files for notice writing.
  109. //
  110. // - When homepageFilename is not "", homepages are written to the specified file
  111. // and omitted from the writer. The file may be read after the Tunnels notice
  112. // with count of 1. The file should be opened read-only for reading.
  113. //
  114. // - When rotatingFilename is not "", all notices are are written to the specified
  115. // file. Diagnostic notices are omitted from the writer. The file is rotated
  116. // when its size exceeds rotatingFileSize. One rotated older file,
  117. // <rotatingFilename>.1, is retained. The files may be read at any time; and
  118. // should be opened read-only for reading. rotatingSyncFrequency specifies how
  119. // many notices are written before syncing the file.
  120. // If either rotatingFileSize or rotatingSyncFrequency are <= 0, default values
  121. // are used.
  122. //
  123. // - If an error occurs when writing to a file, an InternalError notice is emitted to
  124. // the writer.
  125. //
  126. // setNoticeFiles closes open homepage or rotating files before applying the new
  127. // configuration.
  128. func setNoticeFiles(
  129. homepageFilename string,
  130. rotatingFilename string,
  131. rotatingFileSize int,
  132. rotatingSyncFrequency int) error {
  133. singletonNoticeLogger.mutex.Lock()
  134. defer singletonNoticeLogger.mutex.Unlock()
  135. if homepageFilename != "" {
  136. var err error
  137. if singletonNoticeLogger.homepageFile != nil {
  138. singletonNoticeLogger.homepageFile.Close()
  139. }
  140. singletonNoticeLogger.homepageFile, err = os.OpenFile(
  141. homepageFilename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
  142. if err != nil {
  143. return errors.Trace(err)
  144. }
  145. singletonNoticeLogger.homepageFilename = homepageFilename
  146. }
  147. if rotatingFilename != "" {
  148. var err error
  149. if singletonNoticeLogger.rotatingFile != nil {
  150. singletonNoticeLogger.rotatingFile.Close()
  151. }
  152. singletonNoticeLogger.rotatingFile, err = os.OpenFile(
  153. rotatingFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
  154. if err != nil {
  155. return errors.Trace(err)
  156. }
  157. fileInfo, err := singletonNoticeLogger.rotatingFile.Stat()
  158. if err != nil {
  159. return errors.Trace(err)
  160. }
  161. if rotatingFileSize <= 0 {
  162. rotatingFileSize = 1 << 20
  163. }
  164. if rotatingSyncFrequency <= 0 {
  165. rotatingSyncFrequency = 100
  166. }
  167. singletonNoticeLogger.rotatingFilename = rotatingFilename
  168. singletonNoticeLogger.rotatingOlderFilename = rotatingFilename + ".1"
  169. singletonNoticeLogger.rotatingFileSize = int64(rotatingFileSize)
  170. singletonNoticeLogger.rotatingCurrentFileSize = fileInfo.Size()
  171. singletonNoticeLogger.rotatingSyncFrequency = rotatingSyncFrequency
  172. singletonNoticeLogger.rotatingCurrentNoticeCount = 0
  173. }
  174. return nil
  175. }
  176. const (
  177. noticeIsDiagnostic = 1
  178. noticeIsHomepage = 2
  179. noticeClearHomepages = 4
  180. noticeSyncHomepages = 8
  181. noticeSkipRedaction = 16
  182. )
  183. // outputNotice encodes a notice in JSON and writes it to the output writer.
  184. func (nl *noticeLogger) outputNotice(noticeType string, noticeFlags uint32, args ...interface{}) {
  185. if (noticeFlags&noticeIsDiagnostic != 0) && !GetEmitDiagnosticNotices() {
  186. return
  187. }
  188. obj := make(map[string]interface{})
  189. noticeData := make(map[string]interface{})
  190. obj["noticeType"] = noticeType
  191. obj["data"] = noticeData
  192. obj["timestamp"] = time.Now().UTC().Format(common.RFC3339Milli)
  193. for i := 0; i < len(args)-1; i += 2 {
  194. name, ok := args[i].(string)
  195. value := args[i+1]
  196. if ok {
  197. noticeData[name] = value
  198. }
  199. }
  200. encodedJson, err := json.Marshal(obj)
  201. var output []byte
  202. if err == nil {
  203. output = append(encodedJson, byte('\n'))
  204. } else {
  205. // Try to emit a properly formatted notice that the outer client can report.
  206. // One scenario where this is useful is if the preceding Marshal fails due to
  207. // bad data in the args. This has happened for a json.RawMessage field.
  208. output = makeNoticeInternalError(
  209. fmt.Sprintf("marshal notice failed: %s", errors.Trace(err)))
  210. }
  211. // Skip redaction when we need to display browsing activity network addresses
  212. // to users; for example, in the case of the Untunneled notice. Never log
  213. // skipRedaction notices to diagnostics files (outputNoticeToRotatingFile,
  214. // below). The notice writer may still be invoked for a skipRedaction notice;
  215. // the writer must keep all known skipRedaction notices out of any upstream
  216. // diagnostics logs.
  217. skipRedaction := (noticeFlags&noticeSkipRedaction != 0)
  218. if !skipRedaction {
  219. // Ensure direct server IPs are not exposed in notices. The "net" package,
  220. // and possibly other 3rd party packages, will include destination addresses
  221. // in I/O error messages.
  222. output = common.RedactIPAddresses(output)
  223. }
  224. // Don't call RedactFilePaths here, as the file path redaction can
  225. // potentially match many non-path strings. Instead, RedactFilePaths should
  226. // be applied in specific cases.
  227. nl.mutex.Lock()
  228. defer nl.mutex.Unlock()
  229. skipWriter := false
  230. if nl.homepageFile != nil &&
  231. (noticeFlags&noticeIsHomepage != 0) {
  232. skipWriter = true
  233. err := nl.outputNoticeToHomepageFile(noticeFlags, output)
  234. if err != nil {
  235. output := makeNoticeInternalError(
  236. fmt.Sprintf("write homepage file failed: %s", err))
  237. nl.writer.Write(output)
  238. }
  239. }
  240. if nl.rotatingFile != nil {
  241. if !skipWriter {
  242. skipWriter = (noticeFlags&noticeIsDiagnostic != 0)
  243. }
  244. if !skipRedaction {
  245. err := nl.outputNoticeToRotatingFile(output)
  246. if err != nil {
  247. output := makeNoticeInternalError(
  248. fmt.Sprintf("write rotating file failed: %s", err))
  249. nl.writer.Write(output)
  250. }
  251. }
  252. }
  253. if !skipWriter {
  254. _, _ = nl.writer.Write(output)
  255. }
  256. }
  257. // NoticeInteralError is an error formatting or writing notices.
  258. // A NoticeInteralError handler must not call a Notice function.
  259. func makeNoticeInternalError(errorMessage string) []byte {
  260. // Format an Alert Notice (_without_ using json.Marshal, since that can fail)
  261. alertNoticeFormat := "{\"noticeType\":\"InternalError\",\"timestamp\":\"%s\",\"data\":{\"message\":\"%s\"}}\n"
  262. return []byte(fmt.Sprintf(alertNoticeFormat, time.Now().UTC().Format(common.RFC3339Milli), errorMessage))
  263. }
  264. func (nl *noticeLogger) outputNoticeToHomepageFile(noticeFlags uint32, output []byte) error {
  265. if (noticeFlags & noticeClearHomepages) != 0 {
  266. err := nl.homepageFile.Truncate(0)
  267. if err != nil {
  268. return errors.Trace(err)
  269. }
  270. _, err = nl.homepageFile.Seek(0, 0)
  271. if err != nil {
  272. return errors.Trace(err)
  273. }
  274. }
  275. _, err := nl.homepageFile.Write(output)
  276. if err != nil {
  277. return errors.Trace(err)
  278. }
  279. if (noticeFlags & noticeSyncHomepages) != 0 {
  280. err = nl.homepageFile.Sync()
  281. if err != nil {
  282. return errors.Trace(err)
  283. }
  284. }
  285. return nil
  286. }
  287. func (nl *noticeLogger) outputNoticeToRotatingFile(output []byte) error {
  288. nl.rotatingCurrentFileSize += int64(len(output) + 1)
  289. if nl.rotatingCurrentFileSize >= nl.rotatingFileSize {
  290. // Note: all errors are fatal in order to preserve the
  291. // rotatingFileSize limit; e.g., no attempt is made to
  292. // continue writing to the file if it can't be rotated.
  293. err := nl.rotatingFile.Sync()
  294. if err != nil {
  295. return errors.Trace(err)
  296. }
  297. err = nl.rotatingFile.Close()
  298. if err != nil {
  299. return errors.Trace(err)
  300. }
  301. err = os.Rename(nl.rotatingFilename, nl.rotatingOlderFilename)
  302. if err != nil {
  303. return errors.Trace(err)
  304. }
  305. nl.rotatingFile, err = os.OpenFile(
  306. nl.rotatingFilename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
  307. if err != nil {
  308. return errors.Trace(err)
  309. }
  310. nl.rotatingCurrentFileSize = 0
  311. }
  312. _, err := nl.rotatingFile.Write(output)
  313. if err != nil {
  314. return errors.Trace(err)
  315. }
  316. nl.rotatingCurrentNoticeCount += 1
  317. if nl.rotatingCurrentNoticeCount >= nl.rotatingSyncFrequency {
  318. nl.rotatingCurrentNoticeCount = 0
  319. err = nl.rotatingFile.Sync()
  320. if err != nil {
  321. return errors.Trace(err)
  322. }
  323. }
  324. return nil
  325. }
  326. // NoticeInfo is an informational message
  327. func NoticeInfo(format string, args ...interface{}) {
  328. singletonNoticeLogger.outputNotice(
  329. "Info", noticeIsDiagnostic,
  330. "message", fmt.Sprintf(format, args...))
  331. }
  332. // NoticeWarning is a warning message; typically a recoverable error condition
  333. func NoticeWarning(format string, args ...interface{}) {
  334. singletonNoticeLogger.outputNotice(
  335. "Warning", noticeIsDiagnostic,
  336. "message", fmt.Sprintf(format, args...))
  337. }
  338. // NoticeError is an error message; typically an unrecoverable error condition
  339. func NoticeError(format string, args ...interface{}) {
  340. singletonNoticeLogger.outputNotice(
  341. "Error", noticeIsDiagnostic,
  342. "message", fmt.Sprintf(format, args...))
  343. }
  344. // NoticeUserLog is a log message from the outer client user of tunnel-core
  345. func NoticeUserLog(message string) {
  346. singletonNoticeLogger.outputNotice(
  347. "UserLog", noticeIsDiagnostic,
  348. "message", message)
  349. }
  350. // NoticeCandidateServers is how many possible servers are available for the selected region and protocols
  351. func NoticeCandidateServers(
  352. region string,
  353. constraints *protocolSelectionConstraints,
  354. initialCount int,
  355. count int,
  356. duration time.Duration) {
  357. singletonNoticeLogger.outputNotice(
  358. "CandidateServers", noticeIsDiagnostic,
  359. "region", region,
  360. "initialLimitTunnelProtocols", constraints.initialLimitTunnelProtocols,
  361. "initialLimitTunnelProtocolsCandidateCount", constraints.initialLimitTunnelProtocolsCandidateCount,
  362. "limitTunnelProtocols", constraints.limitTunnelProtocols,
  363. "limitTunnelDialPortNumbers", constraints.limitTunnelDialPortNumbers,
  364. "replayCandidateCount", constraints.replayCandidateCount,
  365. "initialCount", initialCount,
  366. "count", count,
  367. "duration", duration.String())
  368. }
  369. // NoticeAvailableEgressRegions is what regions are available for egress from.
  370. // Consecutive reports of the same list of regions are suppressed.
  371. func NoticeAvailableEgressRegions(regions []string) {
  372. sortedRegions := append([]string{}, regions...)
  373. sort.Strings(sortedRegions)
  374. repetitionMessage := strings.Join(sortedRegions, "")
  375. outputRepetitiveNotice(
  376. "AvailableEgressRegions", repetitionMessage, 0,
  377. "AvailableEgressRegions", 0, "regions", sortedRegions)
  378. }
  379. func noticeWithDialParameters(noticeType string, dialParams *DialParameters, postDial bool) {
  380. args := []interface{}{
  381. "diagnosticID", dialParams.ServerEntry.GetDiagnosticID(),
  382. "region", dialParams.ServerEntry.Region,
  383. "protocol", dialParams.TunnelProtocol,
  384. "isReplay", dialParams.IsReplay,
  385. "candidateNumber", dialParams.CandidateNumber,
  386. "establishedTunnelsCount", dialParams.EstablishedTunnelsCount,
  387. "networkType", dialParams.GetNetworkType(),
  388. }
  389. if GetEmitNetworkParameters() {
  390. // Omit appliedTacticsTag as that is emitted in another notice.
  391. if dialParams.BPFProgramName != "" {
  392. args = append(args, "clientBPF", dialParams.BPFProgramName)
  393. }
  394. if dialParams.SelectedSSHClientVersion {
  395. args = append(args, "SSHClientVersion", dialParams.SSHClientVersion)
  396. }
  397. if dialParams.UpstreamProxyType != "" {
  398. args = append(args, "upstreamProxyType", dialParams.UpstreamProxyType)
  399. }
  400. if dialParams.UpstreamProxyCustomHeaderNames != nil {
  401. args = append(args, "upstreamProxyCustomHeaderNames", strings.Join(dialParams.UpstreamProxyCustomHeaderNames, ","))
  402. }
  403. if dialParams.FrontingProviderID != "" {
  404. args = append(args, "frontingProviderID", dialParams.FrontingProviderID)
  405. }
  406. if dialParams.MeekDialAddress != "" {
  407. args = append(args, "meekDialAddress", dialParams.MeekDialAddress)
  408. }
  409. if protocol.TunnelProtocolUsesFrontedMeek(dialParams.TunnelProtocol) {
  410. meekResolvedIPAddress := dialParams.MeekResolvedIPAddress.Load().(string)
  411. if meekResolvedIPAddress != "" {
  412. nonredacted := common.EscapeRedactIPAddressString(meekResolvedIPAddress)
  413. args = append(args, "meekResolvedIPAddress", nonredacted)
  414. }
  415. }
  416. if dialParams.MeekSNIServerName != "" {
  417. args = append(args, "meekSNIServerName", dialParams.MeekSNIServerName)
  418. }
  419. if dialParams.MeekHostHeader != "" {
  420. args = append(args, "meekHostHeader", dialParams.MeekHostHeader)
  421. }
  422. // MeekTransformedHostName is meaningful when meek is used, which is when MeekDialAddress != ""
  423. if dialParams.MeekDialAddress != "" {
  424. args = append(args, "meekTransformedHostName", dialParams.MeekTransformedHostName)
  425. }
  426. if dialParams.SelectedUserAgent {
  427. args = append(args, "userAgent", dialParams.UserAgent)
  428. }
  429. if dialParams.SelectedTLSProfile {
  430. args = append(args, "TLSProfile", dialParams.TLSProfile)
  431. args = append(args, "TLSVersion", dialParams.GetTLSVersionForMetrics())
  432. }
  433. // dialParams.ServerEntry.Region is emitted above.
  434. if dialParams.ServerEntry.LocalSource != "" {
  435. args = append(args, "serverEntrySource", dialParams.ServerEntry.LocalSource)
  436. }
  437. localServerEntryTimestamp := common.TruncateTimestampToHour(
  438. dialParams.ServerEntry.LocalTimestamp)
  439. if localServerEntryTimestamp != "" {
  440. args = append(args, "serverEntryTimestamp", localServerEntryTimestamp)
  441. }
  442. if dialParams.DialPortNumber != "" {
  443. args = append(args, "dialPortNumber", dialParams.DialPortNumber)
  444. }
  445. if dialParams.QUICVersion != "" {
  446. args = append(args, "QUICVersion", dialParams.QUICVersion)
  447. }
  448. if dialParams.QUICDialSNIAddress != "" {
  449. args = append(args, "QUICDialSNIAddress", dialParams.QUICDialSNIAddress)
  450. }
  451. if dialParams.QUICDisablePathMTUDiscovery {
  452. args = append(args, "QUICDisableClientPathMTUDiscovery", dialParams.QUICDisablePathMTUDiscovery)
  453. }
  454. if dialParams.DialDuration > 0 {
  455. args = append(args, "dialDuration", dialParams.DialDuration)
  456. }
  457. if dialParams.NetworkLatencyMultiplier != 0.0 {
  458. args = append(args, "networkLatencyMultiplier", dialParams.NetworkLatencyMultiplier)
  459. }
  460. if dialParams.ConjureTransport != "" {
  461. args = append(args, "conjureTransport", dialParams.ConjureTransport)
  462. }
  463. if dialParams.ResolveParameters != nil {
  464. if dialParams.ResolveParameters.PreresolvedIPAddress != "" {
  465. nonredacted := common.EscapeRedactIPAddressString(dialParams.ResolveParameters.PreresolvedIPAddress)
  466. args = append(args, "DNSPreresolved", nonredacted)
  467. } else {
  468. // See dialParams.ResolveParameters comment in getBaseAPIParameters.
  469. if dialParams.ResolveParameters.PreferAlternateDNSServer {
  470. nonredacted := common.EscapeRedactIPAddressString(dialParams.ResolveParameters.AlternateDNSServer)
  471. args = append(args, "DNSPreferred", nonredacted)
  472. }
  473. if dialParams.ResolveParameters.ProtocolTransformName != "" {
  474. args = append(args, "DNSTransform", dialParams.ResolveParameters.ProtocolTransformName)
  475. }
  476. if postDial {
  477. args = append(args, "DNSAttempt", dialParams.ResolveParameters.GetFirstAttemptWithAnswer())
  478. }
  479. }
  480. }
  481. if dialParams.HTTPTransformerParameters != nil {
  482. if dialParams.HTTPTransformerParameters.ProtocolTransformSpec != nil {
  483. args = append(args, "HTTPTransform", dialParams.HTTPTransformerParameters.ProtocolTransformName)
  484. }
  485. }
  486. if dialParams.DialConnMetrics != nil {
  487. metrics := dialParams.DialConnMetrics.GetMetrics()
  488. for name, value := range metrics {
  489. args = append(args, name, value)
  490. }
  491. }
  492. if dialParams.DialConnNoticeMetrics != nil {
  493. metrics := dialParams.DialConnNoticeMetrics.GetNoticeMetrics()
  494. for name, value := range metrics {
  495. args = append(args, name, value)
  496. }
  497. }
  498. if dialParams.ObfuscatedSSHConnMetrics != nil {
  499. metrics := dialParams.ObfuscatedSSHConnMetrics.GetMetrics()
  500. for name, value := range metrics {
  501. args = append(args, name, value)
  502. }
  503. }
  504. }
  505. singletonNoticeLogger.outputNotice(
  506. noticeType, noticeIsDiagnostic,
  507. args...)
  508. }
  509. // NoticeConnectingServer reports parameters and details for a single connection attempt
  510. func NoticeConnectingServer(dialParams *DialParameters) {
  511. noticeWithDialParameters("ConnectingServer", dialParams, false)
  512. }
  513. // NoticeConnectedServer reports parameters and details for a single successful connection
  514. func NoticeConnectedServer(dialParams *DialParameters) {
  515. noticeWithDialParameters("ConnectedServer", dialParams, true)
  516. }
  517. // NoticeRequestingTactics reports parameters and details for a tactics request attempt
  518. func NoticeRequestingTactics(dialParams *DialParameters) {
  519. noticeWithDialParameters("RequestingTactics", dialParams, false)
  520. }
  521. // NoticeRequestedTactics reports parameters and details for a successful tactics request
  522. func NoticeRequestedTactics(dialParams *DialParameters) {
  523. noticeWithDialParameters("RequestedTactics", dialParams, true)
  524. }
  525. // NoticeActiveTunnel is a successful connection that is used as an active tunnel for port forwarding
  526. func NoticeActiveTunnel(diagnosticID, protocol string, isTCS bool) {
  527. singletonNoticeLogger.outputNotice(
  528. "ActiveTunnel", noticeIsDiagnostic,
  529. "diagnosticID", diagnosticID,
  530. "protocol", protocol,
  531. "isTCS", isTCS)
  532. }
  533. // NoticeSocksProxyPortInUse is a failure to use the configured LocalSocksProxyPort
  534. func NoticeSocksProxyPortInUse(port int) {
  535. singletonNoticeLogger.outputNotice(
  536. "SocksProxyPortInUse", 0,
  537. "port", port)
  538. }
  539. // NoticeListeningSocksProxyPort is the selected port for the listening local SOCKS proxy
  540. func NoticeListeningSocksProxyPort(port int) {
  541. singletonNoticeLogger.outputNotice(
  542. "ListeningSocksProxyPort", 0,
  543. "port", port)
  544. }
  545. // NoticeHttpProxyPortInUse is a failure to use the configured LocalHttpProxyPort
  546. func NoticeHttpProxyPortInUse(port int) {
  547. singletonNoticeLogger.outputNotice(
  548. "HttpProxyPortInUse", 0,
  549. "port", port)
  550. }
  551. // NoticeListeningHttpProxyPort is the selected port for the listening local HTTP proxy
  552. func NoticeListeningHttpProxyPort(port int) {
  553. singletonNoticeLogger.outputNotice(
  554. "ListeningHttpProxyPort", 0,
  555. "port", port)
  556. }
  557. // NoticeClientUpgradeAvailable is an available client upgrade, as per the handshake. The
  558. // client should download and install an upgrade.
  559. func NoticeClientUpgradeAvailable(version string) {
  560. singletonNoticeLogger.outputNotice(
  561. "ClientUpgradeAvailable", 0,
  562. "version", version)
  563. }
  564. // NoticeClientIsLatestVersion reports that an upgrade check was made and the client
  565. // is already the latest version. availableVersion is the version available for download,
  566. // if known.
  567. func NoticeClientIsLatestVersion(availableVersion string) {
  568. singletonNoticeLogger.outputNotice(
  569. "ClientIsLatestVersion", 0,
  570. "availableVersion", availableVersion)
  571. }
  572. // NoticeHomepages emits a series of NoticeHomepage, the sponsor homepages. The client
  573. // should display the sponsor's homepages.
  574. func NoticeHomepages(urls []string) {
  575. for i, url := range urls {
  576. noticeFlags := uint32(noticeIsHomepage)
  577. if i == 0 {
  578. noticeFlags |= noticeClearHomepages
  579. }
  580. if i == len(urls)-1 {
  581. noticeFlags |= noticeSyncHomepages
  582. }
  583. singletonNoticeLogger.outputNotice(
  584. "Homepage", noticeFlags,
  585. "url", url)
  586. }
  587. }
  588. // NoticeClientRegion is the client's region, as determined by the server and
  589. // reported to the client in the handshake.
  590. func NoticeClientRegion(region string) {
  591. singletonNoticeLogger.outputNotice(
  592. "ClientRegion", 0,
  593. "region", region)
  594. }
  595. // NoticeClientAddress is the client's public network address, the IP address
  596. // and port, as seen by the server and reported to the client in the
  597. // handshake.
  598. //
  599. // Note: "address" should remain private and not included in diagnostics logs.
  600. func NoticeClientAddress(address string) {
  601. singletonNoticeLogger.outputNotice(
  602. "ClientAddress", noticeSkipRedaction,
  603. "address", address)
  604. }
  605. // NoticeTunnels is how many active tunnels are available. The client should use this to
  606. // determine connecting/unexpected disconnect state transitions. When count is 0, the core is
  607. // disconnected; when count > 1, the core is connected.
  608. func NoticeTunnels(count int) {
  609. singletonNoticeLogger.outputNotice(
  610. "Tunnels", 0,
  611. "count", count)
  612. }
  613. // NoticeSessionId is the session ID used across all tunnels established by the controller.
  614. func NoticeSessionId(sessionId string) {
  615. singletonNoticeLogger.outputNotice(
  616. "SessionId", noticeIsDiagnostic,
  617. "sessionId", sessionId)
  618. }
  619. // NoticeSplitTunnelRegions reports that split tunnel is on for the given country codes.
  620. func NoticeSplitTunnelRegions(regions []string) {
  621. singletonNoticeLogger.outputNotice(
  622. "SplitTunnelRegions", 0,
  623. "regions", regions)
  624. }
  625. // NoticeUntunneled indicates than an address has been classified as untunneled and is being
  626. // accessed directly.
  627. //
  628. // Note: "address" should remain private; this notice should only be used for alerting
  629. // users, not for diagnostics logs.
  630. func NoticeUntunneled(address string) {
  631. outputRepetitiveNotice(
  632. "Untunneled", address, 0,
  633. "Untunneled", noticeSkipRedaction, "address", address)
  634. }
  635. // NoticeUpstreamProxyError reports an error when connecting to an upstream proxy. The
  636. // user may have input, for example, an incorrect address or incorrect credentials.
  637. func NoticeUpstreamProxyError(err error) {
  638. message := err.Error()
  639. outputRepetitiveNotice(
  640. "UpstreamProxyError", message, 0,
  641. "UpstreamProxyError", 0,
  642. "message", message)
  643. }
  644. // NoticeClientUpgradeDownloadedBytes reports client upgrade download progress.
  645. func NoticeClientUpgradeDownloadedBytes(bytes int64) {
  646. singletonNoticeLogger.outputNotice(
  647. "ClientUpgradeDownloadedBytes", noticeIsDiagnostic,
  648. "bytes", bytes)
  649. }
  650. // NoticeClientUpgradeDownloaded indicates that a client upgrade download
  651. // is complete and available at the destination specified.
  652. func NoticeClientUpgradeDownloaded(filename string) {
  653. singletonNoticeLogger.outputNotice(
  654. "ClientUpgradeDownloaded", 0,
  655. "filename", filename)
  656. }
  657. // NoticeBytesTransferred reports how many tunneled bytes have been
  658. // transferred since the last NoticeBytesTransferred. This is not a diagnostic
  659. // notice: the user app has requested this notice with EmitBytesTransferred
  660. // for functionality such as traffic display; and this frequent notice is not
  661. // intended to be included with feedback.
  662. func NoticeBytesTransferred(diagnosticID string, sent, received int64) {
  663. singletonNoticeLogger.outputNotice(
  664. "BytesTransferred", 0,
  665. "diagnosticID", diagnosticID,
  666. "sent", sent,
  667. "received", received)
  668. }
  669. // NoticeTotalBytesTransferred reports how many tunneled bytes have been
  670. // transferred in total up to this point. This is a diagnostic notice.
  671. func NoticeTotalBytesTransferred(diagnosticID string, sent, received int64) {
  672. singletonNoticeLogger.outputNotice(
  673. "TotalBytesTransferred", noticeIsDiagnostic,
  674. "diagnosticID", diagnosticID,
  675. "sent", sent,
  676. "received", received)
  677. }
  678. // NoticeLocalProxyError reports a local proxy error message. Repetitive
  679. // errors for a given proxy type are suppressed.
  680. func NoticeLocalProxyError(proxyType string, err error) {
  681. // For repeats, only consider the base error message, which is
  682. // the root error that repeats (the full error often contains
  683. // different specific values, e.g., local port numbers, but
  684. // the same repeating root).
  685. // Assumes error format of errors.Trace.
  686. repetitionMessage := err.Error()
  687. index := strings.LastIndex(repetitionMessage, ": ")
  688. if index != -1 {
  689. repetitionMessage = repetitionMessage[index+2:]
  690. }
  691. outputRepetitiveNotice(
  692. "LocalProxyError-"+proxyType, repetitionMessage, 1,
  693. "LocalProxyError", noticeIsDiagnostic,
  694. "message", err.Error())
  695. }
  696. // NoticeBuildInfo reports build version info.
  697. func NoticeBuildInfo() {
  698. singletonNoticeLogger.outputNotice(
  699. "BuildInfo", noticeIsDiagnostic,
  700. "buildInfo", buildinfo.GetBuildInfo())
  701. }
  702. // NoticeExiting indicates that tunnel-core is exiting imminently.
  703. func NoticeExiting() {
  704. singletonNoticeLogger.outputNotice(
  705. "Exiting", 0)
  706. }
  707. // NoticeRemoteServerListResourceDownloadedBytes reports remote server list download progress.
  708. func NoticeRemoteServerListResourceDownloadedBytes(url string, bytes int64, duration time.Duration) {
  709. if !GetEmitNetworkParameters() {
  710. url = "[redacted]"
  711. }
  712. singletonNoticeLogger.outputNotice(
  713. "RemoteServerListResourceDownloadedBytes", noticeIsDiagnostic,
  714. "url", url,
  715. "bytes", bytes,
  716. "duration", duration.String())
  717. }
  718. // NoticeRemoteServerListResourceDownloaded indicates that a remote server list download
  719. // completed successfully.
  720. func NoticeRemoteServerListResourceDownloaded(url string) {
  721. if !GetEmitNetworkParameters() {
  722. url = "[redacted]"
  723. }
  724. singletonNoticeLogger.outputNotice(
  725. "RemoteServerListResourceDownloaded", noticeIsDiagnostic,
  726. "url", url)
  727. }
  728. // NoticeSLOKSeeded indicates that the SLOK with the specified ID was received from
  729. // the Psiphon server. The "duplicate" flags indicates whether the SLOK was previously known.
  730. func NoticeSLOKSeeded(slokID string, duplicate bool) {
  731. singletonNoticeLogger.outputNotice(
  732. "SLOKSeeded", noticeIsDiagnostic,
  733. "slokID", slokID,
  734. "duplicate", duplicate)
  735. }
  736. // NoticeServerTimestamp reports server side timestamp as seen in the handshake.
  737. func NoticeServerTimestamp(diagnosticID string, timestamp string) {
  738. singletonNoticeLogger.outputNotice(
  739. "ServerTimestamp", 0,
  740. "diagnosticID", diagnosticID,
  741. "timestamp", timestamp)
  742. }
  743. // NoticeActiveAuthorizationIDs reports the authorizations the server has accepted.
  744. // Each ID is a base64-encoded accesscontrol.Authorization.ID value.
  745. func NoticeActiveAuthorizationIDs(diagnosticID string, activeAuthorizationIDs []string) {
  746. // Never emit 'null' instead of empty list
  747. if activeAuthorizationIDs == nil {
  748. activeAuthorizationIDs = []string{}
  749. }
  750. singletonNoticeLogger.outputNotice(
  751. "ActiveAuthorizationIDs", 0,
  752. "diagnosticID", diagnosticID,
  753. "IDs", activeAuthorizationIDs)
  754. }
  755. // NoticeTrafficRateLimits reports the tunnel traffic rate limits in place for
  756. // this client, as reported by the server at the start of the tunnel. Values
  757. // of 0 indicate no limit. Values of -1 indicate that the server did not
  758. // report rate limits.
  759. //
  760. // Limitation: any rate limit changes during the lifetime of the tunnel are
  761. // not reported.
  762. func NoticeTrafficRateLimits(
  763. diagnosticID string, upstreamBytesPerSecond, downstreamBytesPerSecond int64) {
  764. singletonNoticeLogger.outputNotice(
  765. "TrafficRateLimits", 0,
  766. "diagnosticID", diagnosticID,
  767. "upstreamBytesPerSecond", upstreamBytesPerSecond,
  768. "downstreamBytesPerSecond", downstreamBytesPerSecond)
  769. }
  770. func NoticeBindToDevice(deviceInfo string) {
  771. outputRepetitiveNotice(
  772. "BindToDevice", deviceInfo, 0,
  773. "BindToDevice", 0, "deviceInfo", deviceInfo)
  774. }
  775. func NoticeNetworkID(networkID string) {
  776. outputRepetitiveNotice(
  777. "NetworkID", networkID, 0,
  778. "NetworkID", 0, "ID", networkID)
  779. }
  780. func NoticeLivenessTest(diagnosticID string, metrics *livenessTestMetrics, success bool) {
  781. if GetEmitNetworkParameters() {
  782. singletonNoticeLogger.outputNotice(
  783. "LivenessTest", noticeIsDiagnostic,
  784. "diagnosticID", diagnosticID,
  785. "metrics", metrics,
  786. "success", success)
  787. }
  788. }
  789. func NoticePruneServerEntry(serverEntryTag string) {
  790. singletonNoticeLogger.outputNotice(
  791. "PruneServerEntry", noticeIsDiagnostic,
  792. "serverEntryTag", serverEntryTag)
  793. }
  794. // NoticeEstablishTunnelTimeout reports that the configured EstablishTunnelTimeout
  795. // duration was exceeded.
  796. func NoticeEstablishTunnelTimeout(timeout time.Duration) {
  797. singletonNoticeLogger.outputNotice(
  798. "EstablishTunnelTimeout", 0,
  799. "timeout", timeout.String())
  800. }
  801. func NoticeFragmentor(diagnosticID string, message string) {
  802. if GetEmitNetworkParameters() {
  803. singletonNoticeLogger.outputNotice(
  804. "Fragmentor", noticeIsDiagnostic,
  805. "diagnosticID", diagnosticID,
  806. "message", message)
  807. }
  808. }
  809. // NoticeApplicationParameters reports application parameters.
  810. func NoticeApplicationParameters(keyValues parameters.KeyValues) {
  811. // Never emit 'null' instead of empty object
  812. if keyValues == nil {
  813. keyValues = parameters.KeyValues{}
  814. }
  815. outputRepetitiveNotice(
  816. "ApplicationParameters", fmt.Sprintf("%+v", keyValues), 0,
  817. "ApplicationParameters", 0,
  818. "parameters", keyValues)
  819. }
  820. // NoticeServerAlert reports server alerts. Each distinct server alert is
  821. // reported at most once per session.
  822. func NoticeServerAlert(alert protocol.AlertRequest) {
  823. // Never emit 'null' instead of empty list
  824. actionURLs := alert.ActionURLs
  825. if actionURLs == nil {
  826. actionURLs = []string{}
  827. }
  828. // This key ensures that each distinct server alert will appear, not repeat,
  829. // and not interfere with other alerts appearing.
  830. repetitionKey := fmt.Sprintf("ServerAlert-%+v", alert)
  831. outputRepetitiveNotice(
  832. repetitionKey, "", 0,
  833. "ServerAlert", 0,
  834. "reason", alert.Reason,
  835. "subject", alert.Subject,
  836. "actionURLs", actionURLs)
  837. }
  838. // NoticeBursts reports tunnel data transfer burst metrics.
  839. func NoticeBursts(diagnosticID string, burstMetrics common.LogFields) {
  840. if GetEmitNetworkParameters() {
  841. singletonNoticeLogger.outputNotice(
  842. "Bursts", noticeIsDiagnostic,
  843. append([]interface{}{"diagnosticID", diagnosticID}, listCommonFields(burstMetrics)...)...)
  844. }
  845. }
  846. // NoticeHoldOffTunnel reports tunnel hold-offs.
  847. func NoticeHoldOffTunnel(diagnosticID string, duration time.Duration) {
  848. if GetEmitNetworkParameters() {
  849. singletonNoticeLogger.outputNotice(
  850. "HoldOffTunnel", noticeIsDiagnostic,
  851. "diagnosticID", diagnosticID,
  852. "duration", duration.String())
  853. }
  854. }
  855. // NoticeSkipServerEntry reports a reason for skipping a server entry when
  856. // preparing dial parameters. To avoid log noise, the server entry
  857. // diagnosticID is not emitted and each reason is reported at most once per
  858. // session.
  859. func NoticeSkipServerEntry(format string, args ...interface{}) {
  860. reason := fmt.Sprintf(format, args...)
  861. repetitionKey := fmt.Sprintf("SkipServerEntryReason-%+v", reason)
  862. outputRepetitiveNotice(
  863. repetitionKey, "", 0,
  864. "SkipServerEntry", 0, "reason", reason)
  865. }
  866. type repetitiveNoticeState struct {
  867. message string
  868. repeats int
  869. }
  870. var repetitiveNoticeMutex sync.Mutex
  871. var repetitiveNoticeStates = make(map[string]*repetitiveNoticeState)
  872. // outputRepetitiveNotice conditionally outputs a notice. Used for noticies which
  873. // often repeat in noisy bursts. For a repeat limit of N, the notice is emitted
  874. // with a "repeats" count on consecutive repeats up to the limit and then suppressed
  875. // until the repetitionMessage differs.
  876. func outputRepetitiveNotice(
  877. repetitionKey, repetitionMessage string, repeatLimit int,
  878. noticeType string, noticeFlags uint32, args ...interface{}) {
  879. repetitiveNoticeMutex.Lock()
  880. defer repetitiveNoticeMutex.Unlock()
  881. state, keyFound := repetitiveNoticeStates[repetitionKey]
  882. if !keyFound {
  883. state = &repetitiveNoticeState{message: repetitionMessage}
  884. repetitiveNoticeStates[repetitionKey] = state
  885. }
  886. emit := true
  887. if keyFound {
  888. if repetitionMessage != state.message {
  889. state.message = repetitionMessage
  890. state.repeats = 0
  891. } else {
  892. state.repeats += 1
  893. if state.repeats > repeatLimit {
  894. emit = false
  895. }
  896. }
  897. }
  898. if emit {
  899. if state.repeats > 0 {
  900. args = append(args, "repeats", state.repeats)
  901. }
  902. singletonNoticeLogger.outputNotice(
  903. noticeType, noticeFlags,
  904. args...)
  905. }
  906. }
  907. // ResetRepetitiveNotices resets the repetitive notice state, so
  908. // the next instance of any notice will not be supressed.
  909. func ResetRepetitiveNotices() {
  910. repetitiveNoticeMutex.Lock()
  911. defer repetitiveNoticeMutex.Unlock()
  912. repetitiveNoticeStates = make(map[string]*repetitiveNoticeState)
  913. }
  914. type noticeObject struct {
  915. NoticeType string `json:"noticeType"`
  916. Data json.RawMessage `json:"data"`
  917. Timestamp string `json:"timestamp"`
  918. }
  919. // GetNotice receives a JSON encoded object and attempts to parse it as a Notice.
  920. // The type is returned as a string and the payload as a generic map.
  921. func GetNotice(notice []byte) (
  922. noticeType string, payload map[string]interface{}, err error) {
  923. var object noticeObject
  924. err = json.Unmarshal(notice, &object)
  925. if err != nil {
  926. return "", nil, errors.Trace(err)
  927. }
  928. var data interface{}
  929. err = json.Unmarshal(object.Data, &data)
  930. if err != nil {
  931. return "", nil, errors.Trace(err)
  932. }
  933. dataValue, ok := data.(map[string]interface{})
  934. if !ok {
  935. return "", nil, errors.TraceNew("invalid data value")
  936. }
  937. return object.NoticeType, dataValue, nil
  938. }
  939. // NoticeReceiver consumes a notice input stream and invokes a callback function
  940. // for each discrete JSON notice object byte sequence.
  941. type NoticeReceiver struct {
  942. mutex sync.Mutex
  943. buffer []byte
  944. callback func([]byte)
  945. }
  946. // NewNoticeReceiver initializes a new NoticeReceiver
  947. func NewNoticeReceiver(callback func([]byte)) *NoticeReceiver {
  948. return &NoticeReceiver{callback: callback}
  949. }
  950. // Write implements io.Writer.
  951. func (receiver *NoticeReceiver) Write(p []byte) (n int, err error) {
  952. receiver.mutex.Lock()
  953. defer receiver.mutex.Unlock()
  954. receiver.buffer = append(receiver.buffer, p...)
  955. index := bytes.Index(receiver.buffer, []byte("\n"))
  956. if index == -1 {
  957. return len(p), nil
  958. }
  959. notice := receiver.buffer[:index]
  960. receiver.callback(notice)
  961. if index == len(receiver.buffer)-1 {
  962. receiver.buffer = receiver.buffer[0:0]
  963. } else {
  964. receiver.buffer = receiver.buffer[index+1:]
  965. }
  966. return len(p), nil
  967. }
  968. // NewNoticeConsoleRewriter consumes JSON-format notice input and parses each
  969. // notice and rewrites in a more human-readable format more suitable for
  970. // console output. The data payload field is left as JSON.
  971. func NewNoticeConsoleRewriter(writer io.Writer) *NoticeReceiver {
  972. return NewNoticeReceiver(func(notice []byte) {
  973. var object noticeObject
  974. _ = json.Unmarshal(notice, &object)
  975. fmt.Fprintf(
  976. writer,
  977. "%s %s %s\n",
  978. object.Timestamp,
  979. object.NoticeType,
  980. string(object.Data))
  981. })
  982. }
  983. // NoticeWriter implements io.Writer and emits the contents of Write() calls
  984. // as Notices. This is to transform logger messages, if they can be redirected
  985. // to an io.Writer, to notices.
  986. type NoticeWriter struct {
  987. noticeType string
  988. }
  989. // NewNoticeWriter initializes a new NoticeWriter
  990. func NewNoticeWriter(noticeType string) *NoticeWriter {
  991. return &NoticeWriter{noticeType: noticeType}
  992. }
  993. // Write implements io.Writer.
  994. func (writer *NoticeWriter) Write(p []byte) (n int, err error) {
  995. singletonNoticeLogger.outputNotice(
  996. writer.noticeType, noticeIsDiagnostic,
  997. "message", string(p))
  998. return len(p), nil
  999. }
  1000. // NoticeCommonLogger maps the common.Logger interface to the notice facility.
  1001. // This is used to make the notice facility available to other packages that
  1002. // don't import the "psiphon" package.
  1003. func NoticeCommonLogger() common.Logger {
  1004. return &commonLogger{}
  1005. }
  1006. type commonLogger struct {
  1007. }
  1008. func (logger *commonLogger) WithTrace() common.LogTrace {
  1009. return &commonLogTrace{
  1010. trace: stacktrace.GetParentFunctionName(),
  1011. }
  1012. }
  1013. func (logger *commonLogger) WithTraceFields(fields common.LogFields) common.LogTrace {
  1014. return &commonLogTrace{
  1015. trace: stacktrace.GetParentFunctionName(),
  1016. fields: fields,
  1017. }
  1018. }
  1019. func (logger *commonLogger) LogMetric(metric string, fields common.LogFields) {
  1020. singletonNoticeLogger.outputNotice(
  1021. metric, noticeIsDiagnostic,
  1022. listCommonFields(fields)...)
  1023. }
  1024. func listCommonFields(fields common.LogFields) []interface{} {
  1025. fieldList := make([]interface{}, 0)
  1026. for name, value := range fields {
  1027. fieldList = append(fieldList, name, value)
  1028. }
  1029. return fieldList
  1030. }
  1031. type commonLogTrace struct {
  1032. trace string
  1033. fields common.LogFields
  1034. }
  1035. func (log *commonLogTrace) outputNotice(
  1036. noticeType string, args ...interface{}) {
  1037. singletonNoticeLogger.outputNotice(
  1038. noticeType, noticeIsDiagnostic,
  1039. append(
  1040. []interface{}{
  1041. "message", fmt.Sprint(args...),
  1042. "trace", log.trace},
  1043. listCommonFields(log.fields)...)...)
  1044. }
  1045. func (log *commonLogTrace) Debug(args ...interface{}) {
  1046. // Ignored.
  1047. }
  1048. func (log *commonLogTrace) Info(args ...interface{}) {
  1049. log.outputNotice("Info", args...)
  1050. }
  1051. func (log *commonLogTrace) Warning(args ...interface{}) {
  1052. log.outputNotice("Alert", args...)
  1053. }
  1054. func (log *commonLogTrace) Error(args ...interface{}) {
  1055. log.outputNotice("Error", args...)
  1056. }