public SecureStream(IClient client)
            : base()
        {
            this.FlushLock = new object();
            this.stream    = new MemoryStream();
            this.Client    = client;

            lock (client.Connection)
            {
                RandomDecimal rnd = new RandomDecimal(DateTime.Now.Millisecond);
                StreamId = rnd.NextDecimal();
                while (client.Connection.Streams.ContainsKey(StreamId))
                {
                    StreamId = rnd.NextDecimal();
                }

                client.Connection.Streams.Add(StreamId, this);
                this.StreamLock = new SyncObject(client);
                client.Connection.SendMessage(new MsgOpenStream(this.StreamId), PacketId.StreamMessages);

                MsgOpenStreamResponse response = StreamLock.Wait <MsgOpenStreamResponse>(default(MsgOpenStreamResponse), 30000);

                if (response == null)
                {
                    throw new TimeoutException("It took too long for the remote host to setup the Stream");
                }

                IsOpen          = true;
                this.StreamLock = new SyncObject(client);
                this.ReadLock   = new SyncObject(client);
            }
        }
Example #2
0
        /// <summary>
        /// Initialize a new SSPServer
        /// </summary>
        /// <param name="serverProperties">The properties for the server</param>
        public SSPServer(ServerProperties serverProperties)
        {
            if (serverProperties == null)
            {
                throw new ArgumentNullException("serverProperties");
            }

            this.serverProperties = serverProperties;
            this.Clients          = new SortedList <decimal, SSPClient>();
            this.randomDecimal    = new RandomDecimal(DateTime.Now.Millisecond);

            SysLogger.Log("Starting server", SysLogType.Debug);

            this.ClientAcceptProcessor4 = new ClientAcceptProcessor();
            this.ClientAcceptProcessor6 = new ClientAcceptProcessor();


            //start the server for IPv4
            this.TcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            this.TcpServer.Bind(new IPEndPoint(IPAddress.Parse(serverProperties.ListenIp), serverProperties.ListenPort));
            this.TcpServer.Listen(100);
            this.TcpServer.BeginAccept(AcceptClientCallback, null);

            if (serverProperties.UseIPv4AndIPv6)
            {
                //start the server for IPv6
                this.TcpServer6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
                this.TcpServer6.Bind(new IPEndPoint(IPAddress.Parse(serverProperties.ListenIp6), serverProperties.ListenPort));
                this.TcpServer6.Listen(100);
                this.TcpServer6.BeginAccept(AcceptClient6Callback, null);
            }

            SysLogger.Log("Started server", SysLogType.Debug);
        }
Example #3
0
        private RandomDecimal CreateRandomDecimal(JToken item)
        {
            int upper = (int)item["upper"];
            int lower = (int)item["lower"];

            var result = new RandomDecimal(lower, upper);

            result.DebugInfo = GetDebugInfo(item);

            return(result);
        }
        /// <summary>
        /// Initialize a new SSPServer
        /// </summary>
        /// <param name="serverProperties">The properties for the server</param>
        public SSPServer(ServerProperties serverProperties)
        {
            if (serverProperties == null)
            {
                throw new ArgumentNullException("serverProperties");
            }

            this.Random           = new RandomDecimal(DateTime.Now.Millisecond);
            this.KeyHandler       = new PrivateKeyHandler(serverProperties.GenerateKeysInBackground);
            this.serverProperties = serverProperties;
            this.Clients          = new SortedList <decimal, SSPClient>();
            this.TcpServer        = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            this.TcpServer.Bind(new IPEndPoint(IPAddress.Parse(serverProperties.ListenIp), serverProperties.ListenPort));
            this.TcpServer.Listen(100);

            if (serverProperties.AllowUdp)
            {
                try
                {
                    this.UdpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    this.UdpServer.Bind(new IPEndPoint(IPAddress.Parse(serverProperties.ListenIp), serverProperties.ListenPort));
                    this.UdpServer.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
                    this.udpAsyncSocket = new SocketAsyncEventArgs();
                    this.udpAsyncSocket.SetBuffer(new byte[70000], 0, 70000);
                    this.udpAsyncSocket.RemoteEndPoint = new IPEndPoint(0, 0);
                    this.udpAsyncSocket.Completed     += UdpAsyncSocketCallback;

                    if (!UdpServer.ReceiveFromAsync(udpAsyncSocket))
                    {
                        UdpAsyncSocketCallback(null, udpAsyncSocket);
                    }
                }
                catch (Exception ex)
                {
                    this.TcpServer.Close();
                    throw ex;
                }
            }

            this.RootSocket_DNS = new RootDns();

            //ThreadPool.QueueUserWorkItem(ServerThread);
            this.Running = true;

            TcpServer.BeginAccept(AsyncAction, null);
        }
        public override void onClientConnect()
        {
            Console.WriteLine("Virtual IP: " + base.VirtualIP);
            Console.Title = "SSP2 Client - ClientId:" + base.ClientId.ToString().Substring(0, 10) + "... - VritualIP:" + base.VirtualIP;
            Console.WriteLine("Connected");
            base.MessageHandler.AddMessage(typeof(TestMessage), "TEST_MESSAGE");
            ISharedTest SharedTest = SharedTest = base.GetSharedClass <ISharedTest>("SharedTest");

            /*string ResolvedDns = base.ResolveDns("TestRootSocket");
             * if (ResolvedDns.Length == 0)
             * {
             *  base.RegisterDns("TestRootSocket");
             *  return;
             * }
             *
             * //peer found, connect to it
             * Console.WriteLine("Connecting to peer " + ResolvedDns);
             * Peer peer = new Peer();
             * PeerErrorCode errorCode = base.ConnectToPeer(ResolvedDns, peer);
             *
             * while (true)
             * {
             *  peer.SendMessage(new TestMessage());
             *  Thread.Sleep(1);
             * }
             * return;*/

            Benchmark BenchLiteCode = new Benchmark();
            int       speedy        = 0;

            while (false)
            {
                BenchLiteCode.Bench(new BenchCallback(() =>
                {
                    //send server our private method, now the server can call our private method ;)
                    //SharedTest.DelegateTest(new Callback<string>(DelegateCallbackTest));
                    SharedTest.SendByteArray(new byte[65535]);
                }));

                if (BenchLiteCode.PastASecond)
                {
                    Console.WriteLine("Call Speed: " + BenchLiteCode.SpeedPerSec + ", Speed: " + Math.Round(((float)speedy / 1000F) / 1000F, 2) + "MBps ");
                    speedy = 0;
                }
            }

            //load a image by opening a stream to the server
            SecureStream ImgStream  = new SecureStream(this);
            int          count      = 0;
            Benchmark    BenchFiles = new Benchmark();

            //Image img = (Image)Bitmap.FromStream(ImgStream);
            //img.Save(@"C:\Users\DragonHunter\Desktop\DownloadedSSP_Image.png");

            while (false)
            {
                Console.WriteLine("Synchronized Server Time: " + base.TimeSync.Hour.ToString("D2") + ":" + base.TimeSync.Minute.ToString("D2") + ":" + base.TimeSync.Second.ToString("D2") + ", " + base.TimeSync.Millisecond);
                Thread.Sleep(1000);
            }

            int         packets        = 0;
            ulong       DataPerSec     = 0;
            Stopwatch   sw             = Stopwatch.StartNew();
            Random      rnd            = new Random();
            TestMessage message        = new TestMessage();
            int         ChannelsClosed = 0;

            while (false)
            {
                TestChannel channel = new TestChannel();

                if (this.OpenChannel(channel) == ChannelError.Success)
                {
                    while (true)
                    {
                        channel.SendMessage(message);
                    }
                    channel.CloseChannel();
                    ChannelsClosed++;

                    if (sw.ElapsedMilliseconds >= 1000)
                    {
                        Console.WriteLine("channels opend/closed: " + ChannelsClosed);
                        sw = Stopwatch.StartNew();
                    }
                }
            }

            RandomDecimal rndDec = new RandomDecimal(DateTime.Now.Millisecond);

            while (base.Connected)
            {
                packets++;
                DataPerSec += (ulong)message.Stuff.Length;
                SharedTest.SendByteArray(message.Stuff);

                if (sw.ElapsedMilliseconds >= 1000)
                {
                    Console.WriteLine("last data size: " + message.Stuff.Length + ", pps:" + packets + ", data/sec:" + DataPerSec + " [" + Math.Round(((float)DataPerSec / 1000F) / 1000F, 2) + "MBps] " + (Math.Round((((float)DataPerSec / 1000F) / 1000F) / 1000F, 2) * 8F) + "Gbps");
                    packets    = 0;
                    DataPerSec = 0;
                    sw         = Stopwatch.StartNew();
                }
            }
            Process.GetCurrentProcess().WaitForExit();
        }
Example #6
0
        public PeerResponse ConnectToPeer(string VirtualIpOrDns)
        {
            SSPClient TargetClient = null;

            //check if dns name
            if (!Regex.IsMatch(VirtualIpOrDns, RootPeer.IpValidationString))
            {
                RootDnsInfo inf = client.Server.RootSocket_DNS.GetDnsRecord(VirtualIpOrDns);
                if (inf != null)
                {
                    VirtualIpOrDns = inf.VirtualIp;
                }
            }

            TargetClient = client.Server.GetClient(VirtualIpOrDns);

            if (TargetClient == null)
            {
                return(new PeerResponse(PeerErrorCode.PeerNotFound, 0, ""));
            }

            //check if server side allows this connection
            if (!client.Server.onPeerConnectionRequest(client, TargetClient))
            {
                return(new PeerResponse(PeerErrorCode.PermissionDenied, 0, ""));
            }

            //check if target client allows this connection
            decimal ConnectionId  = 0;
            bool    HasPermission = false;

            lock (TargetClient.PeerConnections)
            {
                lock (client.PeerConnections)
                {
                    RandomDecimal rnd = new RandomDecimal(DateTime.Now.Millisecond);
                    ConnectionId = rnd.NextDecimal();
                    while (TargetClient.PeerConnections.ContainsKey(ConnectionId) || client.PeerConnections.ContainsKey(ConnectionId))
                    {
                        ConnectionId = rnd.NextDecimal();
                    }

                    try
                    {
                        HasPermission = TargetClient.SharedClientRoot.RequestPeerConnection(client.VirtualIP, ConnectionId);
                    }
                    catch { HasPermission = false; }


                    if (HasPermission)
                    {
                        RootPeer TargetPeer = client.onGetNewPeerObject();
                        TargetPeer._client      = TargetClient;
                        TargetPeer.FromClient   = TargetClient;
                        TargetPeer.ToClient     = client;
                        TargetPeer.VirtualIP    = client.VirtualIP;
                        TargetPeer.Connected    = true;
                        TargetPeer.ConnectionId = ConnectionId;

                        RootPeer FromPeer = client.onGetNewPeerObject();
                        FromPeer._client      = client;
                        FromPeer.FromClient   = client;
                        FromPeer.ToClient     = TargetClient;
                        FromPeer.VirtualIP    = TargetClient.VirtualIP;
                        FromPeer.Connected    = true;
                        FromPeer.ConnectionId = ConnectionId;

                        if (!TargetClient.PeerConnections.ContainsKey(ConnectionId))
                        {
                            TargetClient.PeerConnections.Add(ConnectionId, TargetPeer);
                        }

                        if (!client.PeerConnections.ContainsKey(ConnectionId))
                        {
                            client.PeerConnections.Add(ConnectionId, FromPeer);
                        }

                        TargetClient.SharedClientRoot.NewPeerconnection(ConnectionId);

                        return(new PeerResponse(PeerErrorCode.Success, ConnectionId, TargetClient.VirtualIP));
                    }
                    return(new PeerResponse(PeerErrorCode.PermissionDenied, 0, ""));
                }
            }
        }