diff --git a/RageCoop.Server/Server.cs b/RageCoop.Server/Server.cs index 4b92858..a4ab978 100644 --- a/RageCoop.Server/Server.cs +++ b/RageCoop.Server/Server.cs @@ -141,7 +141,6 @@ namespace RageCoop.Server Logger?.Error(ex.InnerException?.Message ?? ex.Message); return; } - var realMaster = Settings.MasterServer; while (!_stopping) { string msg = @@ -161,7 +160,8 @@ namespace RageCoop.Server HttpResponseMessage response = null; try { - response = await httpClient.PostAsync(realMaster, new StringContent(msg, Encoding.UTF8, "application/json")); + var realUrl = Util.GetFinalRedirect(Settings.MasterServer); + response = await httpClient.PostAsync(realUrl, new StringContent(msg, Encoding.UTF8, "application/json")); } catch (Exception ex) { diff --git a/RageCoop.Server/Util.cs b/RageCoop.Server/Util.cs index 227b295..dea8ea1 100644 --- a/RageCoop.Server/Util.cs +++ b/RageCoop.Server/Util.cs @@ -103,5 +103,65 @@ namespace RageCoop.Server { return values[new Random().Next(values.Length-1)]; } + + public static string GetFinalRedirect(string url) + { + if (string.IsNullOrWhiteSpace(url)) + return url; + + int maxRedirCount = 8; // prevent infinite loops + string newUrl = url; + do + { + HttpWebRequest req = null; + HttpWebResponse resp = null; + try + { + req = (HttpWebRequest)HttpWebRequest.Create(url); + req.Method = "HEAD"; + req.AllowAutoRedirect = false; + resp = (HttpWebResponse)req.GetResponse(); + switch (resp.StatusCode) + { + case HttpStatusCode.OK: + return newUrl; + case HttpStatusCode.Redirect: + case HttpStatusCode.MovedPermanently: + case HttpStatusCode.RedirectKeepVerb: + case HttpStatusCode.RedirectMethod: + newUrl = resp.Headers["Location"]; + if (newUrl == null) + return url; + + if (newUrl.IndexOf("://", System.StringComparison.Ordinal) == -1) + { + // Doesn't have a URL Schema, meaning it's a relative or absolute URL + Uri u = new Uri(new Uri(url), newUrl); + newUrl = u.ToString(); + } + break; + default: + return newUrl; + } + url = newUrl; + } + catch (WebException) + { + // Return the last known good URL + return newUrl; + } + catch + { + return null; + } + finally + { + if (resp != null) + resp.Close(); + } + } while (maxRedirCount-- > 0); + + return newUrl; + } } }