2
0
mirror of https://github.com/esiur/esiur-dotnet.git synced 2025-05-06 11:32:59 +00:00
This commit is contained in:
Ahmed Zamil 2020-06-18 02:27:48 +03:00
parent cca00ca97e
commit 8c2d616d62
18 changed files with 379 additions and 164 deletions

View File

@ -37,7 +37,7 @@ namespace Esyur.Stores.EntityCore
public class EntityResource : IResource public class EntityResource : IResource
{ {
[NotMapped] [NotMapped]
internal int _PrimaryId; internal object _PrimaryId;
public event DestroyedEvent OnDestroy; public event DestroyedEvent OnDestroy;
public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangedEventHandler PropertyChanged;

View File

@ -45,7 +45,7 @@ namespace Esyur.Stores.EntityCore
public event DestroyedEvent OnDestroy; public event DestroyedEvent OnDestroy;
Dictionary<Type, Dictionary<int, WeakReference>> DB = new Dictionary<Type, Dictionary<int, WeakReference>>(); Dictionary<Type, Dictionary<object, WeakReference>> DB = new Dictionary<Type, Dictionary<object, WeakReference>>();
internal struct TypeInfo internal struct TypeInfo
{ {
@ -203,7 +203,7 @@ namespace Esyur.Stores.EntityCore
TypesByName.Add(t.ClrType.Name, ti); TypesByName.Add(t.ClrType.Name, ti);
TypesByType.Add(t.ClrType, ti); TypesByType.Add(t.ClrType, ti);
DB.Add(t.ClrType, new Dictionary<int, WeakReference>()); DB.Add(t.ClrType, new Dictionary<object, WeakReference>());
} }
} }

View File

@ -35,15 +35,19 @@ namespace Esyur.Stores.EntityCore
{ {
public static class EsyurExtensions public static class EsyurExtensions
{ {
public static T CreateResource<T>(this DbContext dbContext, object properties = null) where T:class,IResource //public static T CreateResource<T>(this DbContext dbContext, object properties = null) where T:class,IResource
{ //{
return dbContext.GetInfrastructure().CreateResource<T>(properties); // return dbContext.GetInfrastructure().CreateResource<T>(properties);
} //}
public static T CreateResource<T>(this DbSet<T> dbSet, object properties = null) where T:class,IResource public static T AddResource<T>(this DbSet<T> dbSet, object properties = null) where T:class,IResource
{ {
var resource = dbSet.GetInfrastructure().CreateResource<T>(properties); var store = dbSet.GetInfrastructure().GetService<IDbContextOptions>().FindExtension<EsyurExtensionOptions>().Store;
//var resource = dbSet.GetInfrastructure().CreateResource<T>(properties);
//var resource = Warehouse.New<T>("", options.Store, null, null, null, properties);
var resource = Warehouse.New<T>("", null, null, null, null, properties);
dbSet.Add(resource); dbSet.Add(resource);
return resource; return resource;
} }

View File

@ -8,7 +8,7 @@ namespace Esyur.Core
{ {
HostNotReachable, HostNotReachable,
AccessDenied, AccessDenied,
UserNotFound, UserOrTokenNotFound,
ChallengeFailed, ChallengeFailed,
ResourceNotFound, ResourceNotFound,
AttachDenied, AttachDenied,

View File

@ -97,6 +97,10 @@ namespace Esyur.Data
{ {
return Structure.FromStructure((Structure)value, destinationType); return Structure.FromStructure((Structure)value, destinationType);
} }
else if (destinationType.IsEnum)
{
return Enum.ToObject(destinationType, value);
}
else else
{ {
return Convert.ChangeType(value, destinationType); return Convert.ChangeType(value, destinationType);

View File

@ -134,6 +134,16 @@ namespace Esyur.Data
// return dic.Keys.ToArray(); // return dic.Keys.ToArray();
//} //}
public Structure Add(string key, object value)
{
if (dic.ContainsKey(key))
dic[key] = value;
else
dic.Add(key, value);
return this;
}
public object this[string index] public object this[string index]
{ {
get get

View File

@ -0,0 +1,39 @@
using Esyur.Core;
using Esyur.Net.IIP;
using Esyur.Net.Packets;
using Esyur.Resource;
using System;
using System.Collections.Generic;
using System.Text;
namespace Esyur.Net.HTTP
{
public class IIPoHTTP : HTTPFilter
{
[Attribute]
EntryPoint EntryPoint { get; set; }
public override bool Execute(HTTPConnection sender)
{
if (sender.Request.URL != "iip")
return false;
IIPPacket.IIPPacketAction action = (IIPPacket.IIPPacketAction)Convert.ToByte(sender.Request.Query["a"]);
if (action == IIPPacket.IIPPacketAction.QueryLink)
{
EntryPoint.Query(sender.Request.Query["l"], null).Then(x =>
{
});
}
return true;
}
public override AsyncReply<bool> Trigger(ResourceTrigger trigger)
{
return new AsyncReply<bool>(true);
}
}
}

View File

@ -67,7 +67,7 @@ namespace Esyur.Net.IIP
AsyncReply<bool> openReply; AsyncReply<bool> openReply;
byte[] localPassword; byte[] localPasswordOrToken;
byte[] localNonce, remoteNonce; byte[] localNonce, remoteNonce;
bool ready, readyToEstablish; bool ready, readyToEstablish;
@ -256,13 +256,34 @@ namespace Esyur.Net.IIP
//this.localUsername = username; //this.localUsername = username;
session.LocalAuthentication.Domain = domain; session.LocalAuthentication.Domain = domain;
session.LocalAuthentication.Username = username; session.LocalAuthentication.Username = username;
this.localPassword = DC.ToBytes(password); session.LocalAuthentication.Method = AuthenticationMethod.Credentials;
this.localPasswordOrToken = DC.ToBytes(password);
init(); init();
Assign(socket); Assign(socket);
} }
public DistributedConnection(ISocket socket, string domain, ulong tokenIndex, string token)
{
this.session = new Session(new ClientAuthentication()
, new HostAuthentication());
//Instance.Name = Global.GenerateCode(12);
//this.hostType = AuthenticationType.Client;
//this.domain = domain;
//this.localUsername = username;
session.LocalAuthentication.Domain = domain;
session.LocalAuthentication.TokenIndex = tokenIndex;
session.LocalAuthentication.Method = AuthenticationMethod.Token;
this.localPasswordOrToken = DC.ToBytes(token);
init();
Assign(socket);
}
/// <summary> /// <summary>
/// Create a new instance of a distributed connection /// Create a new instance of a distributed connection
/// </summary> /// </summary>
@ -595,7 +616,9 @@ namespace Esyur.Net.IIP
{ {
if (authPacket.Command == IIPAuthPacket.IIPAuthPacketCommand.Declare) if (authPacket.Command == IIPAuthPacket.IIPAuthPacketCommand.Declare)
{ {
if (authPacket.RemoteMethod == IIPAuthPacket.IIPAuthPacketMethod.Credentials && authPacket.LocalMethod == IIPAuthPacket.IIPAuthPacketMethod.None) session.RemoteAuthentication.Method = authPacket.RemoteMethod;
if (authPacket.RemoteMethod == AuthenticationMethod.Credentials && authPacket.LocalMethod == AuthenticationMethod.None)
{ {
Server.Membership.UserExists(authPacket.RemoteUsername, authPacket.Domain).Then(x => Server.Membership.UserExists(authPacket.RemoteUsername, authPacket.Domain).Then(x =>
{ {
@ -614,54 +637,95 @@ namespace Esyur.Net.IIP
{ {
//Console.WriteLine("User not found"); //Console.WriteLine("User not found");
SendParams().AddUInt8(0xc0) SendParams().AddUInt8(0xc0)
.AddUInt8((byte)ExceptionCode.UserNotFound) .AddUInt8((byte)ExceptionCode.UserOrTokenNotFound)
.AddUInt16(14) .AddUInt16(14)
.AddString("User not found").Done(); .AddString("User not found").Done();
} }
}); });
} }
else if (authPacket.RemoteMethod == AuthenticationMethod.Token && authPacket.LocalMethod == AuthenticationMethod.None)
{
// Check if user and token exists
Server.Membership.TokenExists(authPacket.RemoteTokenIndex, authPacket.Domain).Then(x =>
{
if (x != null)
{
session.RemoteAuthentication.Username = x;
session.RemoteAuthentication.TokenIndex = authPacket.RemoteTokenIndex;
remoteNonce = authPacket.RemoteNonce;
session.RemoteAuthentication.Domain = authPacket.Domain;
SendParams()
.AddUInt8(0xa0)
.AddUInt8Array(localNonce)
.Done();
}
else
{
//Console.WriteLine("User not found");
SendParams().AddUInt8(0xc0)
.AddUInt8((byte)ExceptionCode.UserOrTokenNotFound)
.AddUInt16(15)
.AddString("Token not found").Done();
}
});
}
} }
else if (authPacket.Command == IIPAuthPacket.IIPAuthPacketCommand.Action) else if (authPacket.Command == IIPAuthPacket.IIPAuthPacketCommand.Action)
{ {
if (authPacket.Action == IIPAuthPacket.IIPAuthPacketAction.AuthenticateHash) if (authPacket.Action == IIPAuthPacket.IIPAuthPacketAction.AuthenticateHash)
{ {
var remoteHash = authPacket.Hash; var remoteHash = authPacket.Hash;
AsyncReply<byte[]> reply = null;
Server.Membership.GetPassword(session.RemoteAuthentication.Username, if (session.RemoteAuthentication.Method == AuthenticationMethod.Credentials)
session.RemoteAuthentication.Domain).Then((pw) => {
{ reply = Server.Membership.GetPassword(session.RemoteAuthentication.Username,
if (pw != null) session.RemoteAuthentication.Domain);
{ }
var hashFunc = SHA256.Create(); else if (session.RemoteAuthentication.Method == AuthenticationMethod.Token)
//var hash = hashFunc.ComputeHash(BinaryList.ToBytes(pw, remoteNonce, localNonce)); {
var hash = hashFunc.ComputeHash((new BinaryList()) reply = Server.Membership.GetToken(session.RemoteAuthentication.TokenIndex,
.AddUInt8Array(pw) session.RemoteAuthentication.Domain);
.AddUInt8Array(remoteNonce) }
.AddUInt8Array(localNonce) else
.ToArray()); {
if (hash.SequenceEqual(remoteHash)) // Error
{ }
// send our hash
//var localHash = hashFunc.ComputeHash(BinaryList.ToBytes(localNonce, remoteNonce, pw));
//SendParams((byte)0, localHash);
var localHash = hashFunc.ComputeHash((new BinaryList()).AddUInt8Array(localNonce).AddUInt8Array(remoteNonce).AddUInt8Array(pw).ToArray()); reply.Then((pw) =>
SendParams().AddUInt8(0).AddUInt8Array(localHash).Done(); {
if (pw != null)
{
var hashFunc = SHA256.Create();
//var hash = hashFunc.ComputeHash(BinaryList.ToBytes(pw, remoteNonce, localNonce));
var hash = hashFunc.ComputeHash((new BinaryList())
.AddUInt8Array(pw)
.AddUInt8Array(remoteNonce)
.AddUInt8Array(localNonce)
.ToArray());
if (hash.SequenceEqual(remoteHash))
{
// send our hash
//var localHash = hashFunc.ComputeHash(BinaryList.ToBytes(localNonce, remoteNonce, pw));
//SendParams((byte)0, localHash);
readyToEstablish = true; var localHash = hashFunc.ComputeHash((new BinaryList()).AddUInt8Array(localNonce).AddUInt8Array(remoteNonce).AddUInt8Array(pw).ToArray());
} SendParams().AddUInt8(0).AddUInt8Array(localHash).Done();
else
{ readyToEstablish = true;
//Global.Log("auth", LogType.Warning, "U:" + RemoteUsername + " IP:" + Socket.RemoteEndPoint.Address.ToString() + " S:DENIED"); }
SendParams().AddUInt8(0xc0) else
.AddUInt8((byte)ExceptionCode.AccessDenied) {
.AddUInt16(13) //Global.Log("auth", LogType.Warning, "U:" + RemoteUsername + " IP:" + Socket.RemoteEndPoint.Address.ToString() + " S:DENIED");
.AddString("Access Denied") SendParams().AddUInt8(0xc0)
.Done(); .AddUInt8((byte)ExceptionCode.AccessDenied)
} .AddUInt16(13)
} .AddString("Access Denied")
}); .Done();
}
}
});
} }
else if (authPacket.Action == IIPAuthPacket.IIPAuthPacketAction.NewConnection) else if (authPacket.Action == IIPAuthPacket.IIPAuthPacketAction.NewConnection)
{ {
@ -697,7 +761,7 @@ namespace Esyur.Net.IIP
var hashFunc = SHA256.Create(); var hashFunc = SHA256.Create();
//var localHash = hashFunc.ComputeHash(BinaryList.ToBytes(localPassword, localNonce, remoteNonce)); //var localHash = hashFunc.ComputeHash(BinaryList.ToBytes(localPassword, localNonce, remoteNonce));
var localHash = hashFunc.ComputeHash(new BinaryList() var localHash = hashFunc.ComputeHash(new BinaryList()
.AddUInt8Array(localPassword) .AddUInt8Array(localPasswordOrToken)
.AddUInt8Array(localNonce) .AddUInt8Array(localNonce)
.AddUInt8Array(remoteNonce) .AddUInt8Array(remoteNonce)
.ToArray()); .ToArray());
@ -719,7 +783,7 @@ namespace Esyur.Net.IIP
var remoteHash = hashFunc.ComputeHash(new BinaryList() var remoteHash = hashFunc.ComputeHash(new BinaryList()
.AddUInt8Array(remoteNonce) .AddUInt8Array(remoteNonce)
.AddUInt8Array(localNonce) .AddUInt8Array(localNonce)
.AddUInt8Array(localPassword) .AddUInt8Array(localPasswordOrToken)
.ToArray()); .ToArray());
@ -810,6 +874,12 @@ namespace Esyur.Net.IIP
[Attribute] [Attribute]
public string Password { get; set; } public string Password { get; set; }
[Attribute]
public string Token { get; set; }
[Attribute]
public ulong TokenIndex { get; set; }
[Attribute] [Attribute]
public string Domain { get; set; } public string Domain { get; set; }
/// <summary> /// <summary>
@ -830,12 +900,23 @@ namespace Esyur.Net.IIP
var address = host[0]; var address = host[0];
var port = ushort.Parse(host[1]); var port = ushort.Parse(host[1]);
var username = Username;// Instance.Attributes["username"].ToString();
var domain = Domain != null ? Domain : address;// Instance.Attributes.ContainsKey("domain") ? Instance.Attributes["domain"].ToString() : address; var domain = Domain != null ? Domain : address;
return Connect(null, address, port, username, DC.ToBytes(Password), domain); return Connect(AuthenticationMethod.Credentials, null, address, port, Username, 0, DC.ToBytes(Password), domain);
}
else if (Token != null)
{
var host = Instance.Name.Split(':');
var address = host[0];
var port = ushort.Parse(host[1]);
var domain = Domain != null ? Domain : address;
return Connect(AuthenticationMethod.Token, null, address, port, null, TokenIndex, DC.ToBytes(Token), domain);
} }
} }
@ -867,7 +948,7 @@ namespace Esyur.Net.IIP
x.Suspend(); x.Suspend();
} }
public AsyncReply<bool> Connect(ISocket socket = null, string hostname = null, ushort port = 0, string username = null, byte[] password = null, string domain = null) public AsyncReply<bool> Connect(AuthenticationMethod method = AuthenticationMethod.Certificate, ISocket socket = null, string hostname = null, ushort port = 0, string username = null, ulong tokenIndex = 0, byte[] passwordOrToken = null, string domain = null)
{ {
if (openReply != null) if (openReply != null)
throw new AsyncException(ErrorType.Exception, 0, "Connection in progress"); throw new AsyncException(ErrorType.Exception, 0, "Connection in progress");
@ -879,9 +960,12 @@ namespace Esyur.Net.IIP
session = new Session(new ClientAuthentication() session = new Session(new ClientAuthentication()
, new HostAuthentication()); , new HostAuthentication());
session.LocalAuthentication.Method = method;
session.LocalAuthentication.TokenIndex = tokenIndex;
session.LocalAuthentication.Domain = domain; session.LocalAuthentication.Domain = domain;
session.LocalAuthentication.Username = username; session.LocalAuthentication.Username = username;
localPassword = password; localPasswordOrToken = passwordOrToken;
//localPassword = password;
} }
if (session == null) if (session == null)
@ -933,7 +1017,7 @@ namespace Esyur.Net.IIP
} }
} }
} }
catch catch
{ {
return false; return false;
} }

View File

@ -282,7 +282,7 @@ namespace Esyur.Net
try try
{ {
if (sock == null) if (sock == null)
{ {
Console.Write("sock == null"); Console.Write("sock == null");
@ -295,6 +295,7 @@ namespace Esyur.Net
c.Assign(sock); c.Assign(sock);
try try
{ {
ClientConnected(c); ClientConnected(c);
@ -304,10 +305,10 @@ namespace Esyur.Net
// something wrong with the child. // something wrong with the child.
} }
sock.Begin();
// Accept more // Accept more
//listener.Accept().Then(NewConnection); //listener.Accept().Then(NewConnection);
sock.Begin();
} }

View File

@ -23,6 +23,7 @@ SOFTWARE.
*/ */
using Esyur.Data; using Esyur.Data;
using Esyur.Security.Authority;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -34,7 +35,7 @@ namespace Esyur.Net.Packets
{ {
class IIPAuthPacket : Packet class IIPAuthPacket : Packet
{ {
public enum IIPAuthPacketCommand: byte public enum IIPAuthPacketCommand : byte
{ {
Action = 0, Action = 0,
Declare, Declare,
@ -42,7 +43,7 @@ namespace Esyur.Net.Packets
Error, Error,
} }
public enum IIPAuthPacketAction: byte public enum IIPAuthPacketAction : byte
{ {
// Authenticate // Authenticate
AuthenticateHash, AuthenticateHash,
@ -61,13 +62,6 @@ namespace Esyur.Net.Packets
} }
public enum IIPAuthPacketMethod: byte
{
None,
Certificate,
Credentials,
Token
}
public IIPAuthPacketCommand Command public IIPAuthPacketCommand Command
@ -84,7 +78,7 @@ namespace Esyur.Net.Packets
public byte ErrorCode { get; set; } public byte ErrorCode { get; set; }
public string ErrorMessage { get; set; } public string ErrorMessage { get; set; }
public IIPAuthPacketMethod LocalMethod public AuthenticationMethod LocalMethod
{ {
get; get;
set; set;
@ -108,7 +102,7 @@ namespace Esyur.Net.Packets
set; set;
} }
public IIPAuthPacketMethod RemoteMethod public AuthenticationMethod RemoteMethod
{ {
get; get;
set; set;
@ -122,7 +116,7 @@ namespace Esyur.Net.Packets
public long CertificateId public long CertificateId
{ {
get;set; get; set;
} }
public string LocalUsername public string LocalUsername
@ -178,6 +172,8 @@ namespace Esyur.Net.Packets
set; set;
} }
public ulong RemoteTokenIndex { get; set; }
private uint dataLengthNeeded; private uint dataLengthNeeded;
bool NotEnough(uint offset, uint ends, uint needed) bool NotEnough(uint offset, uint ends, uint needed)
@ -193,7 +189,7 @@ namespace Esyur.Net.Packets
public override string ToString() public override string ToString()
{ {
return Command.ToString() + " " + Action.ToString(); return Command.ToString() + " " + Action.ToString();
} }
public override long Parse(byte[] data, uint offset, uint ends) public override long Parse(byte[] data, uint offset, uint ends)
@ -260,8 +256,8 @@ namespace Esyur.Net.Packets
} }
else if (Command == IIPAuthPacketCommand.Declare) else if (Command == IIPAuthPacketCommand.Declare)
{ {
RemoteMethod = (IIPAuthPacketMethod)((data[offset] >> 4) & 0x3); RemoteMethod = (AuthenticationMethod)((data[offset] >> 4) & 0x3);
LocalMethod = (IIPAuthPacketMethod)((data[offset] >> 2) & 0x3); LocalMethod = (AuthenticationMethod)((data[offset] >> 2) & 0x3);
var encrypt = ((data[offset++] & 0x2) == 0x2); var encrypt = ((data[offset++] & 0x2) == 0x2);
@ -277,11 +273,11 @@ namespace Esyur.Net.Packets
Domain = domain; Domain = domain;
offset += domainLength; offset += domainLength;
if (RemoteMethod == IIPAuthPacketMethod.Credentials)
if (RemoteMethod == AuthenticationMethod.Credentials)
{ {
if (LocalMethod == IIPAuthPacketMethod.None) if (LocalMethod == AuthenticationMethod.None)
{ {
if (NotEnough(offset, ends, 33)) if (NotEnough(offset, ends, 33))
return -dataLengthNeeded; return -dataLengthNeeded;
@ -293,18 +289,33 @@ namespace Esyur.Net.Packets
RemoteNonce = data.Clip(offset, 32); RemoteNonce = data.Clip(offset, 32);
offset += 32; offset += 32;
var length = data[offset++]; var length = data[offset++];
if (NotEnough(offset, ends, length)) if (NotEnough(offset, ends, length))
return -dataLengthNeeded; return -dataLengthNeeded;
RemoteUsername = data.GetString(offset, length); RemoteUsername = data.GetString(offset, length);
offset += length; offset += length;
} }
} }
else if (RemoteMethod == AuthenticationMethod.Token)
{
if (LocalMethod == AuthenticationMethod.None)
{
if (NotEnough(offset, ends, 37))
return -dataLengthNeeded;
RemoteNonce = data.Clip(offset, 32);
offset += 32;
RemoteTokenIndex = data.GetUInt64(offset);
offset += 8;
}
}
if (encrypt) if (encrypt)
{ {
@ -329,31 +340,26 @@ namespace Esyur.Net.Packets
} }
else if (Command == IIPAuthPacketCommand.Acknowledge) else if (Command == IIPAuthPacketCommand.Acknowledge)
{ {
RemoteMethod = (IIPAuthPacketMethod)((data[offset] >> 4) & 0x3); RemoteMethod = (AuthenticationMethod)((data[offset] >> 4) & 0x3);
LocalMethod = (IIPAuthPacketMethod)((data[offset] >> 2) & 0x3); LocalMethod = (AuthenticationMethod)((data[offset] >> 2) & 0x3);
var encrypt = ((data[offset++] & 0x2) == 0x2); var encrypt = ((data[offset++] & 0x2) == 0x2);
if (NotEnough(offset, ends, 1)) if (NotEnough(offset, ends, 1))
return -dataLengthNeeded; return -dataLengthNeeded;
if (RemoteMethod == IIPAuthPacketMethod.Credentials) if (RemoteMethod == AuthenticationMethod.Credentials
|| RemoteMethod == AuthenticationMethod.Token)
{ {
if (LocalMethod == IIPAuthPacketMethod.None) if (LocalMethod == AuthenticationMethod.None)
{ {
if (NotEnough(offset, ends, 32)) if (NotEnough(offset, ends, 32))
return -dataLengthNeeded; return -dataLengthNeeded;
/*
var remoteNonce = new byte[32];
Buffer.BlockCopy(data, (int)offset, remoteNonce, 0, 32);
RemoteNonce = remoteNonce;
*/
RemoteNonce = data.Clip(offset, 32); RemoteNonce = data.Clip(offset, 32);
offset += 32; offset += 32;
} }
} }
if (encrypt) if (encrypt)
@ -385,7 +391,7 @@ namespace Esyur.Net.Packets
offset++; offset++;
ErrorCode = data[offset++]; ErrorCode = data[offset++];
var cl = data.GetUInt16(offset); var cl = data.GetUInt16(offset);
offset += 2; offset += 2;
@ -403,4 +409,4 @@ namespace Esyur.Net.Packets
} }
} }
} }

View File

@ -42,7 +42,7 @@ namespace Esyur.Net.Sockets
public delegate void ISocketConnectEvent(); public delegate void ISocketConnectEvent();
public delegate void ISocketCloseEvent(); public delegate void ISocketCloseEvent();
public interface ISocket: IDestructible public interface ISocket : IDestructible
{ {
SocketState State { get; } SocketState State { get; }
@ -57,6 +57,7 @@ namespace Esyur.Net.Sockets
void Close(); void Close();
AsyncReply<bool> Connect(string hostname, ushort port); AsyncReply<bool> Connect(string hostname, ushort port);
bool Begin(); bool Begin();
AsyncReply<bool> BeginAsync();
//ISocket Accept(); //ISocket Accept();
AsyncReply<ISocket> AcceptAsync(); AsyncReply<ISocket> AcceptAsync();
ISocket Accept(); ISocket Accept();

View File

@ -76,21 +76,19 @@ namespace Esyur.Net.Sockets
{ {
var rt = new AsyncReply<bool>(); var rt = new AsyncReply<bool>();
this.hostname = hostname;
this.server = false;
state = SocketState.Connecting; state = SocketState.Connecting;
await sock.ConnectAsync(hostname, port); await sock.ConnectAsync(hostname, port);
if (server)
await ssl.AuthenticateAsServerAsync(cert);
else
await ssl.AuthenticateAsClientAsync(hostname);
try try
{ {
await BeginAsync();
state = SocketState.Established; state = SocketState.Established;
OnConnect?.Invoke(); OnConnect?.Invoke();
if (!server)
Begin();
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -135,11 +133,28 @@ namespace Esyur.Net.Sockets
private void SendCallback(IAsyncResult ar) private void SendCallback(IAsyncResult ar)
{ {
if (ar != null && ar.AsyncState != null) if (ar != null)
((AsyncReply<bool>)ar.AsyncState).Trigger(true); {
try
{
ssl.EndWrite(ar);
if (ar.AsyncState != null)
((AsyncReply<bool>)ar.AsyncState).Trigger(true);
}
catch
{
if (state != SocketState.Closed && !sock.Connected)
{
state = SocketState.Terminated;
Close();
}
}
}
lock (sendLock) lock (sendLock)
{ {
if (sendBufferQueue.Count > 0) if (sendBufferQueue.Count > 0)
{ {
var kv = sendBufferQueue.Dequeue(); var kv = sendBufferQueue.Dequeue();
@ -151,10 +166,10 @@ namespace Esyur.Net.Sockets
catch (Exception ex) catch (Exception ex)
{ {
asyncSending = false; asyncSending = false;
try try
{ {
kv.Key.Trigger(false); if (kv.Key != null)
kv.Key.Trigger(false);
if (state != SocketState.Closed && !sock.Connected) if (state != SocketState.Closed && !sock.Connected)
{ {
@ -167,7 +182,7 @@ namespace Esyur.Net.Sockets
state = SocketState.Terminated; state = SocketState.Terminated;
} }
Global.Log("TCPSocket", LogType.Error, ex.ToString()); //Global.Log("TCPSocket", LogType.Error, ex.ToString());
} }
} }
else else
@ -223,39 +238,41 @@ namespace Esyur.Net.Sockets
public SSLSocket(Socket Socket, X509Certificate2 certificate, bool authenticateAsServer) public SSLSocket(Socket socket, X509Certificate2 certificate, bool authenticateAsServer)
{ {
cert = certificate; cert = certificate;
sock = Socket; sock = socket;
receiveBuffer = new byte[sock.ReceiveBufferSize]; receiveBuffer = new byte[sock.ReceiveBufferSize];
ssl = new SslStream(new NetworkStream(sock)); ssl = new SslStream(new NetworkStream(sock));
server = authenticateAsServer; server = authenticateAsServer;
if (socket.Connected)
state = SocketState.Established;
} }
public void Close() public void Close()
{ {
if (state != SocketState.Closed && state != SocketState.Terminated) if (state != SocketState.Closed && state != SocketState.Terminated)
{
state = SocketState.Closed; state = SocketState.Closed;
if (sock.Connected) if (sock.Connected)
{
try
{ {
sock.Shutdown(SocketShutdown.Both); try
} {
catch sock.Shutdown(SocketShutdown.Both);
{ }
state = SocketState.Terminated; catch
{
state = SocketState.Terminated;
}
} }
OnClose?.Invoke();
} }
sock.Shutdown(SocketShutdown.Both);
OnClose?.Invoke();
} }
@ -351,6 +368,7 @@ namespace Esyur.Net.Sockets
// } // }
//} //}
public bool Begin() public bool Begin()
{ {
if (began) if (began)
@ -358,6 +376,11 @@ namespace Esyur.Net.Sockets
began = true; began = true;
if (server)
ssl.AuthenticateAsServer(cert);
else
ssl.AuthenticateAsClient(hostname);
if (state == SocketState.Established) if (state == SocketState.Established)
{ {
ssl.BeginRead(receiveBuffer, 0, receiveBuffer.Length, ReceiveCallback, this); ssl.BeginRead(receiveBuffer, 0, receiveBuffer.Length, ReceiveCallback, this);
@ -367,6 +390,26 @@ namespace Esyur.Net.Sockets
return false; return false;
} }
public async AsyncReply<bool> BeginAsync()
{
if (began)
return false;
began = true;
if (server)
await ssl.AuthenticateAsServerAsync(cert);
else
await ssl.AuthenticateAsClientAsync(hostname);
if (state == SocketState.Established)
{
ssl.BeginRead(receiveBuffer, 0, receiveBuffer.Length, ReceiveCallback, this);
return true;
}
else
return false;
}
private void ReceiveCallback(IAsyncResult results) private void ReceiveCallback(IAsyncResult results)
{ {
@ -398,7 +441,7 @@ namespace Esyur.Net.Sockets
Close(); Close();
} }
Global.Log("SSLSocket", LogType.Error, ex.ToString()); //Global.Log("SSLSocket", LogType.Error, ex.ToString());
} }
} }
@ -426,7 +469,7 @@ namespace Esyur.Net.Sockets
return null; return null;
} }
} }
public void Hold() public void Hold()
{ {
@ -441,7 +484,7 @@ namespace Esyur.Net.Sockets
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine(ex); Global.Log(ex);
} }
finally finally
{ {

View File

@ -65,6 +65,11 @@ namespace Esyur.Net.Sockets
SocketAsyncEventArgs socketArgs = new SocketAsyncEventArgs(); SocketAsyncEventArgs socketArgs = new SocketAsyncEventArgs();
public async AsyncReply<bool> BeginAsync()
{
return Begin();
}
public bool Begin() public bool Begin()
{ {
if (began) if (began)
@ -74,7 +79,7 @@ namespace Esyur.Net.Sockets
socketArgs.SetBuffer(receiveBuffer, 0, receiveBuffer.Length); socketArgs.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
socketArgs.Completed += SocketArgs_Completed; socketArgs.Completed += SocketArgs_Completed;
if (!sock.ReceiveAsync(socketArgs)) if (!sock.ReceiveAsync(socketArgs))
SocketArgs_Completed(null, socketArgs); SocketArgs_Completed(null, socketArgs);
@ -176,8 +181,8 @@ namespace Esyur.Net.Sockets
if (State != SocketState.Established) if (State != SocketState.Established)
return; return;
if (e.BytesTransferred < 0) //if (e.BytesTransferred < 0)
Console.WriteLine("BytesTransferred is less than zero"); // Console.WriteLine("BytesTransferred is less than zero");
if (e.BytesTransferred <= 0) if (e.BytesTransferred <= 0)
{ {
@ -185,8 +190,8 @@ namespace Esyur.Net.Sockets
return; return;
} }
if (e.BytesTransferred > 100000) //if (e.BytesTransferred > 100000)
Console.WriteLine("BytesTransferred is large " + e.BytesTransferred); // Console.WriteLine("BytesTransferred is large " + e.BytesTransferred);
recCount = e.BytesTransferred > e.Count ? e.Count : e.BytesTransferred; recCount = e.BytesTransferred > e.Count ? e.Count : e.BytesTransferred;
@ -382,8 +387,24 @@ namespace Esyur.Net.Sockets
private void SendCallback(IAsyncResult ar) private void SendCallback(IAsyncResult ar)
{ {
if (ar != null && ar.AsyncState != null) if (ar != null)
((AsyncReply<bool>)ar.AsyncState).Trigger(true); {
try
{
sock.EndSend(ar);
if (ar.AsyncState != null)
((AsyncReply<bool>)ar.AsyncState).Trigger(true);
}
catch
{
if (state != SocketState.Closed && !sock.Connected)
{
state = SocketState.Terminated;
Close();
}
}
}
lock (sendLock) lock (sendLock)
{ {
@ -401,7 +422,8 @@ namespace Esyur.Net.Sockets
try try
{ {
kv.Key.Trigger(false); if (kv.Key != null)
kv.Key.Trigger(false);
if (state != SocketState.Closed && !sock.Connected) if (state != SocketState.Closed && !sock.Connected)
{ {

View File

@ -322,5 +322,10 @@ namespace Esyur.Net.Sockets
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public AsyncReply<bool> BeginAsync()
{
return sock.BeginAsync();
}
} }
} }

View File

@ -71,10 +71,14 @@ namespace Esyur.Proxy
select p; select p;
#endif #endif
var assemblyName = new AssemblyName("Esyur.Proxy.T." + type.Namespace); var assemblyName = new AssemblyName("Esyur.Proxy.T." + type.Assembly.GetName().Name);// type.Namespace);
assemblyName.Version = type.Assembly.GetName().Version;
assemblyName.CultureInfo = type.Assembly.GetName().CultureInfo;
//assemblyName.SetPublicKeyToken(null);
var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name); var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);
var typeName = Assembly.CreateQualifiedName(assemblyName.FullName, type.Name); var typeName = "Esyur.Proxy.T." + type.FullName;// Assembly.CreateQualifiedName(assemblyName.FullName, "Esyur.Proxy.T." + type.FullName);
var typeBuilder = moduleBuilder.DefineType(typeName, var typeBuilder = moduleBuilder.DefineType(typeName,
TypeAttributes.Public | TypeAttributes.Class, type); TypeAttributes.Public | TypeAttributes.Class, type);

View File

@ -27,16 +27,20 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using static Esyur.Net.Packets.IIPAuthPacket;
namespace Esyur.Security.Authority namespace Esyur.Security.Authority
{ {
public class Authentication public class Authentication
{ {
AuthenticationType type; AuthenticationType type;
public AuthenticationMethod Method { get; set; }
public ulong TokenIndex { get; set; }
public string Username { get; set; } public string Username { get; set; }
public Certificate Certificate { get; set; } public Certificate Certificate { get; set; }
public string Domain { get; set; } public string Domain { get; set; }
public string FullName => Username + "@" + Domain; public string FullName => Username + "@" + Domain;

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Esyur.Security.Authority
{
public enum AuthenticationMethod : byte
{
None,
Certificate,
Credentials,
Token
}
}

View File

@ -35,40 +35,14 @@ using Esyur.Resource;
namespace Esyur.Security.Membership namespace Esyur.Security.Membership
{ {
public interface IMembership:IResource public interface IMembership : IResource
{ {
//IUser[] GetUsers(QueryFilter<string> user);
//bool AddCertificate(Certificate certificate);
//CACertificate[] GetCACertificates(string authority);
//UserCertificate[] GetUserCertificate(string user, string domain);
//DomainCertificate[] GetDomainCertificates(string domain);
AsyncReply<bool> UserExists(string username, string domain); AsyncReply<bool> UserExists(string username, string domain);
AsyncReply<byte[]> GetPassword(string username, string domain); AsyncReply<byte[]> GetPassword(string username, string domain);
AsyncReply<byte[]> GetToken(ulong TokenIndex, string domain);
AsyncReply<bool> Login(Session session); AsyncReply<bool> Login(Session session);
AsyncReply<bool> Logout(Session session); AsyncReply<bool> Logout(Session session);
//ClientAuthentication Authenticate(string username, byte[] credentials, int flag); AsyncReply<string> TokenExists(ulong tokenIndex, string domain);
//HostAuthentication Authenticate(DomainCertificate domainCertificate);
//CoHostAuthentication Authenticate(DomainCertificate hostCertificate, int hostId);
/*
object GetUserInfo(User user, string field);
object[] GetUserInfo(User user, string[] fields);
bool SetUserInfo(User user, string field, object value);
bool SetUserInfo(User user, KeyList<string, object> info);
*/
//bool AddUser(User user, KeyList<string, object> info);
//bool RemoveUser(string username);
} }
} }