Inheritance: System.EventArgs, ILockFreePoolItem, IDisposable
Exemplo n.º 1
0
        private void Disconnect_Completed(Socket socket, ServerAsyncEventArgs e)
        {
            for (; ;)
            {
                int backlog = Thread.VolatileRead(ref acceptBacklog);
                if (isRunning && backlog < maxAcceptBacklog)
                {
                    if (Interlocked.CompareExchange(ref acceptBacklog, backlog + 1, backlog) == backlog)
                    {
                        e.AcceptSocket = socket;

                        try
                        {
                            listener.AcceptAsync(e, Accept_Completed);
                        }
                        catch
                        {
                            EventArgsManager.Put(e);
                        }
                        break;
                    }
                }
                else
                {
                    EventArgsManager.Put(e);
                    break;
                }
            }
        }
Exemplo n.º 2
0
        protected override bool OnTcpReceived(Connection <C> connection, ref ServerAsyncEventArgs e)
        {
            bool result;
            bool oldConnected = connection.SspiContext.Connected;

            if (connection.SspiContext.Connected)
            {
                result = DecryptData(ref e, connection);
            }
            else
            {
                result = Handshake(e, connection);
            }

            // proccess all data from buffer if TLS connected status was changed
            //
            while (result && oldConnected != connection.SspiContext.Connected &&
                   connection.SspiContext.Buffer.IsValid)
            {
                oldConnected = connection.SspiContext.Connected;

                ServerAsyncEventArgs nulle = null;
                if (connection.SspiContext.Connected)
                {
                    result = DecryptData(ref nulle, connection);
                }
                else
                {
                    result = Handshake(nulle, connection);
                }
            }

            return(result);
        }
Exemplo n.º 3
0
        protected override bool OnTcpReceived(Server <C> .Connection <C> connection, ref ServerAsyncEventArgs e)
        {
            bool connected = connection.SspiContext.Connected;
            bool flag;

            if (connection.SspiContext.Connected)
            {
                flag = this.DecryptData(ref e, connection);
            }
            else
            {
                flag = this.Handshake(e, connection);
            }
            while (flag && connected != connection.SspiContext.Connected && connection.SspiContext.Buffer.IsValid)
            {
                connected = connection.SspiContext.Connected;
                ServerAsyncEventArgs ie = null;
                if (connection.SspiContext.Connected)
                {
                    flag = this.DecryptData(ref ie, connection);
                }
                else
                {
                    flag = this.Handshake(ie, connection);
                }
            }
            return(flag);
        }
Exemplo n.º 4
0
        private void Disconnect_Completed(Socket socket, ServerAsyncEventArgs e)
        {
            int num;

            do
            {
                num = Thread.VolatileRead(ref this.acceptBacklog);
                if (!this.isRunning || num >= this.maxAcceptBacklog)
                {
                    goto IL_5B;
                }
            }while (Interlocked.CompareExchange(ref this.acceptBacklog, num + 1, num) != num);
            e.AcceptSocket = socket;
            try
            {
                this.listener.AcceptAsync(e, new ServerAsyncEventArgs.CompletedEventHandler(this.Accept_Completed));
                return;
            }
            catch
            {
                EventArgsManager.Put(e);
                return;
            }
IL_5B:
            EventArgsManager.Put(e);
        }
Exemplo n.º 5
0
        private void Accept_Completed(Socket none, ServerAsyncEventArgs e)
        {
            Socket      acceptSocket = e.AcceptSocket;
            SocketError error        = e.SocketError;

            for (; ;)
            {
                int backlog = Thread.VolatileRead(ref acceptBacklog);
                if (isRunning && backlog <= minAcceptBacklog)
                {
                    e.AcceptSocket = null;

                    listener.AcceptAsync(e, Accept_Completed);
                    break;
                }
                else
                {
                    if (Interlocked.CompareExchange(ref acceptBacklog, backlog - 1, backlog) == backlog)
                    {
                        EventArgsManager.Put(e);
                        break;
                    }
                }
            }

            var connection = CreateConnection(acceptSocket, error);

            if (connection != null)
            {
                NewTcpConnection(connection);
            }
        }
Exemplo n.º 6
0
        private void Connect_Completed(Socket socket1, ServerAsyncEventArgs e)
        {
            bool flag = false;

            Server <C> .Connection <C> connection = null;
            if (e.SocketError == SocketError.Success)
            {
                connection = this.CreateConnection(socket1, e.SocketError);
                flag       = (connection != null);
            }
            else
            {
                while (e.SocketError == SocketError.AddressAlreadyInUse && !this.connections.TryGetValue(e.RemoteEndPoint, out connection))
                {
                    Thread.Sleep(0);
                    if (socket1.ConnectAsync(e))
                    {
                        return;
                    }
                    if (e.SocketError == SocketError.Success)
                    {
                        connection = this.CreateConnection(socket1, e.SocketError);
                        flag       = (connection != null);
                    }
                }
            }
            if (e.SocketError == SocketError.Success && flag)
            {
                this.NewTcpConnection(connection);
            }
            e.Completed = new ServerAsyncEventArgs.CompletedEventHandler(base.Send_Completed);
            e.OnCompleted(socket1);
        }
Exemplo n.º 7
0
        private void Accept_Completed(Socket none, ServerAsyncEventArgs e)
        {
            Socket      acceptSocket = e.AcceptSocket;
            SocketError socketError  = e.SocketError;

            while (true)
            {
                int num = Thread.VolatileRead(ref this.acceptBacklog);
                if (this.isRunning && num <= this.minAcceptBacklog)
                {
                    break;
                }
                if (Interlocked.CompareExchange(ref this.acceptBacklog, num - 1, num) == num)
                {
                    goto Block_3;
                }
            }
            e.AcceptSocket = null;
            this.listener.AcceptAsync(e, new ServerAsyncEventArgs.CompletedEventHandler(this.Accept_Completed));
            goto IL_66;
Block_3:
            EventArgsManager.Put(e);
IL_66:
            Server <C> .Connection <C> connection = this.CreateConnection(acceptSocket, socketError);
            if (connection != null)
            {
                this.NewTcpConnection(connection);
            }
        }
Exemplo n.º 8
0
 public void Dettach(ref ServerAsyncEventArgs e, out ArraySegment <byte> segment1, out ArraySegment <byte> segment2)
 {
     if (this.readerStorage == HeaderContentConnection.Storage.E)
     {
         int num = this.headerData.Count;
         if (this.contentStorage == this.readerStorage)
         {
             num += this.contentData.Count;
         }
         segment1 = this.Detach(ref e, num);
         segment2 = ((this.contentStorage != this.readerStorage) ? this.Dettach(this.contentStorage) : default(ArraySegment <byte>));
         return;
     }
     segment1 = this.Dettach(this.readerStorage);
     if (this.contentStorage == this.readerStorage)
     {
         segment2 = default(ArraySegment <byte>);
         return;
     }
     if (this.contentStorage == HeaderContentConnection.Storage.E)
     {
         segment2 = this.Detach(ref e, this.contentData.Count);
         return;
     }
     segment2 = this.Dettach(this.contentStorage);
 }
Exemplo n.º 9
0
        private static void SocketArgs_Completed(object sender, SocketAsyncEventArgs e)
        {
            ServerAsyncEventArgs serverAsyncEventArgs = e.UserToken as ServerAsyncEventArgs;

            serverAsyncEventArgs.bytesTransferred = e.BytesTransferred;
            serverAsyncEventArgs.Completed(sender as Socket, serverAsyncEventArgs);
        }
Exemplo n.º 10
0
 public void ResetState()
 {
     this.ready                 = false;
     this.headerData            = default(ArraySegment <byte>);
     this.expectedContentLength = 0;
     this.receivedContentLength = 0;
     this.contentData           = default(ArraySegment <byte>);
     this.readerStorage         = HeaderContentConnection.Storage.None;
     this.contentStorage        = HeaderContentConnection.Storage.None;
     this.ResetParser(HeaderContentConnection.ResetReason.ResetStateCalled);
     if (this.buffer1 != null)
     {
         this.buffer1UnusedCount = ((this.buffer1.Count <= 0) ? (this.buffer1UnusedCount + 1) : 0);
         if (this.buffer1.Capacity <= 8192 && this.buffer1UnusedCount < 8)
         {
             this.buffer1.Clear();
         }
         else
         {
             this.buffer1.Free();
         }
     }
     if (this.buffer2 != null)
     {
         this.buffer2.Free();
     }
     if (this.e1 != null)
     {
         this.e1.Dispose();
         this.e1 = null;
     }
     this.keepAliveRecived = 0;
     this.state            = HeaderContentConnection.StreamState.WaitingHeaders;
 }
Exemplo n.º 11
0
        public void Dettach(ref ServerAsyncEventArgs e, out ArraySegment <byte> segment1, out ArraySegment <byte> segment2)
        {
            if (readerStorage == Storage.E)
            {
                int size = headerData.Count;
                if (contentStorage == readerStorage)
                {
                    size += contentData.Count;
                }

                segment1 = Detach(ref e, size);
                segment2 = (contentStorage != readerStorage) ? Dettach(contentStorage) : new ArraySegment <byte>();
            }
            else
            {
                segment1 = Dettach(readerStorage);

                if (contentStorage != readerStorage)
                {
                    if (contentStorage == Storage.E)
                    {
                        segment2 = Detach(ref e, contentData.Count);
                    }
                    else
                    {
                        segment2 = Dettach(contentStorage);
                    }
                }
                else
                {
                    segment2 = new ArraySegment <byte>();
                }
            }
        }
Exemplo n.º 12
0
        private bool Server_Received(Server <C> server, C c, ref ServerAsyncEventArgs e)
        {
            bool result;

            try
            {
                if (this.logger.IsEnabled)
                {
                    this.logger.Write(e, true);
                }
                if (this.Received != null)
                {
                    result = this.Received(this, c, ref e);
                }
                else
                {
                    result = false;
                }
            }
            catch (Exception innerException)
            {
                throw new Exception("Error in Received event handler", innerException);
            }
            return(result);
        }
Exemplo n.º 13
0
        private bool TcpReceiveAsync(Connection <C> connection, ServerAsyncEventArgs e)
        {
            PrepareEventArgs(connection, e);

            try
            {
                connection.SpinLock.Enter();

                e.SequenceNumber = connection.ReceiveQueue.SequenceNumber;

                try
                {
                    if (connection.IsClosed == false)
                    {
                        bool result = connection.Socket.ReceiveAsync(e);
                        connection.ReceiveQueue.SequenceNumber++;
                        return(result);
                    }
                }
                finally
                {
                    connection.SpinLock.Exit();
                }
            }
            catch (ObjectDisposedException)
            {
            }

            EventArgsManager.Put(ref e);
            return(true);
        }
Exemplo n.º 14
0
 protected void PrepareEventArgs(Connection <C> connection, ServerAsyncEventArgs e)
 {
     e.ConnectionId   = connection.Id;
     e.RemoteEndPoint = connection.RemoteEndPoint;
     e.Completed      = Receive_Completed;
     //e.OffsetOffset = offsetOffset;
     //e.Count -= offsetOffset;
 }
Exemplo n.º 15
0
        public override void SendAsync(ServerAsyncEventArgs e)
        {
            var connection = GetTcpConnection(e.RemoteEndPoint);

            OnBeforeSend(connection, e);

            base.SendAsync(connection, e);
        }
Exemplo n.º 16
0
 public static void ConnectAsync(this Socket socket, ServerAsyncEventArgs e, ServerAsyncEventArgs.CompletedEventHandler handler)
 {
     e.Completed = handler;
     if (socket.ConnectAsync(e) == false)
     {
         e.OnCompleted(socket);
     }
 }
Exemplo n.º 17
0
 public static void AcceptAsync(this Socket socket, ServerAsyncEventArgs e, ServerAsyncEventArgs.CompletedEventHandler handler)
 {
     e.Completed = handler;
     if (!socket.AcceptAsync(e))
     {
         e.OnCompleted(socket);
     }
 }
Exemplo n.º 18
0
 public override void SendAsync(ServerAsyncEventArgs e)
 {
     base.OnBeforeSend(null, e);
     e.Completed = new ServerAsyncEventArgs.CompletedEventHandler(base.Send_Completed);
     if (!this.socket.SendToAsync(e))
     {
         e.OnCompleted(this.socket);
     }
 }
Exemplo n.º 19
0
			public void RestoreAddresses(ServerAsyncEventArgs e)
			{
				e.ConnectionId = connectionId;
				e.LocalEndPoint = localEndPoint;
				e.RemoteEndPoint = remoteEndPoint;

				localEndPoint = null;
				remoteEndPoint = null;
			}
Exemplo n.º 20
0
 private void Receive_Completed(Socket socket, ServerAsyncEventArgs e)
 {
     try
     {
         Server <C> .Connection <C> connection;
         this.connections.TryGetValue(e.RemoteEndPoint, out connection);
         if (connection != null && connection.Socket == socket && connection.Id == e.ConnectionId)
         {
             while (true)
             {
                 if (e != null)
                 {
                     connection.ReceiveQueue.Put(e);
                     e = null;
                 }
                 e = connection.ReceiveQueue.GetCurrent();
                 if (e == null)
                 {
                     goto IL_D4;
                 }
                 bool flag = true;
                 if (this.isRunning && e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
                 {
                     flag = !this.OnTcpReceived(connection, ref e);
                 }
                 if (flag)
                 {
                     break;
                 }
                 connection.ReceiveQueue.Next();
                 if (e == null)
                 {
                     e = EventArgsManager.Get();
                 }
                 else
                 {
                     e.SetDefaultValue();
                 }
                 if (this.TcpReceiveAsync(connection, e))
                 {
                     e = null;
                 }
             }
             this.connections.Remove(connection.RemoteEndPoint, connection);
             this.EndTcpConnection(connection);
         }
         IL_D4 :;
     }
     finally
     {
         if (e != null)
         {
             EventArgsManager.Put(ref e);
         }
     }
 }
Exemplo n.º 21
0
		public void SendAsyncSip(ServerAsyncEventArgs e)
		{
			if (AjaxWebsocket.IsAjax(e))
				ajax.ProcessOutgoing(e);
			else
			{
				e.UserTokenForSending2 = SipModule;
				serversManager.SendAsync(e);
			}
		}
Exemplo n.º 22
0
        public bool CopyTransferredFrom(ServerAsyncEventArgs e, int skipBytes)
        {
#if DEBUG
            if (e.Count < skipBytes)
            {
                throw new ArgumentOutOfRangeException();
            }
#endif
            return(CopyFrom(e.Buffer, e.Offset + skipBytes, e.BytesTransferred - skipBytes));
        }
Exemplo n.º 23
0
        public override void SendAsync(ServerAsyncEventArgs e)
        {
            OnBeforeSend(null, e);

            e.Completed = Send_Completed;
            if (socket.SendToAsync(e) == false)
            {
                e.OnCompleted(socket);
            }
        }
Exemplo n.º 24
0
                public void Put(ServerAsyncEventArgs e)
                {
                    int num = e.SequenceNumber % this.size;

                    Interlocked.Exchange <ServerAsyncEventArgs>(ref this.queue[num], e);
                    if (this.disposed && Interlocked.Exchange <ServerAsyncEventArgs>(ref this.queue[num], null) != null)
                    {
                        EventArgsManager.Put(e);
                    }
                }
Exemplo n.º 25
0
		public IncomingMessage(ServerAsyncEventArgs e, SipMessageReader reader, ArraySegment<byte> content)
		{
			if (e.LocalEndPoint.Protocol != ServerProtocol.Udp)
				throw new ArgumentException();

			ConnectionAddresses = new ConnectionAddresses(Transports.Udp, e.LocalEndPoint,
				new IPEndPoint(e.RemoteEndPoint.Address, e.RemoteEndPoint.Port), ServerAsyncEventArgs.AnyNewConnectionId);

			Reader = reader;
			Content = content;
			Header = new ArraySegment<byte>(e.Buffer, e.Offset, e.BytesTransferred - content.Count);
		}
		public int ProccessTransactionUser(int statusCode, ServerAsyncEventArgs e)
		{
			int action = 0;

			switch (State)
			{
				case Transaction.States.Trying:

					action |= Transaction.Action.SendOutgoingMessage;

					if (statusCode >= 100 && statusCode <= 199)
					{
						eventArgs = e.CreateDeepCopy();
						SetState(Transaction.States.Proceeding, ref action);
					}
					else if (statusCode >= 200 && statusCode <= 699)
					{
						if (e.LocalEndPoint.IsTransportUnreliable())
							SetState(Transaction.States.Completed, ref action);
						else
							SetState(Transaction.States.Terminated, ref action);
					}

					break;


				case Transaction.States.Proceeding:

					action |= Transaction.Action.SendOutgoingMessage;

					if (statusCode >= 200 && statusCode <= 699)
					{
						if (e.LocalEndPoint.IsTransportUnreliable())
						{
							eventArgs = e.CreateDeepCopy();
							SetState(Transaction.States.Completed, ref action);
						}
						else
						{
							SetState(Transaction.States.Terminated, ref action);
						}
					}
					break;


				case Transaction.States.Completed:
				case Transaction.States.Terminated:
					break;
			}

			return action;
		}
Exemplo n.º 27
0
        public ServerAsyncEventArgs CreateDeepCopy()
        {
            ServerAsyncEventArgs serverAsyncEventArgs = EventArgsManager.Get();

            serverAsyncEventArgs.CopyAddressesFrom(this);
            serverAsyncEventArgs.offsetOffset = this.offsetOffset;
            serverAsyncEventArgs.count        = this.count;
            serverAsyncEventArgs.AllocateBuffer();
            serverAsyncEventArgs.bytesTransferred    = this.bytesTransferred;
            serverAsyncEventArgs.UserTokenForSending = this.UserTokenForSending;
            System.Buffer.BlockCopy(this.Buffer, this.Offset, serverAsyncEventArgs.Buffer, serverAsyncEventArgs.Offset, serverAsyncEventArgs.Count);
            return(serverAsyncEventArgs);
        }
Exemplo n.º 28
0
 internal void Write(ServerAsyncEventArgs e, bool incomingOutgoing)
 {
     try
     {
         PcapWriter pcapWriter = this.writer;
         if (pcapWriter != null)
         {
             pcapWriter.Write(e.Buffer, e.Offset, incomingOutgoing ? e.BytesTransferred : e.Count, this.Convert(e.LocalEndPoint.Protocol), incomingOutgoing ? e.RemoteEndPoint : e.LocalEndPoint, incomingOutgoing ? e.LocalEndPoint : e.RemoteEndPoint);
         }
     }
     catch (ObjectDisposedException)
     {
     }
 }
Exemplo n.º 29
0
 private void Server_BeforeSend(Server <C> server, C c, ServerAsyncEventArgs e)
 {
     try
     {
         if (this.BeforeSend != null)
         {
             this.BeforeSend(this, c, e);
         }
     }
     catch (Exception innerException)
     {
         throw new Exception("Error in BeforeSend event handler", innerException);
     }
 }
Exemplo n.º 30
0
        private void Connect_Completed(Socket socket1, ServerAsyncEventArgs e)
        {
            bool           newConnection = false;
            Connection <C> connection    = null;

            if (e.SocketError == SocketError.Success)
            {
                connection    = CreateConnection(socket1, e.SocketError);
                newConnection = connection != null;
            }
            else
            {
                while (e.SocketError == SocketError.AddressAlreadyInUse)
                {
                    if (connections.TryGetValue(e.RemoteEndPoint, out connection))
                    {
                        break;
                    }

                    Thread.Sleep(0);

                    if (socket1.ConnectAsync(e))
                    {
                        return;
                    }
                    else
                    {
                        if (e.SocketError == SocketError.Success)
                        {
                            connection    = CreateConnection(socket1, e.SocketError);
                            newConnection = connection != null;
                        }
                    }
                }
            }

            if (e.SocketError == SocketError.Success)
            {
                if (newConnection)
                {
                    NewTcpConnection(connection);
                }
            }

            e.Completed = Send_Completed;
            e.OnCompleted(socket1);
        }
Exemplo n.º 31
0
		static bool ServersManager_Received(ServersManager<HttpConnection> s, HttpConnection connection, ref ServerAsyncEventArgs e)
		{
			bool closeConnection = false, repeat = true;

			while (repeat)
			{
				repeat = connection.Proccess(ref e, out closeConnection);

				if (connection.IsMessageReady)
				{
					httpServer.ProcessIncomingRequest(connection);
					connection.ResetState();
				}
			}

			return !closeConnection;
		}
Exemplo n.º 32
0
 public new void Dispose()
 {
     base.Dispose();
     if (this.buffer1 != null)
     {
         this.buffer1.Dispose();
     }
     if (this.buffer2 != null)
     {
         this.buffer2.Dispose();
     }
     if (this.e1 != null)
     {
         this.e1.Dispose();
         this.e1 = null;
     }
 }
Exemplo n.º 33
0
                public void Dispose()
                {
                    this.disposed = true;
                    ServerAsyncEventArgs serverAsyncEventArgs = null;

                    for (int i = 0; i < this.queue.Length; i++)
                    {
                        if (this.queue[i] != null)
                        {
                            serverAsyncEventArgs = Interlocked.Exchange <ServerAsyncEventArgs>(ref this.queue[i], null);
                        }
                        if (serverAsyncEventArgs != null)
                        {
                            EventArgsManager.Put(ref serverAsyncEventArgs);
                        }
                    }
                }
Exemplo n.º 34
0
        private ArraySegment <byte> Detach(ref ServerAsyncEventArgs e, int size)
        {
            ServerAsyncEventArgs serverAsyncEventArgs = null;

            if (e.BytesTransferred > size)
            {
                serverAsyncEventArgs = e.CreateDeepCopy();
            }
            ArraySegment <byte> result = e.DetachBuffer();

            EventArgsManager.Put(ref e);
            if (serverAsyncEventArgs != null)
            {
                e = serverAsyncEventArgs;
            }
            return(result);
        }
Exemplo n.º 35
0
        protected void SendAsync(Connection <C> connection, ServerAsyncEventArgs e)
        {
            if (connection == null)
            {
                if (e.ConnectionId == ServerAsyncEventArgs.AnyNewConnectionId)
                {
                    try
                    {
                        Socket socket = new Socket(realEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                        socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
                        socket.Bind(realEndPoint);

                        socket.ConnectAsync(e, Connect_Completed);
                    }
                    catch (SocketException ex)
                    {
                        e.Completed   = Send_Completed;
                        e.SocketError = ex.SocketErrorCode;
                        e.OnCompleted(null);
                    }
                }
                else
                {
                    e.Completed   = Send_Completed;
                    e.SocketError = SocketError.NotConnected;
                    e.OnCompleted(null);
                }
            }
            else
            {
                if (e.ConnectionId == ServerAsyncEventArgs.AnyNewConnectionId ||
                    e.ConnectionId == ServerAsyncEventArgs.AnyConnectionId ||
                    e.ConnectionId == connection.Id)
                {
                    connection.Socket.SendAsync(e, Send_Completed);
                }
                else
                {
                    e.Completed   = Send_Completed;
                    e.SocketError = SocketError.NotConnected;
                    e.OnCompleted(null);
                }
            }
        }
Exemplo n.º 36
0
 public static void CopyArrayFrom(this ArraySegment<byte> dst, int dstExtraOffset, ServerAsyncEventArgs e)
 {
     Buffer.BlockCopy(e.Buffer, e.Offset, dst.Array, dst.Offset + dstExtraOffset, Math.Min(e.Count, dst.Count));
 }
Exemplo n.º 37
0
        private void TurnServer_TurnDataReceived(ref ServerAsyncEventArgs e)
        {
            //lock (syncRoot)
            {
                TurnMessage response = null;

                try
                {
                    if (true)//(TransactionServer.GetCachedResponse(e, out response) == false)
                    {
                        TurnMessage request = TurnMessage.Parse(e.Buffer, e.Offset, e.BytesTransferred, TurnMessageRfc.MsTurn);

                        if (Authentificater.Process(request, out response))
                        {
                            Allocation allocation = null;
                            if (request.MsSequenceNumber != null)
                                allocation = allocations.Get(request.MsSequenceNumber.ConnectionId);

                            if (allocation != null)
                            {
                                if (request.MsSequenceNumber != null)
                                    response = allocation.GetResponse(request.MsSequenceNumber.SequenceNumber);
                            }

                            if (response == null)
                            {
                                if (allocation != null)
                                    allocation.TouchLifetime();

                                switch (request.MessageType)
                                {
                                    case MessageType.AllocateRequest:
                                        response = ProcessAllocateRequest(ref allocation, request, e.LocalEndPoint, e.RemoteEndPoint);
                                        break;

                                    case MessageType.SendRequest:
                                        response = ProcessSendRequest(allocation, request, ref e);
                                        break;

                                    case MessageType.SetActiveDestinationRequest:
                                        response = ProcessSetActiveDestinationRequest(allocation, request, e.RemoteEndPoint);
                                        break;
                                }

                                if (allocation != null && response != null)
                                    allocation.SetResponse(response);
                            }
                        }

                        //TransactionServer.CacheResponse(e, response);
                    }
                }
                catch (TurnMessageException ex)
                {
                    response = GetErrorResponse(ex.ErrorCode, e);
                }
                catch (TurnServerException ex)
                {
                    response = GetErrorResponse(ex.ErrorCode, e);
                }
                catch (Exception ex)
                {
                    response = GetErrorResponse(ErrorCode.ServerError, e);

                    logger.WriteError(ex.ToString());
                }

                if (response != null)
                    SendTurn(response, e.LocalEndPoint, e.RemoteEndPoint);
            }
        }
Exemplo n.º 38
0
        private void TurnServer_PeerDataReceived(ref ServerAsyncEventArgs e)
        {
            //lock (syncRoot)
            {
                try
                {
                    Allocation allocation = allocations.GetByPeer(e.LocalEndPoint, e.RemoteEndPoint);

                    if (allocation != null)
                    {
                        allocation.TouchLifetime();

                        if (allocation.IsActiveDestinationEnabled)
                        {
                            e.LocalEndPoint = allocation.Alocated;
                            e.RemoteEndPoint = allocation.ActiveDestination;
                            e.Count = e.BytesTransferred;
                            e.ConnectionId = ServerAsyncEventArgs.AnyNewConnectionId;

                            peerServer.SendAsync(e);

                            e = null;
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.WriteWarning(ex.ToString());
                }
            }
        }
Exemplo n.º 39
0
        public void Dettach(ref ServerAsyncEventArgs e, out ArraySegment<byte> segment1, out ArraySegment<byte> segment2)
        {
            if (readerStorage == Storage.E)
            {
                int size = headerData.Count;
                if (contentStorage == readerStorage)
                    size += contentData.Count;

                segment1 = Detach(ref e, size);
                segment2 = (contentStorage != readerStorage) ? Dettach(contentStorage) : new ArraySegment<byte>();
            }
            else
            {
                segment1 = Dettach(readerStorage);

                if (contentStorage != readerStorage)
                {
                    if (contentStorage == Storage.E)
                        segment2 = Detach(ref e, contentData.Count);
                    else
                        segment2 = Dettach(contentStorage);
                }
                else
                {
                    segment2 = new ArraySegment<byte>();
                }
            }
        }
Exemplo n.º 40
0
			public bool Proccess(ref ServerAsyncEventArgs e, out bool closeConnection)
			{
				this.e = e;

				if (index < maxThread)
				{
					release[index].Set();
					ThreadPool.QueueUserWorkItem(Proccess, index);
					done.WaitOne();
				}
				else
				{
					Proccess();
				}

				index = (index + 1) % (maxThread * 2);

				e = this.e;
				closeConnection = this.closeConnection;
				return repeat;
			}
Exemplo n.º 41
0
        private ArraySegment<byte> Detach(ref ServerAsyncEventArgs e, int size)
        {
            ServerAsyncEventArgs copy = null;
            if (e.BytesTransferred > size)
                copy = e.CreateDeepCopy();

            var result = e.DetachBuffer();

            EventArgsManager.Put(ref e);
            if (copy != null)
                e = copy;

            return result;
        }
Exemplo n.º 42
0
		private static void WriteHttpHeader(ServerAsyncEventArgs e)
		{
			using (var writer = new HttpMessageWriter())
			{
				writer.WriteStatusLine(StatusCodes.OK);
				writer.WriteContentLength(e.Count);
				writer.WriteAccessControlHeaders();
				writer.WriteCRLF();

				e.OffsetOffset -= writer.Count;
				e.Count += writer.Count;
				Buffer.BlockCopy(writer.Buffer, writer.Offset, e.Buffer, e.Offset, writer.Count);
			}
		}
Exemplo n.º 43
0
			public void AddOutgoingMessage(ServerAsyncEventArgs e)
			{
				outgoingMessages.Add(e);
			}
Exemplo n.º 44
0
        public bool Proccess(ref ServerAsyncEventArgs e, out bool closeConnection)
        {
            //  ----------------------------------------------------------
            //  |           | 0  | 1  | 2  | 3  | 4  | 5  | 6  | 7  | 8  |
            //  ----------------------------------------------------------
            //  |         e | H  | HC |    |    |    |    |    |    |    |
            //  |        e1 |    |    | H  | HC | H  | H  |    |    |    |
            //  |   Buffer1 |    |    |    |    |  C |    | H  | HC | H  |
            //  |   Buffer2 |    |    |    |    |    |  C |    |    |  C |
            //  ----------------------------------------------------------

            closeConnection = false;

            switch (state)
            {
                case StreamState.WaitingHeaders:
                    {
                        int oldBytesProccessed = bytesProccessed;

                        var data = new ArraySegment<byte>(e.Buffer, e.Offset + bytesProccessed, e.BytesTransferred - bytesProccessed);

                        PreProcessRaw(data);
                        var result = Parse(data);

                        switch (result.ParseCode)
                        {
                            case ParseCode.NotEnoughData:
                                {
                                    bytesProccessed += data.Count;

                                    ResetParser(ResetReason.NotEnoughData);

                                    Buffer1.Resize(MaximumHeadersSize);
                                    Buffer1.CopyTransferredFrom(e, oldBytesProccessed);
                                    state = StreamState.WaitingHeadersContinue;
                                }
                                break;

                            case ParseCode.Error:
                                {
                                    closeConnection = true;
                                }
                                break;

                            case ParseCode.Skip:
                                {
                                    bytesProccessed += result.Count;
                                }
                                break;

                            case ParseCode.HeaderDone:
                                {
                                    bytesProccessed += result.HeaderLength;

                                    SetReaderStorage(Storage.E, e.Buffer, e.Offset + oldBytesProccessed, result.HeaderLength);

                                    expectedContentLength = result.ContentLength;

                                    if (expectedContentLength <= 0)
                                    {
                                        SetReady();
                                    }
                                    else
                                    {
                                        int bytesLeft = e.BytesTransferred - bytesProccessed;

                                        if (bytesLeft >= expectedContentLength)
                                        {
                                            SetReady(Storage.E, e.Buffer, e.Offset + bytesProccessed, expectedContentLength);
                                            bytesProccessed += expectedContentLength;
                                        }
                                        else
                                        {
                                            if (expectedContentLength <= e.Count - e.BytesTransferred)
                                            {
                                                state = StreamState.WaitingMicroBody;
                                            }
                                            else if (expectedContentLength < MaximumHeadersSize)
                                            {
                                                if (Buffer1.IsInvalid || Buffer1.Capacity < expectedContentLength)
                                                    if (Buffer1.Resize(Math.Max(expectedContentLength, MinimumBuffer1Size)) == false)
                                                        closeConnection = true;

                                                if (closeConnection == false)
                                                {
                                                    Buffer1.CopyTransferredFrom(e, bytesProccessed);
                                                    state = StreamState.WaitingSmallBody;
                                                }
                                            }
                                            else
                                            {
                                                if (Buffer2.Resize(expectedContentLength) == false)
                                                    closeConnection = true;
                                                else
                                                {
                                                    Buffer2.CopyTransferredFrom(e, bytesProccessed);
                                                    state = StreamState.WaitingBigBody;
                                                }
                                            }

                                            if (closeConnection == false)
                                            {
                                                e1 = e;
                                                e = null;
                                                readerStorage = Storage.E1;
                                            }

                                            bytesProccessed += bytesLeft;
                                            receivedContentLength += bytesLeft;
                                        }
                                    }
                                }
                                break;
                        }
                    }
                    break;

                case StreamState.WaitingHeadersContinue:
                    {
                        int count = Math.Min(e.BytesTransferred - bytesProccessed, Buffer1.FreeSize);

                        PreProcessRaw(new ArraySegment<byte>(e.Buffer, e.Offset, e.BytesTransferred - bytesProccessed));

                        System.Buffer.BlockCopy(e.Buffer, e.Offset, Buffer1.Array, Buffer1.Offset + Buffer1.Count, count);

                        var data = new ArraySegment<byte>(Buffer1.Array, Buffer1.Offset, Buffer1.Count + count);
                        var result = Parse(data);

                        switch (result.ParseCode)
                        {
                            case ParseCode.NotEnoughData:
                                {
                                    ResetParser(ResetReason.NotEnoughData);

                                    if (data.Count < Buffer1.Capacity)
                                    {
                                        Buffer1.AddCount(count);
                                        bytesProccessed += count;
                                    }
                                    else
                                    {
                                        closeConnection = true;
                                    }
                                }
                                break;

                            case ParseCode.Error:
                                {
                                    closeConnection = true;
                                }
                                break;

                            case ParseCode.Skip:
                                throw new NotImplementedException();

                            case ParseCode.HeaderDone:
                                {
                                    int delta = result.HeaderLength - Buffer1.Count;
                                    Buffer1.AddCount(delta);
                                    bytesProccessed += delta;

                                    SetReaderStorage(Storage.Buffer1, Buffer1.Array, Buffer1.Offset, result.HeaderLength);

                                    expectedContentLength = result.ContentLength;

                                    if (expectedContentLength <= 0)
                                    {
                                        SetReady();
                                    }
                                    else
                                    {
                                        int bytesLeft = e.BytesTransferred - bytesProccessed;

                                        if (bytesLeft >= expectedContentLength)
                                        {
                                            SetReady(Storage.E, e.Buffer, e.Offset + bytesProccessed, expectedContentLength);
                                            bytesProccessed += expectedContentLength;
                                        }
                                        else
                                        {
                                            if (expectedContentLength < Buffer1.FreeSize)
                                            {
                                                Buffer1.AddCount(bytesLeft);
                                                state = StreamState.WaitingSmallBody;
                                            }
                                            else
                                            {
                                                if (Buffer2.Resize(expectedContentLength) == false)
                                                    closeConnection = true;
                                                Buffer2.CopyTransferredFrom(e, bytesProccessed);
                                                state = StreamState.WaitingBigBody;
                                            }

                                            bytesProccessed += bytesLeft;
                                            receivedContentLength += bytesLeft;
                                        }
                                    }
                                }
                                break;
                        }
                    }
                    break;

                case StreamState.WaitingMicroBody:
                    {
                        int count = Math.Min(e.BytesTransferred - bytesProccessed,
                            expectedContentLength - receivedContentLength);

                        var data = new ArraySegment<byte>(e.Buffer, e.Offset + bytesProccessed, count);

                        PreProcessRaw(data);
                        System.Buffer.BlockCopy(data.Array, data.Offset, e1.Buffer, e1.Offset + e1.BytesTransferred, data.Count);

                        //System.Buffer.BlockCopy(e.Buffer, e.Offset + bytesProccessed,
                        //    e1.Buffer, e1.Offset + e1.BytesTransferred, count);

                        e1.BytesTransferred += count;

                        receivedContentLength += count;
                        bytesProccessed += count;

                        if (receivedContentLength == expectedContentLength)
                            SetReady(Storage.E1, e1.Buffer, e1.Offset + e1.BytesTransferred - receivedContentLength, receivedContentLength);
                    }
                    break;

                case StreamState.WaitingSmallBody:
                    {
                        int count = Math.Min(e.BytesTransferred - bytesProccessed,
                            expectedContentLength - receivedContentLength);

                        var data = new ArraySegment<byte>(e.Buffer, e.Offset + bytesProccessed, count);

                        PreProcessRaw(data);
                        Buffer1.CopyFrom(data);
                        //Buffer1.CopyFrom(e.Buffer, e.Offset + bytesProccessed, count);

                        receivedContentLength += count;
                        bytesProccessed += count;

                        if (receivedContentLength == expectedContentLength)
                            SetReady(Storage.Buffer1, Buffer1.Array, Buffer1.Offset + Buffer1.Count - receivedContentLength, receivedContentLength);
                    }
                    break;

                case StreamState.WaitingBigBody:
                    {
                        int count = Math.Min(e.BytesTransferred - bytesProccessed,
                            expectedContentLength - receivedContentLength);

                        var data = new ArraySegment<byte>(e.Buffer, e.Offset + bytesProccessed, count);

                        PreProcessRaw(data);
                        Buffer2.CopyFrom(data);
                        //Buffer2.CopyFrom(e.Buffer, e.Offset + bytesProccessed, count);

                        receivedContentLength += count;
                        bytesProccessed += count;

                        if (receivedContentLength == expectedContentLength)
                            SetReady(Storage.Buffer2, Buffer2.Array, Buffer2.Offset + Buffer2.Count - receivedContentLength, receivedContentLength);
                    }
                    break;
            }

            bool continueProccessing = closeConnection == false &&
                e != null && bytesProccessed < e.BytesTransferred;

            if (continueProccessing == false)
                bytesProccessed = 0;

            return continueProccessing;
        }
Exemplo n.º 45
0
		private void ServersManager_BeforeSend(ServersManager<Connection> s, Connection c, ServerAsyncEventArgs e)
		{
			if (c != null && c.Mode == Connection.Modes.WebSocket)
			{
				//c.BeforeSend(e);

				var header = new WebSocketHeader()
				{
					Fin = true,
					Opcode = websocketOpcode.HasValue ? websocketOpcode.Value : c.WebSocketHeader.Opcode,
					PayloadLength = e.Count,
				};

				int headerLength = header.GetHeaderLength();

				if (e.OffsetOffset < headerLength)
					throw new InvalidProgramException(@"TransportLayer.ServersManager_BeforeSend no reserved space for WebSocket header");

				e.OffsetOffset -= headerLength;
				e.Count += headerLength;

				header.GenerateHeader(e.OutgoingData);
			}
		}
Exemplo n.º 46
0
		private void ServersManager_Sent(ServersManager<Connection> s, ref ServerAsyncEventArgs e)
		{
			if (e.SocketError != SocketError.Success)
			{
				Tracer.WriteInformation("Send error");

				switch (e.UserTokenForSending2 & 0x000000ff)
				{
					case SipModule:
						SendErrorSip(e.UserTokenForSending);
						break;
					case HttpModule:
						// e.UserTokenForSending2 >> 8 == httpModuleId
						break;
					case AjaxModule:
						ajax.SendError(e.UserTokenForSending);
						break;
				}
			}
		}
Exemplo n.º 47
0
		public void SendAsyncHttp(ServerAsyncEventArgs e, int httpModuleId)
		{
			e.UserTokenForSending2 = HttpModule | (httpModuleId << 8);
			serversManager.SendAsync(e);
		}
Exemplo n.º 48
0
        static bool ServersManager_Received(ServersManager<BaseConnection2> server, BaseConnection c, ref ServerAsyncEventArgs e)
        {
            e.Count = e.BytesTransferred;
            server.SendAsync(e);
            e = null;

            return true;
        }
Exemplo n.º 49
0
		private bool ServersManager_Received(ServersManager<Connection> s, Connection connection1, ref ServerAsyncEventArgs e1)
		{
			connection = connection1;
			e = e1;

			bool closeConnection = OnReceived();

			e1 = e;

			connection = null;
			e = null;

			return closeConnection;
		}
Exemplo n.º 50
0
        public void ResetState()
        {
            ready = false;
            headerData = new ArraySegment<byte>();

            expectedContentLength = 0;
            receivedContentLength = 0;
            contentData = new ArraySegment<byte>();

            readerStorage = Storage.None;
            contentStorage = Storage.None;

            ResetParser(ResetReason.ResetStateCalled);

            if (buffer1 != null)
            {
                buffer1UnusedCount = (buffer1.Count <= 0) ? buffer1UnusedCount + 1 : 0;

                if (buffer1.Capacity <= MaximumHeadersSize && buffer1UnusedCount < 8)
                    buffer1.Clear();
                else
                    buffer1.Free();
            }

            if (buffer2 != null)
                buffer2.Free();

            if (e1 != null)
            {
                e1.Dispose();
                e1 = null;
            }

            keepAliveRecived = 0;

            state = StreamState.WaitingHeaders;
        }
Exemplo n.º 51
0
		private void SendWriter(ServerAsyncEventArgs r, HttpMessageWriter writer)
		{
			r.Count = writer.Count;
			r.OffsetOffset = writer.OffsetOffset;
			r.AttachBuffer(writer.Detach());

			SendAsync(r, false);
		}
Exemplo n.º 52
0
 public bool CopyTransferredFrom(ServerAsyncEventArgs e, int skipBytes)
 {
     #if DEBUG
     if (e.Count < skipBytes)
         throw new ArgumentOutOfRangeException();
     #endif
     return CopyFrom(e.Buffer, e.Offset + skipBytes, e.BytesTransferred - skipBytes);
 }
Exemplo n.º 53
0
		//private bool IsInitialRequest(HttpMessageReader httpReader)
		//{
		//    return httpReader.RequestUri.ToString().Contains("connect=1");
		//}

		//private int GetSessionId(HttpMessageReader httpReader)
		//{
		//    uint cookie;
		//    if (httpReader.TryGetCookieUInt(cookieName, out cookie))
		//        return Session.GetSessionId(GetConnectionId(httpReader), (int)cookie);

		//    return -1;
		//}

		private void SendSipEventArgs(ServerAsyncEventArgs e, Session session)
		{
			session.RestoreAddresses(e);

			WriteHttpHeader(e);
			SendAsync(e, true);
		}
Exemplo n.º 54
0
		public BufferHandle Dettach(ref ServerAsyncEventArgs e)
		{
			ArraySegment<byte> segment1, segment2;
			base.Dettach(ref e, out segment1, out segment2);

			return new BufferHandle(segment1, segment2);
		}
Exemplo n.º 55
0
 static void ServersManager_Sent(ServersManager<BaseConnection2> server, ref ServerAsyncEventArgs e)
 {
     if (e.SocketError != SocketError.Success)
         Console.WriteLine("Sent error: {0}", e.SocketError.ToString());
 }
Exemplo n.º 56
0
        private void GetBuffer(ServerEndPoint local, IPEndPoint remote, int length, out ServerAsyncEventArgs e, out int offset)
        {
            int headerLength = (local.Protocol == ServerProtocol.Tcp) ? TcpFramingHeader.TcpFramingHeaderLength : 0;

            e = EventArgsManager.Get();

            e.ConnectionId = ServerAsyncEventArgs.AnyConnectionId;
            e.LocalEndPoint = local;
            e.RemoteEndPoint = remote;
            e.Count = headerLength + length;
            e.AllocateBuffer();

            if (headerLength > 0)
                TcpFramingHeader.GetBytes(e.Buffer, e.Offset, TcpFrameType.ControlMessage, length);

            offset = e.Offset + headerLength;
        }
Exemplo n.º 57
0
        private bool PeerServer_Received(ServersManager<PeerConnection> s, BaseConnection с, ref ServerAsyncEventArgs e)
        {
            //lock (syncRoot)
            {
                try
                {
                    Allocation allocation = allocations.Get(e.LocalEndPoint);

                    if (allocation != null)
                    {
                        if (allocation.Permissions.IsPermited(e.RemoteEndPoint))
                        {
                            allocation.TouchLifetime();

                            if (allocation.ActiveDestination.IsEqual(e.RemoteEndPoint))
                            {
                                if (e.LocalEndPoint.Protocol == ServerProtocol.Tcp)
                                {
                                    TcpFramingHeader.GetBytes(e.Buffer, e.Offset, TcpFrameType.EndToEndData, e.BytesTransferred);

                                    e.Count = e.OffsetOffset + e.BytesTransferred;
                                    e.OffsetOffset = 0;
                                }
                                else
                                {
                                    e.Count = e.BytesTransferred;
                                }

                                e.LocalEndPoint = allocation.Local;
                                e.RemoteEndPoint = allocation.Reflexive;
                                e.ConnectionId = ServerAsyncEventArgs.AnyConnectionId;

                                turnServer.SendAsync(e);

                                e = null;
                            }
                            else
                            {
                                TurnMessage message = new TurnMessage()
                                {
                                    IsAttributePaddingDisabled = true,
                                    MessageType = MessageType.DataIndication,
                                    TransactionId = TransactionServer.GenerateTransactionId(),

                                    MagicCookie = new MagicCookie(),

                                    RemoteAddress = new RemoteAddress()
                                    {
                                        IpAddress = e.RemoteEndPoint.Address,
                                        Port = (UInt16)e.RemoteEndPoint.Port,
                                    },

                                    Data = new Data()
                                    {
                                        ValueRef = e.Buffer,
                                        ValueRefOffset = e.Offset,
                                        ValueRefLength = e.BytesTransferred,
                                    },
                                };

                                SendTurn(message, allocation.Local, allocation.Reflexive);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.WriteWarning(ex.ToString());
                }
            }

            return true;
        }
Exemplo n.º 58
0
        private TurnMessage ProcessSendRequest(Allocation allocation, TurnMessage request, ref ServerAsyncEventArgs e)
        {
            try
            {
                if (allocation == null)
                    throw new TurnServerException(ErrorCode.NoBinding);

                if (request.Data == null || request.DestinationAddress == null)
                    throw new TurnServerException(ErrorCode.BadRequest);

                allocation.Permissions.Permit(request.DestinationAddress.IpEndPoint);

                e.LocalEndPoint = allocation.Alocated;
                e.RemoteEndPoint = request.DestinationAddress.IpEndPoint;
                e.Offset = request.Data.ValueRefOffset;
                e.Count = request.Data.ValueRefLength;
                e.ConnectionId = ServerAsyncEventArgs.AnyNewConnectionId;

                peerServer.SendAsync(e);

                e = null;
            }
            catch (Exception ex)
            {
                logger.WriteWarning(ex.ToString());
            }

            // [MS-TURN] The server MUST NOT respond to a client with either
            // a Send response or a Send error response.
            return null;
        }
Exemplo n.º 59
0
        public new void Dispose()
        {
            base.Dispose();

            if (buffer1 != null)
                buffer1.Dispose();

            if (buffer2 != null)
                buffer2.Dispose();

            if (e1 != null)
            {
                e1.Dispose();
                e1 = null;
            }
        }
Exemplo n.º 60
0
		private void SendAsyncAjax(ServerAsyncEventArgs e, bool sipAjax)
		{
			e.UserTokenForSending2 = sipAjax ? SipModule : AjaxModule;
			serversManager.SendAsync(e);
		}