forked from TRON-US/go-btfs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
p2p_proxy.go
77 lines (64 loc) · 2.11 KB
/
p2p_proxy.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
package corehttp
import (
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"strings"
core "github.com/TRON-US/go-btfs/core"
protocol "github.com/libp2p/go-libp2p-core/protocol"
p2phttp "github.com/libp2p/go-libp2p-http"
)
// P2PProxyOption is an endpoint for proxying a HTTP request to another btfs peer
func P2PProxyOption() ServeOption {
return func(ipfsNode *core.IpfsNode, _ net.Listener, mux *http.ServeMux) (*http.ServeMux, error) {
mux.HandleFunc("/p2p/", func(w http.ResponseWriter, request *http.Request) {
// parse request
parsedRequest, err := parseRequest(request)
if err != nil {
handleError(w, "failed to parse request", err, 400)
return
}
request.Host = "" // Let URL's Host take precedence.
request.URL.Path = parsedRequest.httpPath
target, err := url.Parse(fmt.Sprintf("libp2p://%s", parsedRequest.target))
if err != nil {
handleError(w, "failed to parse url", err, 400)
return
}
rt := p2phttp.NewTransport(ipfsNode.PeerHost, p2phttp.ProtocolOption(parsedRequest.name))
proxy := httputil.NewSingleHostReverseProxy(target)
proxy.Transport = rt
proxy.ServeHTTP(w, request)
})
return mux, nil
}
}
type proxyRequest struct {
target string
name protocol.ID
httpPath string // path to send to the proxy-host
}
// from the url path parse the peer-ID, name and http path
// /p2p/$peer_id/http/$http_path
// or
// /p2p/$peer_id/x/$protocol/http/$http_path
func parseRequest(request *http.Request) (*proxyRequest, error) {
path := request.URL.Path
split := strings.SplitN(path, "/", 5)
if len(split) < 5 {
return nil, fmt.Errorf("Invalid request path '%s'", path)
}
if split[3] == "http" {
return &proxyRequest{split[2], protocol.ID("/http"), split[4]}, nil
}
split = strings.SplitN(path, "/", 7)
if len(split) < 7 || split[3] != "x" || split[5] != "http" {
return nil, fmt.Errorf("Invalid request path '%s'", path)
}
return &proxyRequest{split[2], protocol.ID("/x/" + split[4] + "/http"), split[6]}, nil
}
func handleError(w http.ResponseWriter, msg string, err error, code int) {
http.Error(w, fmt.Sprintf("%s: %s", msg, err), code)
}