notice.go 42 KB

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