Example #1
0
        private void ProcessConnectionBuffer(ref ConnectionState state)
        {
            Socket clientSocket = state.ClientSocket;

            NBTConnectionReceiveBuffer receiveBuffer = state.ReceiveBuffer;

            while (receiveBuffer.HasCompletePacket())
            {
                SessionPacket packet = null;
                try
                {
                    packet = receiveBuffer.DequeuePacket();
                }
                catch (Exception ex)
                {
                    state.ClientSocket.Close();
                    state.LogToServer(Severity.Warning, "Rejected Invalid NetBIOS session packet: {0}", ex.Message);
                    break;
                }

                if (packet != null)
                {
                    ProcessPacket(packet, ref state);
                }
            }
        }
Example #2
0
        public bool Connect(IPAddress serverAddress, SMBTransportType transport, bool forceExtendedSecurity, string serverName = null)
        {
            m_transport = transport;
            if (!m_isConnected)
            {
                m_forceExtendedSecurity = forceExtendedSecurity;
                int port;
                port = transport == SMBTransportType.NetBiosOverTCP ? NetBiosOverTCPPort : DirectTCPPort;

                if (!ConnectSocket(serverAddress, port))
                {
                    return(false);
                }

                if (transport == SMBTransportType.NetBiosOverTCP)
                {
                    SessionRequestPacket sessionRequest = new SessionRequestPacket();
                    sessionRequest.CalledName  = NetBiosUtils.GetMSNetBiosName(serverName ?? "*SMBSERVER", NetBiosSuffix.FileServiceService);
                    sessionRequest.CallingName = NetBiosUtils.GetMSNetBiosName(Environment.MachineName, NetBiosSuffix.WorkstationService);
                    TrySendPacket(m_clientSocket, sessionRequest);

                    SessionPacket sessionResponsePacket = WaitForSessionResponsePacket();
                    if (!(sessionResponsePacket is PositiveSessionResponsePacket))
                    {
                        m_clientSocket.Disconnect(false);
                        if (!ConnectSocket(serverAddress, port))
                        {
                            return(false);
                        }

                        NameServiceClient nameServiceClient = new NameServiceClient(serverAddress);
                        serverName = nameServiceClient.GetServerName();
                        if (serverName == null)
                        {
                            return(false);
                        }

                        sessionRequest.CalledName = serverName;
                        TrySendPacket(m_clientSocket, sessionRequest);

                        sessionResponsePacket = WaitForSessionResponsePacket();
                        if (!(sessionResponsePacket is PositiveSessionResponsePacket))
                        {
                            return(false);
                        }
                    }
                }

                bool supportsDialect = NegotiateDialect(m_forceExtendedSecurity);
                if (!supportsDialect)
                {
                    m_clientSocket.Close();
                }
                else
                {
                    m_isConnected = true;
                }
            }
            return(m_isConnected);
        }
Example #3
0
    void OnReceiveStartSession(int node, PacketId id, byte[] data)
    {
        Debug.Log("ReceiveStartSession");

#if UNUSE_MATCHING_SERVER
        SessionData response = new SessionData();

        {
            int         memberNum = NetConfig.PLAYER_MAX;
            string      hostname  = Dns.GetHostName();
            IPAddress[] adrList   = Dns.GetHostAddresses(hostname);
            response.endPoints = new EndPointData[memberNum];

            response.result   = MatchingResult.Success;
            response.playerId = GlobalParam.get().global_account_id;
            response.members  = memberNum;

            for (int i = 0; i < memberNum; ++i)
            {
                response.endPoints[i]           = new EndPointData();
                response.endPoints[i].ipAddress = adrList[0].ToString();
                response.endPoints[i].port      = NetConfig.GAME_PORT;
            }
        }
#else
        SessionPacket packet   = new SessionPacket(data);
        SessionData   response = packet.GetPacket();
#endif
        playerId = response.playerId;

        SetSessionMembers(response.result, response.members, response.endPoints);

        matchingState = State.MatchingEnded;
    }
Example #4
0
        public void ProcessPacket(byte[] packetBytes, StateObject state)
        {
            SessionPacket packet = null;

#if DEBUG
            packet = SessionPacket.GetSessionPacket(packetBytes);
#else
            try
            {
                packet = SessionPacket.GetSessionPacket(packetBytes);
            }
            catch (Exception)
            {
                state.ClientSocket.Close();
                return;
            }
#endif
            if (packet is SessionRequestPacket && m_transport == SMBTransportType.NetBiosOverTCP)
            {
                PositiveSessionResponsePacket response = new PositiveSessionResponsePacket();
                TrySendPacket(state, response);
            }
            else if (packet is SessionKeepAlivePacket && m_transport == SMBTransportType.NetBiosOverTCP)
            {
                // [RFC 1001] NetBIOS session keep alives do not require a response from the NetBIOS peer
            }
            else if (packet is SessionMessagePacket)
            {
                SMBMessage message = null;
#if DEBUG
                message = SMBMessage.GetSMBMessage(packet.Trailer);
                Log("[{0}] Message Received: {1} Commands, First Command: {2}, Packet length: {3}", DateTime.Now.ToString("HH:mm:ss:ffff"), message.Commands.Count, message.Commands[0].CommandName.ToString(), packet.Length);
#else
                try
                {
                    message = SMBMessage.GetSMBMessage(packet.Trailer);
                }
                catch (Exception)
                {
                    state.ClientSocket.Close();
                    return;
                }
#endif
                ProcessMessage(message, state);
            }
            else
            {
#if DEBUG
                Log("[{0}] Invalid NetBIOS packet", DateTime.Now.ToString("HH:mm:ss:ffff"));
#endif
                state.ClientSocket.Close();
                return;
            }
        }
Example #5
0
 public static void TrySendPacket(Socket serverSocket, SessionPacket response)
 {
     try
     {
         serverSocket.Send(response.GetBytes());
     }
     catch (SocketException)
     {
     }
     catch (ObjectDisposedException)
     {
     }
 }
Example #6
0
 public static void TrySendPacket(Socket socket, SessionPacket packet)
 {
     try
     {
         socket.Send(packet.GetBytes());
     }
     catch (SocketException)
     {
     }
     catch (ObjectDisposedException)
     {
     }
 }
    void OnReceiveStartSession(int node, PacketId id, byte[] data)
    {
        Debug.Log("ReceiveStartSession");

        SessionPacket packet   = new SessionPacket(data);
        SessionData   response = packet.GetPacket();

        playerId = response.playerId;

        SetSessionMembers(response.result, response.members, response.endPoints);

        matchingState = State.MatchingEnded;
    }
Example #8
0
 public static async Task TrySendPacketAsync(Socket socket, SessionPacket packet, CancellationToken cancellationToken = default)
 {
     try
     {
         var packetBytes = packet.GetBytes().AsMemory();
         await socket.SendAsync(packetBytes, SocketFlags.None, cancellationToken);
     }
     catch (SocketException)
     {
     }
     catch (ObjectDisposedException)
     {
     }
 }
        public void LoadSummary(Packet[] packets, byte driver_index)
        {
            if (packets.Length == 0)
            {
                throw new Exception("The length of the supplied packet array was 0!");
            }

            SessionId = packets[0].UniqueSessionId;

            //Get circuit
            foreach (Packet p in packets)
            {
                if (p.PacketType == PacketType.Session)
                {
                    SessionPacket sp = (SessionPacket)p;

                    //Circuit
                    Circuit = sp.SessionTrack;

                    //Session mode
                    SessionMode = sp.SessionTypeMode;
                }

                if (p.PacketType == PacketType.Participants)
                {
                    ParticipantPacket pp = (ParticipantPacket)p;

                    //Selected team
                    SelectedTeam = pp.FieldParticipantData[driver_index].ManufacturingTeam;

                    //Selected Driver
                    SelectedDriver = pp.FieldParticipantData[driver_index].PilotingDriver;

                    //Name
                    string driver_name       = pp.FieldParticipantData[driver_index].Name.TrimEnd('\0');
                    string driver_name_clean = "";
                    foreach (char c in driver_name)
                    {
                        int as_int = Convert.ToInt32(c);
                        if ((as_int < 127 && as_int != 92) == true || as_int == 160) //It is in the normal character range and not a backward slash OR it is a blank space.
                        {
                            driver_name_clean = driver_name_clean + c.ToString();
                        }
                    }
                    DriverName = driver_name_clean;
                }
            }
            SessionCreatedAt = DateTimeOffset.Now;
        }
Example #10
0
        public static void TrySendPacket(StateObject state, SessionPacket response)
        {
            Socket clientSocket = state.ClientSocket;

            try
            {
                clientSocket.Send(response.GetBytes());
            }
            catch (SocketException)
            {
            }
            catch (ObjectDisposedException)
            {
            }
        }
Example #11
0
        /// <summary>创建会话</summary>
        /// <param name="client"></param>
        /// <returns></returns>
        protected virtual TcpSession CreateSession(Socket client)
        {
            var session = new TcpSession(this, client);

            // 服务端不支持掉线重连
            session.AutoReconnect      = 0;
            session.Log                = Log;
            session.LogSend            = LogSend;
            session.LogReceive         = LogReceive;
            session.StatSend.Parent    = StatSend;
            session.StatReceive.Parent = StatReceive;
            session.Packet             = SessionPacket?.Create();
            session.ProcessAsync       = ProcessAsync;

            return(session);
        }
Example #12
0
        private void ProcessPacket(SessionPacket packet, ConnectionState state)
        {
            if (packet is SessionMessagePacket)
            {
                SMB1Message message;
                try
                {
                    message = SMB1Message.GetSMB1Message(packet.Trailer);
                }
                catch (Exception ex)
                {
                    Log("Invalid SMB1 message: " + ex.Message);
                    state.ClientSocket.Close();
                    m_isConnected = false;
                    return;
                }

                // [MS-CIFS] 3.2.5.1 - If the MID value is the reserved value 0xFFFF, the message can be an OpLock break
                // sent by the server. Otherwise, if the PID and MID values of the received message are not found in the
                // Client.Connection.PIDMIDList, the message MUST be discarded.
                if ((message.Header.MID != 0xFFFF || message.Header.Command != CommandName.SMB_COM_LOCKING_ANDX) && (message.Header.PID != 0 || message.Header.MID != 0))
                {
                    return;
                }

                lock (m_incomingQueueLock)
                {
                    m_incomingQueue.Add(message);
                    m_incomingQueueEventHandle?.Set();
                }
            }
            else if ((packet is PositiveSessionResponsePacket || packet is NegativeSessionResponsePacket) && m_transport == SMBTransportType.NetBiosOverTcp)
            {
                m_sessionResponsePacket = packet;
                m_sessionResponseEventHandle?.Set();
            }
            else if (packet is SessionKeepAlivePacket && m_transport == SMBTransportType.NetBiosOverTcp)
            {
                // [RFC 1001] NetBIOS session keep alives do not require a response from the NetBIOS peer
            }
            else
            {
                Log("Inappropriate NetBIOS session packet");
                state.ClientSocket.Close();
            }
        }
Example #13
0
        public static bool TrySendPacket(Socket socket, SessionPacket packet)
        {
            bool success = false;

            try
            {
                socket.Send(packet.GetBytes());
                success = true;
            }
            catch (SocketException)
            {
            }
            catch (ObjectDisposedException)
            {
            }
            return(success);
        }
Example #14
0
        private void ProcessPacket(SessionPacket packet, ConnectionState state)
        {
            if (packet is SessionKeepAlivePacket && m_transport == SMBTransportType.NetBiosOverTCP)
            {
                // [RFC 1001] NetBIOS session keep alives do not require a response from the NetBIOS peer
            }
            else if (packet is PositiveSessionResponsePacket && m_transport == SMBTransportType.NetBiosOverTCP)
            {
            }
            else if (packet is NegativeSessionResponsePacket && m_transport == SMBTransportType.NetBiosOverTCP)
            {
                m_clientSocket.Dispose();
                m_isConnected = false;
            }
            else if (packet is SessionMessagePacket)
            {
                SMB2Command command;
                try
                {
                    command = SMB2Command.ReadResponse(packet.Trailer, 0);
                }
                catch (Exception ex)
                {
                    Log("Invalid SMB2 response: " + ex.Message);
                    m_clientSocket.Dispose();
                    m_isConnected = false;
                    return;
                }

                // [MS-SMB2] 3.2.5.1.2 - If the MessageId is 0xFFFFFFFFFFFFFFFF, this is not a reply to a previous request,
                // and the client MUST NOT attempt to locate the request, but instead process it as follows:
                // If the command field in the SMB2 header is SMB2 OPLOCK_BREAK, it MUST be processed as specified in 3.2.5.19.
                // Otherwise, the response MUST be discarded as invalid.
                if (command.Header.MessageID != 0xFFFFFFFFFFFFFFFF || command.Header.Command == SMB2CommandName.OplockBreak)
                {
                    lock (m_incomingQueueLock)
                    {
                        m_credits += command.Header.Credits;
                        Log("[ProcessPacket] CreditsResponse:" + m_credits);

                        m_incomingQueue.Add(command);
                        m_incomingQueueEventHandle.Set();
                    }
                }
            }
        }
Example #15
0
        public void Packet4()
        {
            SessionPacket ph = m;

            FlexBuffer buf = new FlexBuffer(new byte[] { (byte)VERSION,
                                                         unchecked ((byte)BYTE), 2, 0, unchecked ((byte)NONE) });

            mh.handled = false;

            ph.SessionPacket(who, buf);

            Assert.AreEqual(What.OOB_NOTIFY_HANDLER, mh.what);
            Assert.AreEqual(ps, m.GetTransport());
            Assert.AreEqual(who, mh.xsender);
            Assert.IsNotNull(mh.xmsg);
            Assert.AreEqual(MyValueFactory.mt_add_result, mh.xmsg.GetXType);
            Assert.AreEqual(0, mh.xmsg.Count);
        }
Example #16
0
        internal SessionPacket WaitForSessionResponsePacket()
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            while (stopwatch.ElapsedMilliseconds < TimeOut)
            {
                if (m_sessionResponsePacket != null)
                {
                    SessionPacket result = m_sessionResponsePacket;
                    m_sessionResponsePacket = null;
                    return(result);
                }

                m_sessionResponseEventHandle.WaitOne(100);
            }

            return(null);
        }
Example #17
0
        public void Packet1()
        {
            //    PacketHandler ph = m;
            SessionPacket ph = m;

            FlexBuffer buf = new FlexBuffer(new byte[] { (byte)VERSION,
                                                         unchecked ((byte)BYTE), 1, 0, unchecked ((byte)NONE) });

            mh.handled = true;

            //   ph.Packet( who, buf );
            ph.SessionPacket(who, buf);

            Assert.AreEqual(What.TESTMESSAGEHANDLERMESSAGE, mh.what);
            Assert.AreEqual(ps, m.GetTransport());
            Assert.AreEqual(who, mh.xsender);
            Assert.IsNotNull(mh.xmsg);
            Assert.AreEqual(MyValueFactory.mt_add, mh.xmsg.GetXType);
            Assert.AreEqual(0, mh.xmsg.Count);
        }
Example #18
0
        private SessionPacket WaitForSessionResponsePacket()
        {
            const int timeOut   = 5000;
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            while (stopwatch.ElapsedMilliseconds < timeOut)
            {
                if (m_sessionResponsePacket != null)
                {
                    SessionPacket result = m_sessionResponsePacket;
                    m_sessionResponsePacket = null;
                    return(result);
                }

                m_sessionResponseEventHandle?.WaitOne(100);
            }

            throw new TimeoutException($"WaitForSessionResponsePacket timed out after {timeOut} ms");
        }
        private void ProcessSessionAcknowledgement(ClientConnection client, SubPacket packet)
        {
            packet.DebugPrintSubPacket();
            SessionPacket sessionPacket = new SessionPacket(packet.data);
            String        clientVersion = sessionPacket.version;

            Program.Log.Info("Got acknowledgment for secure session.");
            Program.Log.Info("CLIENT VERSION: {0}", clientVersion);

            uint userId = Database.GetUserIdFromSession(sessionPacket.session);

            client.currentUserId       = userId;
            client.currentSessionToken = sessionPacket.session;;

            if (userId == 0)
            {
                ErrorPacket errorPacket = new ErrorPacket(sessionPacket.sequence, 0, 0, 13001, "Your session has expired, please login again.");
                SubPacket   subpacket   = errorPacket.BuildPacket();
                subpacket.SetTargetId(0xe0006868);
                BasePacket errorBasePacket = BasePacket.CreatePacket(subpacket, true, false);
                BasePacket.EncryptPacket(client.blowfish, errorBasePacket);
                client.QueuePacket(errorBasePacket);

                Program.Log.Info("Invalid session, kicking...");
                return;
            }

            Program.Log.Info("USER ID: {0}", userId);

            List <Account> accountList    = new List <Account>();
            Account        defaultAccount = new Account();

            defaultAccount.id   = 1;
            defaultAccount.name = "FINAL FANTASY XIV";
            accountList.Add(defaultAccount);
            AccountListPacket listPacket = new AccountListPacket(1, accountList);
            BasePacket        basePacket = BasePacket.CreatePacket(listPacket.BuildPackets(), true, false);

            BasePacket.EncryptPacket(client.blowfish, basePacket);
            client.QueuePacket(basePacket);
        }
Example #20
0
        private void ProcessConnectionBuffer(ConnectionState state)
        {
            NBTConnectionReceiveBuffer receiveBuffer = state.ReceiveBuffer;

            while (receiveBuffer.HasCompletePacket())
            {
                SessionPacket packet = null;
                try
                {
                    packet = receiveBuffer.DequeuePacket();
                }
                catch (Exception)
                {
                    state.ClientSocket.Close();
                    break;
                }

                if (packet != null)
                {
                    ProcessPacket(packet, state);
                }
            }
        }
Example #21
0
    void ProxyManager_OnPacketLog(Packet packet, GridProxy.Direction direction, System.Net.IPEndPoint endpoint)
    {
        Application.Invoke((xsender, xe) =>
        {
            PacketCounter++;

            if (direction == GridProxy.Direction.Incoming)
            {
                PacketsInCounter++;
                PacketsInBytes += packet.Length;
            }
            else
            {
                PacketsOutCounter++;
                PacketsOutBytes += packet.Length;
            }

            SessionPacket sessionPacket = new SessionPacket(packet, direction, endpoint,
                                                            PacketDecoder.InterpretOptions(packet.Header) + " Seq: " + packet.Header.Sequence.ToString() + " Freq:" + packet.Header.Frequency.ToString());

            sessionPacket.Columns = new string[] { PacketCounter.ToString(), sessionPacket.TimeStamp.ToString("HH:mm:ss.fff"), sessionPacket.Protocol, sessionPacket.Name, sessionPacket.Length.ToString(), sessionPacket.Host, sessionPacket.ContentType };
            messages.AddSession(sessionPacket);
        });
    }
Example #22
0
        private void ProcessPacket(SessionPacket packet, ConnectionState state)
        {
            if (packet is SessionKeepAlivePacket && m_transport == SMBTransportType.NetBiosOverTCP)
            {
                // [RFC 1001] NetBIOS session keep alives do not require a response from the NetBIOS peer
            }
            else if (packet is PositiveSessionResponsePacket && m_transport == SMBTransportType.NetBiosOverTCP)
            {
            }
            else if (packet is NegativeSessionResponsePacket && m_transport == SMBTransportType.NetBiosOverTCP)
            {
                m_clientSocket.Close();
                m_isConnected = false;
            }
            else if (packet is SessionMessagePacket)
            {
                SMB1Message message;
                try
                {
                    message = SMB1Message.GetSMB1Message(packet.Trailer);
                }
                catch (Exception ex)
                {
                    Log("Invalid SMB1 message: " + ex.Message);
                    m_clientSocket.Close();
                    m_isConnected = false;
                    return;
                }

                lock (m_incomingQueueLock)
                {
                    m_incomingQueue.Add(message);
                    m_incomingQueueEventHandle.Set();
                }
            }
        }
Example #23
0
 public void SetSession(SessionPacket session)
 {
 }
Example #24
0
        private void ProcessPacket(SessionPacket packet, ref ConnectionState state)
        {
            if (packet is SessionMessagePacket)
            {
                // Note: To be compatible with SMB2 specifications, we must accept SMB_COM_NEGOTIATE.
                // We will disconnect the connection if m_enableSMB1 == false and the client does not support SMB2.
                bool acceptSMB1 = (state.Dialect == SMBDialect.NotSet || state.Dialect == SMBDialect.NTLM012);
                bool acceptSMB2 = (m_enableSMB2 && (state.Dialect == SMBDialect.NotSet || state.Dialect == SMBDialect.SMB202 || state.Dialect == SMBDialect.SMB210 || state.Dialect == SMBDialect.SMB300));

                if (SMB1Header.IsValidSMB1Header(packet.Trailer))
                {
                    if (!acceptSMB1)
                    {
                        state.LogToServer(Severity.Verbose, "Rejected SMB1 message");
                        state.ClientSocket.Close();
                        return;
                    }

                    SMB1Message message = null;
                    try
                    {
                        message = SMB1Message.GetSMB1Message(packet.Trailer);
                    }
                    catch (Exception ex)
                    {
                        state.LogToServer(Severity.Warning, "Invalid SMB1 message: " + ex.Message);
                        state.ClientSocket.Close();
                        return;
                    }
                    state.LogToServer(Severity.Verbose, "SMB1 message received: {0} requests, First request: {1}, Packet length: {2}", message.Commands.Count, message.Commands[0].CommandName.ToString(), packet.Length);
                    if (state.Dialect == SMBDialect.NotSet && m_enableSMB2)
                    {
                        // Check if the client supports SMB 2
                        List <string> smb2Dialects = SMB2.NegotiateHelper.FindSMB2Dialects(message);
                        if (smb2Dialects.Count > 0)
                        {
                            SMB2Command response = SMB2.NegotiateHelper.GetNegotiateResponse(smb2Dialects, m_securityProvider, state, m_transport, m_serverGuid, m_serverStartTime);
                            if (state.Dialect != SMBDialect.NotSet)
                            {
                                state = new SMB2ConnectionState(state);
                                m_connectionManager.AddConnection(state);
                            }
                            EnqueueResponse(state, response);
                            return;
                        }
                    }

                    if (m_enableSMB1)
                    {
                        ProcessSMB1Message(message, ref state);
                    }
                    else
                    {
                        // [MS-SMB2] 3.3.5.3.2 If the string is not present in the dialect list and the server does not implement SMB,
                        // the server MUST disconnect the connection [..] without sending a response.
                        state.LogToServer(Severity.Verbose, "Rejected SMB1 message");
                        state.ClientSocket.Close();
                    }
                }
                else if (SMB2Header.IsValidSMB2Header(packet.Trailer))
                {
                    if (!acceptSMB2)
                    {
                        state.LogToServer(Severity.Verbose, "Rejected SMB2 message");
                        state.ClientSocket.Close();
                        return;
                    }

                    List <SMB2Command> requestChain;
                    try
                    {
                        requestChain = SMB2Command.ReadRequestChain(packet.Trailer, 0);
                    }
                    catch (Exception ex)
                    {
                        state.LogToServer(Severity.Warning, "Invalid SMB2 request chain: " + ex.Message);
                        state.ClientSocket.Close();
                        return;
                    }
                    state.LogToServer(Severity.Verbose, "SMB2 request chain received: {0} requests, First request: {1}, Packet length: {2}", requestChain.Count, requestChain[0].CommandName.ToString(), packet.Length);
                    ProcessSMB2RequestChain(requestChain, ref state);
                }
                else
                {
                    state.LogToServer(Severity.Warning, "Invalid SMB message");
                    state.ClientSocket.Close();
                }
            }
            else if (packet is SessionRequestPacket && m_transport == SMBTransportType.NetBiosOverTCP)
            {
                PositiveSessionResponsePacket response = new PositiveSessionResponsePacket();
                state.SendQueue.Enqueue(response);
            }
            else if (packet is SessionKeepAlivePacket && m_transport == SMBTransportType.NetBiosOverTCP)
            {
                // [RFC 1001] NetBIOS session keep alives do not require a response from the NetBIOS peer
            }
            else
            {
                state.LogToServer(Severity.Warning, "Inappropriate NetBIOS session packet");
                state.ClientSocket.Close();
                return;
            }
        }
    void OnReceiveStartSession(int node, PacketId id, byte[] data)
    {
        Debug.Log("ReceiveStartSession");

        SessionPacket packet = new SessionPacket(data);
        SessionData response = packet.GetPacket();

        playerId = response.playerId;

        SetSessionMembers(response.result, response.members, response.endPoints);

        matchingState = State.MatchingEnded;
    }
Example #26
0
        public bool Connect(IPAddress serverAddress, SMBTransportType transport)
        {
            // Sometimes underline socket is disconnected, but m_isConnected flag is still true.
            // This cause the caller try to reuse the client and fail on all calls.
            if (m_clientSocket != null && !m_clientSocket.Connected)
            {
                // Since reconnect doesn't work for now, return false directly make response faster
                return(false);
            }

            m_transport = transport;
            if (!m_isConnected)
            {
                int port;
                if (transport == SMBTransportType.NetBiosOverTCP)
                {
                    port = NetBiosOverTCPPort;
                }
                else
                {
                    port = DirectTCPPort;
                }

                if (!ConnectSocket(serverAddress, port))
                {
                    return(false);
                }

                if (transport == SMBTransportType.NetBiosOverTCP)
                {
                    SessionRequestPacket sessionRequest = new SessionRequestPacket();
                    sessionRequest.CalledName  = NetBiosUtils.GetMSNetBiosName("*SMBSERVER", NetBiosSuffix.FileServiceService);
                    sessionRequest.CallingName = NetBiosUtils.GetMSNetBiosName(Environment.MachineName, NetBiosSuffix.WorkstationService);
                    TrySendPacket(m_clientSocket, sessionRequest);

                    SessionPacket sessionResponsePacket = WaitForSessionResponsePacket();
                    if (!(sessionResponsePacket is PositiveSessionResponsePacket))
                    {
                        m_clientSocket.Disconnect(false);
                        if (!ConnectSocket(serverAddress, port))
                        {
                            return(false);
                        }

                        NameServiceClient nameServiceClient = new NameServiceClient(serverAddress);
                        string            serverName        = nameServiceClient.GetServerName();
                        if (serverName == null)
                        {
                            return(false);
                        }

                        sessionRequest.CalledName = serverName;
                        TrySendPacket(m_clientSocket, sessionRequest);

                        sessionResponsePacket = WaitForSessionResponsePacket();
                        if (!(sessionResponsePacket is PositiveSessionResponsePacket))
                        {
                            return(false);
                        }
                    }
                }

                bool supportsDialect = NegotiateDialect();
                if (!supportsDialect)
                {
                    m_clientSocket.Close();
                }
                else
                {
                    m_isConnected = true;
                }
            }
            return(m_isConnected);
        }
Example #27
0
	void StartSession(int node, int roomId)
	{
		string str = "ReceiveStartSessionRequest[roomId:" + roomId + "]";
		Debug.Log(str);
		
		SessionData response = new SessionData();

		RoomContent room = null;
		if (rooms_.ContainsKey(roomId) == true) {
			
			room = rooms_[roomId];

			response.endPoints = new EndPointData[maxMemberNum];
			
			int index = 0;
			for (int i = 0; i < maxMemberNum; ++i) {
				if (room.members[i] != -1) {
					
					IPEndPoint ep = network_.GetEndPoint(room.members[i]) as IPEndPoint;
					response.endPoints[index].ipAddress = ep.Address.ToString();
					response.endPoints[index].port = NetConfig.GAME_PORT;
					++index;
				}	
			}
			
			response.members = index;
			response.result = MatchingResult.Success;
		}
		else {
			response.result = MatchingResult.RoomIsGone;
		}

		if (room != null) {

			rooms_[roomId].isClosed = true;

			str = "Request room id: " + roomId + " MemberNum:" + response.members + " result:" + response.result;
			Debug.Log(str);

			for (int i = 0; i < response.members; ++i) {
				str = "member[" + i + "]" + ":" + response.endPoints[i].ipAddress + ":" + response.endPoints[i].port;
				Debug.Log(str);
			}

			int index = 0;
			for (int i = 0; i < room.members.Length; ++i) {

				int target = room.members[i];

				if (target != -1) {
						
					response.playerId = index;

					SessionPacket packet = new SessionPacket(response);
					
					network_.SendReliable<SessionData>(target, packet);

					++index;
				}
			}


		}
	}
Example #28
0
	void OnReceiveStartSession(int node, PacketId id, byte[] data)
	{
		Debug.Log("ReceiveStartSession");

#if UNUSE_MATCHING_SERVER
		SessionData response = new SessionData();

		{
			int memberNum = NetConfig.PLAYER_MAX;
			string hostname = Dns.GetHostName();
			IPAddress[] adrList = Dns.GetHostAddresses(hostname);
			response.endPoints = new EndPointData[memberNum];

			response.result = MatchingResult.Success;
			response.playerId = GlobalParam.get().global_account_id;
			response.members = memberNum;

			for (int i = 0; i < memberNum; ++i) {
				response.endPoints[i] = new EndPointData();
				response.endPoints[i].ipAddress = adrList[0].ToString();
				response.endPoints[i].port = NetConfig.GAME_PORT;
			}

		}
#else
		SessionPacket packet = new SessionPacket(data);
		SessionData response = packet.GetPacket();
#endif
		playerId = response.playerId;

		SetSessionMembers(response.result, response.members, response.endPoints);

		matchingState = State.MatchingEnded;
	}
Example #29
0
 public void SetSession(SessionPacket session)
 {
     this.handler = session;
 }
    private static void StartListener()
    {
        UdpClient  listener = new UdpClient(listenPort);
        IPAddress  ip       = IPAddress.Parse(ipString);
        IPEndPoint groupEP  = new IPEndPoint(ip, listenPort);

        ResultVM = new MatchResultViewModel();

        var p  = new Packet();
        var sp = new SessionPacket();

        int  sTick          = -1;
        int  pTick          = -1;
        bool isQualiStated  = false;
        bool isRaceStated   = false;
        bool isPlayerStated = false;
        bool isRacing       = true;

        try
        {
            Console.WriteLine($"{DateTime.Now:t} Waiting for broadcast on {ipString}:{listenPort}");

            while (true)
            {
                byte[] bytes = listener.Receive(ref groupEP);
                p.LoadBytes(bytes);

                if (p.PacketType == PacketType.FinalClassification) // once when Qualifying/Race is finished
                {
                    if (!isRacing && !isQualiStated)
                    {
                        isQualiStated = true;

                        ResultVM.LoadQualiData(bytes);

                        Console.WriteLine($"{DateTime.Now:t} Qualifying time has been recorded.");
                    }
                    else if (isRacing && !isRaceStated)
                    {
                        isRaceStated = true;

                        ResultVM.LoadRaceData(bytes);
                        Console.WriteLine($"{DateTime.Now:t} Players in race : {ResultVM.NumberOfPlayers}");

                        DataExport.ExportToExcel(ResultVM);
                        DataExport.ExportToConsole(ResultVM);

                        Console.WriteLine($"{DateTime.Now:t} Race result has been exported to Excel file.");
                    }
                }
                else if (p.PacketType == PacketType.Session)
                {
                    sTick = (sTick + 1) % 60; // 2 times per sec; check once per 30s
                    if (sTick != 0)
                    {
                        continue;
                    }
                    sp.LoadBytes(bytes);

                    // SessionType.ShortQualifying actually = 7  ???
                    if ((int)sp.SessionTypeMode == 7 || sp.SessionTypeMode == SessionPacket.SessionType.OneShotQualifying)
                    {
                        if (isRacing) // First detection of quali session
                        {
                            Console.WriteLine($"{DateTime.Now:t} Current session : Qualifying");
                            isRacing = false;
                        }
                    }
                    else if (sp.SessionTypeMode == SessionPacket.SessionType.Race || sp.SessionTypeMode == SessionPacket.SessionType.Race2)
                    {
                        if (!isRacing) // First detection of race session
                        {
                            Console.WriteLine($"{DateTime.Now:t} Current session : Race");
                            isRacing = true;
                        }
                    }
                }
                #region refresh name (enabled)
                else if (p.PacketType == PacketType.Participants)
                {
                    pTick = (pTick + 1) % 6; // once every 5s; check once per 30s
                    if (pTick != 0)
                    {
                        continue;
                    }

                    ResultVM.LoadParticipantData(bytes);
                    if (!isPlayerStated)
                    {
                        Console.WriteLine($"{DateTime.Now:t} Player names have been recorded.");
                        isPlayerStated = true;
                    }
                }
                #endregion

                // Console.WriteLine($"Received broadcast from {groupEP} :");
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine($"{DateTime.Now:T} {e}");
        }
        finally
        {
            listener.Close();
        }
    }
Example #31
0
    void StartSession(int node, int roomId)
    {
        string str = "ReceiveStartSessionRequest[roomId:" + roomId + "]";

        Debug.Log(str);

        SessionData response = new SessionData();

        RoomContent room = null;

        if (rooms_.ContainsKey(roomId) == true)
        {
            room = rooms_[roomId];

            response.endPoints = new EndPointData[maxMemberNum];

            int index = 0;
            for (int i = 0; i < maxMemberNum; ++i)
            {
                if (room.members[i] != -1)
                {
                    IPEndPoint ep = network_.GetEndPoint(room.members[i]) as IPEndPoint;
                    response.endPoints[index].ipAddress = ep.Address.ToString();
                    response.endPoints[index].port      = NetConfig.GAME_PORT;
                    ++index;
                }
            }

            response.members = index;
            response.result  = MatchingResult.Success;
        }
        else
        {
            response.result = MatchingResult.RoomIsGone;
        }

        if (room != null)
        {
            rooms_[roomId].isClosed = true;

            str = "Request room id: " + roomId + " MemberNum:" + response.members + " result:" + response.result;
            Debug.Log(str);

            for (int i = 0; i < response.members; ++i)
            {
                str = "member[" + i + "]" + ":" + response.endPoints[i].ipAddress + ":" + response.endPoints[i].port;
                Debug.Log(str);
            }

            int index = 0;
            for (int i = 0; i < room.members.Length; ++i)
            {
                int target = room.members[i];

                if (target != -1)
                {
                    response.playerId = index;

                    SessionPacket packet = new SessionPacket(response);

                    network_.SendReliable <SessionData>(target, packet);

                    ++index;
                }
            }
        }
    }
Example #32
0
        private void ProcessPacket(SessionPacket packet, ConnectionState state)
        {
            if (packet is SessionMessagePacket)
            {
                SMB2Command command;
                try
                {
                    command = SMB2Command.ReadResponse(packet.Trailer, 0);
                }
                catch (Exception ex)
                {
                    Log("Invalid SMB2 response: " + ex.Message);
                    state.ClientSocket.Close();
                    m_isConnected = false;
                    return;
                }

                m_availableCredits += command.Header.Credits;

                if (m_transport == SMBTransportType.DirectTCPTransport && command is NegotiateResponse)
                {
                    NegotiateResponse negotiateResponse = (NegotiateResponse)command;
                    if ((negotiateResponse.Capabilities & Capabilities.LargeMTU) > 0)
                    {
                        // [MS-SMB2] 3.2.5.1 Receiving Any Message - If the message size received exceeds Connection.MaxTransactSize, the client MUST disconnect the connection.
                        // Note: Windows clients do not enforce the MaxTransactSize value, we add 256 bytes.
                        int maxPacketSize = SessionPacket.HeaderLength + (int)Math.Min(negotiateResponse.MaxTransactSize, ClientMaxTransactSize) + 256;
                        if (maxPacketSize > state.ReceiveBuffer.Buffer.Length)
                        {
                            state.ReceiveBuffer.IncreaseBufferSize(maxPacketSize);
                        }
                    }
                }

                // [MS-SMB2] 3.2.5.1.2 - If the MessageId is 0xFFFFFFFFFFFFFFFF, this is not a reply to a previous request,
                // and the client MUST NOT attempt to locate the request, but instead process it as follows:
                // If the command field in the SMB2 header is SMB2 OPLOCK_BREAK, it MUST be processed as specified in 3.2.5.19.
                // Otherwise, the response MUST be discarded as invalid.
                if (command.Header.MessageID != 0xFFFFFFFFFFFFFFFF || command.Header.Command == SMB2CommandName.OplockBreak)
                {
                    lock (m_incomingQueueLock)
                    {
                        m_incomingQueue.Add(command);
                        m_incomingQueueEventHandle.Set();
                    }
                }
            }
            else if ((packet is PositiveSessionResponsePacket || packet is NegativeSessionResponsePacket) && m_transport == SMBTransportType.NetBiosOverTCP)
            {
                m_sessionResponsePacket = packet;
                m_sessionResponseEventHandle.Set();
            }
            else if (packet is SessionKeepAlivePacket && m_transport == SMBTransportType.NetBiosOverTCP)
            {
                // [RFC 1001] NetBIOS session keep alives do not require a response from the NetBIOS peer
            }
            else
            {
                Log("Inappropriate NetBIOS session packet");
                state.ClientSocket.Close();
            }
        }
Example #33
0
        /// <summary>创建会话</summary>
        /// <param name="remoteEP"></param>
        /// <returns></returns>
        public virtual ISocketSession CreateSession(IPEndPoint remoteEP)
        {
            if (Disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            var sessions = _Sessions;

            if (sessions == null)
            {
                return(null);
            }

            // 平均执行耗时260.80ns,其中55%花在sessions.Get上面,Get里面有加锁操作

            if (!Active)
            {
                // 根据目标地址适配本地IPv4/IPv6
                Local.Address = Local.Address.GetRightAny(remoteEP.AddressFamily);

                if (!Open())
                {
                    return(null);
                }
            }

            // 需要查找已有会话,已有会话不存在时才创建新会话
            var session = sessions.Get(remoteEP + "");

            if (session != null)
            {
                return(session);
            }

            // 相同远程地址可能同时发来多个数据包,而底层采取多线程方式同时调度,导致创建多个会话
            lock (sessions)
            {
                // 需要查找已有会话,已有会话不存在时才创建新会话
                session = sessions.Get(remoteEP + "");
                if (session != null)
                {
                    return(session);
                }

                var us = new UdpSession(this, remoteEP);
                us.Log        = Log;
                us.LogSend    = LogSend;
                us.LogReceive = LogReceive;
                // UDP不好分会话统计
                //us.StatSend.Parent = StatSend;
                //us.StatReceive.Parent = StatReceive;
                us.Packet = SessionPacket?.Create();

                session = us;
                if (sessions.Add(session))
                {
                    //us.ID = g_ID++;
                    // 会话改为原子操作,避免多线程冲突
                    us.ID = Interlocked.Increment(ref g_ID);
                    us.Start();

                    if (StatSession != null)
                    {
                        StatSession.Increment(1);
                    }

                    // 触发新会话事件
                    NewSession?.Invoke(this, new SessionEventArgs {
                        Session = session
                    });
                }
            }

            return(session);
        }