forked from 9seconds/mtg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
257 lines (227 loc) · 6.29 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"io"
"math/rand"
"os"
"syscall"
"time"
"github.com/juju/errors"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
kingpin "gopkg.in/alecthomas/kingpin.v2"
"github.com/9seconds/mtg/config"
"github.com/9seconds/mtg/ntp"
"github.com/9seconds/mtg/proxy"
"github.com/9seconds/mtg/stats"
)
var version = "dev" // this has to be set by build ld flags
var (
app = kingpin.New("mtg", "Simple MTPROTO proxy.")
debug = app.Flag("debug",
"Run in debug mode.").
Short('d').
Envar("MTG_DEBUG").
Bool()
verbose = app.Flag("verbose",
"Run in verbose mode.").
Short('v').
Envar("MTG_VERBOSE").
Bool()
bindIP = app.Flag("bind-ip",
"Which IP to bind to.").
Short('b').
Envar("MTG_IP").
Default("127.0.0.1").
IP()
bindPort = app.Flag("bind-port",
"Which port to bind to.").
Short('p').
Envar("MTG_PORT").
Default("3128").
Uint16()
publicIPv4 = app.Flag("public-ipv4",
"Which IPv4 address is public.").
Short('4').
Envar("MTG_IPV4").
IP()
publicIPv4Port = app.Flag("public-ipv4-port",
"Which IPv4 port is public. Default is 'bind-port' value.").
Envar("MTG_IPV4_PORT").
Uint16()
publicIPv6 = app.Flag("public-ipv6",
"Which IPv6 address is public.").
Short('6').
Envar("MTG_IPV6").
IP()
publicIPv6Port = app.Flag("public-ipv6-port",
"Which IPv6 port is public. Default is 'bind-port' value.").
Envar("MTG_IPV6_PORT").
Uint16()
statsIP = app.Flag("stats-ip",
"Which IP bind stats server to.").
Short('t').
Envar("MTG_STATS_IP").
Default("127.0.0.1").
IP()
statsPort = app.Flag("stats-port",
"Which port bind stats to.").
Short('q').
Envar("MTG_STATS_PORT").
Default("3129").
Uint16()
statsdIP = app.Flag("statsd-ip",
"Which IP should we use for working with statsd.").
Envar("MTG_STATSD_IP").
String()
statsdPort = app.Flag("statsd-port",
"Which port should we use for working with statsd.").
Envar("MTG_STATSD_PORT").
Default("8125").
Uint16()
statsdNetwork = app.Flag("statsd-network",
"Which network is used to work with statsd. Only 'tcp' and 'udp' are supported.").
Envar("MTG_STATSD_NETWORK").
Default("udp").
String()
statsdPrefix = app.Flag("statsd-prefix",
"Which bucket prefix should we use for sending stats to statsd.").
Envar("MTG_STATSD_PREFIX").
Default("mtg").
String()
statsdTagsFormat = app.Flag("statsd-tags-format",
"Which tag format should we use to send stats metrics. Valid options are 'datadog' and 'influxdb'.").
Envar("MTG_STATSD_TAGS_FORMAT").
String()
statsdTags = app.Flag("statsd-tags",
"Tags to use for working with statsd (specified as 'key=value').").
Envar("MTG_STATSD_TAGS").
StringMap()
prometheusPrefix = app.Flag("prometheus-prefix",
"Which namespace to use to send stats to Prometheus.").
Envar("MTG_PROMETHEUS_PREFIX").
Default("mtg").
String()
writeBufferSize = app.Flag("write-buffer",
"Write buffer size in bytes. You can think about it as a buffer from client to Telegram.").
Short('w').
Envar("MTG_BUFFER_WRITE").
Default("65536").
Uint32()
readBufferSize = app.Flag("read-buffer",
"Read buffer size in bytes. You can think about it as a buffer from Telegram to client.").
Short('r').
Envar("MTG_BUFFER_READ").
Default("131072").
Uint32()
secureOnly = app.Flag("secure-only",
"Support clients with dd-secrets only.").
Short('s').
Envar("MTG_SECURE_ONLY").
Bool()
antiReplayMaxSize = app.Flag("anti-replay-max-size",
"Max size of antireplay cache in megabytes.").
Envar("MTG_ANTIREPLAY_MAXSIZE").
Default("128").
Int()
antiReplayEvictionTime = app.Flag("anti-replay-eviction-time",
"Eviction time period for obfuscated2 handshakes").
Envar("MTG_ANTIREPLAY_EVICTIONTIME").
Default("168h").
Duration()
secret = app.Arg("secret", "Secret of this proxy.").Required().HexBytes()
adtag = app.Arg("adtag", "ADTag of the proxy.").HexBytes()
)
func main() { // nolint: gocyclo
rand.Seed(time.Now().UTC().UnixNano())
app.Version(version)
app.HelpFlag.Short('h')
kingpin.MustParse(app.Parse(os.Args[1:]))
err := setRLimit()
if err != nil {
usage(err.Error())
}
conf, err := config.NewConfig(*debug, *verbose,
*writeBufferSize, *readBufferSize,
*bindIP, *publicIPv4, *publicIPv6, *statsIP,
*bindPort, *publicIPv4Port, *publicIPv6Port, *statsPort, *statsdPort,
*statsdIP, *statsdNetwork, *statsdPrefix, *statsdTagsFormat,
*statsdTags, *prometheusPrefix, *secureOnly,
*antiReplayMaxSize, *antiReplayEvictionTime,
*secret, *adtag,
)
if err != nil {
usage(err.Error())
}
atom := zap.NewAtomicLevel()
switch {
case conf.Debug:
atom.SetLevel(zapcore.DebugLevel)
case conf.Verbose:
atom.SetLevel(zapcore.InfoLevel)
default:
atom.SetLevel(zapcore.ErrorLevel)
}
encoderCfg := zap.NewProductionEncoderConfig()
logger := zap.New(zapcore.NewCore(
zapcore.NewJSONEncoder(encoderCfg),
zapcore.Lock(os.Stderr),
atom,
))
zap.ReplaceGlobals(logger)
defer logger.Sync() // nolint: errcheck
printURLs(conf.GetURLs())
zap.S().Debugw("Configuration", "config", conf)
if conf.UseMiddleProxy() {
zap.S().Infow("Use middle proxy connection to Telegram")
if diff, err := ntp.Fetch(); err != nil {
zap.S().Warnw("Could not fetch time data from NTP")
} else {
if diff >= time.Second {
usage(fmt.Sprintf("You choose to use middle proxy but your clock drift (%s) "+
"is bigger than 1 second. Please, sync your time", diff))
}
go ntp.AutoUpdate()
}
} else {
zap.S().Infow("Use direct connection to Telegram")
}
if err := stats.Init(conf); err != nil {
panic(err)
}
server, err := proxy.NewProxy(conf)
if err != nil {
panic(err)
}
if err := server.Serve(); err != nil {
zap.S().Fatalw("Server stopped", "error", err)
}
}
func setRLimit() (err error) {
rLimit := syscall.Rlimit{}
err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit)
if err != nil {
err = errors.Annotate(err, "Cannot get rlimit")
return
}
rLimit.Cur = rLimit.Max
err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit)
if err != nil {
err = errors.Annotate(err, "Cannot set rlimit")
}
return
}
func printURLs(data interface{}) {
encoder := json.NewEncoder(os.Stdout)
encoder.SetEscapeHTML(false)
encoder.SetIndent("", " ")
err := encoder.Encode(data)
if err != nil {
panic(err)
}
}
func usage(msg string) {
io.WriteString(os.Stderr, msg+"\n") // nolint: errcheck, gosec
os.Exit(1)
}