notice.go 41 KB

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