Пример #1
0
        public void IsSubsetOf ()
        {
		s1 = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "12.13.14.15", 80);
		s1.AddPermission(NetworkAccess.Accept, TransportType.All, "10.11.4.*", SocketPermission.AllPorts);
		s2 = new SocketPermission(NetworkAccess.Connect, TransportType.All, "12.13.14.15", 80);
		s2.AddPermission(NetworkAccess.Accept, TransportType.All, "10.11.*.*", 9090);
		
		Assert.IsFalse (s1.IsSubsetOf (s2), "#1");
		Assert.IsFalse (s2.IsSubsetOf (s1), "#2");

		s1 = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "12.13.14.15", 80);
		s1.AddPermission(NetworkAccess.Accept, TransportType.All, "10.11.4.*", 9090);
		s2 = new SocketPermission(NetworkAccess.Connect, TransportType.All, "12.13.14.15", 80);
		s2.AddPermission(NetworkAccess.Accept, TransportType.All, "10.11.*.*", 9090);
		
		Assert.IsFalse (s2.IsSubsetOf (s1), "#4");
		
		s1 = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "12.13.*.*", 80);
		s2 = new SocketPermission(NetworkAccess.Connect, TransportType.All, "12.13.14.*", 80);
		Assert.IsTrue (s1.IsSubsetOf (s2), "#5");
		Assert.IsFalse (s2.IsSubsetOf (s1), "#6");

		s1 = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "12.13.14.15", 80);
		s1.AddPermission(NetworkAccess.Accept, TransportType.Tcp, "10.11.*.*", 9090);
		s2 = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "12.13.14.15", 80);
		s2.AddPermission(NetworkAccess.Accept, TransportType.All, "10.11.4.*", SocketPermission.AllPorts);
		Assert.IsTrue (s1.IsSubsetOf (s2), "#7");
		Assert.IsFalse (s2.IsSubsetOf (s1), "#8");
	}
        public void IsSubsetOf ()
        {
		s1 = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "12.13.14.15", 80);
		s1.AddPermission(NetworkAccess.Accept, TransportType.All, "10.11.4.*", SocketPermission.AllPorts);
		s2 = new SocketPermission(NetworkAccess.Connect, TransportType.All, "12.13.14.15", 80);
		s2.AddPermission(NetworkAccess.Accept, TransportType.All, "10.11.*.*", 9090);
		
		Assertion.Assert ("#1", !s1.IsSubsetOf (s2));
		Assertion.Assert ("#2", !s2.IsSubsetOf (s1));

		s1 = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "12.13.14.15", 80);
		s1.AddPermission(NetworkAccess.Accept, TransportType.All, "10.11.4.*", 9090);
		s2 = new SocketPermission(NetworkAccess.Connect, TransportType.All, "12.13.14.15", 80);
		s2.AddPermission(NetworkAccess.Accept, TransportType.All, "10.11.*.*", 9090);
		
		Assertion.Assert ("#4", !s2.IsSubsetOf (s1));
		
		s1 = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "12.13.*.*", 80);
		s2 = new SocketPermission(NetworkAccess.Connect, TransportType.All, "12.13.14.*", 80);
		Assertion.Assert ("#5", s1.IsSubsetOf (s2));
		Assertion.Assert ("#6", !s2.IsSubsetOf (s1));

		s1 = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "12.13.14.15", 80);
		s1.AddPermission(NetworkAccess.Accept, TransportType.Tcp, "10.11.*.*", 9090);
		s2 = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "12.13.14.15", 80);
		s2.AddPermission(NetworkAccess.Accept, TransportType.All, "10.11.4.*", SocketPermission.AllPorts);
		Assertion.Assert ("#7", s1.IsSubsetOf (s2));
		Assertion.Assert ("#8", !s2.IsSubsetOf (s1));
	}
Пример #3
0
        public Tracker(string configfile)
        {
            Configuration = new TrackerConfig(configfile);
            Logger.Active = Configuration.Log;

            peers = new Dictionary<int, Peer>();
            rooms = new Dictionary<string, Room>();

            // Listening on socket
            IPAddress ipAddr = IPAddress.Parse(Configuration.IPAddress);
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, Configuration.Port);
            SocketPermission permission = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, "", Configuration.Port);
            permission.Demand();

            try
            {
                listener = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                listener.Bind(ipEndPoint);

                Console.WriteLine("Listening at IP " + ipEndPoint.Address + " and port " + ipEndPoint.Port + ".");

                listener.Listen(Configuration.Backlog);

                AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
                listener.BeginAccept(aCallback, listener);
            }
            catch (SocketException exc)
            {
                Logger.WriteLine(exc);
            }
        }
        public void GetReady () 
        {
		s1 = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "12.13.14.15", 80);
		//s1.AddPermission(NetworkAccess.Accept, TransportType.All, "localhost", 8080);
		//s1.AddPermission(NetworkAccess.Accept, TransportType.All, "123", SocketPermission.AllPorts);
		//s1.AddPermission(NetworkAccess.Accept, TransportType.All, "www.ximian.com", SocketPermission.AllPorts);
		//s1.AddPermission(NetworkAccess.Accept, TransportType.All, "120.4.3.2", SocketPermission.AllPorts);
		//s1.AddPermission(NetworkAccess.Accept, TransportType.Tcp, "www.google.com", 80);
		//s1.AddPermission(NetworkAccess.Accept, TransportType.All, "1.*.10.*.99", SocketPermission.AllPorts);
		//s1.AddPermission(NetworkAccess.Accept, TransportType.All, "128.0.0.1", SocketPermission.AllPorts);
		//s1.AddPermission(NetworkAccess.Accept, TransportType.All, "0.0.0.0", SocketPermission.AllPorts);
		s1.AddPermission(NetworkAccess.Accept, TransportType.All, "10.11.4.*", SocketPermission.AllPorts);

		s2 = new SocketPermission(NetworkAccess.Connect, TransportType.All, "12.13.14.15", 80);
		//s2.AddPermission(NetworkAccess.Accept, TransportType.All, "localhost", 8080);
		//s2.AddPermission(NetworkAccess.Accept, TransportType.All, "123", 8080);
		//s2.AddPermission(NetworkAccess.Accept, TransportType.Tcp, "www.google.com", SocketPermission.AllPorts);
		s2.AddPermission(NetworkAccess.Accept, TransportType.All, "213.*.*.*", SocketPermission.AllPorts);
		//s2.AddPermission(NetworkAccess.Accept, TransportType.All, "128.0.0.1", 9090);
		s2.AddPermission(NetworkAccess.Accept, TransportType.Tcp, "216.239.*.*", SocketPermission.AllPorts);
		//s2.AddPermission(NetworkAccess.Accept, TransportType.All, "128.0.0.1", SocketPermission.AllPorts);
		//s2.AddPermission(NetworkAccess.Accept, TransportType.Tcp, "120.4.3.2", 80);
		//s2.AddPermission(NetworkAccess.Accept, TransportType.All, "196.*.*.*", SocketPermission.AllPorts);
		//s2.AddPermission(NetworkAccess.Accept, TransportType.All, "1.*.*.*.99", SocketPermission.AllPorts);
		s2.AddPermission(NetworkAccess.Accept, TransportType.All, "10.11.*.*", 9090);
		//s2.AddPermission(NetworkAccess.Accept, TransportType.All, "10.11.4.7", SocketPermission.AllPorts);		
	}
Пример #5
0
        public void Connect()
        {
            if (c == null) return;

            SocketPermission permission = new SocketPermission(System.Security.Permissions.PermissionState.Unrestricted);
            permission.Demand();

            IPHostEntry heserver = Dns.Resolve(c.XMLConf.Host);
            IPAddress iadd = (IPAddress)heserver.AddressList[0];
            IPEndPoint ip = new IPEndPoint(iadd, c.XMLConf.Port);

            s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.NoDelay, 1);
            s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DontFragment, 1);

            while(!s.Connected)
            {
                try
                {
                    s.Connect(ip);
                }
                catch (Exception e)
                {
                    //MessageBox.Show("Verbindung fehlgeschlagen! "+e.Message);
                    c.use_network = false;
                    Thread.Sleep(1000);
                }
            }

            c.use_network = true;

            SendHelloToZusi(s);
        }
Пример #6
0
        public void Connect(ref Socket s, string server, int port, string id)
        {
            SocketPermission permission = new SocketPermission(System.Security.Permissions.PermissionState.Unrestricted);
            permission.Demand();

            IPHostEntry heserver = Dns.Resolve(server);
            IPAddress iadd = (IPAddress)heserver.AddressList[0];
            IPEndPoint ip = new IPEndPoint(iadd, port);

            s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            //s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.NoDelay, 1);
            //s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DontFragment, 1);

            while(!s.Connected)
            {
                try
                {
                    s.Connect(ip);
                }
                catch (Exception e)
                {
                    //MessageBox.Show("Verbindung fehlgeschlagen! "+e.Message);
                    m_net.SetConnected(false);
                    Thread.Sleep(1000);
                }
            }

            m_net.SetConnected(true);

            client_id = id;

            SendHelloToZusi(s);
        }
        public void start()
        {
            parent.textBoxServerLog.AppendText("Connecting..." + Environment.NewLine);

            SocketPermission permission = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, "", SocketPermission.AllPorts);

            /*Stellt irgendwas mit der IP Adresse an. Diese muss vom Server Computer sein.
            Soweit ich das verstanden habe, gibt es bei Computern mit mehreren Netwerkgeräten mehrere mögliche
            Ip Adressen. Deswegen wird hier die erste ausgewählt.
            Jetzt wird ein neuer Endpoint angelegt an welchem die Verbindung stattfinden wird.*/
            IPHostEntry ipHost = Dns.GetHostEntry("192.168.178.39");
            IPAddress ipAddr = ipHost.AddressList[0];
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 6666);

            /*Ein neuer Socket wird angelegt (Server-Socket). Stream wegen Datenübertragung und TCP spezifiziert
            das zu verwendende Protokoll.
            Mit Bind wird der Socket an den festgelegten Endpoint gebunden.
            Listen spezifiziert eine maximale Anzahl an Clients. Versuchen mehr als hier angegeben sich zu verbinden,
            so bekommen sie einen "server is busy error".*/
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            server.Bind(ipEndPoint);
            server.Listen(1);

            while (true)
            {
                /*Jetzt wird ein weiter Socket erstellt, dieser ist nötig um etwas senden bzw empfangen 
                 * zu könnnen. */
                Socket handler = server.Accept();

                String data = null;

                /*So lange etwas ankommt, wird alles in den String gespeichert. Tritt das Ende der Nachricht ein,
                 ("<EOF>"), so ist der Empfangsvorgang beendet.*/
                while (true)
                {
                    byte[] bytes = new byte[1024];
                    int bytesRec = handler.Receive(bytes);
                    data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    if (data.IndexOf("<EOF>") > -1)
                    {
                        break;
                    }
                }
                
                //data.Remove() Die Endung aus dem String entfernen
                parent.textBoxServerLog.AppendText("Empfangen: " + data + Environment.NewLine);

                ///* Als Antwort wird die empfangene Nachricht wieder zurück gesendet */
                byte[] msg = Encoding.ASCII.GetBytes(data);
                handler.Send(msg);

                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
                parent.textBoxServerLog.AppendText("Connection closed" + Environment.NewLine);
            }
        }
Пример #8
0
 static public void CheckTrust()
 {
     try
     {
         SocketPermission permission =
             new SocketPermission(PermissionState.Unrestricted);
         s_FullTrust = SecurityManager.IsGranted(permission);
     }
     catch (Exception)
     {
         // ignore
     }
 }
Пример #9
0
        static Socket CreateBoundSocket(IPEndPoint endpoint)
        {
            // demand permission
            var permission = new SocketPermission(
                NetworkAccess.Connect, TransportType.Tcp,
                endpoint.Address.ToString(), endpoint.Port);
            permission.Demand();

            // create a tcp socket to listen
            var socket = new Socket(
                AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket.Bind(endpoint);

            return socket;
        }
Пример #10
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="asClient"></param>
        /// <returns></returns>
        public IConnection Connect(bool asClient)
        {
            _asClient = asClient;

            var _permission = new SocketPermission(
                NetworkAccess.Accept,     // Allowed to accept connections 
                TransportType.Tcp,        // Defines transport types 
                "",                       // The IP addresses of local host 
                SocketPermission.AllPorts // Specifies all ports 
                );

            _permission.Demand();
            IPAddress ipAddress = null;
            if (_address != null)
            {
                ipAddress = IPAddress.Parse(_address);
            }
            else
            {
                // Resolves a host name to an IPHostEntry instance 
                IPHostEntry ipHost = Dns.GetHostEntry("");
                ipAddress = ipHost.AddressList[0];
            }

            var _endPoint = new IPEndPoint(ipAddress, _port);
            // Create one Socket object to setup Tcp connection 
            var _socket = new Socket(
                ipAddress.AddressFamily,// Specifies the addressing scheme 
                SocketType.Stream,   // The type of socket  
                ProtocolType.Tcp     // Specifies the protocols  
                );
            _socket.NoDelay = false;   // Using the Nagle algorithm 

            // Establishes a connection to a remote host 
            if (asClient)
            {
                _socket.Connect(_endPoint);
            }
            else
            {
                _socket.Bind(_endPoint);
                _socket.Listen(10);
                _socket.NoDelay = false;
            }

            return new TcpConnection<MessageBuilder>(_socket) { IsClient = asClient};
        }
Пример #11
0
        private void Start_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Creates one SocketPermission object for access restrictions
                permission = new SocketPermission(
                NetworkAccess.Accept,     // Allowed to accept connections 
                TransportType.Tcp,        // Defines transport types 
                "",                       // The IP addresses of local host 
                SocketPermission.AllPorts // Specifies all ports 
                );

                // Listening Socket object 
                sListener = null;

                // Ensures the code to have permission to access a Socket 
                permission.Demand();

                // Resolves a host name to an IPHostEntry instance 
                IPHostEntry ipHost = Dns.GetHostEntry("");

                // Gets first IP address associated with a localhost 
                //IPAddress ipAddr = ipHost.AddressList[1];
                IPAddress ipAddr = IPAddress.Parse("172.20.95.232");

                // Creates a network endpoint 
                ipEndPoint = new IPEndPoint(ipAddr, 4510);

                // Create one Socket object to listen the incoming connection 
                sListener = new Socket(
                    ipAddr.AddressFamily,
                    SocketType.Stream,
                    ProtocolType.Tcp
                    );

                // Associates a Socket with a local endpoint 
                sListener.Bind(ipEndPoint);

                tbStatus.Text = "Server started.";

                Start_Button.IsEnabled = false;
                StartListen_Button.IsEnabled = true;
            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }
        }
Пример #12
0
        private void Connect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Create one SocketPermission for socket access restrictions 
                SocketPermission permission = new SocketPermission(
                    NetworkAccess.Connect,    // Connection permission 
                    TransportType.Tcp,        // Defines transport types 
                    "",                       // Gets the IP addresses 
                    SocketPermission.AllPorts // All ports 
                    );

                // Ensures the code to have permission to access a Socket 
                permission.Demand();

                // Resolves a host name to an IPHostEntry instance            
                IPHostEntry ipHost = Dns.GetHostEntry("Pc-TOSH");

                // Gets first IP address associated with a localhost 
                IPAddress ipAddr = ipHost.AddressList[1];
                //IPAddress ipAdress = IPAddress.Parse("10.76.175.31");

                // Creates a network endpoint 
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 4510);

                // Create one Socket object to setup Tcp connection 
                senderSock = new Socket(
                    ipAddr.AddressFamily,// Specifies the addressing scheme 
                    SocketType.Stream,   // The type of socket  
                    ProtocolType.Tcp     // Specifies the protocols  
                    );

                senderSock.NoDelay = false;   // Using the Nagle algorithm 

                // Establishes a connection to a remote host 
                senderSock.Connect(ipEndPoint);
                tbStatus.Text = "Socket connected to " + senderSock.RemoteEndPoint.ToString();

                Connect_Button.IsEnabled = false;
                Send_Button.IsEnabled = true;
            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }

        }
Пример #13
0
 protected override SocketPermission GetPermission()
 {
     try
     {
         SocketPermission permission = new SocketPermission
             (
                 NetworkAccess.Connect,
                 TransportType.Tcp,
                 _host,
                 SocketPermission.AllPorts
             );
         permission.Demand();
         return permission;
     }
     catch (Exception e)
     {
         _boundary.Notify(e.ToString());
         return null;
     }
 }
        private void start_the_server()
        {
            try
            {
                // Creates one SocketPermission object for access restrictions
                permission = new SocketPermission(
                NetworkAccess.Accept,     // Allowed to accept connections 
                TransportType.Tcp,        // Defines transport types 
                "",                       // The IP addresses of local host 
                SocketPermission.AllPorts // Specifies all ports 
                );

                // Listening Socket object 
                sListener = null;

                // Ensures the code to have permission to access a Socket 
                permission.Demand();

                // Resolves a host name to an IPHostEntry instance 
                IPHostEntry ipHost = Dns.GetHostEntry("");

                // Gets first IP address associated with a localhost 
                IPAddress ipAddr = ipHost.AddressList[0];

                // Creates a network endpoint 
                ipEndPoint = new IPEndPoint(ipAddr, 4610);

                // Create one Socket object to listen the incoming connection 
                sListener = new Socket(
                    ipAddr.AddressFamily,
                    SocketType.Stream,
                    ProtocolType.Tcp
                    );

                // Associates a Socket with a local endpoint 
                sListener.Bind(ipEndPoint);

                lbl_server_status.Text = "Server started Successfully.";
            }
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }
        }
Пример #15
0
        internal static Socket Start()
        {
            SocketPermission permission;
            Socket sListener;
            IPEndPoint ipEndPoint;

            // Creates one SocketPermission object for access restrictions
            permission = new SocketPermission(
            NetworkAccess.Accept,     // Allowed to accept connections 
            TransportType.Tcp,        // Defines transport types 
            "",                       // The IP addresses of local host 
            SocketPermission.AllPorts // Specifies all ports 
            );

            // Listening Socket object 
            sListener = null;

            // Ensures the code to have permission to access a Socket 
            permission.Demand();

            // Resolves a host name to an IPHostEntry instance 
            IPHostEntry ipHost = Dns.GetHostEntry("");
            // Gets first IP address associated with a localhost 
            IPAddress ipAddr = ipHost.AddressList[1];
            //IPAddress ipAddr = IPAddress.Parse("172.20.95.232");

            // Creates a network endpoint 
            ipEndPoint = new IPEndPoint(ipAddr, 4510);

            // Create one Socket object to listen the incoming connection 
            sListener = new Socket(
                ipAddr.AddressFamily,
                SocketType.Stream,
                ProtocolType.Tcp
                );

            // Associates a Socket with a local endpoint 
            sListener.Bind(ipEndPoint);

            return sListener;
        }
Пример #16
0
        /* This method is invoked when the 'Connect' button is clicked.
         * It connects the client to the server asynchronously.
         */
        private void Connect_Click(object sender, RoutedEventArgs e)
        {
            // The code is written in try block so as to catch any exceptions, if thrown
            try
            {
                // Create one SocketPermission for socket access restrictions
                SocketPermission permission = new SocketPermission(
                    NetworkAccess.Connect,                          // Connection permission
                    TransportType.Tcp,                              // Defines transport types
                    "",                                             // Gets the IP addresses
                    SocketPermission.AllPorts                       // All ports
                    );

                // Ensures the code to have permission to access a Socket
                permission.Demand();
                // Resolves a host name to an IPHostEntry instance
                IPHostEntry ipHost = Dns.GetHostEntry("");
                // Gets first IP address associated with a localhost
                IPAddress ipAddr = ipHost.AddressList[0];
                // Creates a network endpoint
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 4510);

                // Create one Socket object to setup Tcp connection
                senderSock = new Socket(
                    ipAddr.AddressFamily,           // Specifies the addressing scheme
                    SocketType.Stream,              // The type of socket
                    ProtocolType.Tcp                // Specifies the protocols
                    );

                // Establishes a connection to a remote host
                senderSock.Connect(ipEndPoint);

                // Disabling the 'Connect' button
                Connect_Button.IsEnabled = false;
                // Enabling the 'Send' button
                Send_Button.IsEnabled = true;
            }
            // Used for catching any exceptions, if thrown
            catch (Exception exc) { MessageBox.Show(exc.ToString()); }
        }
Пример #17
0
        public void Start()
        {
            Console.WriteLine("Heartchat server starting...");

            byte[] buffer = new byte[1024];

            var permission = new SocketPermission(NetworkAccess.Accept,
                   TransportType.Tcp, "", SocketPermission.AllPorts);

            IPHostEntry ipHost = Dns.GetHostEntry("");
            IPAddress ipAddr = ipHost.AddressList[3]; // WTF?
            var ipEndPoint = new IPEndPoint(ipAddr, Port);

            var socket = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                Console.WriteLine("Binding on {0}:{1}", ipEndPoint.Address, ipEndPoint.Port);
                socket.Bind(ipEndPoint);
                socket.Listen(10);

                while (true)
                {
                    syncEvent.Reset();

                    Console.WriteLine("Waiting for connection...");

                    socket.BeginAccept(new AsyncCallback(OnAcceptCallback), socket);

                    syncEvent.WaitOne();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("ERROR!" + e.Message);
            }

            Console.WriteLine("Press any key...");
            Console.ReadKey();
        }
Пример #18
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            SocketPermission perm = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, robotAddress, 8027);
            perm.Demand();
            IPAddress ipAddr = IPAddress.Parse(robotAddress);
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 8027);

            senderSock = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            senderSock.NoDelay = false;
            senderSock.Connect(ipEndPoint);
            statusTextBlock.Text = "Spojeno s " + senderSock.RemoteEndPoint.ToString() + ".";

            DispatcherTimer dt = new DispatcherTimer();
            dt.Tick += new EventHandler(dt_Tick);
            dt.Interval = new TimeSpan(0, 0, 1);
            dt.Start();

            /*if (phoneAddress != "")
            {
                myControl.MediaPlayer.Play(new Uri("http://" + phoneAddress + ":8080/mjpeg/"));
            }*/
        }
		public override IPermission Intersect (IPermission target)
		{
			if (target == null) 
				return null;
				
			SocketPermission perm = target as SocketPermission;
			if (perm == null) 
				throw new ArgumentException ("Argument not of type SocketPermission");
			
			if (m_noRestriction) 
				return IntersectEmpty (perm) ? null : perm.Copy ();
				
			if (perm.m_noRestriction)
				return IntersectEmpty (this) ? null : this.Copy ();
				
			SocketPermission newperm = new SocketPermission (PermissionState.None);
			Intersect (this.m_connectList, perm.m_connectList, newperm.m_connectList);
			Intersect (this.m_acceptList, perm.m_acceptList, newperm.m_acceptList);
			return IntersectEmpty (newperm) ? null : newperm;			
		}
Пример #20
0
//************* public methods *************************





        /// <devdoc>
        ///    <para>Associates a socket with an end point.</para>
        /// </devdoc>
        public void Bind(EndPoint localEP) {

            if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "Bind", localEP);

            if (CleanedUp) {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            //
            // parameter validation
            //
            if (localEP==null) {
                throw new ArgumentNullException("localEP");
            }

            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::Bind() localEP:" + localEP.ToString());

            EndPoint endPointSnapshot = localEP;
            IPEndPoint ipSnapshot = localEP as IPEndPoint;

            //
            // for now security is implemented only on IPEndPoint
            // If EndPoint is of other type - unmanaged code permisison is demanded
            //
            if (ipSnapshot != null)
            {
                // Take a snapshot that will make it immutable and not derived.
                ipSnapshot = ipSnapshot.Snapshot();                                
                // DualMode: Do the security check on the users IPv4 address, but map to IPv6 before binding.
                endPointSnapshot = RemapIPEndPoint(ipSnapshot);

                //
                // create the permissions the user would need for the call
                //
                SocketPermission socketPermission
                    = new SocketPermission(
                        NetworkAccess.Accept,
                        Transport,
                        ipSnapshot.Address.ToString(),
                        ipSnapshot.Port);
                //
                // demand for them
                //
                socketPermission.Demand();

                // Here the permission check has succeded.
                // NB: if local port is 0, then winsock will assign some>1024,
                //     so assuming that this is safe. We will not check the
                //     NetworkAccess.Accept permissions in Receive.
            }
            else {
                //<





                ExceptionHelper.UnmanagedPermission.Demand();
            }

            //
            // ask the EndPoint to generate a SocketAddress that we
            // can pass down to winsock
            //
            SocketAddress socketAddress = CallSerializeCheckDnsEndPoint(endPointSnapshot);
            DoBind(endPointSnapshot, socketAddress);
            if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "Bind", "");
        }
Пример #21
0
        //
        // socketAddress must always be the result of remoteEP.Serialize()
        //
        private SocketAddress CheckCacheRemote(ref EndPoint remoteEP, bool isOverwrite)
        {
            IPEndPoint ipSnapshot = remoteEP as IPEndPoint;

            if (ipSnapshot != null)
            {
                // Snapshot to avoid external tampering and malicious derivations if IPEndPoint
                ipSnapshot = ipSnapshot.Snapshot();
                // DualMode: Do the security check on the user input address, but return an IPEndPoint 
                // mapped to an IPv6 address.
                remoteEP = RemapIPEndPoint(ipSnapshot);
            }

            // This doesn't use SnapshotAndSerialize() because we need the ipSnapshot later.
            SocketAddress socketAddress = CallSerializeCheckDnsEndPoint(remoteEP);

            // We remember the first peer we have communicated with
            SocketAddress permittedRemoteAddress = m_PermittedRemoteAddress;
            if (permittedRemoteAddress != null && permittedRemoteAddress.Equals(socketAddress))
            {
                return permittedRemoteAddress;
            }

            //
            // for now SocketPermission supports only IPEndPoint
            //
            if (ipSnapshot != null)
            {
                //
                // create the permissions the user would need for the call
                //
                SocketPermission socketPermission
                    = new SocketPermission(
                        NetworkAccess.Connect,
                        Transport,
                        ipSnapshot.Address.ToString(),
                        ipSnapshot.Port);
                //
                // demand for them
                //
                socketPermission.Demand();
            }
            else {
                //
                // for V1 we will demand permission to run UnmanagedCode for
                // an EndPoint that is not an IPEndPoint until we figure out how these fit
                // into the whole picture of SocketPermission
                //

                ExceptionHelper.UnmanagedPermission.Demand();
            }
            //cache only the first peer we communicated with
            if (m_PermittedRemoteAddress == null || isOverwrite) {
                m_PermittedRemoteAddress = socketAddress;
            }

            return socketAddress;
        }
	public void IsSubsetOf2 ()
	{
		s1 = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "12.13.14.15", 80);
		s1.AddPermission(NetworkAccess.Accept, TransportType.All, "10.11.4.*", 9090);
		s2 = new SocketPermission(NetworkAccess.Connect, TransportType.All, "12.13.14.15", 80);
		s2.AddPermission(NetworkAccess.Accept, TransportType.All, "10.11.*.*", 9090);
		
		Assertion.Assert ("#3: bug in MS.Net", s1.IsSubsetOf (s2));
	}
Пример #23
0
        public bool JoinRoom(string roomId)
        {
            try
            {
                if ((IsConnected) && (!IsInRoom))
                {
                    Logger.WriteLine("Requesting to join room " + roomId);
                    Message request = Message.CreateMessageJoin(PeerId, roomId);
                    byte[] buffer = new byte[1024];

                    lock (trackerPaddle)
                    {
                        trackerSocket.Send(request.data, 0, request.data.Length, SocketFlags.None);
                        trackerSocket.Receive(buffer, buffer.Length, SocketFlags.None);
                    }

                    Message response = new Message(buffer);
                    Message.MessageType responseType = response.GetMessageType();
                    if (responseType == Message.MessageType.CreatorInfo)
                    {
                        IPAddress ip;
                        int port;
                        response.GetCreatorInfo(out ip, out port);

                        Logger.WriteLine("GunbondPeer (Peer - Tracker): Creator Info");
                        Logger.WriteLine("Hostname : " + ip);
                        Logger.WriteLine("Port     : " + port);

                        SocketPermission permission = new SocketPermission(
                             NetworkAccess.Connect,
                             TransportType.Tcp,
                             "",
                             SocketPermission.AllPorts
                             );
                        permission.Demand();

                        byte[] bufferFromCreator = new byte[1024];

                        lock (nextPeerPaddle)
                        {
                            IPEndPoint ipEndPoint = new IPEndPoint(ip, port);
                            nextPeerSocket = new Socket(
                                ip.AddressFamily,
                                SocketType.Stream,
                                ProtocolType.Tcp
                                );

                            nextPeerSocket.NoDelay = false;
                            nextPeerSocket.Connect(ipEndPoint);
                            Message messageConnectToCreator = Message.CreateMessageHandshakePeerCreator(PeerId, Configuration.ListenPort);

                            nextPeerSocket.Send(messageConnectToCreator.data, 0, messageConnectToCreator.data.Length, SocketFlags.None);
                            nextPeerSocket.Receive(bufferFromCreator, bufferFromCreator.Length, SocketFlags.None);
                        }

                        keepAliveRoom = new Thread(new ThreadStart(SendAliveNextPeer));
                        keepAliveRoom.Start();

                        Message messageFromCreator = new Message(bufferFromCreator);
                        Message.MessageType fromCreatorMessageType = messageFromCreator.GetMessageType();
                        if (fromCreatorMessageType == Message.MessageType.Success)
                        {
                            IsInRoom = true;
                            IsCreator = false;

                            Logger.WriteLine("Successfully joined room.");
                            return true;
                        }
                        else
                        {
                            Logger.WriteLine("Request join room failed 1.");
                            return false;
                        }

                    }
                    else if (responseType == Message.MessageType.Failed)
                    {
                        Console.WriteLine("Request join room failed 2.");
                        return false;
                    }
                    else
                    {
                        Console.WriteLine("Response unrecognized.");
                        return false;
                    }
                }
                else if (!IsConnected)
                {
                    Console.WriteLine("Not connected to tracker, connect to tracker first.");
                    return false;
                }
                else if (IsInRoom)
                {
                    Console.WriteLine("Currently in room, quit room first.");
                    return false;
                }
                else
                {
                    Console.WriteLine("Unknown error.");
                    return false;
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.ToString());
                return false;
            }
        }
Пример #24
0
        public bool ConnectTracker()
        {
            try
            {
                if (!IsConnected)
                {
                    SocketPermission permission = new SocketPermission(
                        NetworkAccess.Connect,
                        TransportType.Tcp,
                        "",
                        SocketPermission.AllPorts
                        );

                    permission.Demand();

                    IPAddress trackerAddr;
                    if (IPAddress.TryParse(Configuration.TrackerAddress, out trackerAddr))
                    {
                        byte[] buffer = new byte[1024];
                        lock (trackerPaddle)
                        {
                            IPEndPoint ipEndPoint = new IPEndPoint(trackerAddr, Configuration.Port);
                            trackerSocket = new Socket(
                                trackerAddr.AddressFamily,
                                SocketType.Stream,
                                ProtocolType.Tcp
                               );

                            trackerSocket.NoDelay = false;
                            trackerSocket.Connect(ipEndPoint);
                            Message request = Message.CreateMessageHandshakePeer();

                            trackerSocket.Send(request.data, 0, request.data.Length, SocketFlags.None);
                            trackerSocket.Receive(buffer, buffer.Length, SocketFlags.None);
                        }

                        Message response = new Message(buffer);
                        if (response.GetMessageType() == Message.MessageType.HandshakeTracker)
                        {
                            int peerId;
                            response.GetHandshakeTracker(out peerId);
                            PeerId = peerId;
                            IsConnected = true;
                            Logger.WriteLine("Connection to tracker is successfully established. PeerID: " + PeerId);

                            IPAddress ipAddr = (trackerSocket.LocalEndPoint as IPEndPoint).Address;
                            IPEndPoint ipEndPointListener = new IPEndPoint(ipAddr, Configuration.ListenPort);
                            SocketPermission permissionListener = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, "", Configuration.ListenPort);

                            listenerSocket = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                            listenerSocket.Bind(ipEndPointListener);

                            permission.Demand();

                            waitPeer = new Thread(new ParameterizedThreadStart(WaitPeer));
                            waitPeer.Start(4);

                            keepAlive = new Thread(new ThreadStart(SendAliveTracker));
                            keepAlive.Start();
                            return true;
                        }
                        else
                        {
                            Logger.WriteLine("Failed to connect to tracker.");
                            return false;
                        }
                    }
                    else
                    {
                        Logger.WriteLine("Failed to connect, tracker not found.");
                        return false;
                    }
                }
                else
                {
                    Logger.WriteLine("Already connected to tracker.");
                    return false;
                }
            }
            catch (SocketException exc)
            {
                Logger.WriteLine(exc);
                return false;
            }
        }
Пример #25
0
    public async Task Attach(CancellationToken cancellationToken) {
      System.Diagnostics.Debug.Assert(CurrentState == State.Idle);

      SocketPermission permission = new SocketPermission(
                NetworkAccess.Connect,
                TransportType.Tcp,
                kServerHostname,
                kServerPort);
      permission.Demand();

      IPAddress ipAddress = new IPAddress(new byte[] { 127, 0, 0, 1 });
      IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, kServerPort);

      socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
                          ProtocolType.Tcp);
      socket.Blocking = false;
      socket.NoDelay = true;
      socket.ReceiveBufferSize = 1024 * 1024;
      socket.SendBufferSize = 1024 * 1024;
      socket.ReceiveTimeout = 0;
      socket.SendTimeout = 0;

      OnStateChanged(State.Attaching);

      while (true) {
        Task task = Task.Factory.FromAsync(socket.BeginConnect, socket.EndConnect, ipEndPoint, null);
        try {
          await task.WithCancellation(cancellationToken);
        } catch (OperationCanceledException) {
          socket.Close();
          socket = null;
          OnStateChanged(State.Idle);
          return;
        } catch (SocketException e) {
          if (e.SocketErrorCode == SocketError.ConnectionRefused) {
            // Not found - emulator may still be starting.
            System.Diagnostics.Debug.WriteLine("Connection refused; trying again...");
            continue;
          }
          OnStateChanged(State.Idle);
          return;
        }
        break;
      }

      // Start recv pump.
      Dispatch.Issue(() => ReceivePump());

      var fbb = BeginRequest();
      AttachRequest.StartAttachRequest(fbb);
      int requestDataOffset = AttachRequest.EndAttachRequest(fbb);
      var response = await CommitRequest(fbb, RequestData.AttachRequest, requestDataOffset);

      System.Diagnostics.Debug.Assert(response.ResponseDataType ==
                                      ResponseData.AttachResponse);
      var attachResponse = new AttachResponse();
      response.GetResponseData(attachResponse);

      // Open mmap to share memory.
      memoryHandle = FileMapping.OpenFileMapping(
          FileMapAccess.FILE_MAP_ALL_ACCESS, false, attachResponse.MemoryFile);
      if (memoryHandle.IsInvalid) {
        System.Diagnostics.Debug.Fail("Unable to open target memory");
        Detach();
        return;
      }

      // Open mmap to code cache.
      codeCacheHandle =
          FileMapping.OpenFileMapping(FileMapAccess.FILE_MAP_ALL_ACCESS, false,
                                      attachResponse.CodeCacheFile);
      if (codeCacheHandle.IsInvalid) {
        System.Diagnostics.Debug.Fail("Unable to open target code cache");
        Detach();
        return;
      }
      codeCachePtr = FileMapping.MapViewOfFileEx(
          codeCacheHandle, FileMapAccess.FILE_MAP_ALL_ACCESS, 0, 0,
          attachResponse.CodeCacheSize, attachResponse.CodeCacheBase);

      // Setup the memory system. This maps the emulator memory into our address
      // space.
      if (!Memory.InitializeMapping(memoryHandle)) {
        Detach();
        return;
      }

      OnStateChanged(State.Attached);
    }
Пример #26
0
        public void start(string ip, int port, int number)
        {
            Log.Info("正在启动监听");

            SocketPermission permission = new SocketPermission(
                NetworkAccess.Accept,
                TransportType.Tcp,
                "",
                SocketPermission.AllPorts
                );

            Socket sListener = null;
            try
            {

                permission.Demand();

                IPAddress ipAddr = IPAddress.Parse(ip);
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, port);

                sListener = new Socket(
                    ipAddr.AddressFamily,
                    SocketType.Stream,
                    ProtocolType.Tcp
                    );

                sListener.Bind(ipEndPoint);
                sListener.Listen(number);

                Log.Info(string.Format("监听已启动在 {0}", ipEndPoint));

                sListener.BeginAccept(new AsyncCallback(AcceptCallback), sListener);

            }
            catch (Exception ex)
            {
                Console.WriteLine("Server Error : {0}", ex.ToString());
                Log.Debug(string.Format("ERROR : {0}", ex.Message));
                return;
            }

            if (sListener.Connected)
            {
                sListener.Shutdown(SocketShutdown.Receive);
                sListener.Close();
            }
        }
Пример #27
0
        //
        // socketAddress must always be the result of remoteEP.Serialize()
        //
        private void CheckCacheRemote(SocketAddress socketAddress, EndPoint remoteEP, bool isOverwrite) {
            // We remember the first peer we have communicated with
            if (m_PermittedRemoteAddress != null && m_PermittedRemoteAddress.Equals(socketAddress)) {
                return;
            }
            //
            // for now SocketPermission supports only IPEndPoint
            //
            if (remoteEP.GetType()==typeof(IPEndPoint)) {
                //
                // cast the EndPoint to IPEndPoint
                //
                IPEndPoint remoteIPEndPoint = (IPEndPoint)remoteEP;
                //
                // create the permissions the user would need for the call
                //
                SocketPermission socketPermission
                    = new SocketPermission(
                        NetworkAccess.Connect,
                        Transport,
                        remoteIPEndPoint.Address.ToString(),
                        remoteIPEndPoint.Port);
                //
                // demand for them
                //
                socketPermission.Demand();
            }
            else {
                //
                // for V1 we will demand permission to run UnmanagedCode for
                // an EndPoint that is not an IPEndPoint until we figure out how these fit
                // into the whole picture of SocketPermission
                //

                (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Demand();
            }
            //cache only the first peer we communicated with
            if (m_PermittedRemoteAddress == null || isOverwrite) {
                m_PermittedRemoteAddress = socketAddress;
            }
        }
Пример #28
0
        /// <include file='doc\Socket.uex' path='docs/doc[@for="Socket.Bind"]/*' />
        /// <devdoc>
        ///    <para>Associates a socket with an end point.</para>
        /// </devdoc>
        public void Bind(EndPoint localEP) {
            if (CleanedUp) {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            //
            // parameter validation
            //
            if (localEP==null) {
                throw new ArgumentNullException("localEP");
            }

            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::Bind() localEP:" + localEP.ToString());

            EndPoint endPointSnapshot = localEP;
            //
            // for now security is implemented only on IPEndPoint
            // If EndPoint is of other type - unmanaged code permisison is demanded
            //
            if (endPointSnapshot.GetType()==typeof(IPEndPoint)) {
                //
                // cast the EndPoint to IPEndPoint
                //
                endPointSnapshot = new IPEndPoint(((IPEndPoint)localEP).Address, ((IPEndPoint)localEP).Port);
                IPEndPoint localIPEndPoint = (IPEndPoint)endPointSnapshot;
                //
                // create the permissions the user would need for the call
                //
                SocketPermission socketPermission
                    = new SocketPermission(
                        NetworkAccess.Accept,
                        Transport,
                        localIPEndPoint.Address.ToString(),
                        localIPEndPoint.Port);
                //
                // demand for them
                //
                socketPermission.Demand();

                // Here the permission check has succeded.
                // NB: if local port is 0, then winsock will assign some>1024,
                //     so assuming that this is safe. We will not check the
                //     NetworkAccess.Accept permissions in Receive.
            }
            else {

                (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Demand();
            }

            //
            // ask the EndPoint to generate a SocketAddress that we
            // can pass down to winsock
            //
            SocketAddress socketAddress = endPointSnapshot.Serialize();

            int errorCode =
                UnsafeNclNativeMethods.OSSOCK.bind(
                    m_Handle,
                    socketAddress.m_Buffer,
                    socketAddress.m_Size );

            //
            // if the native call fails we'll throw a SocketException
            //
            if (errorCode!=SocketErrors.Success) {
                //
                // update our internal state after this socket error and throw
                //
                SocketException socketException = new SocketException();
                UpdateStatusAfterSocketError();
                throw socketException;
            }

            if (m_RightEndPoint==null) {
                //
                // save a copy of the EndPoint so we can use it for Create()
                //
                m_RightEndPoint = endPointSnapshot;
            }

        }
	public override IPermission Intersect(IPermission target)
			{
				if(target == null)
				{
					return target;
				}
				else if(!(target is SocketPermission))
				{
					throw new ArgumentException(S._("Arg_PermissionMismatch"));
				}
				else if(((SocketPermission)target).IsUnrestricted())
				{
					return Copy();
				}
				else if(IsUnrestricted())
				{
					return target.Copy();
				}
				else
				{
					SocketPermission perm = new SocketPermission
						(PermissionState.None);
					EndpointPermission newInfo;
					foreach(EndpointPermission info in permissions)
					{
						foreach(EndpointPermission info2 in
									((SocketPermission)target).permissions)
						{
							newInfo = Intersect(info, info2);
							if(newInfo != null)
							{
								perm.permissions.Add(newInfo);
							}
						}
					}
					return perm;
				}
			}
Пример #30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (SiteSecurity.IsInRole("admin") == false)
            {
                Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
            }

            ID = "EditConfigBox";

            SharedBasePage requestPage = Page as SharedBasePage;
            SiteConfig siteConfig = requestPage.SiteConfig;

            if (!IsPostBack)
            {
                textContact.Text = siteConfig.Contact;
                textCopyright.Text = siteConfig.Copyright;
                textPassword.Text = passwordPlaceHolder;
                textConfirmPassword.Text = passwordPlaceHolder;
                textFrontPageCategory.Text = siteConfig.FrontPageCategory;
                textFrontPageDayCount.Text = siteConfig.FrontPageDayCount.ToString();
                textFrontPageEntryCount.Text = siteConfig.FrontPageEntryCount.ToString();
                textEntriesPerPage.Text = siteConfig.EntriesPerPage.ToString();
                textContentLookaheadDays.Text = siteConfig.ContentLookaheadDays.ToString();
                textMainMaxDaysInRss.Text = siteConfig.RssDayCount.ToString();
                textMainMaxEntriesInRss.Text = siteConfig.RssMainEntryCount.ToString();
                textOtherMaxEntriesInRss.Text = siteConfig.RssEntryCount.ToString();
                checkAlwaysIncludeContentInRSS.Checked = siteConfig.AlwaysIncludeContentInRSS;
                checkEnableRSSItemFooter.Checked = siteConfig.EnableRssItemFooters;
                textRSSItemFooter.Text = siteConfig.RssItemFooter;
                checkPop3Enabled.Checked = siteConfig.EnablePop3;
                textPop3Interval.Text = siteConfig.Pop3Interval.ToString();
                textPop3Server.Text = siteConfig.Pop3Server;
                textPop3SubjectPrefix.Text = siteConfig.Pop3SubjectPrefix;
                textPop3Username.Text = siteConfig.Pop3Username;
                textPop3Password.Text = passwordPlaceHolder;
                textPop3PasswordRepeat.Text = passwordPlaceHolder;
                textRoot.Text = siteConfig.Root;
                textSmtpServer.Text = siteConfig.SmtpServer;
                textSmtpPort.Text = siteConfig.SmtpPort.ToString();
                checkUseSSLForSMTP.Checked = siteConfig.UseSSLForSMTP;
                textNotificationEmailAddress.Text = siteConfig.NotificationEMailAddress;
                textSubtitle.Text = siteConfig.Subtitle;
                textSmtpServer.Text = siteConfig.SmtpServer;
                checkEnableCoComment.Checked = siteConfig.EnableCoComment;
                checkComments.Checked = siteConfig.SendCommentsByEmail;
                checkPingbacks.Checked = siteConfig.SendPingbacksByEmail;
                checkReferrals.Checked = siteConfig.SendReferralsByEmail;
                checkPosts.Checked = siteConfig.SendPostsByEmail;
                checkTrackbacks.Checked = siteConfig.SendTrackbacksByEmail;
                checkShowCommentCounters.Checked = siteConfig.ShowCommentCount;
                checkEnableAutoPingback.Checked = siteConfig.EnableAutoPingback;
                checkEnableBloggerApi.Checked = siteConfig.EnableBloggerApi;
                checkEnableComments.Checked = siteConfig.EnableComments;
                checkEnableCommentApi.Checked = siteConfig.EnableCommentApi;
                checkShowCommentsWhenViewingEntry.Checked = siteConfig.ShowCommentsWhenViewingEntry;
                checkEnableConfigEditService.Checked = siteConfig.EnableConfigEditService;
                checkEnableEditService.Checked = siteConfig.EnableEditService;
                checkEnableAutoSave.Checked = siteConfig.EnableAutoSave;
                checkEnablePingbackService.Checked = siteConfig.EnablePingbackService;
                checkEnableTrackbackService.Checked = siteConfig.EnableTrackbackService;
                checkEnableClickThrough.Checked = siteConfig.EnableClickThrough;
                checkEnableAggregatorBugging.Checked = siteConfig.EnableAggregatorBugging;
                checkXssEnabled.Checked = siteConfig.EnableXSSUpstream;
                textXssEndpoint.Text = siteConfig.XSSUpstreamEndpoint;
                textXssInterval.Text = siteConfig.XSSUpstreamInterval.ToString();
                textXssPassword.Text = passwordPlaceHolder;
                textXssPasswordRepeat.Text = passwordPlaceHolder;
                textXssUsername.Text = siteConfig.XSSUpstreamUsername;
                textXssRssFilename.Text = siteConfig.XSSRSSFilename;
                checkPop3InlineAttachedPictures.Checked = siteConfig.Pop3InlineAttachedPictures;
                textPop3AttachedPicturesPictureThumbnailHeight.Text = siteConfig.Pop3InlinedAttachedPicturesThumbHeight.ToString();
                mailDeletionAll.Checked = siteConfig.Pop3DeleteAllMessages;
                mailDeletionProcessed.Checked = !siteConfig.Pop3DeleteAllMessages;
                logIgnoredEmails.Checked = siteConfig.Pop3LogIgnoredEmails;
                checkShowItemDescriptionInAggregatedViews.Checked = siteConfig.ShowItemDescriptionInAggregatedViews;
                checkEnableStartPageCaching.Checked = siteConfig.EnableStartPageCaching;
                checkEnableBlogrollDescription.Checked = siteConfig.EnableBlogrollDescription;
                checkEntryTitleAsLink.Checked = siteConfig.EntryTitleAsLink;
                checkEnableUrlRewriting.Checked = siteConfig.EnableUrlRewriting;
                checkEnableCrosspost.Checked = siteConfig.EnableCrossposts;
                checkCategoryAllEntries.Checked = siteConfig.CategoryAllEntries;
                checkReferralUrlBlacklist.Checked = siteConfig.EnableReferralUrlBlackList;
                textReferralBlacklist.Text = siteConfig.ReferralUrlBlackList;
                checkCaptchaEnabled.Checked = siteConfig.EnableCaptcha;
                checkReferralBlacklist404s.Checked = siteConfig.EnableReferralUrlBlackList404s;
                textRSSChannelImage.Text = siteConfig.ChannelImageUrl;
                checkEnableTitlePermaLink.Checked = siteConfig.EnableTitlePermaLink;
                checkEnableTitlePermaLinkUnique.Checked = siteConfig.EnableTitlePermaLinkUnique;
                checkEnableTitlePermaLinkSpaces.Checked = siteConfig.EnableTitlePermaLinkSpaces;
                checkEnableEncryptLoginPassword.Checked = siteConfig.EncryptLoginPassword;
                checkEnableSmtpAuthentication.Checked = siteConfig.EnableSmtpAuthentication;
                textSmtpUsername.Text = siteConfig.SmtpUserName;
                textSmtpPassword.Text = passwordPlaceHolder;
                textRssLanguage.Text = siteConfig.RssLanguage;
                checkEnableSearchHighlight.Checked = siteConfig.EnableSearchHighlight;
                checkEnableEntryReferral.Checked = siteConfig.EnableEntryReferrals;
                textFeedBurnerName.Text = siteConfig.FeedBurnerName;
                checkUseFeedScheme.Checked = siteConfig.UseFeedSchemeForSyndication;
                checkLogBlockedReferrals.Checked = siteConfig.LogBlockedReferrals;

                //populate the title space replacement options
                dropDownTitlePermalinkReplacementCharacter.Items.Clear();//in casee someone adds them in the ascx
                foreach (string s in TitleMapperModule.TitlePermalinkSpaceReplacementOptions) dropDownTitlePermalinkReplacementCharacter.Items.Add(s);
                dropDownTitlePermalinkReplacementCharacter.SelectedValue = siteConfig.TitlePermalinkSpaceReplacement;

                checkSpamBlockingEnabled.Checked = siteConfig.EnableSpamBlockingService;
                textSpamBlockingApiKey.Text = siteConfig.SpamBlockingServiceApiKey;
                optionSpamHandling.SelectedValue = siteConfig.EnableSpamModeration ? SPAM_OPTION_SAVE : SPAM_OPTION_DELETE;

                // setup the checkbox list to select which tags to allow
                checkBoxListAllowedTags.DataSource = siteConfig.AllowedTags;
                checkBoxListAllowedTags.DataTextField = "Name";
                checkBoxListAllowedTags.DataValueField = "Name";

                // enable comment moderation 
                checkCommentsRequireApproval.Checked = siteConfig.CommentsRequireApproval;

                // allow html and comments
                checkAllowHtml.Checked = siteConfig.CommentsAllowHtml;

                // populate from config - Gravatar
                GravatarPopulateForm();

                // supress email address display
                checkDisableEmailDisplay.Checked = siteConfig.SupressEmailAddressDisplay;

                checkEnableCommentDays.Checked = siteConfig.EnableCommentDays;

                checkAttemptToHtmlTidyContent.Checked = siteConfig.HtmlTidyContent;
                checkResolveCommenterIP.Checked = siteConfig.ResolveCommenterIP;

                //if ( siteConfig.EnableCommentDays ) 
                //{
                if (siteConfig.DaysCommentsAllowed > 0)
                {
                    textDaysCommentsAllowed.Text = siteConfig.DaysCommentsAllowed.ToString();
                }
                //} 
                //else 
                //{
                //	textDaysCommentsAllowed.Text = null;
                //}

                // supress email address display
                checkDisableEmailDisplay.Checked = siteConfig.SupressEmailAddressDisplay;

                checkEnableCommentDays.Checked = siteConfig.EnableCommentDays;

                //if ( siteConfig.EnableCommentDays ) 
                //{
                if (siteConfig.DaysCommentsAllowed > 0)
                {
                    textDaysCommentsAllowed.Text = siteConfig.DaysCommentsAllowed.ToString();
                }
                //} 
                //else 
                //{
                //	textDaysCommentsAllowed.Text = null;
                //}

                // email daily report
                checkDailyReport.Text = resmgr.GetString("text_daily_activity_report");
                checkDailyReport.Checked = siteConfig.EnableDailyReportEmail;

                WindowsTimeZoneCollection timeZones = WindowsTimeZone.TimeZones;
                foreach (WindowsTimeZone tz in timeZones)
                {
                    listTimeZones.Items.Add(new ListItem(tz.DisplayName, tz.ZoneIndex.ToString()));
                }
                listTimeZones.SelectedValue = siteConfig.DisplayTimeZoneIndex.ToString();
                checkUseUTC.Checked = !siteConfig.AdjustDisplayTimeZone;

                //FIX: hardcoded path
                ThemeDictionary themes = BlogTheme.Load(SiteUtilities.MapPath("themes"));
                foreach (BlogTheme theme in themes.Values)
                {
                    // setting the selected item like this instead of
                    // using 	listThemes.SelectedValue = siteConfig.Theme;
                    // prevents the page from breaking.

                    ListItem item = new ListItem(theme.Title, theme.Name);
                    if (item.Value == siteConfig.Theme)
                    {
                        item.Selected = true;
                    }
                    listThemes.Items.Add(item);
                }

                textTitle.Text = siteConfig.Title;

                checkBoxListPingServices.DataSource = PingServiceCollection;
                checkBoxListPingServices.DataTextField = "Hyperlink";
                checkBoxListPingServices.DataValueField = "Endpoint";

                drpEntryEditControl.Items.Clear();
                foreach (string potentialAssembly in Directory.GetFiles(HttpRuntime.BinDirectory, "*.dll"))
                {
                    try
                    {
                        Assembly a = Assembly.LoadFrom(potentialAssembly);
                        foreach (Type potentialType in a.GetTypes())
                        {
                            if (potentialType.BaseType == typeof(EditControlAdapter))
                            {
                                drpEntryEditControl.Items.Add(new ListItem(potentialType.Name, potentialType.AssemblyQualifiedName));
                            }
                        }
                    }
                    catch (Exception)
                    {
                        //swallow
                    }
                }

                //Reasonable default
                if (string.IsNullOrEmpty(siteConfig.EntryEditControl))
                {
                    siteConfig.EntryEditControl = typeof(TinyMCEAdapter).AssemblyQualifiedName;
                }
                DataBind();

                ListItem li = drpEntryEditControl.Items.FindByText(siteConfig.EntryEditControl);
                if (li != null)
                {
                    li.Selected = true;
                }
                else
                {
                    drpEntryEditControl.SelectedIndex = 0;
                }

                foreach (PingService ps in siteConfig.PingServices)
                {
                    checkBoxListPingServices.Items.FindByValue(ps.Endpoint).Selected = true;
                }

                foreach (ValidTag tag in siteConfig.AllowedTags)
                {
                    checkBoxListAllowedTags.Items.FindByValue(tag.Name).Selected = tag.IsAllowed;
                }

                //check for Smtp permission
                if (SecurityManager.IsGranted(new SmtpPermission(SmtpAccess.ConnectToUnrestrictedPort)))
                {
                    phSmtpTrustWarning.Visible = false;
                }
                else
                {
                    phSmtpTrustWarning.Visible = true;
                }

                //check for Socket permission
                SocketPermission sp;
                if (String.IsNullOrEmpty(textPop3Server.Text))
                {
                    sp = new SocketPermission(PermissionState.Unrestricted);
                }
                else
                {
                    sp = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, textPop3Server.Text, 110);
                }

                if (SecurityManager.IsGranted(sp))
                {
                    phPop3TrustWarning.Visible = false;
                }
                else
                {
                    phPop3TrustWarning.Visible = true;
                }

                // georss stuff
                checkEnableGeoRss.Checked = siteConfig.EnableGeoRss;
                textGoogleMapsApi.Text = siteConfig.GoogleMapsApiKey;
                textDefaultLatitude.Text = siteConfig.DefaultLatitude.ToString(CultureInfo.InvariantCulture);
                textDefaultLongitude.Text = siteConfig.DefaultLongitude.ToString(CultureInfo.InvariantCulture);
                checkEnableGoogleMaps.Checked = siteConfig.EnableGoogleMaps;
                checkEnableDefaultLatLongForNonGeoCodedPosts.Checked = siteConfig.EnableDefaultLatLongForNonGeoCodedPosts;

                // OpenId
                chkAllowOpenIdAdmin.Checked = siteConfig.AllowOpenIdAdmin;
                chkAllowOpenIdCommenter.Checked = siteConfig.AllowOpenIdComments;
                chkBypassSpamOpenIdCommenter.Checked = siteConfig.BypassSpamOpenIdComment;


            } // end if !postback

            //enable list controls that may have been enabled client-side
            //in 2.0 if they are not enable we won't get there postback data
            checkBoxListAllowedTags.Enabled = true;
            dropGravatarRating.Enabled = true;
        }
Пример #31
0
 private bool IntersectEmpty(SocketPermission permission)
 {
     return(!permission.m_noRestriction &&
            (permission.m_connectList.Count == 0) &&
            (permission.m_acceptList.Count == 0));
 }