forked from alash3al/httpsify
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhttpsify.go
More file actions
206 lines (177 loc) · 5.48 KB
/
httpsify.go
File metadata and controls
206 lines (177 loc) · 5.48 KB
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
// httpsify is a transparent blazing fast https offloader with auto certificates renewal .
// this software is published under MIT License .
// by Mohammed Al ashaal <alash3al.xyz> with the help of those opensource libraries [github.com/xenolf/lego, github.com/dkumor/acmewrapper] .
package main
import (
"crypto/tls"
"flag"
"github.com/dkumor/acmewrapper"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/scottjg/go-nat"
)
// --------------
const version = "httpsify/holepuncher/v1"
var (
port = flag.String("port", "4443", "the port that will serve the https requests")
ddns = flag.String("ddns", "", "specify provider (e.g. namecheap or iwantmyname) or update url")
cert = flag.String("cert", "./cert.pem", "the cert.pem save-path")
key = flag.String("key", "./key.pem", "the key.pem save-path")
backend = flag.String("backend", "http://127.0.0.1:80", "the backend http server that will serve the terminated requests")
info = flag.String("info", "yes", "whether to send information about httpsify or not ^_^")
skipnatfwd = flag.Bool("skipnatfwd", false, "don't automatically setup a port forwarding rule on the upstream NAT router")
)
// --------------
var domain = ""
func init() {
flag.Parse()
args := flag.Args()
if len(args) < 1 {
log.Fatalf("need to specify a domain name")
}
domain = args[0]
}
// --------------
func main() {
portNum, err := strconv.Atoi(*port)
if err != nil {
log.Fatalf("bogus port: %s", err)
}
backendUrl, err := url.Parse(*backend)
if err != nil {
log.Fatalf("bogus backend url: %s", err)
}
if !*skipnatfwd {
gw, err := nat.DiscoverGateway()
if err != nil {
log.Fatalf("error: %s", err)
}
gw.DeletePortMapping("tcp", portNum, 443)
err = gw.AddPortMapping("tcp", portNum, 443, "https", 60*time.Second)
if err != nil {
log.Fatalf("error: %s", err)
}
// unmap the port if you ctrl-C or if we finish running main().
// in other situations, we may leak the mapping, but it will expire
// after a minute, so it could be worse.
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for _ = range c {
gw.DeletePortMapping("tcp", portNum, 443)
os.Exit(1)
}
}()
go func() {
for {
time.Sleep(30 * time.Second)
err = gw.AddPortMapping("tcp", portNum, 443, "https", 60*time.Second)
if err != nil {
log.Fatalf("error: %s", err)
}
}
}()
}
if *ddns != "" {
updateUrl := ""
dnsUsername := os.Getenv("DNS_USERNAME")
dnsPassword := os.Getenv("DNS_PASSWORD")
var req *http.Request
switch *ddns {
case "namecheap":
if dnsPassword == "" {
log.Fatalf("Need to define DNS_PASSWORD in your environment")
}
domainLevels := strings.Split(domain, ".")
host := "@"
sld := domain
if len(domainLevels) > 2 {
host = strings.Join(domainLevels[0:(len(domainLevels)-2)], ".")
sld = strings.Join(domainLevels[(len(domainLevels)-2):len(domainLevels)], ".")
}
updateUrl = "https://dynamicdns.park-your-domain.com/update?host=" + host + "&domain=" + sld + "&password=" + dnsPassword
req, err = http.NewRequest("GET", updateUrl, nil)
break
case "iwantmyname":
if dnsPassword == "" || dnsUsername == "" {
log.Fatalf("Need to define DNS_USERNAME and DNS_PASSWORD in your environment")
}
updateUrl = "https://iwantmyname.com/basicauth/ddns?hostname=" + domain
req, err = http.NewRequest("GET", updateUrl, nil)
if req != nil {
req.SetBasicAuth(dnsUsername, dnsPassword)
}
break
default:
if dnsPassword == "" || dnsUsername == "" {
log.Print("Warning: ddns url specified without username/password")
}
req, err = http.NewRequest("GET", updateUrl, nil)
if req != nil && dnsPassword != "" && dnsUsername != "" {
req.SetBasicAuth(dnsUsername, dnsPassword)
}
}
if err != nil {
log.Fatalf("ddns error: %v", err)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalf("ddns error: %v", err)
}
if resp.StatusCode != 200 {
log.Fatalf("ddns error: got http status code %v from api", resp.StatusCode)
}
go func() {
for {
time.Sleep(60 * time.Second)
resp, err := client.Do(req)
if err != nil {
log.Println("ddns error: %v", err)
}
if resp.StatusCode != 200 {
log.Println("ddns error: got http status code %v from api", resp.StatusCode)
}
}
}()
}
acme, err := acmewrapper.New(acmewrapper.Config{
Domains: []string{domain},
Address: ":" + *port,
TLSCertFile: *cert,
TLSKeyFile: *key,
RegistrationFile: filepath.Dir(*cert) + "/lets-encrypt-user.reg",
PrivateKeyFile: filepath.Dir(*cert) + "/lets-encrypt-user.pem",
TOSCallback: acmewrapper.TOSAgree,
})
if err != nil {
log.Fatal("err> " + err.Error())
}
listener, err := tls.Listen("tcp", ":"+*port, acme.TLSConfig())
if err != nil {
log.Fatal("err> " + err.Error())
}
reverseProxy := httputil.NewSingleHostReverseProxy(backendUrl)
log.Fatal(http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
uip, uport, _ := net.SplitHostPort(r.RemoteAddr)
r.Host = r.Host
r.Header.Set("Host", r.Host)
r.Header.Set("X-Real-IP", uip)
r.Header.Set("X-Remote-IP", uip)
r.Header.Set("X-Remote-Port", uport)
r.Header.Set("X-Forwarded-For", uip)
r.Header.Set("X-Forwarded-Proto", "https")
r.Header.Set("X-Forwarded-Host", r.Host)
r.Header.Set("X-Forwarded-Port", *port)
reverseProxy.ServeHTTP(w, r)
})))
}