follow redirects in posh

Daniel Gultsch created

Change summary

libs/MemorizingTrustManager/src/de/duenndns/ssl/MemorizingTrustManager.java | 29 
1 file changed, 22 insertions(+), 7 deletions(-)

Detailed changes

libs/MemorizingTrustManager/src/de/duenndns/ssl/MemorizingTrustManager.java 🔗

@@ -458,10 +458,14 @@ public class MemorizingTrustManager {
 	}
 
 	private List<String> getPoshFingerprintsFromServer(String domain) {
+		return getPoshFingerprintsFromServer(domain, "https://"+domain+"/.well-known/posh/xmpp-client.json",-1,true);
+	}
+
+	private List<String> getPoshFingerprintsFromServer(String domain, String url, int maxTtl, boolean followUrl) {
+		Log.d("mtm","downloading json for "+domain+" from "+url);
 		try {
 			List<String> results = new ArrayList<>();
-			URL url = new URL("https://"+domain+"/.well-known/posh/xmpp-client.json");
-			HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
+			HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
 			connection.setConnectTimeout(5000);
 			connection.setReadTimeout(5000);
 			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
@@ -472,6 +476,22 @@ public class MemorizingTrustManager {
 			}
 			JSONObject jsonObject = new JSONObject(builder.toString());
 			in.close();
+			int expires = jsonObject.getInt("expires");
+			if (expires <= 0) {
+				return new ArrayList<>();
+			}
+			if (maxTtl >= 0) {
+				expires = Math.min(maxTtl,expires);
+			}
+			String redirect;
+			try {
+				redirect = jsonObject.getString("url");
+			} catch (JSONException e) {
+				redirect = null;
+			}
+			if (followUrl && redirect != null && redirect.toLowerCase().startsWith("https")) {
+				return getPoshFingerprintsFromServer(domain, redirect, expires, false);
+			}
 			JSONArray fingerprints = jsonObject.getJSONArray("fingerprints");
 			for(int i = 0; i < fingerprints.length(); i++) {
 				JSONObject fingerprint = fingerprints.getJSONObject(i);
@@ -480,11 +500,6 @@ public class MemorizingTrustManager {
 					results.add(sha256);
 				}
 			}
-			int expires = jsonObject.getInt("expires");
-			if (expires <= 0) {
-				return new ArrayList<>();
-			}
-			in.close();
 			writeFingerprintsToCache(domain, results,1000L * expires+System.currentTimeMillis());
 			return results;
 		} catch (Exception e) {