Skip to content

Commit

Permalink
#6 check for protocol
Browse files Browse the repository at this point in the history
  • Loading branch information
Yegor Bugayenko committed Apr 1, 2016
1 parent 9de447e commit 1ce0f2f
Showing 1 changed file with 58 additions and 23 deletions.
81 changes: 58 additions & 23 deletions src/main/java/io/jare/tk/TkRelay.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,21 @@ public Response act(final Request req) throws IOException {
);
}
final URI uri = URI.create(param.next().trim());
return new RsWithHeader(
new TkProxy(uri.toString()).act(
TkRelay.request(req, this.path(uri))
),
String.format("X-Jare-Target: %s", uri)
);
}

/**
* Build destination path.
* @param uri URI of destination
* @return Destination path
* @throws HttpException If fails
*/
private String path(final URI uri) throws HttpException {
final String host = uri.getHost().toLowerCase(Locale.ENGLISH);
final Iterator<Domain> domains = this.base.domain(host);
if (!domains.hasNext()) {
Expand All @@ -81,35 +96,55 @@ public Response act(final Request req) throws IOException {
String.format("domain \"%s\" is not registered", host)
);
}
if (!uri.isAbsolute()) {
throw new HttpException(
HttpURLConnection.HTTP_BAD_REQUEST,
String.format("URI \"%s\" is not absolute", uri)
);
}
final String protocol = uri.getScheme();
if (!"https".equals(protocol) && !"http".equals(protocol)) {
throw new HttpException(
HttpURLConnection.HTTP_BAD_REQUEST,
String.format(
"protocol must be either HTTP or HTTPS at \"%s\"",
uri
)
);
}
final String path;
if (uri.getPath().isEmpty()) {
path = "/";
} else {
path = uri.getPath();
}
return new RsWithHeader(
new TkProxy(uri.toString()).act(
new Request() {
@Override
public Iterable<String> head() throws IOException {
return Iterables.concat(
Collections.singleton(
String.format(
"GET %s HTTP/1.1",
path
)
),
Iterables.skip(req.head(), 1)
);
}
@Override
public InputStream body() throws IOException {
return req.body();
}
}
),
String.format("X-Jare-Target: %s", uri)
);
return path;
}

/**
* The request to send.
* @param req Original request
* @param path Destination path
* @return Request
*/
private static Request request(final Request req, final String path) {
return new Request() {
@Override
public Iterable<String> head() throws IOException {
return Iterables.concat(
Collections.singleton(
String.format(
"GET %s HTTP/1.1",
path
)
),
Iterables.skip(req.head(), 1)
);
}
@Override
public InputStream body() throws IOException {
return req.body();
}
};
}
}

0 comments on commit 1ce0f2f

Please sign in to comment.