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