notice.go 40 KB

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