Skip to content

Commit e1a50bc

Browse files
author
Ajay Kannan
committed
Add scheme to user-provided host if necessary
1 parent c6b7f27 commit e1a50bc

1 file changed

Lines changed: 39 additions & 1 deletion

File tree

gcloud-java-datastore/src/main/java/com/google/gcloud/spi/DefaultDatastoreRpc.java

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,10 @@
4040
import org.json.JSONObject;
4141
import org.json.JSONTokener;
4242

43+
import java.net.InetAddress;
44+
import java.net.MalformedURLException;
45+
import java.net.URL;
46+
import java.net.UnknownHostException;
4347
import java.util.HashMap;
4448
import java.util.Map;
4549

@@ -62,14 +66,48 @@ public class DefaultDatastoreRpc implements DatastoreRpc {
6266
}
6367

6468
public DefaultDatastoreRpc(DatastoreOptions options) {
69+
String normalizedHost = normalizeHost(options.host());
6570
client = DatastoreFactory.get().create(
6671
new Builder()
6772
.dataset(options.projectId())
68-
.host(options.host())
73+
.host(normalizedHost)
6974
.initializer(options.httpRequestInitializer())
7075
.build());
7176
}
7277

78+
private static String normalizeHost(String host) {
79+
host = host.toLowerCase();
80+
if (includesScheme(host)) {
81+
if (host.startsWith("https://") && isLocalHost(host)) {
82+
throw new IllegalArgumentException(
83+
"\"https\" is not supported for localhost. Use \"http\" instead.");
84+
} else {
85+
return host;
86+
}
87+
}
88+
return "http://" + host;
89+
}
90+
91+
private static boolean isLocalHost(String host) {
92+
if (host != null) {
93+
try {
94+
String normalizedHost = host;
95+
if (!includesScheme(normalizedHost)) {
96+
normalizedHost = "http://" + normalizedHost;
97+
}
98+
InetAddress hostAddr = InetAddress.getByName(new URL(normalizedHost).getHost());
99+
return hostAddr.isAnyLocalAddress() || hostAddr.isLoopbackAddress();
100+
} catch (UnknownHostException | MalformedURLException e) {
101+
// ignore
102+
}
103+
}
104+
return false;
105+
}
106+
107+
private static boolean includesScheme(String url) {
108+
return url.startsWith("http://") || url.startsWith("https://");
109+
}
110+
73111
private static DatastoreRpcException translate(DatastoreException exception) {
74112
String message = exception.getMessage();
75113
String reasonStr = "";

0 commit comments

Comments
 (0)