forked from rchunping/https-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
91 lines (79 loc) · 2.3 KB
/
main.go
File metadata and controls
91 lines (79 loc) · 2.3 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
package main
import (
"crypto/tls"
"flag"
"log"
"net/http"
"strings"
"syscall"
)
func main() {
var pemPath, keyPath, proto, listen, users string
var uid, gid int
flag.StringVar(&pemPath, "pem", "server.pem", "path to pem file")
flag.StringVar(&keyPath, "key", "server.key", "path to key file")
flag.StringVar(&proto, "proto", "http", "Proxy protocol (http or https)")
flag.StringVar(&listen, "listen", ":8080", "listen address, default :8080")
flag.StringVar(&users, "users", "", "user:password list")
flag.IntVar(&uid, "uid", -1, "run as user id")
flag.IntVar(&gid, "gid", -1, "run as group")
flag.Parse()
if proto != "http" && proto != "https" {
log.Fatal("Protocol must be either http or https")
}
var userList []User
for _, up := range strings.Split(users, ";") {
if ms := strings.Split(up, ":"); len(ms) == 2 && len(ms[0]) > 0 {
userList = append(userList, User{ms[0], ms[1]})
}
}
server := &http.Server{
Addr: listen,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if len(userList) > 0 && !basicAuth(w, r, userList) {
return
}
if r.Method == http.MethodConnect {
handleTunneling(w, r)
} else {
handleHTTP(w, r)
}
}),
// TLSNextProto not-nil to disable HTTP/2.
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
}
if proto == "https" {
// https://github.com/golang/go/blob/377646589d5fb0224014683e0d1f1db35e60c3ac/src/net/http/server.go#L3342
var err error
tlsConfig := tls.Config{}
tlsConfig.Certificates = make([]tls.Certificate, 1)
tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(pemPath, keyPath)
if err != nil {
log.Fatal("Failed to load x509 key, " + err.Error())
}
// The config may be loaded as root in openwrt + acme
server.TLSConfig = &tlsConfig
}
// Drop root privileges, and switch to new uid:gid
if gid > 0 {
err := syscall.Setgroups([]int{})
if err != nil {
log.Fatal("Failed to unset groups, " + err.Error())
}
err = syscall.Setgid(gid)
if err != nil {
log.Fatal("Failed to set new group, " + err.Error())
}
}
if uid > 0 {
err := syscall.Setuid(uid)
if err != nil {
log.Fatal("Failed to set new user, " + err.Error())
}
}
if proto == "http" {
log.Fatal(server.ListenAndServe())
} else {
log.Fatal(server.ListenAndServeTLS("", ""))
}
}