forked from malfunkt/hyperfox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
232 lines (192 loc) · 5.58 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
// Copyright (c) 2012-2014 José Carlos Nieto, https://menteslibres.net/xiam
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package main
import (
"database/sql"
"flag"
"fmt"
"log"
"os"
"github.com/xiam/hyperfox/proxy"
"github.com/xiam/hyperfox/tools/capture"
"github.com/xiam/hyperfox/tools/logger"
"upper.io/db"
"upper.io/db/sqlite"
)
const version = "0.9"
const (
defaultAddress = `0.0.0.0`
defaultPort = uint(1080)
defaultSSLPort = uint(10443)
defaultCaptureCollection = `capture`
defaultDatabase = `hyperfox-%05d.db`
)
const collectionCreateSQL = `CREATE TABLE "` + defaultCaptureCollection + `" (
"id" INTEGER PRIMARY KEY,
"origin" VARCHAR(255),
"method" VARCHAR(10),
"status" INTEGER,
"content_type" VARCHAR(50),
"content_length" INTEGER,
"host" VARCHAR(255),
"url" TEXT,
"scheme" VARCHAR(10),
"path" TEXT,
"header" TEXT,
"body" BLOB,
"request_header" TEXT,
"request_body" BLOB,
"date_start" VARCHAR(20),
"date_end" VARCHAR(20),
"time_taken" INTEGER
)`
var (
flagDatabase = flag.String("d", "", "Path to database.")
flagAddress = flag.String("l", defaultAddress, "Bind address.")
flagPort = flag.Uint("p", defaultPort, "Port to bind to.")
flagSSLPort = flag.Uint("s", defaultSSLPort, "Port to bind to (SSL mode).")
flagSSLCertFile = flag.String("c", "", "Path to root CA certificate.")
flagSSLKeyFile = flag.String("k", "", "Path to root CA key.")
)
var (
enableDatabaseSave = false
)
var (
sess db.Database
col db.Collection
)
// dbsetup sets up the database.
func dbsetup() error {
var err error
var databaseName string
if *flagDatabase == "" {
// Let's find an unused database file.
for i := 0; ; i++ {
databaseName = fmt.Sprintf(defaultDatabase, i)
if _, err := os.Stat(databaseName); err != nil {
// File does not exists (yet).
// And that's OK.
break
}
}
} else {
// Use the provided database name.
databaseName = *flagDatabase
}
// Attempting to open database.
if sess, err = db.Open(sqlite.Adapter, sqlite.ConnectionURL{Database: databaseName}); err != nil {
log.Fatalf(ErrDatabaseConnection.Error(), err)
}
// Collection lookup.
col, err = sess.Collection(defaultCaptureCollection)
if err == nil {
// Collection exists! Nothing else to do.
log.Printf("Using database %s.", databaseName)
return nil
}
log.Printf("Initializing database %s...", databaseName)
if err != db.ErrCollectionDoesNotExist {
// This error is different to a missing collection error.
log.Fatalf(ErrDatabaseConnection.Error(), err)
}
// Collection does not exists, let's create it.
if drv, ok := sess.Driver().(*sql.DB); ok {
// Execute CREATE TABLE.
if _, err = drv.Exec(collectionCreateSQL); err != nil {
log.Fatalf(ErrDatabaseConnection.Error(), err)
}
// Try pulling collection again.
if col, err = sess.Collection(defaultCaptureCollection); err != nil {
log.Fatalf(ErrDatabaseConnection.Error(), err)
}
}
return nil
}
// Parses flags and initializes Hyperfox tool.
func main() {
var err error
var sslEnabled bool
// Banner.
log.Printf("Hyperfox v%s // https://hyperfox.org\n", version)
log.Printf("By José Carlos Nieto.\n\n")
// Parsing command line flags.
flag.Parse()
// Opening database.
if err = dbsetup(); err != nil {
log.Fatalf("db: %q", err)
}
defer sess.Close()
// Is SSL enabled?
if *flagSSLPort > 0 && *flagSSLCertFile != "" {
sslEnabled = true
}
// User requested SSL mode.
if sslEnabled {
if *flagSSLCertFile == "" {
flag.Usage()
log.Fatal(ErrMissingSSLCert)
}
if *flagSSLKeyFile == "" {
flag.Usage()
log.Fatal(ErrMissingSSLKey)
}
os.Setenv(proxy.EnvSSLCert, *flagSSLCertFile)
os.Setenv(proxy.EnvSSLKey, *flagSSLKeyFile)
}
// Creatig proxy.
p := proxy.NewProxy()
// Attaching logger.
p.AddLogger(logger.Stdout{})
// Attaching capture tool.
res := make(chan capture.Response, 256)
p.AddBodyWriteCloser(capture.New(res))
// Saving captured data with a goroutine.
go func() {
for {
select {
case r := <-res:
if _, err := col.Append(r); err != nil {
log.Printf(ErrDatabaseError.Error(), err)
}
}
}
}()
if err = startServices(); err != nil {
log.Fatal("startServices:", err)
}
fmt.Println("")
cerr := make(chan error)
// Starting proxy servers.
go func() {
if err := p.Start(fmt.Sprintf("%s:%d", *flagAddress, *flagPort)); err != nil {
cerr <- err
}
}()
if sslEnabled {
go func() {
if err := p.StartTLS(fmt.Sprintf("%s:%d", *flagAddress, *flagSSLPort)); err != nil {
cerr <- err
}
}()
}
err = <-cerr
log.Fatalf(ErrBindFailed.Error(), err)
}