diff --git a/Esyur.Stores.EntityCore/EntityResource.cs b/Esyur.Stores.EntityCore/EntityResource.cs index 6aa9721..a2aa464 100644 --- a/Esyur.Stores.EntityCore/EntityResource.cs +++ b/Esyur.Stores.EntityCore/EntityResource.cs @@ -37,7 +37,7 @@ namespace Esyur.Stores.EntityCore public class EntityResource : IResource { [NotMapped] - internal int _PrimaryId; + internal object _PrimaryId; public event DestroyedEvent OnDestroy; public event PropertyChangedEventHandler PropertyChanged; diff --git a/Esyur.Stores.EntityCore/EntityStore.cs b/Esyur.Stores.EntityCore/EntityStore.cs index d042875..3b7f1b5 100644 --- a/Esyur.Stores.EntityCore/EntityStore.cs +++ b/Esyur.Stores.EntityCore/EntityStore.cs @@ -45,7 +45,7 @@ namespace Esyur.Stores.EntityCore public event DestroyedEvent OnDestroy; - Dictionary> DB = new Dictionary>(); + Dictionary> DB = new Dictionary>(); internal struct TypeInfo { @@ -203,7 +203,7 @@ namespace Esyur.Stores.EntityCore TypesByName.Add(t.ClrType.Name, ti); TypesByType.Add(t.ClrType, ti); - DB.Add(t.ClrType, new Dictionary()); + DB.Add(t.ClrType, new Dictionary()); } } diff --git a/Esyur.Stores.EntityCore/EsyurExtensions.cs b/Esyur.Stores.EntityCore/EsyurExtensions.cs index eeb7291..35e3fed 100644 --- a/Esyur.Stores.EntityCore/EsyurExtensions.cs +++ b/Esyur.Stores.EntityCore/EsyurExtensions.cs @@ -35,15 +35,19 @@ namespace Esyur.Stores.EntityCore { public static class EsyurExtensions { - public static T CreateResource(this DbContext dbContext, object properties = null) where T:class,IResource - { - return dbContext.GetInfrastructure().CreateResource(properties); + //public static T CreateResource(this DbContext dbContext, object properties = null) where T:class,IResource + //{ + // return dbContext.GetInfrastructure().CreateResource(properties); - } + //} - public static T CreateResource(this DbSet dbSet, object properties = null) where T:class,IResource + public static T AddResource(this DbSet dbSet, object properties = null) where T:class,IResource { - var resource = dbSet.GetInfrastructure().CreateResource(properties); + var store = dbSet.GetInfrastructure().GetService().FindExtension().Store; + + //var resource = dbSet.GetInfrastructure().CreateResource(properties); + //var resource = Warehouse.New("", options.Store, null, null, null, properties); + var resource = Warehouse.New("", null, null, null, null, properties); dbSet.Add(resource); return resource; } diff --git a/Esyur/Core/ExceptionCode.cs b/Esyur/Core/ExceptionCode.cs index 61d28ae..603101f 100644 --- a/Esyur/Core/ExceptionCode.cs +++ b/Esyur/Core/ExceptionCode.cs @@ -8,7 +8,7 @@ namespace Esyur.Core { HostNotReachable, AccessDenied, - UserNotFound, + UserOrTokenNotFound, ChallengeFailed, ResourceNotFound, AttachDenied, diff --git a/Esyur/Data/DataConverter.cs b/Esyur/Data/DataConverter.cs index 25c9c0a..9d919c0 100644 --- a/Esyur/Data/DataConverter.cs +++ b/Esyur/Data/DataConverter.cs @@ -97,6 +97,10 @@ namespace Esyur.Data { return Structure.FromStructure((Structure)value, destinationType); } + else if (destinationType.IsEnum) + { + return Enum.ToObject(destinationType, value); + } else { return Convert.ChangeType(value, destinationType); diff --git a/Esyur/Data/Structure.cs b/Esyur/Data/Structure.cs index a558eb1..1c2ab12 100644 --- a/Esyur/Data/Structure.cs +++ b/Esyur/Data/Structure.cs @@ -134,6 +134,16 @@ namespace Esyur.Data // 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] { get diff --git a/Esyur/Net/HTTP/IIPoHTTP.cs b/Esyur/Net/HTTP/IIPoHTTP.cs new file mode 100644 index 0000000..34a05d3 --- /dev/null +++ b/Esyur/Net/HTTP/IIPoHTTP.cs @@ -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 Trigger(ResourceTrigger trigger) + { + return new AsyncReply(true); + } + } +} diff --git a/Esyur/Net/IIP/DistributedConnection.cs b/Esyur/Net/IIP/DistributedConnection.cs index 1ef8bc7..8e46959 100644 --- a/Esyur/Net/IIP/DistributedConnection.cs +++ b/Esyur/Net/IIP/DistributedConnection.cs @@ -67,7 +67,7 @@ namespace Esyur.Net.IIP AsyncReply openReply; - byte[] localPassword; + byte[] localPasswordOrToken; byte[] localNonce, remoteNonce; bool ready, readyToEstablish; @@ -256,13 +256,34 @@ namespace Esyur.Net.IIP //this.localUsername = username; session.LocalAuthentication.Domain = domain; session.LocalAuthentication.Username = username; - this.localPassword = DC.ToBytes(password); + session.LocalAuthentication.Method = AuthenticationMethod.Credentials; + this.localPasswordOrToken = DC.ToBytes(password); init(); 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); + } + + /// /// Create a new instance of a distributed connection /// @@ -595,7 +616,9 @@ namespace Esyur.Net.IIP { 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 => { @@ -614,54 +637,95 @@ namespace Esyur.Net.IIP { //Console.WriteLine("User not found"); SendParams().AddUInt8(0xc0) - .AddUInt8((byte)ExceptionCode.UserNotFound) + .AddUInt8((byte)ExceptionCode.UserOrTokenNotFound) .AddUInt16(14) .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) { if (authPacket.Action == IIPAuthPacket.IIPAuthPacketAction.AuthenticateHash) { var remoteHash = authPacket.Hash; + AsyncReply reply = null; - Server.Membership.GetPassword(session.RemoteAuthentication.Username, - session.RemoteAuthentication.Domain).Then((pw) => - { - 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); + if (session.RemoteAuthentication.Method == AuthenticationMethod.Credentials) + { + reply = Server.Membership.GetPassword(session.RemoteAuthentication.Username, + session.RemoteAuthentication.Domain); + } + else if (session.RemoteAuthentication.Method == AuthenticationMethod.Token) + { + reply = Server.Membership.GetToken(session.RemoteAuthentication.TokenIndex, + session.RemoteAuthentication.Domain); + } + else + { + // Error + } - var localHash = hashFunc.ComputeHash((new BinaryList()).AddUInt8Array(localNonce).AddUInt8Array(remoteNonce).AddUInt8Array(pw).ToArray()); - SendParams().AddUInt8(0).AddUInt8Array(localHash).Done(); + reply.Then((pw) => + { + 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; - } - else - { - //Global.Log("auth", LogType.Warning, "U:" + RemoteUsername + " IP:" + Socket.RemoteEndPoint.Address.ToString() + " S:DENIED"); - SendParams().AddUInt8(0xc0) - .AddUInt8((byte)ExceptionCode.AccessDenied) - .AddUInt16(13) - .AddString("Access Denied") - .Done(); - } - } - }); + var localHash = hashFunc.ComputeHash((new BinaryList()).AddUInt8Array(localNonce).AddUInt8Array(remoteNonce).AddUInt8Array(pw).ToArray()); + SendParams().AddUInt8(0).AddUInt8Array(localHash).Done(); + + readyToEstablish = true; + } + else + { + //Global.Log("auth", LogType.Warning, "U:" + RemoteUsername + " IP:" + Socket.RemoteEndPoint.Address.ToString() + " S:DENIED"); + SendParams().AddUInt8(0xc0) + .AddUInt8((byte)ExceptionCode.AccessDenied) + .AddUInt16(13) + .AddString("Access Denied") + .Done(); + } + } + }); } else if (authPacket.Action == IIPAuthPacket.IIPAuthPacketAction.NewConnection) { @@ -697,7 +761,7 @@ namespace Esyur.Net.IIP var hashFunc = SHA256.Create(); //var localHash = hashFunc.ComputeHash(BinaryList.ToBytes(localPassword, localNonce, remoteNonce)); var localHash = hashFunc.ComputeHash(new BinaryList() - .AddUInt8Array(localPassword) + .AddUInt8Array(localPasswordOrToken) .AddUInt8Array(localNonce) .AddUInt8Array(remoteNonce) .ToArray()); @@ -719,7 +783,7 @@ namespace Esyur.Net.IIP var remoteHash = hashFunc.ComputeHash(new BinaryList() .AddUInt8Array(remoteNonce) .AddUInt8Array(localNonce) - .AddUInt8Array(localPassword) + .AddUInt8Array(localPasswordOrToken) .ToArray()); @@ -810,6 +874,12 @@ namespace Esyur.Net.IIP [Attribute] public string Password { get; set; } + [Attribute] + public string Token { get; set; } + + [Attribute] + public ulong TokenIndex { get; set; } + [Attribute] public string Domain { get; set; } /// @@ -830,12 +900,23 @@ namespace Esyur.Net.IIP var address = host[0]; 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(); } - public AsyncReply Connect(ISocket socket = null, string hostname = null, ushort port = 0, string username = null, byte[] password = null, string domain = null) + public AsyncReply 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) throw new AsyncException(ErrorType.Exception, 0, "Connection in progress"); @@ -879,9 +960,12 @@ namespace Esyur.Net.IIP session = new Session(new ClientAuthentication() , new HostAuthentication()); + session.LocalAuthentication.Method = method; + session.LocalAuthentication.TokenIndex = tokenIndex; session.LocalAuthentication.Domain = domain; session.LocalAuthentication.Username = username; - localPassword = password; + localPasswordOrToken = passwordOrToken; + //localPassword = password; } if (session == null) @@ -933,7 +1017,7 @@ namespace Esyur.Net.IIP } } } - catch + catch { return false; } diff --git a/Esyur/Net/NetworkServer.cs b/Esyur/Net/NetworkServer.cs index 0c9b6b9..1871743 100644 --- a/Esyur/Net/NetworkServer.cs +++ b/Esyur/Net/NetworkServer.cs @@ -282,7 +282,7 @@ namespace Esyur.Net try { - + if (sock == null) { Console.Write("sock == null"); @@ -295,6 +295,7 @@ namespace Esyur.Net c.Assign(sock); + try { ClientConnected(c); @@ -304,10 +305,10 @@ namespace Esyur.Net // something wrong with the child. } - + sock.Begin(); + // Accept more //listener.Accept().Then(NewConnection); - sock.Begin(); } diff --git a/Esyur/Net/Packets/IIPAuthPacket.cs b/Esyur/Net/Packets/IIPAuthPacket.cs index 189a357..7da99f2 100644 --- a/Esyur/Net/Packets/IIPAuthPacket.cs +++ b/Esyur/Net/Packets/IIPAuthPacket.cs @@ -23,6 +23,7 @@ SOFTWARE. */ using Esyur.Data; +using Esyur.Security.Authority; using System; using System.Collections.Generic; using System.Linq; @@ -34,7 +35,7 @@ namespace Esyur.Net.Packets { class IIPAuthPacket : Packet { - public enum IIPAuthPacketCommand: byte + public enum IIPAuthPacketCommand : byte { Action = 0, Declare, @@ -42,7 +43,7 @@ namespace Esyur.Net.Packets Error, } - public enum IIPAuthPacketAction: byte + public enum IIPAuthPacketAction : byte { // Authenticate AuthenticateHash, @@ -61,13 +62,6 @@ namespace Esyur.Net.Packets } - public enum IIPAuthPacketMethod: byte - { - None, - Certificate, - Credentials, - Token - } public IIPAuthPacketCommand Command @@ -84,7 +78,7 @@ namespace Esyur.Net.Packets public byte ErrorCode { get; set; } public string ErrorMessage { get; set; } - public IIPAuthPacketMethod LocalMethod + public AuthenticationMethod LocalMethod { get; set; @@ -108,7 +102,7 @@ namespace Esyur.Net.Packets set; } - public IIPAuthPacketMethod RemoteMethod + public AuthenticationMethod RemoteMethod { get; set; @@ -122,7 +116,7 @@ namespace Esyur.Net.Packets public long CertificateId { - get;set; + get; set; } public string LocalUsername @@ -178,6 +172,8 @@ namespace Esyur.Net.Packets set; } + public ulong RemoteTokenIndex { get; set; } + private uint dataLengthNeeded; bool NotEnough(uint offset, uint ends, uint needed) @@ -193,7 +189,7 @@ namespace Esyur.Net.Packets public override string ToString() { - return Command.ToString() + " " + Action.ToString(); + return Command.ToString() + " " + Action.ToString(); } public override long Parse(byte[] data, uint offset, uint ends) @@ -260,8 +256,8 @@ namespace Esyur.Net.Packets } else if (Command == IIPAuthPacketCommand.Declare) { - RemoteMethod = (IIPAuthPacketMethod)((data[offset] >> 4) & 0x3); - LocalMethod = (IIPAuthPacketMethod)((data[offset] >> 2) & 0x3); + RemoteMethod = (AuthenticationMethod)((data[offset] >> 4) & 0x3); + LocalMethod = (AuthenticationMethod)((data[offset] >> 2) & 0x3); var encrypt = ((data[offset++] & 0x2) == 0x2); @@ -277,11 +273,11 @@ namespace Esyur.Net.Packets Domain = domain; offset += domainLength; - - if (RemoteMethod == IIPAuthPacketMethod.Credentials) + + if (RemoteMethod == AuthenticationMethod.Credentials) { - if (LocalMethod == IIPAuthPacketMethod.None) + if (LocalMethod == AuthenticationMethod.None) { if (NotEnough(offset, ends, 33)) return -dataLengthNeeded; @@ -293,18 +289,33 @@ namespace Esyur.Net.Packets RemoteNonce = data.Clip(offset, 32); offset += 32; - + var length = data[offset++]; if (NotEnough(offset, ends, length)) return -dataLengthNeeded; - RemoteUsername = data.GetString(offset, length); + RemoteUsername = data.GetString(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) { @@ -329,31 +340,26 @@ namespace Esyur.Net.Packets } else if (Command == IIPAuthPacketCommand.Acknowledge) { - RemoteMethod = (IIPAuthPacketMethod)((data[offset] >> 4) & 0x3); - LocalMethod = (IIPAuthPacketMethod)((data[offset] >> 2) & 0x3); + RemoteMethod = (AuthenticationMethod)((data[offset] >> 4) & 0x3); + LocalMethod = (AuthenticationMethod)((data[offset] >> 2) & 0x3); var encrypt = ((data[offset++] & 0x2) == 0x2); if (NotEnough(offset, ends, 1)) 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)) return -dataLengthNeeded; - /* - var remoteNonce = new byte[32]; - Buffer.BlockCopy(data, (int)offset, remoteNonce, 0, 32); - RemoteNonce = remoteNonce; - */ - RemoteNonce = data.Clip(offset, 32); offset += 32; - } + } } if (encrypt) @@ -385,7 +391,7 @@ namespace Esyur.Net.Packets offset++; ErrorCode = data[offset++]; - + var cl = data.GetUInt16(offset); offset += 2; @@ -403,4 +409,4 @@ namespace Esyur.Net.Packets } } - } +} diff --git a/Esyur/Net/Sockets/ISocket.cs b/Esyur/Net/Sockets/ISocket.cs index 434dbae..999afc5 100644 --- a/Esyur/Net/Sockets/ISocket.cs +++ b/Esyur/Net/Sockets/ISocket.cs @@ -42,7 +42,7 @@ namespace Esyur.Net.Sockets public delegate void ISocketConnectEvent(); public delegate void ISocketCloseEvent(); - public interface ISocket: IDestructible + public interface ISocket : IDestructible { SocketState State { get; } @@ -57,6 +57,7 @@ namespace Esyur.Net.Sockets void Close(); AsyncReply Connect(string hostname, ushort port); bool Begin(); + AsyncReply BeginAsync(); //ISocket Accept(); AsyncReply AcceptAsync(); ISocket Accept(); diff --git a/Esyur/Net/Sockets/SSLSocket.cs b/Esyur/Net/Sockets/SSLSocket.cs index 1a38e2a..5ee6c40 100644 --- a/Esyur/Net/Sockets/SSLSocket.cs +++ b/Esyur/Net/Sockets/SSLSocket.cs @@ -76,21 +76,19 @@ namespace Esyur.Net.Sockets { var rt = new AsyncReply(); + this.hostname = hostname; + this.server = false; + state = SocketState.Connecting; await sock.ConnectAsync(hostname, port); - if (server) - await ssl.AuthenticateAsServerAsync(cert); - else - await ssl.AuthenticateAsClientAsync(hostname); try { + await BeginAsync(); state = SocketState.Established; OnConnect?.Invoke(); - if (!server) - Begin(); } catch (Exception ex) { @@ -135,11 +133,28 @@ namespace Esyur.Net.Sockets private void SendCallback(IAsyncResult ar) { - if (ar != null && ar.AsyncState != null) - ((AsyncReply)ar.AsyncState).Trigger(true); + if (ar != null) + { + try + { + ssl.EndWrite(ar); + + if (ar.AsyncState != null) + ((AsyncReply)ar.AsyncState).Trigger(true); + } + catch + { + if (state != SocketState.Closed && !sock.Connected) + { + state = SocketState.Terminated; + Close(); + } + } + } lock (sendLock) { + if (sendBufferQueue.Count > 0) { var kv = sendBufferQueue.Dequeue(); @@ -151,10 +166,10 @@ namespace Esyur.Net.Sockets catch (Exception ex) { asyncSending = false; - try { - kv.Key.Trigger(false); + if (kv.Key != null) + kv.Key.Trigger(false); if (state != SocketState.Closed && !sock.Connected) { @@ -167,7 +182,7 @@ namespace Esyur.Net.Sockets state = SocketState.Terminated; } - Global.Log("TCPSocket", LogType.Error, ex.ToString()); + //Global.Log("TCPSocket", LogType.Error, ex.ToString()); } } 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; - sock = Socket; + sock = socket; receiveBuffer = new byte[sock.ReceiveBufferSize]; ssl = new SslStream(new NetworkStream(sock)); server = authenticateAsServer; + if (socket.Connected) + state = SocketState.Established; } public void Close() { if (state != SocketState.Closed && state != SocketState.Terminated) + { state = SocketState.Closed; - if (sock.Connected) - { - try + if (sock.Connected) { - sock.Shutdown(SocketShutdown.Both); - } - catch - { - state = SocketState.Terminated; + try + { + sock.Shutdown(SocketShutdown.Both); + } + catch + { + state = SocketState.Terminated; + } } + + OnClose?.Invoke(); } - - sock.Shutdown(SocketShutdown.Both); - - OnClose?.Invoke(); } @@ -351,6 +368,7 @@ namespace Esyur.Net.Sockets // } //} + public bool Begin() { if (began) @@ -358,6 +376,11 @@ namespace Esyur.Net.Sockets began = true; + if (server) + ssl.AuthenticateAsServer(cert); + else + ssl.AuthenticateAsClient(hostname); + if (state == SocketState.Established) { ssl.BeginRead(receiveBuffer, 0, receiveBuffer.Length, ReceiveCallback, this); @@ -367,6 +390,26 @@ namespace Esyur.Net.Sockets return false; } + public async AsyncReply 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) { @@ -398,7 +441,7 @@ namespace Esyur.Net.Sockets 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; } } - + public void Hold() { @@ -441,7 +484,7 @@ namespace Esyur.Net.Sockets } catch (Exception ex) { - Console.WriteLine(ex); + Global.Log(ex); } finally { diff --git a/Esyur/Net/Sockets/TCPSocket.cs b/Esyur/Net/Sockets/TCPSocket.cs index f2410fd..42a8e92 100644 --- a/Esyur/Net/Sockets/TCPSocket.cs +++ b/Esyur/Net/Sockets/TCPSocket.cs @@ -65,6 +65,11 @@ namespace Esyur.Net.Sockets SocketAsyncEventArgs socketArgs = new SocketAsyncEventArgs(); + public async AsyncReply BeginAsync() + { + return Begin(); + } + public bool Begin() { if (began) @@ -74,7 +79,7 @@ namespace Esyur.Net.Sockets socketArgs.SetBuffer(receiveBuffer, 0, receiveBuffer.Length); socketArgs.Completed += SocketArgs_Completed; - + if (!sock.ReceiveAsync(socketArgs)) SocketArgs_Completed(null, socketArgs); @@ -176,8 +181,8 @@ namespace Esyur.Net.Sockets if (State != SocketState.Established) return; - if (e.BytesTransferred < 0) - Console.WriteLine("BytesTransferred is less than zero"); + //if (e.BytesTransferred < 0) + // Console.WriteLine("BytesTransferred is less than zero"); if (e.BytesTransferred <= 0) { @@ -185,8 +190,8 @@ namespace Esyur.Net.Sockets return; } - if (e.BytesTransferred > 100000) - Console.WriteLine("BytesTransferred is large " + e.BytesTransferred); + //if (e.BytesTransferred > 100000) + // Console.WriteLine("BytesTransferred is large " + e.BytesTransferred); recCount = e.BytesTransferred > e.Count ? e.Count : e.BytesTransferred; @@ -382,8 +387,24 @@ namespace Esyur.Net.Sockets private void SendCallback(IAsyncResult ar) { - if (ar != null && ar.AsyncState != null) - ((AsyncReply)ar.AsyncState).Trigger(true); + if (ar != null) + { + try + { + sock.EndSend(ar); + + if (ar.AsyncState != null) + ((AsyncReply)ar.AsyncState).Trigger(true); + } + catch + { + if (state != SocketState.Closed && !sock.Connected) + { + state = SocketState.Terminated; + Close(); + } + } + } lock (sendLock) { @@ -401,7 +422,8 @@ namespace Esyur.Net.Sockets try { - kv.Key.Trigger(false); + if (kv.Key != null) + kv.Key.Trigger(false); if (state != SocketState.Closed && !sock.Connected) { diff --git a/Esyur/Net/Sockets/WSSocket.cs b/Esyur/Net/Sockets/WSSocket.cs index 715c552..1f622c3 100644 --- a/Esyur/Net/Sockets/WSSocket.cs +++ b/Esyur/Net/Sockets/WSSocket.cs @@ -322,5 +322,10 @@ namespace Esyur.Net.Sockets { throw new NotImplementedException(); } + + public AsyncReply BeginAsync() + { + return sock.BeginAsync(); + } } } \ No newline at end of file diff --git a/Esyur/Proxy/ResourceProxy.cs b/Esyur/Proxy/ResourceProxy.cs index 15888ad..e9945ec 100644 --- a/Esyur/Proxy/ResourceProxy.cs +++ b/Esyur/Proxy/ResourceProxy.cs @@ -71,10 +71,14 @@ namespace Esyur.Proxy select p; #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 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, TypeAttributes.Public | TypeAttributes.Class, type); diff --git a/Esyur/Security/Authority/Authentication.cs b/Esyur/Security/Authority/Authentication.cs index e236a7f..d4d5ebd 100644 --- a/Esyur/Security/Authority/Authentication.cs +++ b/Esyur/Security/Authority/Authentication.cs @@ -27,16 +27,20 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using static Esyur.Net.Packets.IIPAuthPacket; namespace Esyur.Security.Authority { public class Authentication { - AuthenticationType type; - + AuthenticationType type; + + public AuthenticationMethod Method { get; set; } + + public ulong TokenIndex { get; set; } public string Username { get; set; } - public Certificate Certificate { get; set; } + public Certificate Certificate { get; set; } public string Domain { get; set; } public string FullName => Username + "@" + Domain; diff --git a/Esyur/Security/Authority/AuthenticationMethod.cs b/Esyur/Security/Authority/AuthenticationMethod.cs new file mode 100644 index 0000000..56a0d27 --- /dev/null +++ b/Esyur/Security/Authority/AuthenticationMethod.cs @@ -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 + } +} diff --git a/Esyur/Security/Membership/IMembership.cs b/Esyur/Security/Membership/IMembership.cs index ab5bc8e..80f36a0 100644 --- a/Esyur/Security/Membership/IMembership.cs +++ b/Esyur/Security/Membership/IMembership.cs @@ -35,40 +35,14 @@ using Esyur.Resource; namespace Esyur.Security.Membership { - public interface IMembership:IResource + public interface IMembership : IResource { - //IUser[] GetUsers(QueryFilter user); - - //bool AddCertificate(Certificate certificate); - - //CACertificate[] GetCACertificates(string authority); - //UserCertificate[] GetUserCertificate(string user, string domain); - //DomainCertificate[] GetDomainCertificates(string domain); - - AsyncReply UserExists(string username, string domain); AsyncReply GetPassword(string username, string domain); + AsyncReply GetToken(ulong TokenIndex, string domain); AsyncReply Login(Session session); AsyncReply Logout(Session session); - //ClientAuthentication Authenticate(string username, byte[] credentials, int flag); - //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 info); - */ - - //bool AddUser(User user, KeyList info); - //bool RemoveUser(string username); - - - - - + AsyncReply TokenExists(ulong tokenIndex, string domain); } }