Merge pull request #20 from DeKaN/warning-fixes

Warning fixes
This commit is contained in:
pr701 2022-08-20 21:55:29 +03:00 committed by GitHub
commit ed8859ce19
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 130 additions and 631 deletions

View File

@ -62,7 +62,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
//Error 52 - Данная учетная запись была заблокирована в связи с многочисленными нарушениями условий использования службы Battle.net //Error 52 - Данная учетная запись была заблокирована в связи с многочисленными нарушениями условий использования службы Battle.net
//Error 53 - Действие данной учетной записи было приостановлено в связи с нарушениями условий использования службы Batle.net. //Error 53 - Действие данной учетной записи было приостановлено в связи с нарушениями условий использования службы Batle.net.
int VersionRetail = 82785; //74291 - 2.7.0, 76761 - 2.7.1, 79575 - 2.7.2; int VersionRetail = 81850; //74291 - 2.7.0, 76761 - 2.7.1, 79575 - 2.7.2;
int VersionPTR = 79151; int VersionPTR = 79151;
string version = ""; string version = "";
int a = request.ApplicationVersion; int a = request.ApplicationVersion;
@ -94,7 +94,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
{ {
Logger.Error("Подключение не правильной версии клиента!"); Logger.Error("Подключение не правильной версии клиента!");
var ercomplete = LogonResult.CreateBuilder().SetErrorCode(28); var ercomplete = LogonResult.CreateBuilder().SetErrorCode(28);
(controller as HandlerController).Client.MakeRPC((lid) => AuthenticationListener.CreateStub((controller as HandlerController).Client).OnLogonComplete(controller, ercomplete.Build(), callback => { })); //(controller as HandlerController).Client.MakeRPC((lid) => AuthenticationListener.CreateStub((controller as HandlerController).Client).OnLogonComplete(controller, ercomplete.Build(), callback => { }));
} }
switch (request.Locale) switch (request.Locale)
{ {

View File

@ -60,14 +60,14 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var GAS = D3.Client.GameAccountSettings.CreateBuilder() var GAS = D3.Client.GameAccountSettings.CreateBuilder()
.SetShowDifficultySelector(false) .SetShowDifficultySelector(false)
.SetUseGameHandicapDeprecated(true) .SetUseGameHandicapDeprecated(true)
//.SetSeasonJourneySeasonNumber(2) .SetSeasonJourneySeasonNumber(10)
//.SetViewedAnniversaryScreenYear(1) .SetViewedAnniversaryScreenYear(1)
.SetAccountFlags(0) .SetAccountFlags(0)
//.SetAccountFlags((uint)D3.Account.Digest.Types.Flags.MASTER_DIFFICULTY_UNLOCKED) .SetAccountFlags((uint)D3.Account.Digest.Types.Flags.MASTER_DIFFICULTY_UNLOCKED)
//.SetAchievementsTimeLastViewed(DateTimeExtensions.ToUnixTime(DateTime.UtcNow)) .SetAchievementsTimeLastViewed(DateTimeExtensions.ToUnixTime(DateTime.UtcNow))
//.SetViewedAnniversaryScreenYear(1) //.SetViewedAnniversaryScreenYear(1)
//.SetViewedWhatsNewVersion(Client.Account.GameAccount.DBGameAccount.ViewedNewVersion) .SetViewedWhatsNewVersion(20)
//.SetViewedWhatsNewSeason(Client.Account.GameAccount.DBGameAccount.ViewedNewSeason) .SetViewedWhatsNewSeason(20)
.SetRmtLastUsedCurrency("PLATINUM") .SetRmtLastUsedCurrency("PLATINUM")
.SetRmtPreferredCurrency("PLATINUM") .SetRmtPreferredCurrency("PLATINUM")
@ -77,7 +77,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
Init.SetChatRestrictionContentLicenseId(0); Init.SetChatRestrictionContentLicenseId(0);
Init.SetAchievementsContentHandle(D3.OnlineService.ContentHandle.CreateBuilder().SetHash("d143e14d7d59897bd8bedb040ab40738bbfcb3d234fd52338d90e67fe43c573e").SetRegion("EU").SetUsage(".achu")); Init.SetAchievementsContentHandle(D3.OnlineService.ContentHandle.CreateBuilder().SetHash("20375546335DA13E31554A104FE036B5BCC878D715108F1FCEB50AB85BD87478").SetRegion("EU").SetUsage(".achu"));
HeroDigestListResponse.Builder d = HeroDigestListResponse.CreateBuilder(); HeroDigestListResponse.Builder d = HeroDigestListResponse.CreateBuilder();
foreach (Toon t in Client.Account.GameAccount.Toons) foreach (Toon t in Client.Account.GameAccount.Toons)
{ {
@ -101,9 +101,9 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
" OnlineService.Region.Id=5");*/ " OnlineService.Region.Id=5");*/
Init.SetSyncedVars( Init.SetSyncedVars(
" OnlineService.Season.Num=1" + //Номер сезона " OnlineService.Season.Num=1" + //Номер сезона
" OnlineService.Season.State=0" + //Статус сезона, 1 - Активирован, 0 - Деактивирован " OnlineService.Season.State=1" + //Статус сезона, 1 - Активирован, 0 - Деактивирован
" OnlineService.Leaderboard.Era=1" + " OnlineService.Leaderboard.Era=1" +
" OnlineService.AnniversaryEvent.Status=0" + //Событие юбилея, 1-Старый Тристам " OnlineService.AnniversaryEvent.Status=1" + //Событие юбилея, 1-Старый Тристам
" ChallengeRift.ChallengeNumber=1" + //Номер портала дерзаний. " ChallengeRift.ChallengeNumber=1" + //Номер портала дерзаний.
" OnlineService.FreeToPlay=true" + //Магазин за платину " OnlineService.FreeToPlay=true" + //Магазин за платину
" OnlineService.Store.Status=0" + //Статус Магазина, 0 - Включен, 1 - Отключен " OnlineService.Store.Status=0" + //Статус Магазина, 0 - Включен, 1 - Отключен

View File

@ -95,6 +95,8 @@ namespace DiIiS_NA.GameServer.ClientSystem
while ((end - _incomingBuffer.Position) >= 9 && this.Connection.IsOpen()) while ((end - _incomingBuffer.Position) >= 9 && this.Connection.IsOpen())
{ {
var message = _incomingBuffer.ParseMessage(); var message = _incomingBuffer.ParseMessage();
//217
//
if (message == null) continue; if (message == null) continue;
try try
{ {

View File

@ -728,7 +728,6 @@ namespace DiIiS_NA.GameServer.GSSystem.PlayerSystem
foreach (var ghost in cryptwrld.GetActorsBySNO(5360)) foreach (var ghost in cryptwrld.GetActorsBySNO(5360))
ghost.Destroy(); ghost.Destroy();
break; break;
break;
#endregion #endregion
#region A1-Q4 Event_DoK #region A1-Q4 Event_DoK
case 139823: //Event_DoK_Kill.cnv case 139823: //Event_DoK_Kill.cnv

View File

@ -254,6 +254,8 @@ namespace DiIiS_NA.GameServer.GSSystem.PlayerSystem
_owner.GrantCriteria(74987243308421); _owner.GrantCriteria(74987243308421);
if (item.ItemType.Name.Contains("ScoundrelSpecial")) if (item.ItemType.Name.Contains("ScoundrelSpecial"))
_owner.GrantCriteria(74987243308422); _owner.GrantCriteria(74987243308422);
_owner.PlayEffect(Effect.Sound, 196576);
return success; return success;
} }

View File

@ -470,6 +470,9 @@ namespace DiIiS_NA.GameServer.GSSystem.PlayerSystem
Attributes[GameAttribute.Currencies_Discovered] = 0x0011FFF8; Attributes[GameAttribute.Currencies_Discovered] = 0x0011FFF8;
Attributes[GameAttribute.Stash_Tabs_Purchased_With_Gold] = 5; Attributes[GameAttribute.Stash_Tabs_Purchased_With_Gold] = 5;
this.Attributes[GameAttribute.Skill, 30592] = 1;
this.Attributes[GameAttribute.Resource_Degeneration_Prevented] = false;
this.Attributes[GameAttribute.Resource_Degeneration_Stop_Point] = 0;
//scripted //this.Attributes[GameAttribute.Skill_Total, 0x7545] = 1; //Axe Operate Gizmo //scripted //this.Attributes[GameAttribute.Skill_Total, 0x7545] = 1; //Axe Operate Gizmo
//scripted //this.Attributes[GameAttribute.Skill_Total, 0x76B7] = 1; //Punch! //scripted //this.Attributes[GameAttribute.Skill_Total, 0x76B7] = 1; //Punch!
//scripted //this.Attributes[GameAttribute.Skill_Total, 0x6DF] = 1; //Use Item //scripted //this.Attributes[GameAttribute.Skill_Total, 0x6DF] = 1; //Use Item
@ -5299,7 +5302,13 @@ namespace DiIiS_NA.GameServer.GSSystem.PlayerSystem
Amount = item.Attributes[GameAttribute.Gold], Amount = item.Attributes[GameAttribute.Gold],
Type = FloatingAmountMessage.FloatType.Gold, Type = FloatingAmountMessage.FloatType.Gold,
}); });
this.InGameClient.SendMessage(new PlayEffectMessage()
{
ActorId = this.DynamicID(this),
Effect = Effect.GoldPickup,
PlayerId = 0
});
PlayEffect(Effect.Sound, 36726);
this.Inventory.PickUpGold(item); this.Inventory.PickUpGold(item);
this.GroundItems.Remove(item.GlobalID); this.GroundItems.Remove(item.GlobalID);
item.Destroy(); item.Destroy();
@ -5340,6 +5349,7 @@ namespace DiIiS_NA.GameServer.GSSystem.PlayerSystem
Amount = item.Attributes[GameAttribute.ItemStackQuantityLo], Amount = item.Attributes[GameAttribute.ItemStackQuantityLo],
Type = FloatingAmountMessage.FloatType.Platinum, Type = FloatingAmountMessage.FloatType.Platinum,
}); });
PlayEffect(Effect.Sound, 433266);
this.Inventory.PickUpPlatinum(item); this.Inventory.PickUpPlatinum(item);
this.GroundItems.Remove(item.GlobalID); this.GroundItems.Remove(item.GlobalID);

View File

@ -25,8 +25,6 @@ using System.Collections.Generic;
//Blizzless Project 2022 //Blizzless Project 2022
using System.Linq; using System.Linq;
//Blizzless Project 2022 //Blizzless Project 2022
using System.Text;
//Blizzless Project 2022
using System.Threading.Tasks; using System.Threading.Tasks;
namespace DiIiS_NA.GameServer.GSSystem.PowerSystem.Implementations namespace DiIiS_NA.GameServer.GSSystem.PowerSystem.Implementations
@ -42,7 +40,7 @@ namespace DiIiS_NA.GameServer.GSSystem.PowerSystem.Implementations
var ShockWavePos = PowerMath.TranslateDirection2D(User.Position, TargetPosition, var ShockWavePos = PowerMath.TranslateDirection2D(User.Position, TargetPosition,
User.Position, User.Position,
ScriptFormula(23)); ScriptFormula(23));
var maxHits = 2; var maxHits = 1;
for (int i = 0; i < maxHits; ++i) for (int i = 0; i < maxHits; ++i)
{ {
AttackPayload attack = new AttackPayload(this); AttackPayload attack = new AttackPayload(this);
@ -76,7 +74,7 @@ namespace DiIiS_NA.GameServer.GSSystem.PowerSystem.Implementations
else else
{ {
if (Rand.NextDouble() < ScriptFormula(0)) if (Rand.NextDouble() < ScriptFormula(0))
Knockback(hitPayload.Target, ScriptFormula(5), ScriptFormula(6), ScriptFormula(7)); Knockback(hitPayload.Target, 0.8f, 2, -0.03f);
} }
}; };
attack.Apply(); attack.Apply();
@ -704,7 +702,7 @@ namespace DiIiS_NA.GameServer.GSSystem.PowerSystem.Implementations
if (Rune_B > 0) if (Rune_B > 0)
{ {
AttackPayload attack = new AttackPayload(this); AttackPayload attack = new AttackPayload(this);
attack.Targets = GetEnemiesInArcDirection(User.Position, TargetPosition, ScriptFormula(14), ScriptFormula(15)); attack.Targets = GetEnemiesInArcDirection(User.Position, TargetPosition, 22, 1);
attack.AddWeaponDamage(ScriptFormula(23), DamageType.Physical); attack.AddWeaponDamage(ScriptFormula(23), DamageType.Physical);
attack.Apply(); attack.Apply();
yield break; yield break;

View File

@ -98,7 +98,7 @@ namespace DiIiS_NA.GameServer.GSSystem.PowerSystem.Implementations
{ {
WeaponDamage(Targets, 1.50f, DamageType.Cold); WeaponDamage(Targets, 1.50f, DamageType.Cold);
EffectActor Explosion1 = SpawnEffect(defaultEff, TargetPosition, 0, WaitSeconds(2f)); EffectActor Explosion1 = SpawnEffect(defaultEff, TargetPosition, 0, WaitSeconds(2f));
Explosion.PlayEffect(Effect.PlayEffectGroup, 471410); Explosion1.PlayEffect(Effect.PlayEffectGroup, 471410);
foreach (var Target in Targets.Actors) foreach (var Target in Targets.Actors)
AddBuff(Target, new DebuffChilled(0.4f, WaitSeconds(0.5f))); AddBuff(Target, new DebuffChilled(0.4f, WaitSeconds(0.5f)));
} }

View File

@ -90,8 +90,6 @@ namespace DiIiS_NA.GameServer.GSSystem.PowerSystem.Payloads
public void Apply() public void Apply()
{ {
Task.Delay(1).ContinueWith((a) => {
if (this.Targets == null) this.Targets = new TargetList(); if (this.Targets == null) this.Targets = new TargetList();
if (this.Target.World != null) if (this.Target.World != null)
{ {
@ -104,7 +102,6 @@ namespace DiIiS_NA.GameServer.GSSystem.PowerSystem.Payloads
{ {
return; return;
} }
if (this.Target is Player && this.DamageEntries.Count > 0) if (this.Target is Player && this.DamageEntries.Count > 0)
{ {
Player player = (Player)this.Target; Player player = (Player)this.Target;
@ -113,13 +110,12 @@ namespace DiIiS_NA.GameServer.GSSystem.PowerSystem.Payloads
extra.OnTargeted(player, null); extra.OnTargeted(player, null);
} }
if (this.Context.User is Player && this.Context.Target is Monster && this.Context.Target.GBHandle.Type == 1) if (this.Context.User is Player && this.Context.Target is Monster && this.Context.Target.GBHandle.Type == 1)
{ {
(this.Context.User as Player).ExpBonusData.MonsterAttacked((this.Context.User as Player).InGameClient.Game.TickCounter); (this.Context.User as Player).ExpBonusData.MonsterAttacked((this.Context.User as Player).InGameClient.Game.TickCounter);
((this.Context.Target as Monster).Brain as AISystem.Brains.MonsterBrain).AttackedBy = this.Context.User; ((this.Context.Target as Monster).Brain as AISystem.Brains.MonsterBrain).AttackedBy = this.Context.User;
} }
// main targets
foreach (Actor target in this.Targets.Actors) foreach (Actor target in this.Targets.Actors)
{ {
if (target == null || target.World == null || target.World != null && target.World.PowerManager.IsDeletingActor(target)) if (target == null || target.World == null || target.World != null && target.World.PowerManager.IsDeletingActor(target))
@ -143,9 +139,6 @@ namespace DiIiS_NA.GameServer.GSSystem.PowerSystem.Payloads
payload.Apply(); payload.Apply();
} }
} }
});
} }
private bool _DoCriticalHit(Actor user, Actor target, float chcBonus = 0f) private bool _DoCriticalHit(Actor user, Actor target, float chcBonus = 0f)

View File

@ -100,7 +100,6 @@ namespace DiIiS_NA.GameServer.GSSystem.PowerSystem.Payloads
plr.World.BuffManager.AddBuff(plr, plr, new SpiritVesselCooldownBuff()); plr.World.BuffManager.AddBuff(plr, plr, new SpiritVesselCooldownBuff());
return; return;
} }
if (plr.SkillSet.HasPassive(156484) && plr.World.BuffManager.GetFirstBuff<NearDeathExperienceCooldownBuff>(plr) == null) //NearDeathExperience (monk) if (plr.SkillSet.HasPassive(156484) && plr.World.BuffManager.GetFirstBuff<NearDeathExperienceCooldownBuff>(plr) == null) //NearDeathExperience (monk)
{ {
plr.Attributes[GameAttribute.Hitpoints_Cur] = plr.Attributes[GameAttribute.Hitpoints_Max_Total] * 0.35f; plr.Attributes[GameAttribute.Hitpoints_Cur] = plr.Attributes[GameAttribute.Hitpoints_Max_Total] * 0.35f;
@ -114,14 +113,14 @@ namespace DiIiS_NA.GameServer.GSSystem.PowerSystem.Payloads
{ {
Hireling mon = (Hireling)this.Target; Hireling mon = (Hireling)this.Target;
mon.Dead = true; mon.Dead = true;
Task.Delay(10000).ContinueWith(a => {
if (mon.Dead) if (mon.Dead)
{ {
mon.Attributes[GameAttribute.Hitpoints_Cur] = mon.Attributes[GameAttribute.Hitpoints_Max_Total]; mon.Attributes[GameAttribute.Hitpoints_Cur] = mon.Attributes[GameAttribute.Hitpoints_Max_Total];
mon.Attributes.BroadcastChangedIfRevealed(); mon.Attributes.BroadcastChangedIfRevealed();
mon.Dead = false; mon.Dead = false;
} }
});
return; return;
} }
this.Successful = true; this.Successful = true;
@ -153,18 +152,18 @@ namespace DiIiS_NA.GameServer.GSSystem.PowerSystem.Payloads
}); });
((this.Target as NecromancerSkeleton_A).Master as Player).NecroSkeletons.Remove(this.Target); ((this.Target as NecromancerSkeleton_A).Master as Player).NecroSkeletons.Remove(this.Target);
} }
if (this is BaseGolem || if (this.Target is BaseGolem ||
this is IceGolem || this.Target is IceGolem ||
this is BoneGolem || this.Target is BoneGolem ||
this is DecayGolem || this.Target is DecayGolem ||
this is ConsumeFleshGolem || this.Target is ConsumeFleshGolem ||
this is BloodGolem) this.Target is BloodGolem)
{ {
((this.Target as NecromancerSkeleton_A).Master as Player).InGameClient.SendMessage(new MessageSystem.Message.Definitions.Pet.PetDetachMessage() ((this.Target as Minion).Master as Player).InGameClient.SendMessage(new MessageSystem.Message.Definitions.Pet.PetDetachMessage()
{ {
PetId = this.Target.DynamicID(((this.Target as Minion).Master as Player)) PetId = this.Target.DynamicID(((this.Target as Minion).Master as Player))
}); });
((this.Target as NecromancerSkeleton_A).Master as Player).ActiveGolem = null; ((this.Target as Minion).Master as Player).ActiveGolem = null;
} }
if (this.Target is Player) if (this.Target is Player)
{ {

View File

@ -30,11 +30,14 @@ namespace DiIiS_NA.GameServer.MessageSystem.Message.Definitions.Attribute
} }
public override void Encode(GameBitBuffer buffer) public override void Encode(GameBitBuffer buffer)
{
//if (ActorID != 0)
{ {
buffer.WriteUInt(32, ActorID); buffer.WriteUInt(32, ActorID);
Attribute.Encode(buffer); Attribute.Encode(buffer);
Attribute.EncodeValue(buffer); Attribute.EncodeValue(buffer);
} }
}
public override void AsText(StringBuilder b, int pad) public override void AsText(StringBuilder b, int pad)
{ {

View File

@ -33,12 +33,15 @@ namespace DiIiS_NA.GameServer.MessageSystem.Message.Definitions.Attribute
} }
public override void Encode(GameBitBuffer buffer) public override void Encode(GameBitBuffer buffer)
{
//if (ActorID != 0)
{ {
buffer.WriteUInt(32, ActorID); buffer.WriteUInt(32, ActorID);
buffer.WriteInt(4, atKeyVals.Length); buffer.WriteInt(4, atKeyVals.Length);
for (int i = 0; i < atKeyVals.Length; i++) { atKeyVals[i].Encode(buffer); } for (int i = 0; i < atKeyVals.Length; i++) { atKeyVals[i].Encode(buffer); }
for (int i = 0; i < atKeyVals.Length; i++) { atKeyVals[i].EncodeValue(buffer); } for (int i = 0; i < atKeyVals.Length; i++) { atKeyVals[i].EncodeValue(buffer); }
} }
}
public override void AsText(StringBuilder b, int pad) public override void AsText(StringBuilder b, int pad)
{ {

View File

@ -64,4 +64,53 @@ namespace DiIiS_NA.GameServer.MessageSystem.Message.Definitions.Connection
} }
} }
[Message(Opcodes.SpingMessage)]
public class SPingMessage : GameMessage, ISelfHandler
{
public void Handle(GameClient client)
{
client.SendMessage(new SpongMessage()
{
});
}
public override void Parse(GameBitBuffer buffer)
{
}
public override void Encode(GameBitBuffer buffer)
{
}
public override void AsText(StringBuilder b, int pad)
{
}
}
[Message(Opcodes.SpongMessage)]
public class SpongMessage : GameMessage
{
public SpongMessage() : base(Opcodes.PongMessage) { }
public override void Parse(GameBitBuffer buffer)
{
}
public override void Encode(GameBitBuffer buffer)
{
}
public override void AsText(StringBuilder b, int pad)
{
}
}
} }

View File

@ -22,7 +22,7 @@ namespace DiIiS_NA.GameServer.MessageSystem.Message.Definitions.Game
{ {
this.SNOPackHash = snoPacketHash; this.SNOPackHash = snoPacketHash;
this.ProtocolHash = protocol; this.ProtocolHash = protocol;
this.Version = "DiIiS Server - 2.7.1.78185"; this.Version = "DiIiS Server - 2.7.3.82753";
} }
public VersionsMessage() : base(Opcodes.VersionsMessage) { } public VersionsMessage() : base(Opcodes.VersionsMessage) { }

View File

@ -967,7 +967,7 @@ namespace DiIiS_NA.GameServer.MessageSystem
PingMessage = 390, // //SIZE12 PingMessage = 390, // //SIZE12
PongMessage = 391, // //SIZE12 PongMessage = 391, // //SIZE12
SpingMessage = 392, // //SIZE8SimpleMessage62 SpingMessage = 392, // //SIZE8SimpleMessage62
SpongMessagge = 393, // //SIZE8SimpleMessage63 SpongMessage = 393, // //SIZE8SimpleMessage63
ServerNotificationDataMessage = 394, // //SIZE16 ServerNotificationDataMessage = 394, // //SIZE16
BroadcastTextMessage = 395, // //SIZE1032 BroadcastTextMessage = 395, // //SIZE1032
LoadCompleteMessage = 396, // //SIZE8SimpleMessage63 LoadCompleteMessage = 396, // //SIZE8SimpleMessage63

View File

@ -41,60 +41,6 @@ namespace DiIiS_NA.REST.Http
public class HttpHelper public class HttpHelper
{ {
public static byte[] CreateResponse2(HttpCode httpCode, bool closeConnection = false)
{
var sb = new StringBuilder();
//Blizzless Project 2022
using (var sw = new StringWriter(sb))
{
sw.WriteLine($"HTTP/1.1 {(int)httpCode} {httpCode}");
sw.WriteLine($"Date: {DateTime.Now.ToUniversalTime():r}");
sw.WriteLine("Server: Apache");
//sw.WriteLine("Retry-After: 600");
sw.WriteLine($"Content-Length: 0");
//sw.WriteLine("Vary: Accept-Encoding");
sw.WriteLine("[Request URI: https://cdn.discordapp.com/attachments/826902540460490753/830193471871647804/bgs-key-fingerprint");
if (closeConnection)
sw.WriteLine("Connection: close");
sw.WriteLine("Content-Type: text/plain;charset=UTF-8");
//sw.WriteLine("[Request URI: http://eu.depot.battle.net:1119/adff75d57de90974f8e383c2a54ebd3d83838899d938fe33369a4e305f224fa9.bpk]");
//System.IO.File.WriteAllLines(@"C:\WriteLines.txt", lines);
//sw.WriteLine(System.IO.File.ReadAllText("bgs-key-fingerprint"));
}
return Encoding.UTF8.GetBytes(sb.ToString());
}
public static byte[] CreateResponse1(HttpCode httpCode, byte[] content, bool closeConnection = false)
{
var sb = new StringBuilder();
//Blizzless Project 2022
using (var sw = new StringWriter(sb))
{
sw.WriteLine($"HTTP/1.1 {(int)httpCode} {httpCode}");
//sw.WriteLine($"Date: {DateTime.Now.ToUniversalTime():r}");
sw.WriteLine("Server: Apache/2.2.15 (CentOS)");
//sw.WriteLine("Retry-After: 600");
sw.WriteLine($"Content-Length: {content.Length}");
//sw.WriteLine("Vary: Accept-Encoding");
if (closeConnection)
sw.WriteLine("Connection: close");
sw.WriteLine("Content-Type: text/plain;charset=UTF-8");
//sw.WriteLine("[Request URI: http://eu.depot.battle.net:1119/adff75d57de90974f8e383c2a54ebd3d83838899d938fe33369a4e305f224fa9.bpk]");
sw.WriteLine(content);
}
return Encoding.UTF8.GetBytes(sb.ToString() + content);
}
public static byte[] CreateResponseAlt(HttpCode httpCode, string content, bool closeConnection = false) public static byte[] CreateResponseAlt(HttpCode httpCode, string content, bool closeConnection = false)
{ {
@ -103,14 +49,9 @@ using (var sw = new StringWriter(sb))
//Blizzless Project 2022 //Blizzless Project 2022
using (var sw = new StringWriter(sb)) using (var sw = new StringWriter(sb))
{ {
//sw.WriteLine($"HTTP/1.1 404 Not Found");
//sw.WriteLine("Connection: close");
//*
sw.WriteLine($"HTTP/1.1 {(int)httpCode} {httpCode}"); sw.WriteLine($"HTTP/1.1 {(int)httpCode} {httpCode}");
sw.WriteLine("Connection: close"); ; sw.WriteLine("Connection: close"); ;
sw.WriteLine($"Content-Length: 0\r\n"); sw.WriteLine($"Content-Length: 0\r\n");
//*/
//sw.WriteLine();
} }
return Encoding.UTF8.GetBytes(sb.ToString()); return Encoding.UTF8.GetBytes(sb.ToString());
@ -124,13 +65,7 @@ using (var sw = new StringWriter(sb))
using (var sw = new StringWriter(sb)) using (var sw = new StringWriter(sb))
{ {
sw.WriteLine($"HTTP/1.1 {(int)httpCode} {httpCode}"); sw.WriteLine($"HTTP/1.1 {(int)httpCode} {httpCode}");
//sw.WriteLine($"Date: {DateTime.Now.ToUniversalTime():r}");
//sw.WriteLine("Server: Arctium-Emulation");
//sw.WriteLine("Retry-After: 600");
sw.WriteLine($"Content-Length: {content.Length}"); sw.WriteLine($"Content-Length: {content.Length}");
//sw.WriteLine("Vary: Accept-Encoding");
if (closeConnection) if (closeConnection)
sw.WriteLine("Connection: close"); sw.WriteLine("Connection: close");

View File

@ -19,9 +19,6 @@ namespace DiIiS_NA.REST.Manager
{ {
if (!value) if (!value)
{ {
// if (!message.IsEmpty())
// Log.outFatal(LogFilter.Server, message);
throw new Exception(memberName); throw new Exception(memberName);
} }
} }

View File

@ -21,7 +21,6 @@ namespace DiIiS_NA.REST.Manager
int _port = Config.Instance.PORT; int _port = Config.Instance.PORT;
if (_port < 0 || _port > 0xFFFF) if (_port < 0 || _port > 0xFFFF)
{ {
//Log.outError(LogFilter.Network, "Specified login service port ({0}) out of allowed range (1-65535), defaulting to 8081", _port);
_port = 8081; _port = 8081;
} }
@ -29,7 +28,6 @@ namespace DiIiS_NA.REST.Manager
IPAddress address; IPAddress address;
if (!IPAddress.TryParse(configuredAddress, out address)) if (!IPAddress.TryParse(configuredAddress, out address))
{ {
//Log.outError(LogFilter.Network, "Could not resolve LoginREST.ExternalAddress {0}", configuredAddress);
return false; return false;
} }
_externalAddress = new IPEndPoint(address, _port); _externalAddress = new IPEndPoint(address, _port);
@ -37,13 +35,11 @@ namespace DiIiS_NA.REST.Manager
configuredAddress = Config.Instance.IP; configuredAddress = Config.Instance.IP;
if (!IPAddress.TryParse(configuredAddress, out address)) if (!IPAddress.TryParse(configuredAddress, out address))
{ {
//Log.outError(LogFilter.Network, "Could not resolve LoginREST.ExternalAddress {0}", configuredAddress);
return false; return false;
} }
_localAddress = new IPEndPoint(address, _port); _localAddress = new IPEndPoint(address, _port);
// set up form inputs
_formInputs.Type = "LOGIN_FORM"; _formInputs.Type = "LOGIN_FORM";
var input = new FormInput(); var input = new FormInput();

View File

@ -16,7 +16,6 @@ namespace DiIiS_NA.REST.Manager
Acceptor = new AsyncAcceptor(); Acceptor = new AsyncAcceptor();
if (!Acceptor.Start(bindIp, port)) if (!Acceptor.Start(bindIp, port))
{ {
//Log.outError(LogFilter.Network, "StartNetwork failed to Start AsyncAcceptor");
return false; return false;
} }
@ -67,7 +66,7 @@ namespace DiIiS_NA.REST.Manager
} }
catch (Exception err) catch (Exception err)
{ {
//Log.outException(err);
} }
} }

View File

@ -24,7 +24,6 @@ namespace DiIiS_NA.REST.Networking
IPAddress bindIP; IPAddress bindIP;
if (!IPAddress.TryParse(ip, out bindIP)) if (!IPAddress.TryParse(ip, out bindIP))
{ {
//Log.outError(LogFilter.Network, "Server can't be started: Invalid IP-Address ({0})", ip);
return false; return false;
} }
@ -35,7 +34,6 @@ namespace DiIiS_NA.REST.Networking
} }
catch (SocketException ex) catch (SocketException ex)
{ {
//Log.outException(ex);
return false; return false;
} }

View File

@ -53,9 +53,6 @@ namespace DiIiS_NA.REST.Networking
void AddNewSockets() void AddNewSockets()
{ {
//if (_newSockets.Empty())
// return;
foreach (var socket in _newSockets.ToArray()) foreach (var socket in _newSockets.ToArray())
{ {
if (!socket.IsOpen()) if (!socket.IsOpen())
@ -73,14 +70,13 @@ namespace DiIiS_NA.REST.Networking
void Run() void Run()
{ {
//Log.outDebug(LogFilter.Network, "Network Thread Starting");
int sleepTime = 10; int sleepTime = 10;
while (!_stopped) while (!_stopped)
{ {
Thread.Sleep(sleepTime); Thread.Sleep(sleepTime);
uint tickStart = 0;//Time.GetMSTime(); uint tickStart = 0;
AddNewSockets(); AddNewSockets();
@ -99,11 +95,9 @@ namespace DiIiS_NA.REST.Networking
} }
} }
uint diff = 0;//Time.GetMSTimeDiffToNow(tickStart); uint diff = 0;
sleepTime = (int)(diff > 10 ? 0 : 10 - diff); sleepTime = (int)(diff > 10 ? 0 : 10 - diff);
} }
//Log.outDebug(LogFilter.Misc, "Network Thread exits");
_newSockets.Clear(); _newSockets.Clear();
_Sockets.Clear(); _Sockets.Clear();
} }

View File

@ -32,148 +32,7 @@ using DiIiS_NA.GameServer.MessageSystem;
namespace DiIiS_NA.REST namespace DiIiS_NA.REST
{ {
public enum LoginStatements public class RestSession : SocketBase
{
SEL_REALMLIST,
DEL_EXPIRED_IP_BANS,
UPD_EXPIRED_ACCOUNT_BANS,
SEL_IP_INFO,
INS_IP_AUTO_BANNED,
SEL_ACCOUNT_BANNED_ALL,
SEL_ACCOUNT_BANNED_BY_USERNAME,
DEL_ACCOUNT_BANNED,
UPD_ACCOUNT_INFO_CONTINUED_SESSION,
SEL_ACCOUNT_INFO_CONTINUED_SESSION,
UPD_VS,
SEL_ACCOUNT_ID_BY_NAME,
SEL_ACCOUNT_LIST_BY_NAME,
SEL_ACCOUNT_INFO_BY_NAME,
SEL_ACCOUNT_LIST_BY_EMAIL,
SEL_ACCOUNT_BY_IP,
INS_IP_BANNED,
DEL_IP_NOT_BANNED,
SEL_IP_BANNED_ALL,
SEL_IP_BANNED_BY_IP,
SEL_ACCOUNT_BY_ID,
INS_ACCOUNT_BANNED,
UPD_ACCOUNT_NOT_BANNED,
DEL_REALM_CHARACTERS_BY_REALM,
DEL_REALM_CHARACTERS,
INS_REALM_CHARACTERS,
SEL_SUM_REALM_CHARACTERS,
INS_ACCOUNT,
INS_REALM_CHARACTERS_INIT,
UPD_EXPANSION,
UPD_ACCOUNT_LOCK,
UPD_ACCOUNT_LOCK_COUNTRY,
INS_LOG,
UPD_USERNAME,
UPD_PASSWORD,
UPD_EMAIL,
UPD_REG_EMAIL,
UPD_MUTE_TIME,
UPD_MUTE_TIME_LOGIN,
UPD_LAST_IP,
UPD_LAST_ATTEMPT_IP,
UPD_ACCOUNT_ONLINE,
UPD_UPTIME_PLAYERS,
DEL_OLD_LOGS,
DEL_ACCOUNT_ACCESS,
DEL_ACCOUNT_ACCESS_BY_REALM,
INS_ACCOUNT_ACCESS,
GET_ACCOUNT_ID_BY_USERNAME,
GET_ACCOUNT_ACCESS_GMLEVEL,
GET_GMLEVEL_BY_REALMID,
GET_USERNAME_BY_ID,
SEL_CHECK_PASSWORD,
SEL_CHECK_PASSWORD_BY_NAME,
SEL_PINFO,
SEL_PINFO_BANS,
SEL_GM_ACCOUNTS,
SEL_ACCOUNT_INFO,
SEL_ACCOUNT_ACCESS_GMLEVEL_TEST,
SEL_ACCOUNT_ACCESS,
SEL_ACCOUNT_RECRUITER,
SEL_BANS,
SEL_ACCOUNT_WHOIS,
SEL_REALMLIST_SECURITY_LEVEL,
DEL_ACCOUNT,
SEL_IP2NATION_COUNTRY,
SEL_AUTOBROADCAST,
SEL_LAST_ATTEMPT_IP,
SEL_LAST_IP,
GET_EMAIL_BY_ID,
INS_ALDL_IP_LOGGING,
INS_FACL_IP_LOGGING,
INS_CHAR_IP_LOGGING,
INS_FALP_IP_LOGGING,
SEL_ACCOUNT_ACCESS_BY_ID,
SEL_RBAC_ACCOUNT_PERMISSIONS,
INS_RBAC_ACCOUNT_PERMISSION,
DEL_RBAC_ACCOUNT_PERMISSION,
INS_ACCOUNT_MUTE,
SEL_ACCOUNT_MUTE_INFO,
DEL_ACCOUNT_MUTED,
SEL_BNET_AUTHENTICATION,
UPD_BNET_AUTHENTICATION,
SEL_BNET_ACCOUNT_INFO,
UPD_BNET_LAST_LOGIN_INFO,
UPD_BNET_GAME_ACCOUNT_LOGIN_INFO,
SEL_BNET_CHARACTER_COUNTS_BY_ACCOUNT_ID,
SEL_BNET_CHARACTER_COUNTS_BY_BNET_ID,
SEL_BNET_LAST_PLAYER_CHARACTERS,
DEL_BNET_LAST_PLAYER_CHARACTERS,
INS_BNET_LAST_PLAYER_CHARACTERS,
INS_BNET_ACCOUNT,
SEL_BNET_ACCOUNT_EMAIL_BY_ID,
SEL_BNET_ACCOUNT_ID_BY_EMAIL,
UPD_BNET_PASSWORD,
SEL_BNET_ACCOUNT_SALT_BY_ID,
SEL_BNET_CHECK_PASSWORD,
UPD_BNET_ACCOUNT_LOCK,
UPD_BNET_ACCOUNT_LOCK_CONTRY,
SEL_BNET_ACCOUNT_ID_BY_GAME_ACCOUNT,
UPD_BNET_GAME_ACCOUNT_LINK,
SEL_BNET_MAX_ACCOUNT_INDEX,
SEL_BNET_GAME_ACCOUNT_LIST,
UPD_BNET_FAILED_LOGINS,
INS_BNET_ACCOUNT_AUTO_BANNED,
DEL_BNET_EXPIRED_ACCOUNT_BANNED,
UPD_BNET_RESET_FAILED_LOGINS,
SEL_LAST_CHAR_UNDELETE,
UPD_LAST_CHAR_UNDELETE,
SEL_ACCOUNT_TOYS,
REP_ACCOUNT_TOYS,
SEL_BATTLE_PETS,
INS_BATTLE_PETS,
DEL_BATTLE_PETS,
UPD_BATTLE_PETS,
SEL_BATTLE_PET_SLOTS,
INS_BATTLE_PET_SLOTS,
DEL_BATTLE_PET_SLOTS,
SEL_ACCOUNT_HEIRLOOMS,
REP_ACCOUNT_HEIRLOOMS,
SEL_ACCOUNT_MOUNTS,
REP_ACCOUNT_MOUNTS,
SEL_BNET_ITEM_APPEARANCES,
INS_BNET_ITEM_APPEARANCES,
SEL_BNET_ITEM_FAVORITE_APPEARANCES,
INS_BNET_ITEM_FAVORITE_APPEARANCE,
DEL_BNET_ITEM_FAVORITE_APPEARANCE,
MAX_LOGINDATABASE_STATEMENTS
}
public class RestSession : SocketBase//SSLSocket
{ {
public static bool ToGet = false; public static bool ToGet = false;
public static int b = 0; public static int b = 0;
@ -196,20 +55,8 @@ namespace DiIiS_NA.REST
{ {
if (httpRequest.Path == "200") if (httpRequest.Path == "200")
{ {
//HandleLoginRequest(httpRequest);
//SendResponse(HttpCode.OK, Global.Global.SessionMgr.GetFormInput());
}
else if (httpRequest.Path == "/fakeclient/")
{
switch (httpRequest.Method)
{
case "GET":
default:
SendResponseAlt(HttpCode.OK);
break;
} }
}
else if (httpRequest.Path == "/client/alert?targetRegion=ruRU") else if (httpRequest.Path == "/client/alert?targetRegion=ruRU")
{ {
switch (httpRequest.Method) switch (httpRequest.Method)
@ -230,28 +77,6 @@ namespace DiIiS_NA.REST
break; break;
} }
} }
else if (httpRequest.Path == "/shop" || httpRequest.Path == "/D3/ruRU/client/alert?targetRegion=US" || httpRequest.Path == "/D3/ruRU/client/alert?targetRegion=EU")
{
switch (httpRequest.Method)
{
case "GET":
default:
Shop(httpRequest);
break;
}
}
else if (httpRequest.Path == "/key" || httpRequest.Path == "/key/" || httpRequest.Path == "/bgs-key-fingerprint"
|| httpRequest.Path == "/Bnet/zxx/client/bgs-key-fingerprint")
{
switch (httpRequest.Method)
{
case "GET":
default:
Logger.Info("...return bgs-key-fingerprint.");
Key(httpRequest);
break;
}
}
else else
{ {
switch (httpRequest.Method) switch (httpRequest.Method)
@ -271,15 +96,14 @@ namespace DiIiS_NA.REST
public void HandleConnectRequest(HttpHeader request) public void HandleConnectRequest(HttpHeader request)
{ {
// Login form is the same for all clients...
SendResponse(HttpCode.OK, Global.Global.SessionMgr.GetFormInput()); SendResponse(HttpCode.OK, Global.Global.SessionMgr.GetFormInput());
} }
public void HandleInfoRequest(HttpHeader request) public void HandleInfoRequest(HttpHeader request)
{ {
SendResponseHtml(HttpCode.OK, " Welcome to BlizzLess.Net" + //System.Environment.NewLine + SendResponseHtml(HttpCode.OK, "Welcome to BlizzLess.Net" +
"\nBuild " + Program.Build +// + System.Environment.NewLine + "\nBuild " + Program.Build +
"\nSupport: 2.7.1.77744, PTR: 2.7.2.78988"); "\nSupport: 2.7.4");
} }
public static byte[] StringToByteArray(string hex) public static byte[] StringToByteArray(string hex)
@ -290,69 +114,20 @@ namespace DiIiS_NA.REST
.ToArray(); .ToArray();
} }
public void Key(HttpHeader request)
{
//SendBytes(StringToByteArray("485454502f312e3120323030204f4b0d0a5365727665723a204170616368652f322e322e3135202843656e744f53290d0a436f6e74656e742d547970653a20746578742f706c61696e3b20636861727365743d5554462d380d0a582d5661726e6973683a203434393539303836380d0a5669613a20312e31207661726e6973682d76340d0a4163636570742d52616e6765733a2062797465730d0a582d4c4c49443a2032346361623335333637316439643831333564356163346536346561363766640d0a4167653a2032343434390d0a446174653a205361742c2031302041707220323032312030313a31333a343320474d540d0a4c6173742d4d6f6469666965643a205475652c2030322046656220323032312030313a35333a343020474d540d0a436f6e74656e742d4c656e6774683a2033323736310d0a436f6e6e656374696f6e3a206b6565702d616c6976650d0a0d0a"));
//SendResponseAlt(HttpCode.OK);
//SendResponseAlt(HttpCode.OK);
//SendResponseHtmlAlt(HttpCode.OK, System.IO.File.ReadAllText("bgs-key-fingerprint"));
SendResponseHtmlAlt(HttpCode.OK, "");
}
public void Shop(HttpHeader request)
{
SendResponseHtml(HttpCode.OK, " Welcome to BlizzLess.Net" + //System.Environment.NewLine +
"\nBuild " + Program.Build +// + System.Environment.NewLine +
"\nSupport: 2.7.1.77744, PTR: 2.7.2.78988");
}
void SendResponse<T>(HttpCode code, T response) void SendResponse<T>(HttpCode code, T response)
{ {
AsyncWrite(HttpHelper.CreateResponse(code, JSON.Json.CreateString(response))); AsyncWrite(HttpHelper.CreateResponse(code, JSON.Json.CreateString(response)));
} }
void SendBytes(byte[] array)
{
AsyncWrite(array);
}
void SendResponseAlt(HttpCode code)
{
AsyncWrite(HttpHelper.CreateResponse2(code));
}
void SendResponseByte(HttpCode code, byte[] array)
{
AsyncWrite(HttpHelper.CreateResponse1(code, array));
}
void SendResponseHtml(HttpCode code, string response) void SendResponseHtml(HttpCode code, string response)
{ {
AsyncWrite(HttpHelper.CreateResponse(code, response)); AsyncWrite(HttpHelper.CreateResponse(code, response));
} }
void SendResponseHtmlAlt(HttpCode code, string response)
{
AsyncWrite(HttpHelper.CreateResponseAlt(code, response));
//CloseSocket();
}
public override void Start() public override void Start()
{ {
AsyncRead(); AsyncRead();
} }
string CalculateShaPassHash(string name, string password)
{
SHA256 sha256 = SHA256.Create();
var i = sha256.ComputeHash(Encoding.UTF8.GetBytes(name));
return sha256.ComputeHash(Encoding.UTF8.GetBytes(i.ToHexString() + ":" + password)).ToHexString();
}
public void HandleLoginRequest(HttpHeader request) public void HandleLoginRequest(HttpHeader request)
{ {
LogonData loginForm = Json.CreateObject<LogonData>(request.Content); LogonData loginForm = Json.CreateObject<LogonData>(request.Content);
@ -382,10 +157,6 @@ namespace DiIiS_NA.REST
} }
} }
//PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_BNET_AUTHENTICATION);
//stmt.AddValue(0, login);
//SQLResult result = DB.Login.Query(stmt);
bool result = false; bool result = false;
if(AccountManager.GetAccountBySaltTicket(password + " asa " + login.ToLower()) != null) if(AccountManager.GetAccountBySaltTicket(password + " asa " + login.ToLower()) != null)
@ -394,84 +165,8 @@ namespace DiIiS_NA.REST
result = true; result = true;
} }
//result = true; if (result)
if (result)// || loginForm.Inputs.Count == 0)
{ {
#region
/*
uint accountId = result.Read<uint>(0);
string pass_hash = result.Read<string>(1);
uint failedLogins = result.Read<uint>(2);
string loginTicket = result.Read<string>(3);
uint loginTicketExpiry = result.Read<uint>(4);
bool isBanned = result.Read<ulong>(5) != 0;
if (CalculateShaPassHash(login, password) == pass_hash)
{
if (loginTicket.IsEmpty() || loginTicketExpiry < Time.UnixTime)
{
byte[] ticket = new byte[0].GenerateRandomKey(20);
loginTicket = "TC-" + ticket.ToHexString();
}
stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_BNET_AUTHENTICATION);
stmt.AddValue(0, loginTicket);
stmt.AddValue(1, Time.UnixTime + 3600);
stmt.AddValue(2, accountId);
DB.Login.Execute(stmt);
loginResult.LoginTicket = loginTicket;
}
else if (!isBanned)
{
uint maxWrongPassword = ConfigMgr.GetDefaultValue("WrongPass.MaxCount", 0u);
if (ConfigMgr.GetDefaultValue("WrongPass.Logging", false))
Log.outDebug(LogFilter.Network, "[{0}, Account {1}, Id {2}] Attempted to connect with wrong password!", request.Host, login, accountId);
if (maxWrongPassword != 0)
{
SQLTransaction trans = new SQLTransaction();
stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_BNET_FAILED_LOGINS);
stmt.AddValue(0, accountId);
trans.Append(stmt);
++failedLogins;
Log.outDebug(LogFilter.Network, "MaxWrongPass : {0}, failed_login : {1}", maxWrongPassword, accountId);
if (failedLogins >= maxWrongPassword)
{
BanMode banType = ConfigMgr.GetDefaultValue("WrongPass.BanType", BanMode.Ip);
int banTime = ConfigMgr.GetDefaultValue("WrongPass.BanTime", 600);
if (banType == BanMode.Account)
{
stmt = DB.Login.GetPreparedStatement(LoginStatements.INS_BNET_ACCOUNT_AUTO_BANNED);
stmt.AddValue(0, accountId);
}
else
{
stmt = DB.Login.GetPreparedStatement(LoginStatements.INS_IP_AUTO_BANNED);
stmt.AddValue(0, request.Host);
}
stmt.AddValue(1, banTime);
trans.Append(stmt);
stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_BNET_RESET_FAILED_LOGINS);
stmt.AddValue(0, accountId);
trans.Append(stmt);
}
DB.Login.CommitTransaction(trans);
}
}
*/
#endregion
//TODO: Передача уникального тикета
loginResult.AuthenticationState = "DONE"; loginResult.AuthenticationState = "DONE";
SendResponse(HttpCode.OK, loginResult); SendResponse(HttpCode.OK, loginResult);
Logger.Warn("Аутентификация завершена: Логин - {0}. Cоединение с REST разорвано.", login); Logger.Warn("Аутентификация завершена: Логин - {0}. Cоединение с REST разорвано.", login);
@ -484,8 +179,6 @@ namespace DiIiS_NA.REST
SendResponse(HttpCode.BadRequest, loginResult); SendResponse(HttpCode.BadRequest, loginResult);
Logger.Error("Аутентификация неудалась: Логин - {0}. Cоединение с REST разорвано.", login); Logger.Error("Аутентификация неудалась: Логин - {0}. Cоединение с REST разорвано.", login);
} }
//Аутентификация завершена
CloseSocket(); CloseSocket();
} }

View File

@ -1,170 +0,0 @@
//Blizzless Project 2022
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Net;
//Blizzless Project 2022
using System.Net.Security;
//Blizzless Project 2022
using System.Net.Sockets;
//Blizzless Project 2022
using System.Security.Cryptography.X509Certificates;
namespace DiIiS_NA.REST
{
public abstract class SSLSocket : ISocket
{
private static readonly Logger Logger = LogManager.CreateLogger();
protected SSLSocket(Socket socket)
{
_socket = socket;
_remoteAddress = ((IPEndPoint)_socket.RemoteEndPoint).Address;
_remotePort = (ushort)((IPEndPoint)_socket.RemoteEndPoint).Port;
_receiveBuffer = new byte[ushort.MaxValue];
_stream = new SslStream(new NetworkStream(socket), false);
}
public abstract void Start();
public virtual bool Update()
{
return IsOpen();
}
public IPAddress GetRemoteIpAddress()
{
return _remoteAddress;
}
public ushort GetRemotePort()
{
return _remotePort;
}
public void AsyncRead()
{
if (!IsOpen())
return;
try
{
_stream.BeginRead(_receiveBuffer, 0, _receiveBuffer.Length, ReadHandlerInternal, _stream);
}
catch (Exception ex)
{
Logger.ErrorException(ex, "");
}
}
void ReadHandlerInternal(IAsyncResult result)
{
int bytes = 0;
try
{
bytes = _stream.EndRead(result);
}
catch (Exception ex)
{
Logger.ErrorException(ex, "");
}
ReadHandler(bytes);
}
public abstract void ReadHandler(int transferredBytes);
public void AsyncHandshake(X509Certificate2 certificate)
{
try
{
if(certificate == null)
certificate = new X509Certificate2("bnetserver.p12", "123");
_stream.BeginAuthenticateAsServer(certificate, false, true, OnTLSAuthentication, this._stream);
}
catch (Exception ex)
{
Logger.ErrorException(ex, "");
CloseSocket();
return;
}
}
void OnTLSAuthentication(IAsyncResult result)
{
try
{
_stream.EndAuthenticateAsServer(result);
if (_stream.IsEncrypted)
{
Logger.Info("Connection Established.");
AsyncRead();
}
}
catch (Exception e)
{
Logger.FatalException(e, "OnTLSAuthentication() exception: ");
}
}
public void AsyncWrite(byte[] data)
{
if (!IsOpen())
return;
try
{
_stream.Write(data, 0, data.Length);
}
catch (Exception ex)
{
Logger.ErrorException(ex, "");
}
}
public void CloseSocket()
{
try
{
_closed = true;
_socket.Shutdown(SocketShutdown.Both);
_socket.Close();
}
catch (Exception ex)
{
Logger.ErrorException(ex, GetRemoteIpAddress().ToString());
//Log.outDebug(LogFilter.Network, "WorldSocket.CloseSocket: {0} errored when shutting down socket: {1}", GetRemoteIpAddress().ToString(), ex.Message);
}
OnClose();
}
public void SetNoDelay(bool enable)
{
_socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, enable);
}
public virtual void OnClose() { }
public bool IsOpen() { return !_closed; }
public byte[] GetReceiveBuffer()
{
return _receiveBuffer;
}
Socket _socket;
internal SslStream _stream;
byte[] _receiveBuffer;
volatile bool _closed;
IPAddress _remoteAddress;
ushort _remotePort;
}
}

View File

@ -154,7 +154,6 @@ using (var socketEventargs = new SocketAsyncEventArgs())
catch (Exception ex) catch (Exception ex)
{ {
Logger.ErrorException(ex, GetRemoteIpAddress().ToString()); Logger.ErrorException(ex, GetRemoteIpAddress().ToString());
// Log.outDebug(LogFilter.Network, "WorldSocket.CloseSocket: {0} errored when shutting down socket: {1}", GetRemoteIpAddress().ToString(), ex.Message);
} }
OnClose(); OnClose();