forked from pfoo/ifconfig.pm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
232 lines (202 loc) · 5.93 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
package main
import (
"fmt"
"net"
"net/http"
"net/http/fcgi"
"os"
"path"
"strconv"
"strings"
"time"
"github.com/brandfolder/gin-gorelic"
"github.com/coreos/go-systemd/activation"
"github.com/gin-gonic/gin"
)
// Logger is a simple log handler, out puts in the standard of apache access log common.
// See http://httpd.apache.org/docs/2.2/logs.html#accesslog
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
t := time.Now()
ip, err := net.ResolveTCPAddr("tcp", c.Request.RemoteAddr)
if err != nil {
c.Abort()
}
// before request
c.Next()
// after request
user := "-"
if c.Request.URL.User != nil {
user = c.Request.URL.User.Username()
}
latency := time.Since(t)
// This is the format of Apache Log Common, with an additional field of latency
fmt.Printf("%v - %v [%v] \"%v %v %v\" %v %v %v\n",
ip.IP, user, t.Format(time.RFC3339), c.Request.Method, c.Request.URL.Path,
c.Request.Proto, c.Writer.Status(), c.Request.ContentLength, latency)
}
}
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
func testRemoteTCPPort(address string) bool {
_, err := net.DialTimeout("tcp", address, 3*time.Second)
if err != nil {
return false
}
return true
}
func mainHandler(c *gin.Context) {
fields := strings.Split(c.Params.ByName("field"), ".")
ip, err := net.ResolveTCPAddr("tcp", c.Request.RemoteAddr)
if err != nil {
c.Abort()
}
//proxy handling stuff
// use CF-Connecting-IP header as ip if available (this means app is invoked behind a proxy)
cfIP := net.ParseIP(c.Request.Header.Get("CF-Connecting-IP"))
if cfIP != nil {
ip.IP = cfIP
}
// use CF-Connecting-PORT header as source port if available (this means app is invoked behind a proxy)
cfPORT := c.Request.Header.Get("CF-Connecting-PORT")
if cfPORTnum, err := strconv.Atoi(cfPORT); err == nil {
ip.Port = cfPORTnum
}
// Use CF-Connection header instead of HTTP Connection header if available (this means app is invoked behind a proxy)
ConnectionHeader := c.Request.Header.Get("Connection")
if cfCONN := c.Request.Header.Get("CF-Connection"); cfCONN != "" {
ConnectionHeader = cfCONN
}
if fields[0] == "porttest" {
if len(fields) >= 2 {
if port, err := strconv.Atoi(fields[1]); err == nil && port > 0 && port <= 65535 {
c.String(200, fmt.Sprintln(testRemoteTCPPort(ip.IP.String()+":"+fields[1])))
} else {
c.String(400, "Invalid Port Number")
}
} else {
c.String(400, "Need Port")
}
return
}
c.Set("ip", ip.IP.String())
c.Set("port", ip.Port)
c.Set("ua", c.Request.UserAgent())
c.Set("protocol", c.Request.Proto)
c.Set("lang", c.Request.Header.Get("Accept-Language"))
c.Set("encoding", c.Request.Header.Get("Accept-Encoding"))
c.Set("method", c.Request.Method)
c.Set("connection", ConnectionHeader)
c.Set("mime", c.Request.Header.Get("Accept"))
c.Set("charset", c.Request.Header.Get("Accept-Charset"))
c.Set("referer", c.Request.Header.Get("Referer"))
c.Set("via", c.Request.Header.Get("Via"))
c.Set("forwarded", c.Request.Header.Get("X-Forwarded-For"))
c.Set("country", c.Request.Header.Get("CF-IPCountry"))
r := strings.NewReplacer("0", "No", "1", "Yes")
c.Set("dnt", r.Replace(c.Request.Header.Get("DNT")))
c.Set("cache", c.Request.Header.Get("cache-control"))
ua := strings.Split(c.Request.UserAgent(), "/")
// Only lookup hostname if the results are going to need it.
if stringInSlice(fields[0], []string{"all", "host"}) || (fields[0] == "" && ua[0] != "curl" && ua[0] != "Wget" && ua[0] != "fetch") {
hostnames, err := net.LookupAddr(ip.IP.String())
if err != nil {
c.Set("host", "")
} else {
c.Set("host", hostnames[0])
}
}
wantsJSON := false
if len(fields) >= 2 && fields[1] == "json" {
wantsJSON = true
}
switch fields[0] {
case "":
//If the user is using curl, wget or fetch, then we should just return the IP, else we show the home page.
if ua[0] == "curl" || ua[0] == "Wget" || ua[0] == "fetch" {
c.String(200, fmt.Sprintln(ip.IP))
} else {
c.HTML(200, "index.html", c.Keys)
}
return
case "request":
c.JSON(200, c.Request)
return
case "all":
if wantsJSON {
c.JSON(200, c.Keys)
} else {
c.String(200, "%v", c.Keys)
}
return
}
fieldResult, exists := c.Get(fields[0])
if !exists {
c.String(404, "Not Found")
return
}
c.String(200, fmt.Sprintln(fieldResult))
}
// FileServer is a basic file serve handler, this is just here as an example.
// gin.Static() should be used instead
func FileServer(root string) gin.HandlerFunc {
return func(c *gin.Context) {
file := c.Params.ByName("file")
if !strings.HasPrefix(file, "/") {
file = "/" + file
}
http.ServeFile(c.Writer, c.Request, path.Join(root, path.Clean(file)))
}
}
func main() {
r := gin.New()
r.Use(gin.Recovery())
r.Use(Logger())
r.LoadHTMLGlob("templates/*")
if NEWRELIC_LICENSE_KEY := os.Getenv("NEWRELIC_LICENSE_KEY"); NEWRELIC_LICENSE_KEY != "" {
var NEWRELIC_APPLICATION_NAME string
if NEWRELIC_APPLICATION_NAME = os.Getenv("NEWRELIC_APPLICATION_NAME"); NEWRELIC_APPLICATION_NAME == "" {
NEWRELIC_APPLICATION_NAME = "ifconfig.io"
}
gorelic.InitNewrelicAgent(NEWRELIC_LICENSE_KEY, NEWRELIC_APPLICATION_NAME, true)
r.Use(gorelic.Handler)
}
r.GET("/:field", mainHandler)
r.GET("/", mainHandler)
// Create a listener for FCGI
fcgi_listen, err := net.Listen("tcp", "127.0.0.1:4000")
if err != nil {
panic(err)
}
errc := make(chan error)
go func(errc chan error) {
for err := range errc {
panic(err)
}
}(errc)
go func(errc chan error) {
errc <- fcgi.Serve(fcgi_listen, r)
}(errc)
// Listen on whatever systemd tells us to.
listeners, err := activation.Listeners()
if err != nil {
fmt.Printf("Could not get systemd listerns with err %q", err)
}
for _, listener := range listeners {
go func(errc chan error) {
errc <- http.Serve(listener, r)
}(errc)
}
port := os.Getenv("PORT")
host := os.Getenv("HOST")
if port == "" {
port = "8080"
}
errc <- r.Run(host + ":" + port)
}