Skip to content

Commit

Permalink
🚑 Ipc
Browse files Browse the repository at this point in the history
  • Loading branch information
AigioL committed Jan 2, 2024
1 parent 6880574 commit 55d785a
Show file tree
Hide file tree
Showing 9 changed files with 94 additions and 153 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,16 @@ private static string GetMobileUrl(string region)
/// 地理位置 IP
/// </summary>
/// <returns></returns>
public async Task<HttpResponseMessage> GEOIP()
public async Task<ApiRspImpl<string>> GEOIP(CancellationToken cancellationToken = default)
{
using var sendArgs = new WebApiClientSendArgs(GEOIPURL);
var result = await SendAsync<HttpResponseMessage>(sendArgs);
return result!;
using var rsp = await SendAsync<HttpResponseMessage>(sendArgs, cancellationToken);
var result = await rsp!.Content.ReadAsStringAsync(cancellationToken);
return ApiRspHelper.Ok(result)!;
}

/// <inheritdoc/>
public async Task<HttpResponseMessage> EnRoll(string region, byte[] encrypted)
public async Task<ApiRspImpl<byte[]>> EnRoll(string region, byte[] encrypted, CancellationToken cancellationToken = default)
{
using var sendArgs = new WebApiClientSendArgs(GetMobileUrl(region) + ENROLL_PATH)
{
Expand All @@ -88,31 +89,22 @@ public async Task<HttpResponseMessage> EnRoll(string region, byte[] encrypted)
req.Content = content;
},
};
var result = await SendAsync<HttpResponseMessage>(sendArgs);
return result!;
using var rsp = await SendAsync<HttpResponseMessage>(sendArgs, cancellationToken);
var result = await rsp!.Content.ReadAsByteArrayAsync(cancellationToken);
return ApiRspHelper.Ok(result)!;
}

/// <summary>
/// 令牌同步
/// </summary>
/// <param name="region"></param>
/// <returns></returns>
public HttpResponseMessage Sync(string region)
/// <inheritdoc/>
public async Task<ApiRspImpl<byte[]>> Sync(string region, CancellationToken cancellationToken = default)
{
using var sendArgs = new WebApiClientSendArgs(GetMobileUrl(region) + SYNC_PATH);
#pragma warning disable CS0618 // 类型或成员已过时
var result = Send<HttpResponseMessage>(sendArgs);
#pragma warning restore CS0618 // 类型或成员已过时
return result!;
using var rsp = await SendAsync<HttpResponseMessage>(sendArgs, cancellationToken);
var result = await rsp!.Content.ReadAsByteArrayAsync(cancellationToken);
return ApiRspHelper.Ok(result)!;
}

/// <summary>
/// 恢复
/// </summary>
/// <param name="serial"></param>
/// <param name="serialBytes"></param>
/// <returns></returns>
public async Task<HttpResponseMessage> ReStore(string serial, byte[] serialBytes)
/// <inheritdoc/>
public async Task<ApiRspImpl<byte[]>> ReStore(string serial, byte[] serialBytes, CancellationToken cancellationToken = default)
{
using var sendArgs = new WebApiClientSendArgs(GetMobileUrl(serial) + RESTORE_PATH)
{
Expand All @@ -124,12 +116,13 @@ public async Task<HttpResponseMessage> ReStore(string serial, byte[] serialBytes
req.Content = content;
},
};
var result = await SendAsync<HttpResponseMessage>(sendArgs);
return result!;
using var rsp = await SendAsync<HttpResponseMessage>(sendArgs, cancellationToken);
var result = await rsp!.Content.ReadAsByteArrayAsync(cancellationToken);
return ApiRspHelper.Ok(result)!;
}

/// <inheritdoc/>
public async Task<HttpResponseMessage> ReStoreValidate(string serial, byte[] postbytes)
public async Task<ApiRspImpl<byte[]>> ReStoreValidate(string serial, byte[] postbytes, CancellationToken cancellationToken = default)
{
using var sendArgs = new WebApiClientSendArgs(GetMobileUrl(serial) + RESTOREVALIDATE_PATH)
{
Expand All @@ -141,7 +134,8 @@ public async Task<HttpResponseMessage> ReStoreValidate(string serial, byte[] pos
req.Content = content;
},
};
var result = await SendAsync<HttpResponseMessage>(sendArgs);
return result!;
using var rsp = await SendAsync<HttpResponseMessage>(sendArgs, cancellationToken);
var result = await rsp!.Content.ReadAsByteArrayAsync(cancellationToken);
return ApiRspHelper.Ok(result)!;
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
#pragma warning disable IDE0130 // 命名空间与文件夹结构不匹配
using Org.BouncyCastle.Asn1.Pkcs;

namespace BD.SteamClient8.Impl;

/// <summary>
Expand All @@ -19,11 +21,13 @@ sealed class GoogleAuthenticatorNetServiceImpl(IServiceProvider serviceProvider,
const string TIME_SYNC_URL = "http://www.google.com";

/// <inheritdoc/>
public async Task<HttpResponseMessage> TimeSync()
public async Task<ApiRspImpl<(HttpStatusCode statusCode, string? date)>> TimeSync(CancellationToken cancellationToken = default)
{
using var requestMessage = new HttpRequestMessage(HttpMethod.Get, TIME_SYNC_URL);
using var client = new HttpClient();
client.Timeout = new TimeSpan(0, 0, 5);
return await client.SendAsync(requestMessage);
using var rsp = await client.SendAsync(requestMessage, cancellationToken);
var date = rsp.Headers.GetValues("Date").First();
return (rsp.StatusCode, date);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ namespace Microsoft.Extensions.DependencyInjection;

public static partial class ServiceCollectionExtensions
{
#if (WINDOWS || MACCATALYST || MACOS || LINUX) && !(IOS || ANDROID)
#if !(IOS || ANDROID)

/// <summary>
/// 尝试添加 Steamworks LocalApi Service
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,38 +13,43 @@ public interface IAuthenticatorNetService
/// <summary>
/// 地理位置 IP
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<HttpResponseMessage> GEOIP();
Task<ApiRspImpl<string>> GEOIP(CancellationToken cancellationToken = default);

/// <summary>
/// 令牌添加
/// </summary>
/// <param name="region"></param>
/// <param name="encrypted"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<HttpResponseMessage> EnRoll(string region, byte[] encrypted);
Task<ApiRspImpl<byte[]>> EnRoll(string region, byte[] encrypted, CancellationToken cancellationToken = default);

/// <summary>
/// 令牌同步
/// </summary>
/// <param name="region"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
HttpResponseMessage Sync(string region);
Task<ApiRspImpl<byte[]>> Sync(string region, CancellationToken cancellationToken = default);

/// <summary>
/// 令牌恢复
/// </summary>
/// <param name="serial"></param>
/// <param name="serialBytes"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<HttpResponseMessage> ReStore(string serial, byte[] serialBytes);
Task<ApiRspImpl<byte[]>> ReStore(string serial, byte[] serialBytes, CancellationToken cancellationToken = default);

/// <summary>
/// 令牌恢复验证
/// </summary>
/// <param name="serial"></param>
/// <param name="postbytes"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<HttpResponseMessage> ReStoreValidate(string serial, byte[] postbytes);
Task<ApiRspImpl<byte[]>> ReStoreValidate(string serial, byte[] postbytes, CancellationToken cancellationToken = default);
}
}
151 changes: 44 additions & 107 deletions src/BD.SteamClient8/Authenticator/Models/BattleNetAuthenticator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -205,20 +205,8 @@ public async void EnrollAsync()
string? responseString = null;
try
{
using var georesponse = await IAuthenticatorNetService.Instance.GEOIP();
// OK?
if (georesponse.StatusCode == HttpStatusCode.OK)
{
using var ms = new MemoryStream();
using var bs = await georesponse.Content.ReadAsStreamAsync();
var temp = new byte[RESPONSE_BUFFER_SIZE];
int read;
while ((read = bs.Read(temp, 0, RESPONSE_BUFFER_SIZE)) != 0)
{
ms.Write(temp, 0, read);
}
responseString = Encoding.UTF8.GetString(ms.ToArray());
}
var georesponse = await IAuthenticatorNetService.Instance.GEOIP();
responseString = georesponse?.Content;
}
catch (Exception)
{
Expand Down Expand Up @@ -299,24 +287,8 @@ public async void EnrollAsync()
try
{
var response = await IAuthenticatorNetService.Instance.EnRoll(region, encrypted);

// OK?
if (response.StatusCode != HttpStatusCode.OK)
{
throw new AuthenticatorInvalidEnrollResponseException(string.Format("{0}: {1}", (int)response.StatusCode, response.RequestMessage?.RequestUri));
}

// load back the buffer - should only be a byte[45]
using var ms = new MemoryStream();
//using (BufferedStream bs = new BufferedStream(response.GetResponseStream()))
using var bs = await response.Content.ReadAsStreamAsync();
var temp = new byte[RESPONSE_BUFFER_SIZE];
int read;
while ((read = bs.Read(temp, 0, RESPONSE_BUFFER_SIZE)) != 0)
{
ms.Write(temp, 0, read);
}
responseData = ms.ToArray();
responseData = response.Content;
responseData.ThrowIsNull();

// check it is correct size
if (responseData.Length != ENROLL_RESPONSE_SIZE)
Expand Down Expand Up @@ -381,7 +353,7 @@ public void Enroll(bool testmode)
/// <summary>
/// Synchronise this authenticator's time with server time. We update our data record with the difference from our UTC time.
/// </summary>
public override void Sync()
public override async void Sync()
{
// check if data is protected
if (SecretKey == null && EncryptedData != null)
Expand All @@ -400,31 +372,14 @@ public override void Sync()
// create a connection to time sync server
// get response
byte[]? responseData = null;
using (var response = IAuthenticatorNetService.Instance.Sync(Region))
{
// OK?
if (response.ThrowIsNull().StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException(string.Format("{0}: {1}", (int)response.StatusCode, response.RequestMessage));
}
var response = await IAuthenticatorNetService.Instance.Sync(Region);
responseData = response.Content;
responseData.ThrowIsNull();

// load back the buffer - should only be a byte[8]
using var ms = new MemoryStream();
// using (BufferedStream bs = new BufferedStream(response.GetResponseStream()))
using var bs = response.Content.ReadAsStream();
var temp = new byte[RESPONSE_BUFFER_SIZE];
int read;
while ((read = bs.Read(temp, 0, RESPONSE_BUFFER_SIZE)) != 0)
{
ms.Write(temp, 0, read);
}
responseData = ms.ToArray();

// check it is correct size
if (responseData.Length != SYNC_RESPONSE_SIZE)
{
throw new AuthenticatorInvalidSyncResponseException(string.Format("Invalid response data size (expected " + SYNC_RESPONSE_SIZE + " got {0}", responseData.Length));
}
// check it is correct size
if (responseData.Length != SYNC_RESPONSE_SIZE)
{
throw new AuthenticatorInvalidSyncResponseException(string.Format("Invalid response data size (expected " + SYNC_RESPONSE_SIZE + " got {0}", responseData.Length));
}

// return data:
Expand Down Expand Up @@ -469,30 +424,21 @@ public async void RestoreAsync(string serial, string restoreCode)

byte[]? challenge = null;
{
using var response = await IAuthenticatorNetService.Instance.ReStore(serial, serialBytes);
var response = await IAuthenticatorNetService.Instance.ReStore(serial, serialBytes);
// OK?
if (!response.IsSuccessStatusCode)
{
if ((int)response.StatusCode >= 500 && (int)response.StatusCode < 600)
{
throw new AuthenticatorInvalidRestoreResponseException(string.Format("No response from server ({0}). Perhaps maintainence?", (int)response.StatusCode));
}
else
{
throw new AuthenticatorInvalidRestoreResponseException(string.Format("Error communicating with server: {0} - {1}", (int)response.StatusCode, response.StatusCode));
}
}

// load back the buffer - should only be a byte[32]
using var ms = new MemoryStream();
using var bs = await response.Content.ReadAsStreamAsync();
var temp = new byte[RESPONSE_BUFFER_SIZE];
int read;
while ((read = bs.Read(temp, 0, RESPONSE_BUFFER_SIZE)) != 0)
{
ms.Write(temp, 0, read);
}
challenge = ms.ToArray();
//if (!response.IsSuccessStatusCode)
//{
// if ((int)response.StatusCode >= 500 && (int)response.StatusCode < 600)
// {
// throw new AuthenticatorInvalidRestoreResponseException(string.Format("No response from server ({0}). Perhaps maintainence?", (int)response.StatusCode));
// }
// else
// {
// throw new AuthenticatorInvalidRestoreResponseException(string.Format("Error communicating with server: {0} - {1}", (int)response.StatusCode, response.StatusCode));
// }
//}
challenge = response.Content;
challenge.ThrowIsNull();

// check it is correct size
if (challenge.Length != RESTOREINIT_BUFFER_SIZE)
Expand Down Expand Up @@ -541,34 +487,25 @@ public async void RestoreAsync(string serial, string restoreCode)

byte[]? secretKey = null;
{
using var response = await IAuthenticatorNetService.Instance.ReStoreValidate(serial, postbytes);
var response = await IAuthenticatorNetService.Instance.ReStoreValidate(serial, postbytes);
// OK?
if (!response.IsSuccessStatusCode)
{
if ((int)response.StatusCode >= 500 && (int)response.StatusCode < 600)
{
throw new AuthenticatorInvalidRestoreResponseException(string.Format("No response from server ({0}). Perhaps maintainence?", (int)response.StatusCode));
}
else if ((int)response.StatusCode >= 600 && (int)response.StatusCode < 700)
{
throw new AuthenticatorInvalidRestoreCodeException("Invalid serial number or restore code.");
}
else
{
throw new AuthenticatorInvalidRestoreResponseException(string.Format("Error communicating with server: {0} - {1}", (int)response.StatusCode, response.StatusCode));
}
}

// load back the buffer - should only be a byte[32]
using var ms = new MemoryStream();
using var bs = await response.Content.ReadAsStreamAsync();
var temp = new byte[RESPONSE_BUFFER_SIZE];
int read;
while ((read = bs.Read(temp, 0, RESPONSE_BUFFER_SIZE)) != 0)
{
ms.Write(temp, 0, read);
}
secretKey = ms.ToArray();
//if (!response.IsSuccessStatusCode)
//{
// if ((int)response.StatusCode >= 500 && (int)response.StatusCode < 600)
// {
// throw new AuthenticatorInvalidRestoreResponseException(string.Format("No response from server ({0}). Perhaps maintainence?", (int)response.StatusCode));
// }
// else if ((int)response.StatusCode >= 600 && (int)response.StatusCode < 700)
// {
// throw new AuthenticatorInvalidRestoreCodeException("Invalid serial number or restore code.");
// }
// else
// {
// throw new AuthenticatorInvalidRestoreResponseException(string.Format("Error communicating with server: {0} - {1}", (int)response.StatusCode, response.StatusCode));
// }
//}
secretKey = response.Content;
secretKey.ThrowIsNull();

// check it is correct size
if (secretKey.Length != RESTOREVALIDATE_BUFFER_SIZE)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ public interface IAuthenticatorNetService
/// <summary>
/// 同步时间
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<HttpResponseMessage> TimeSync();
Task<ApiRspImpl<(HttpStatusCode statusCode, string? date)>> TimeSync(CancellationToken cancellationToken = default);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -84,15 +84,15 @@ public override async void Sync()
try
{
// we use the Header response field from a request to www.google.come
using var response = await IAuthenticatorNetService.Instance.TimeSync();
var response = await IAuthenticatorNetService.Instance.TimeSync();

// OK?
if (response.StatusCode != HttpStatusCode.OK)
if (response.Content.statusCode != HttpStatusCode.OK)
{
throw new ApplicationException(string.Format("{0}: {1}", (int)response.StatusCode, response.RequestMessage));
throw new ApplicationException(string.Format("{0}: {1}", response.Content, response.GetMessage()));
}

string headerdate = response.Headers.GetValues("Date").First();
var headerdate = response.Content.date;
if (string.IsNullOrEmpty(headerdate) == false)
{
if (DateTime.TryParse(headerdate, out var dt) == true)
Expand Down
Loading

0 comments on commit 55d785a

Please sign in to comment.