1
1
package corehttp
2
2
3
3
import (
4
+ "net"
4
5
"net/http"
5
6
"os"
7
+ "strconv"
6
8
"strings"
7
9
8
10
cors "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/rs/cors"
28
30
ipfs daemon --api-http-header 'Access-Control-Allow-Origin: *'
29
31
`
30
32
33
+ var defaultLocalhostOrigins = []string {
34
+ "http://127.0.0.1:<port>" ,
35
+ "https://127.0.0.1:<port>" ,
36
+ "http://localhost:<port>" ,
37
+ "https://localhost:<port>" ,
38
+ }
39
+
31
40
func addCORSFromEnv (c * cmdsHttp.ServerConfig ) {
32
41
origin := os .Getenv (originEnvKey )
33
42
if origin != "" {
@@ -57,8 +66,41 @@ func addHeadersFromConfig(c *cmdsHttp.ServerConfig, nc *config.Config) {
57
66
c .Headers = nc .API .HTTPHeaders
58
67
}
59
68
69
+ func addCORSDefaults (c * cmdsHttp.ServerConfig ) {
70
+ // by default use localhost origins
71
+ if len (c .CORSOpts .AllowedOrigins ) == 0 {
72
+ c .CORSOpts .AllowedOrigins = defaultLocalhostOrigins
73
+ }
74
+
75
+ // by default, use GET, PUT, POST
76
+ if len (c .CORSOpts .AllowedMethods ) == 0 {
77
+ c .CORSOpts .AllowedMethods = []string {"GET" , "POST" , "PUT" }
78
+ }
79
+ }
80
+
81
+ func patchCORSVars (c * cmdsHttp.ServerConfig , addr net.Addr ) {
82
+
83
+ // we have to grab the port from an addr, which may be an ip6 addr.
84
+ // TODO: this should take multiaddrs and derive port from there.
85
+ port := ""
86
+ if tcpaddr , ok := addr .(* net.TCPAddr ); ok {
87
+ port = strconv .Itoa (tcpaddr .Port )
88
+ } else if udpaddr , ok := addr .(* net.UDPAddr ); ok {
89
+ port = strconv .Itoa (udpaddr .Port )
90
+ }
91
+
92
+ // we're listening on tcp/udp with ports. ("udp!?" you say? yeah... it happens...)
93
+ for i , o := range c .CORSOpts .AllowedOrigins {
94
+ // TODO: allow replacing <host>. tricky, ip4 and ip6 and hostnames...
95
+ if port != "" {
96
+ o = strings .Replace (o , "<port>" , port , - 1 )
97
+ }
98
+ c .CORSOpts .AllowedOrigins [i ] = o
99
+ }
100
+ }
101
+
60
102
func CommandsOption (cctx commands.Context ) ServeOption {
61
- return func (n * core.IpfsNode , mux * http.ServeMux ) (* http.ServeMux , error ) {
103
+ return func (n * core.IpfsNode , l net. Listener , mux * http.ServeMux ) (* http.ServeMux , error ) {
62
104
63
105
cfg := & cmdsHttp.ServerConfig {
64
106
CORSOpts : & cors.Options {
@@ -68,6 +110,8 @@ func CommandsOption(cctx commands.Context) ServeOption {
68
110
69
111
addHeadersFromConfig (cfg , n .Repo .Config ())
70
112
addCORSFromEnv (cfg )
113
+ addCORSDefaults (cfg )
114
+ patchCORSVars (cfg , l .Addr ())
71
115
72
116
cmdHandler := cmdsHttp .NewHandler (cctx , corecommands .Root , cfg )
73
117
mux .Handle (cmdsHttp .ApiPath + "/" , cmdHandler )
0 commit comments