3030import org .apache .tools .ant .BuildException ;
3131import org .apache .tools .ant .Project ;
3232import org .apache .tools .ant .ProjectComponent ;
33+ import org .apache .tools .ant .taskdefs .Get ;
3334
3435/**
3536 * Condition to wait for a HTTP request to succeed. Its attribute(s) are:
4243public class Http extends ProjectComponent implements Condition {
4344 private static final int ERROR_BEGINS = 400 ;
4445 private static final String DEFAULT_REQUEST_METHOD = "GET" ;
46+ private static final String HTTP = "http" ;
47+ private static final String HTTPS = "https" ;
4548
4649 private String spec = null ;
4750 private String requestMethod = DEFAULT_REQUEST_METHOD ;
@@ -124,11 +127,7 @@ public boolean eval() throws BuildException {
124127 try {
125128 URLConnection conn = url .openConnection ();
126129 if (conn instanceof HttpURLConnection ) {
127- HttpURLConnection http = (HttpURLConnection ) conn ;
128- http .setRequestMethod (requestMethod );
129- http .setInstanceFollowRedirects (followRedirects );
130- http .setReadTimeout (readTimeout );
131- int code = http .getResponseCode ();
130+ int code = request ((HttpURLConnection ) conn , url );
132131 log ("Result code for " + spec + " was " + code ,
133132 Project .MSG_VERBOSE );
134133 return code > 0 && code < errorsBeginAt ;
@@ -144,4 +143,39 @@ public boolean eval() throws BuildException {
144143 }
145144 return true ;
146145 }
146+
147+ private int request (final HttpURLConnection http , final URL url ) throws IOException {
148+ http .setRequestMethod (requestMethod );
149+ http .setInstanceFollowRedirects (followRedirects );
150+ http .setReadTimeout (readTimeout );
151+ final int firstStatusCode = http .getResponseCode ();
152+ if (Get .isMoved (firstStatusCode )) {
153+ final String newLocation = http .getHeaderField ("Location" );
154+ final URL newURL = new URL (newLocation );
155+ if (redirectionAllowed (url , newURL )) {
156+ final URLConnection newConn = newURL .openConnection ();
157+ if (newConn instanceof HttpURLConnection ) {
158+ log ("Following redirect from " + url + " to " + newURL );
159+ return request ((HttpURLConnection ) newConn , newURL );
160+ }
161+ }
162+ }
163+ return firstStatusCode ;
164+ }
165+
166+ private boolean redirectionAllowed (final URL from , final URL to ) {
167+ if (from .equals (to )) {
168+ // most simple case of an infinite redirect loop
169+ return false ;
170+ }
171+ if (!(from .getProtocol ().equals (to .getProtocol ())
172+ || (HTTP .equals (from .getProtocol ())
173+ && HTTPS .equals (to .getProtocol ())))) {
174+ log ("Redirection detected from "
175+ + from .getProtocol () + " to " + to .getProtocol ()
176+ + ". Protocol switch unsafe, not allowed." );
177+ return false ;
178+ }
179+ return true ;
180+ }
147181}
0 commit comments