notice.go 43 KB

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