-
Notifications
You must be signed in to change notification settings - Fork 4
/
tracker.go
1584 lines (1482 loc) · 48.8 KB
/
tracker.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
/*===----------- tracker.go - tracking utility written in go -------------===
*
*
* This file is licensed under the Apache 2 License. See LICENSE for details.
*
* Copyright (c) 2018 Andrew Grosser. All Rights Reserved.
*
* `...
* yNMMh`
* dMMMh`
* dMMMh`
* dMMMh`
* dMMMd`
* dMMMm.
* dMMMm.
* dMMMm. /hdy.
* ohs+` yMMMd. yMMM-
* .mMMm. yMMMm. oMMM/
* :MMMd` sMMMN. oMMMo
* +MMMd` oMMMN. oMMMy
* sMMMd` /MMMN. oMMMh
* sMMMd` /MMMN- oMMMd
* oMMMd` :NMMM- oMMMd
* /MMMd` -NMMM- oMMMm
* :MMMd` .mMMM- oMMMm`
* -NMMm. `mMMM: oMMMm`
* .mMMm. dMMM/ +MMMm`
* `hMMm. hMMM/ /MMMm`
* yMMm. yMMM/ /MMMm`
* oMMm. oMMMo -MMMN.
* +MMm. +MMMo .MMMN-
* +MMm. /MMMo .NMMN-
* ` +MMm. -MMMs .mMMN: `.-.
* /hys:` +MMN- -NMMy `hMMN: .yNNy
* :NMMMy` sMMM/ .NMMy yMMM+-dMMMo
* +NMMMh-hMMMo .mMMy +MMMmNMMMh`
* /dMMMNNMMMs .dMMd -MMMMMNm+`
* .+mMMMMMN: .mMMd `NMNmh/`
* `/yhhy: `dMMd /+:`
* `hMMm`
* `hMMm.
* .mMMm:
* :MMMd-
* -NMMh.
* ./:.
*
*===----------------------------------------------------------------------===
*/
package main
import (
"crypto/tls"
"database/sql"
"encoding/csv"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/ClickHouse/clickhouse-go/v2"
"github.com/gocql/gocql"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/nats-io/nats.go"
"github.com/pierrec/lz4/v4"
"golang.org/x/crypto/acme/autocert"
)
var upgrader = websocket.Upgrader{
// Allow all connections for simplicity
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// //////////////////////////////////////
// Get the system setup from the config.json file:
// //////////////////////////////////////
type session interface {
connect() error
close() error
prune() error
write(w *WriteArgs) error
listen() error
serve(w *http.ResponseWriter, r *http.Request, s *ServiceArgs) error
auth(s *ServiceArgs) error
}
type KeyValue struct {
Key string
Value interface{}
}
type Field struct {
Type string
Id string
Default string
DestParamHash string
}
type Query struct {
Statement string
QueryType string
Fields []Field
}
type Filter struct {
Type string
Alias string
Id string
Queries []Query
}
type Prune struct {
Table string
TTL int64
PageSize int
CFlagsIgnore []int64
ClearAll bool
ClearParams bool
ClearNumericParams bool
Fields []Field
}
type WriteArgs struct {
WriteType int
Values *map[string]interface{}
IsServer bool
SaveCookie bool
IP string
Browser string
Language string
URI string
Host string
EventID uuid.UUID
CallingService *Service
}
type ServiceArgs struct {
ServiceType int
Values *map[string]string
IsServer bool
IP string
Browser string
Language string
URI string
EventID uuid.UUID
}
type TableType uint64
const (
// Primary Event Tables
TABLE_EVENTS TableType = 1 << iota // 1 << 0 = 1
TABLE_EVENTS_RECENT // 1 << 1 = 2
// Session/Visitor Tables
TABLE_VISITORS // 1 << 2 = 4
TABLE_VISITORS_LATEST // 1 << 3 = 8
TABLE_SESSIONS // 1 << 4 = 16
// Tracking/Analytics Tables
TABLE_IPS // 1 << 5 = 32
TABLE_ROUTED // 1 << 6 = 64
TABLE_HITS // 1 << 7 = 128
TABLE_DAILIES // 1 << 8 = 256
TABLE_OUTCOMES // 1 << 9 = 512
TABLE_REFERRERS // 1 << 10 = 1024
TABLE_REFERRALS // 1 << 11 = 2048
TABLE_REFERRED // 1 << 12 = 4096
TABLE_HOSTS // 1 << 13 = 8192
TABLE_BROWSERS // 1 << 14 = 16384
TABLE_NODES // 1 << 15 = 32768
TABLE_LOCATIONS // 1 << 16 = 65536
TABLE_ALIASES // 1 << 17 = 131072
TABLE_USERS // 1 << 18 = 262144
TABLE_USERNAMES // 1 << 19 = 524288
TABLE_EMAILS // 1 << 20 = 1048576
TABLE_CELLS // 1 << 21 = 2097152
TABLE_REQS // 1 << 22 = 4194304
// LTV Related Tables
TABLE_LTV // 1 << 23 = 8388608
TABLE_LTVU // 1 << 24 = 16777216
TABLE_LTVV // 1 << 25 = 33554432
// Other Tables
TABLE_AGREEMENTS // 1 << 26 = 67108864
TABLE_AGREED // 1 << 27 = 134217728
TABLE_JURISDICTIONS // 1 << 28 = 268435456
TABLE_REDIRECTS // 1 << 29 = 536870912
TABLE_REDIRECT_HISTORY // 1 << 30 = 1073741824
TABLE_COUNTERS // 1 << 31 = 2147483648
TABLE_UPDATES // 1 << 32 = 4294967296
TABLE_LOGS // 1 << 33 = 8589934592
// Common Table Groups
TABLE_ALL_EVENTS = TABLE_EVENTS | TABLE_EVENTS_RECENT
TABLE_ALL_VISITORS = TABLE_VISITORS | TABLE_VISITORS_LATEST | TABLE_SESSIONS
TABLE_ALL_LTV = TABLE_LTV | TABLE_LTVU | TABLE_LTVV
TABLE_ALL_REDIRECTS = TABLE_REDIRECTS | TABLE_REDIRECT_HISTORY
TABLE_ALL = ^uint64(0)
)
// Helper methods for bitwise operations
func (t TableType) Has(table TableType) bool {
return t&table != 0
}
func (t TableType) Add(table TableType) TableType {
return t | table
}
func (t TableType) Remove(table TableType) TableType {
return t &^ table
}
// String returns the string representation of the table name
func (t TableType) String() string {
switch t {
// Primary Event Tables
case TABLE_EVENTS:
return "events"
case TABLE_EVENTS_RECENT:
return "events_recent"
// Session/Visitor Tables
case TABLE_VISITORS:
return "visitors"
case TABLE_VISITORS_LATEST:
return "visitors_latest"
case TABLE_SESSIONS:
return "sessions"
// Tracking/Analytics Tables
case TABLE_IPS:
return "ips"
case TABLE_ROUTED:
return "routed"
case TABLE_HITS:
return "hits"
case TABLE_DAILIES:
return "dailies"
case TABLE_OUTCOMES:
return "outcomes"
case TABLE_REFERRERS:
return "referrers"
case TABLE_REFERRALS:
return "referrals"
case TABLE_REFERRED:
return "referred"
case TABLE_HOSTS:
return "hosts"
case TABLE_BROWSERS:
return "browsers"
case TABLE_NODES:
return "nodes"
case TABLE_LOCATIONS:
return "locations"
case TABLE_ALIASES:
return "aliases"
case TABLE_USERS:
return "users"
case TABLE_USERNAMES:
return "usernames"
case TABLE_EMAILS:
return "emails"
case TABLE_CELLS:
return "cells"
case TABLE_REQS:
return "reqs"
// LTV Related Tables
case TABLE_LTV:
return "ltv"
case TABLE_LTVU:
return "ltvu"
case TABLE_LTVV:
return "ltvv"
// Other Tables
case TABLE_AGREEMENTS:
return "agreements"
case TABLE_AGREED:
return "agreed"
case TABLE_JURISDICTIONS:
return "jurisdictions"
case TABLE_REDIRECTS:
return "redirects"
case TABLE_REDIRECT_HISTORY:
return "redirect_history"
case TABLE_COUNTERS:
return "counters"
case TABLE_UPDATES:
return "updates"
case TABLE_LOGS:
return "logs"
default:
return "unknown"
}
}
type Service struct {
Service string
Hosts []string
CACert string
Cert string
Key string
Secure bool
Critical bool
Context string
Filter []Filter
Prune []Prune
Format string
MessageLimit int
ByteLimit int
Timeout time.Duration
Connections int
Retries int
AttemptAll bool
Consumer bool
Ephemeral bool
Note string
Session session
Skip bool
ProxyRealtimeStorageService *Service
ProxyRealtimeStorageServiceName string
ProxyRealtimeStorageServiceTables TableType
}
type ClickhouseService struct { //Implements 'session'
Configuration *Service
Session *clickhouse.Conn
AppConfig *Configuration
}
type DuckService struct { //Implements 'session'
Configuration *Service
Session *sql.DB
AppConfig *Configuration
HealthCheckTicker *time.Ticker
HealthCheckDone chan bool
S3Client *s3.S3
}
type CassandraService struct { //Implements 'session'
Configuration *Service
Session *gocql.Session
AppConfig *Configuration
}
type NatsService struct { //Implements 'session'
Configuration *Service
nc *nats.Conn
ec *nats.EncodedConn
AppConfig *Configuration
}
type FacebookService struct { //Implements 'session'
Configuration *Service
AppConfig *Configuration
}
type GeoIP struct {
IPStart string `json:"ips"`
IPEnd string `json:"ipe"`
CountryISO2 string `json:"iso2"`
Country string `json:"country"`
Region string `json:"region"`
City string `json:"city"`
Latitude float64 `json:"lat"`
Longitude float64 `json:"lon"`
Zip string `json:"zip"`
Timezone string `json:"tz"`
}
type Configuration struct {
ConfigFile string
Domains []string //Domains in Trust, LetsEncrypt domains
StaticDirectory string //Static FS Directory (./public/)
TempDirectory string
UseGeoIP bool
UseRegionDescriptions bool
UseRemoveIP bool
GeoIPVersion int
IPv4GeoIPZip string
IPv6GeoIPZip string
IPv4GeoIPCSVDest string
IPv6GeoIPCSVDest string
UseLocalTLS bool
IgnoreInsecureTLS bool
TLSCert string
TLSKey string
Notify []Service
Consume []Service
API Service
PrefixPrivateHash string
ProxyUrl string
ProxyUrlFilter string
IgnoreProxyOptions bool
ProxyForceJson bool
ProxyPort string
ProxyPortTLS string
ProxyExceptHTTP string
ProxyPortRedirect string
ProxyDailyLimit uint64
ProxyDailyLimitChecker string //Service, Ex. casssandra
ProxyDailyLimitCheck func(string) uint64
SchemaVersion int
ApiVersion int
CFlagsMarketing int64
CFlagsIgnore bool
Debug bool
UrlFilter string
UrlFilterMatchGroup int
AllowOrigin string
IsUrlFiltered bool
MaximumConnections int
ReadTimeoutSeconds int
ReadHeaderTimeoutSeconds int
WriteTimeoutSeconds int
IdleTimeoutSeconds int
MaxHeaderBytes int
DefaultRedirect string
IgnoreQueryParamsKey string
AccountHashMixer string
PruneLogsTTL int
PruneLogsOnly bool
PruneLogsSkip bool
PruneLogsPageSize int
PruneUpdateConfig bool
PruneLimit int
PruneSkipToTimestamp int64
S3Bucket string
S3Prefix string
S3Region string
S3AccessKeyID string
S3SecretAccessKey string
HealthCheckInterval int
NodeId string
InactivityTimeoutSeconds int
MaxShardSizeBytes int64
}
// ////////////////////////////////////// Constants
const (
PONG string = "pong"
API_LIMIT_REACHED string = "API Limit Reached"
SERVICE_TYPE_CLICKHOUSE string = "clickhouse"
SERVICE_TYPE_NATS string = "nats"
SERVICE_TYPE_FACEBOOK string = "facebook"
SERVICE_TYPE_DUCKDB string = "duckdb"
SERVICE_TYPE_CASSANDRA string = "cassandra"
FB_PIXEL string = "FB_PIXEL"
FB_TOKEN string = "FB_TOKEN"
NATS_QUEUE_GROUP = "tracker"
IDX_PREFIX_IPV4 = "gip4::"
IDX_PREFIX_IPV6 = "gip6::"
)
const (
WRITE_LOG = 1 << iota
WRITE_UPDATE = 1 << iota
WRITE_COUNT = 1 << iota
WRITE_EVENT = 1 << iota
WRITE_LTV = 1 << iota
WRITE_ALL = ^uint64(0)
WRITE_DESC_LOG = "log"
WRITE_DESC_UPDATE = "update"
WRITE_DESC_COUNT = "count"
WRITE_DESC_EVENT = "event"
)
const (
SVC_GET_REDIRECTS = 1 << iota
SVC_POST_REDIRECT = 1 << iota
SVC_GET_REDIRECT = 1 << iota
SVC_GET_AGREE = 1 << iota
SVC_POST_AGREE = 1 << iota
SVC_GET_JURISDICTIONS = 1 << iota
SVC_GET_GEOIP = 1 << iota
SVC_DESC_GET_REDIRECTS = "getRedirects"
SVC_DESC_POST_REDIRECT = "postRedirect"
SVC_DESC_GET_REDIRECT = "getRedirect"
SVC_DESC_GET_AGREE = "getAgreememts"
SVC_DESC_POST_AGREE = "postAgreements"
SVC_DESC_GET_JURISDICTIONS = "getJurisdictions"
)
var (
// Quote Ident replacer.
regexQiReplacer = strings.NewReplacer("\n", `\n`, `\`, `\\`, `"`, `\"`)
regexCount = regexp.MustCompile(`\.count\.(.*)`)
regexUpdate = regexp.MustCompile(`\.update\.(.*)`)
regexFilterUrl = regexp.MustCompile(`(.*)`)
regexInternalURI = regexp.MustCompile(`.*(/tr/|/img/|/pub/|/str/|/rdr/)v[0-9]+.*`) //TODO: MUST FILTER INTERNAL ROUTES, UPDATE IF ADDING A NEW ROUTE, PROXY OK!!!
regexUtmPrefix = regexp.MustCompile(`utm_`)
)
// ////////////////////////////////////// Transparent GIF
var TRACKING_GIF = []byte{0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x1, 0x0, 0x1, 0x0, 0x80, 0x0, 0x0, 0xff, 0xff, 0xff, 0x0, 0x0, 0x0, 0x2c, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x1, 0x0, 0x0, 0x2, 0x2, 0x44, 0x1, 0x0, 0x3b}
var kv = (*KV)(nil)
// //////////////////////////////////////
// Start here
// //////////////////////////////////////
func main() {
fmt.Println("\n\n//////////////////////////////////////////////////////////////")
fmt.Println("Tracker.")
fmt.Println("Software to track growth and visitor usage")
fmt.Println("https://github.com/sfproductlabs/tracker")
fmt.Println("(c) Copyright 2018-2021 SF Product Labs LLC.")
fmt.Println("Use of this software is subject to the LICENSE agreement.")
fmt.Println("//////////////////////////////////////////////////////////////\n\n")
//////////////////////////////////////// LOAD CONFIG
fmt.Println("Starting services...")
configFile := "config.json"
var fbPixelFlag = flag.String("fb-pixel", "", "provide facebook pixel")
var fbTokenFlag = flag.String("fb-token", "", "provide facebook token")
var prune = flag.Bool("prune", false, "prune items")
var logsOnly = flag.Bool("logs-only", false, "clear out log only")
flag.Parse()
if len(flag.Args()) > 0 {
configFile = flag.Args()[0]
}
fmt.Println("Configuration file: ", configFile)
file, _ := os.Open(configFile)
defer file.Close()
decoder := json.NewDecoder(file)
configuration := Configuration{}
err := decoder.Decode(&configuration)
if err != nil {
fmt.Println("error:", err)
}
configuration.ConfigFile = configFile
configuration.NodeId = uuid.New().String()
//////////////////////////////////////// OVERRIDE FACEBOOK VARIABLES
var fbPixel = os.Getenv(FB_PIXEL)
var fbToken = os.Getenv(FB_TOKEN)
if fbPixel == "" {
fbPixel = *fbPixelFlag
}
if fbToken == "" {
fbToken = *fbTokenFlag
}
if fbPixel != "" || fbToken != "" {
var fbNotify = &Service{}
var fbFound = false
for idx := range configuration.Notify {
s := &configuration.Notify[idx]
if s.Service == SERVICE_TYPE_FACEBOOK {
fbNotify = s
fbFound = true
}
}
if fbPixel != "" {
fbNotify.Context = fbPixel
}
if fbToken != "" {
fbNotify.Key = fbToken
}
fbNotify.Service = SERVICE_TYPE_FACEBOOK
if !fbFound {
fbNotify.AttemptAll = false
configuration.Notify = append(configuration.Notify, *fbNotify)
}
}
//////////////////////////////////////// SETUP CACHE
cache := cacheDir()
if cache == "" {
log.Fatal("Bad Cache.")
}
//////////////////////////////////////// Prime rand
//Setup rand
rand.Seed(time.Now().UTC().UnixNano())
////////////////////////////////////////SETUP FILTER
if configuration.UrlFilter != "" {
fmt.Println("Setting up URL prefix filter...")
configuration.IsUrlFiltered = true
regexFilterUrl, _ = regexp.Compile(configuration.UrlFilter)
}
////////////////////////////////////////SETUP ORIGIN
if configuration.AllowOrigin == "" {
configuration.AllowOrigin = "*"
}
if configuration.MaxShardSizeBytes == 0 {
configuration.MaxShardSizeBytes = 100 * 1024 * 1024 //100MB
}
//////////////////////////////////////// SETUP CONFIG VARIABLES
fmt.Println("Trusted domains: ", configuration.Domains)
apiVersion := "v" + strconv.Itoa(configuration.ApiVersion)
//LetsEncrypt needs 443 & 80, So only override if possible
proxyPort := ":http"
if configuration.UseLocalTLS && configuration.ProxyPort != "" {
proxyPort = configuration.ProxyPort
}
proxyPortTLS := ":https"
if configuration.UseLocalTLS && configuration.ProxyPort != "" {
proxyPortTLS = configuration.ProxyPortTLS
}
if !configuration.UseLocalTLS && (configuration.ProxyPort != "" || configuration.ProxyPortTLS != "") {
log.Fatalln("[CRITICAL] Can not use non-standard ports with LetsEncyrpt")
}
// allow redirect target port to be different than listening port (443 vs. 8443)
proxyPortRedirect := proxyPortTLS
if configuration.ProxyPortRedirect != "" {
proxyPortRedirect = configuration.ProxyPortRedirect
}
//////////////////////////////////////// LOAD NOTIFIERS
notification_services := make(map[string]*Service)
for idx := range configuration.Notify {
s := &configuration.Notify[idx]
notification_services[s.Service] = s
switch s.Service {
case SERVICE_TYPE_CLICKHOUSE:
fmt.Printf("Notify #%d: Connecting to ClickHouse: %s\n", idx, s.Hosts)
clickhouse := ClickhouseService{
Configuration: s,
AppConfig: &configuration,
}
err = clickhouse.connect()
if err != nil || s.Session == nil {
if s.Critical {
log.Fatalf("[CRITICAL] Notify #%d. Could not connect to ClickHouse. %s\n", idx, err)
} else {
fmt.Printf("[ERROR] Notify #%d. Could not connect to ClickHouse. %s\n", idx, err)
continue
}
}
//Now attach the one and only API service, replace if multiple
if !s.Skip {
configuration.API = *s
}
case SERVICE_TYPE_DUCKDB:
fmt.Printf("Notify #%d: Connecting to DuckDB: %s\n", idx, s.Hosts)
duck := DuckService{
Configuration: s,
AppConfig: &configuration,
}
err = duck.connect()
if err != nil || s.Session == nil {
if s.Critical {
log.Fatalf("[CRITICAL] Notify #%d. Could not connect to duck. %s\n", idx, err)
} else {
fmt.Printf("[ERROR] Notify #%d. Could not connect to duck. %s\n", idx, err)
continue
}
}
//Now attach the one and only API service, replace if multiple
if !s.Skip {
configuration.API = *s
}
case SERVICE_TYPE_CASSANDRA:
fmt.Printf("Notify #%d: Connecting to Cassandra Cluster: %s\n", idx, s.Hosts)
cassandra := CassandraService{
Configuration: s,
AppConfig: &configuration,
}
err = cassandra.connect()
if err != nil || s.Session == nil {
if s.Critical {
log.Fatalf("[CRITICAL] Notify #%d. Could not connect to Cassandra Cluster. %s\n", idx, err)
} else {
fmt.Printf("[ERROR] Notify #%d. Could not connect to Cassandra Cluster. %s\n", idx, err)
continue
}
}
var seq int
if err := cassandra.Session.Query(`SELECT seq FROM sequences where name='DB_VER' LIMIT 1`).Consistency(gocql.One).Scan(&seq); err != nil || seq != configuration.SchemaVersion {
log.Fatalln("[CRITICAL] Cassandra Bad DB_VER", err)
} else {
fmt.Printf("Notify #%d: Connected to Cassandra: DB_VER %d\n", idx, seq)
}
//Now attach the one and only API service, replace if multiple
if !s.Skip {
configuration.API = *s
}
case SERVICE_TYPE_NATS:
//TODO:
fmt.Printf("[ERROR] Notify #%d: NATS notifier not implemented\n", idx)
case SERVICE_TYPE_FACEBOOK:
facebook := FacebookService{
Configuration: s,
AppConfig: &configuration,
}
err = facebook.connect()
if s.Critical && (s.Context == "" || s.Key == "" || err != nil) {
log.Fatalf("[CRITICAL] Notify #%d. Could not setup connection to Facebook CAPI.\n", idx)
}
if !s.Skip {
configuration.API = *s
}
fmt.Printf("Notify #%d: Facebook CAPI configured for events\n", idx)
default:
fmt.Printf("[ERROR] %s #%d Notifier not implemented\n", s.Service, idx)
}
}
//////////////////////////////////////// SETUP NOTIFICATION PROXIES
for _, s := range notification_services {
if s.ProxyRealtimeStorageServiceName != "" {
s.ProxyRealtimeStorageService = notification_services[s.ProxyRealtimeStorageServiceName]
}
}
//////////////////////////////////////// LETS JUST PRUNE AND QUIT?
if *prune {
for idx := range configuration.Notify {
s := &configuration.Notify[idx]
if s.Session != nil {
switch s.Service {
case SERVICE_TYPE_CASSANDRA:
configuration.PruneLogsOnly = *logsOnly || configuration.PruneLogsOnly
err := s.Session.prune()
if err != nil {
fmt.Println("\nLast prune error...\n", err)
}
default:
fmt.Println("[ERROR]")
}
}
}
os.Exit(0)
return
} else {
//////////////////////////////////////// LOAD CONSUMERS
for idx := range configuration.Consume {
s := &configuration.Consume[idx]
switch s.Service {
case SERVICE_TYPE_CASSANDRA:
fmt.Printf("[ERROR] Consume #%d: Cassandra consumer not implemented\n", idx)
case SERVICE_TYPE_DUCKDB:
fmt.Printf("[ERROR] Consume #%d: DuckDB consumer not implemented\n", idx)
case SERVICE_TYPE_CLICKHOUSE:
fmt.Printf("[ERROR] Consume #%d: ClickHouse consumer not implemented\n", idx)
case SERVICE_TYPE_NATS:
fmt.Printf("Consume #%d: Connecting to NATS Cluster: %s\n", idx, s.Hosts)
gonats := NatsService{
Configuration: s,
AppConfig: &configuration,
}
err = gonats.connect()
if err != nil || s.Session == nil {
if s.Critical {
log.Fatalf("[CRITICAL] Notify #%d. Could not connect to NATS Cluster. %s\n", idx, err)
} else {
fmt.Printf("[ERROR] Notify #%d. Could not connect to NATS Cluster. %s\n", idx, err)
continue
}
} else {
fmt.Printf("Consume #%d: Connected to NATS.\n", idx)
}
s.Session.listen()
case SERVICE_TYPE_FACEBOOK:
fmt.Printf("[ERROR] Consume #%d: Facebook consumer not implemented\n", idx)
default:
fmt.Printf("[ERROR] %s #%d Consumer not implemented\n", s.Service, idx)
}
}
}
//////////////////////////////////////// SSL CERT MANAGER
certManager := autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(configuration.Domains...),
Cache: autocert.DirCache(cache),
}
server := &http.Server{ // HTTP REDIR SSL RENEW
Addr: proxyPortTLS,
ReadTimeout: time.Duration(configuration.ReadTimeoutSeconds) * time.Second,
ReadHeaderTimeout: time.Duration(configuration.ReadHeaderTimeoutSeconds) * time.Second,
WriteTimeout: time.Duration(configuration.WriteTimeoutSeconds) * time.Second,
IdleTimeout: time.Duration(configuration.IdleTimeoutSeconds) * time.Second,
MaxHeaderBytes: configuration.MaxHeaderBytes, //1 << 20 // 1 MB
TLSConfig: &tls.Config{ // SEC PARAMS
GetCertificate: certManager.GetCertificate,
PreferServerCipherSuites: true,
InsecureSkipVerify: configuration.IgnoreInsecureTLS,
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, // Required by Go (and HTTP/2 RFC), even if you only present ECDSA certs
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
},
//MinVersion: tls.VersionTLS12,
//CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
},
}
//////////////////////////////////////// MAX CHANNELS
connc := make(chan struct{}, configuration.MaximumConnections)
for i := 0; i < configuration.MaximumConnections; i++ {
connc <- struct{}{}
}
//////////////////////////////////////// WEBSOCKET
http.HandleFunc("/tr/"+apiVersion+"/ws", func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println("Error upgrading to WebSocket:", err)
return
}
defer conn.Close()
fmt.Println("Client connected!")
wargs := WriteArgs{
WriteType: WRITE_EVENT,
IP: getIP(r),
Browser: r.Header.Get("user-agent"),
Language: r.Header.Get("accept-language"),
URI: r.RequestURI,
Host: getHost(r),
IsServer: false,
}
for {
// Read message
messageType, msg, err := conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
fmt.Printf("WebSocket error: %v\n", err)
}
break
}
var data map[string]interface{}
// Handle different message types
switch messageType {
case websocket.TextMessage:
// Handle uncompressed JSON
if err := json.Unmarshal(msg, &data); err != nil {
fmt.Printf("Error parsing JSON: %v\n", err)
continue
}
case websocket.BinaryMessage:
// Decompress LZ4 data
dst := make([]byte, len(msg)*3)
decompressed, err := lz4.UncompressBlock(msg, dst)
if err != nil {
fmt.Printf("Error decompressing message: %v\n", err)
continue
}
// Parse JSON
if err := json.Unmarshal(dst[:decompressed], &data); err != nil {
fmt.Printf("Error parsing JSON: %v\n", err)
continue
}
}
wargs.EventID = uuid.Must(uuid.NewUUID())
wargs.Values = &data
trackWithArgs(&configuration, &w, r, &wargs)
}
})
//////////////////////////////////////// REDIRECT URL & SHORTENER
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
select {
case <-connc:
sargs := ServiceArgs{
ServiceType: SVC_GET_REDIRECT,
}
if err = serveWithArgs(&configuration, &w, r, &sargs); err != nil {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(err.Error()))
} else {
values := make(map[string]interface{})
values["etyp"] = "redirect"
values["ename"] = "short_rdr"
values["last"] = r.RequestURI
wargs := WriteArgs{
WriteType: WRITE_EVENT,
IP: getIP(r),
Browser: r.Header.Get("user-agent"),
Language: r.Header.Get("accept-language"),
EventID: uuid.Must(uuid.NewUUID()),
URI: r.RequestURI,
Host: getHost(r),
IsServer: false,
Values: &values,
}
trackWithArgs(&configuration, &w, r, &wargs)
}
connc <- struct{}{}
default:
w.Header().Set("Retry-After", "1")
http.Error(w, "Maximum clients reached on this node.", http.StatusServiceUnavailable)
}
})
//////////////////////////////////////// PROXY API ROUTES
if configuration.ProxyUrl != "" {
fmt.Println("Proxying to:", configuration.ProxyUrl)
origin, _ := url.Parse(configuration.ProxyUrl)
director := func(req *http.Request) {
req.Header.Add("X-Forwarded-Host", req.Host)
req.Header.Add("X-Origin-Host", origin.Host)
if configuration.ProxyForceJson {
req.Header.Set("content-type", "application/json")
}
req.URL.Scheme = "http"
req.URL.Host = origin.Host
}
proxy := &httputil.ReverseProxy{Director: director}
proxyFilter, _ := regexp.Compile(configuration.ProxyUrlFilter)
http.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
if !configuration.IgnoreProxyOptions && r.Method == http.MethodOptions {
//Lets just allow requests to this endpoint
w.Header().Set("access-control-allow-origin", configuration.AllowOrigin)
w.Header().Set("access-control-allow-credentials", "true")
w.Header().Set("access-control-allow-headers", "Authorization,Accept,X-CSRFToken,User")
w.Header().Set("access-control-allow-methods", "GET,POST,HEAD,PUT,DELETE")
w.Header().Set("access-control-max-age", "1728000")
w.WriteHeader(http.StatusOK)
return
}
//TODO: Check certificate in cookie
select {
case <-connc:
//Check API Limit
if err := check(&configuration, r); err != nil {
w.WriteHeader(http.StatusTooManyRequests)
w.Write([]byte(API_LIMIT_REACHED))
return
}
//Proxy
w.Header().Set("Strict-Transport-Security", "max-age=15768000 ; includeSubDomains")
w.Header().Set("access-control-allow-origin", configuration.AllowOrigin)
proxy.ServeHTTP(w, r)
//Track
if configuration.ProxyUrlFilter != "" && !proxyFilter.MatchString(r.URL.Path) {
track(&configuration, &w, r)
}
connc <- struct{}{}
default:
w.Header().Set("Retry-After", "1")
http.Error(w, "Maximum clients reached on this node.", http.StatusServiceUnavailable)
}
})
}
//////////////////////////////////////// STATUS TEST ROUTE
http.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) {
json, _ := json.Marshal([2]KeyValue{KeyValue{Key: "client", Value: getIP(r)}, KeyValue{Key: "conns", Value: configuration.MaximumConnections - len(connc)}})
w.WriteHeader(http.StatusOK)
w.Header().Set("access-control-allow-origin", configuration.AllowOrigin)
w.Header().Set("Content-Type", "application/json")
w.Write(json)
})
//////////////////////////////////////// PING PONG TEST ROUTE
http.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("access-control-allow-origin", configuration.AllowOrigin)
w.Write([]byte(PONG))
})
//////////////////////////////////////// CLEAR ROUTE
http.HandleFunc("/clear", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("access-control-allow-origin", configuration.AllowOrigin)
w.Header().Set("clear-site-data", "\"*\"")
w.Write([]byte("OK"))
})