public override IDataTransferable Duplicate()
        {
            IWCCertificate m = new IWCCertificate();

            m.FromOSD(ToOSD());
            return(m);
        }
        public void ParseIWCCertificateForURLs(IWCCertificate c)
        {
            IConfigurationService configService = m_registry.RequestModuleInterface <IConfigurationService>();

            //Give the Urls to the config service
            configService.AddNewUrls(c.Connection.UserName, c.Connection.SecureUrls);
            AddConnection(c);
            c.Active = true;
        }
        public ThreatLevel GetThreatLevelForUrl(string URL)
        {
            IWCCertificate cert = CertificateVerification.GetCertificateByUrl(URL);

            if (cert != null)
            {
                return(cert.ThreatLevel);
            }
            return(m_untrustedConnectionsDefaultTrust);
        }
        public void DeleteRemoteHost(IWCCertificate connection)
        {
            OSDMap request = connection.ToOSD(false);

            request["Method"] = "Delete";
            OSDMap reply = WebUtils.PostToService(connection.Connection.RecieverURL, request);

            if (!reply["Success"].AsBoolean())
            {
                m_log.Warn("[IWC]: Failed to delete remote host @ " + connection.Connection.RecieverURL);
            }
        }
 private void RemoveConnection(IWCCertificate c)
 {
     if (Connections.Contains(c))
     {
         Connections.Remove(c);
         IGenericsConnector genericsConnector = DataManager.DataManager.RequestPlugin <IGenericsConnector>();
         if (genericsConnector != null)
         {
             genericsConnector.RemoveGeneric(UUID.Zero, "InterWorldConnections", c.Connection.RecieverURL);
         }
     }
 }
        /// <summary>
        /// Add a certificate for the given connection
        /// </summary>
        /// <param name="module"></param>
        /// <param name="cmds"></param>
        private void AddIWCConnection(string module, string[] cmds)
        {
            string Url = MainConsole.Instance.CmdPrompt("Url to the connection");

            //Be user friendly, add the http:// if needed as well as the final /
            Url = (Url.StartsWith("http://") || Url.StartsWith("https://")) ? Url : "http://" + Url;
            Url = Url.EndsWith("/") ? Url + "iwcconnection" : Url + "/iwcconnection";

            IWCCertificate con = FindConnectionByURL(Url);

            if (con != null)
            {
                if (con.Active)
                {
                    m_log.Warn("A connection to this server already exists.");
                }
                else
                {
                    string activate = MainConsole.Instance.CmdPrompt("A connection to this server already exists, do you wish to active it?");
                    if (activate == "yes" || activate == "true")
                    {
                        TryAddConnection(con);
                    }
                }
                return;
            }
            con                        = new IWCCertificate();
            con.Connection             = new IWCConnection();
            con.Connection.RecieverURL = Url;
            IHttpServer server = m_registry.RequestModuleInterface <ISimulationBase>().GetHttpServer(0);

            con.Connection.SenderURL = server.HostName + ":" + server.Port + "/iwcconnection";
            string timeUntilExpires = MainConsole.Instance.CmdPrompt("Time until the connection expires (ends, in days)");
            string trustLevel       = MainConsole.Instance.CmdPrompt("Trust level of this connection");
            int    timeInDays       = int.Parse(timeUntilExpires);
            string UserName         = MainConsole.Instance.CmdPrompt("User Name for this connection (can be blank)");
            string Password         = MainConsole.Instance.CmdPrompt("Password for this connection");

            //Build the certificate
            if (UserName == "")
            {
                UserName = UUID.Random().ToString();
            }
            con.Connection.UserName = UserName;
            con.Connection.Password = Password;
            con.ValidUntil          = DateTime.Now.AddDays(timeInDays);

            //Add the certificate now
            CertificateVerification.AddCertificate(con);
            con.ThreatLevel = (ThreatLevel)Enum.Parse(typeof(ThreatLevel), trustLevel);

            TryAddConnection(con);
        }
        public void TryAddConnection(IWCCertificate c)
        {
            c = BuildSecureUrlsForConnection(c);
            IWCConnection cert = OutgoingPublicComms.QueryRemoteHost(c.Connection);

            if (cert != null)
            {
                c.Connection = cert;
                ParseIWCCertificateForURLs(c);
            }
            else
            {
                c.Active = false;
            }
        }
        private void RemoveIWCConnection(string module, string[] cmds)
        {
            string         Url = MainConsole.Instance.CmdPrompt("Url to the connection");
            IWCCertificate c   = FindConnectionByURL(Url);

            if (c == null)
            {
                m_log.Warn("Could not find the connection.");
                return;
            }
            OutgoingPublicComms.DeleteRemoteHost(c);
            RemoveConnection(c);
            IConfigurationService configService = m_registry.RequestModuleInterface <IConfigurationService>();

            //Remove the Urls from the config service
            configService.RemoveUrls(c.Connection.UserName);
        }
        /// <summary>
        /// Create secure Urls that only us and the sim that called us know of
        /// This Urls is used to add/remove agents and other information from the other sim
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public IWCCertificate BuildSecureUrlsForConnection(IWCCertificate c)
        {
            IGridRegistrationService gridRegistration = Registry.RequestModuleInterface <IGridRegistrationService>();

            if (gridRegistration != null)
            {
                IGridService gridService = Registry.RequestModuleInterface <IGridService>();
                if (gridService != null)
                {
                    GridRegion r = gridService.GetRegionByName(UUID.Zero, c.Connection.UserName + "_Link");
                    if (r == null)
                    {
                        uint  rX           = (uint)Util.RandomClass.Next(10000, 1000000);
                        uint  rY           = (uint)Util.RandomClass.Next(10000, 1000000);
                        ulong regionhandle = Utils.UIntsToLong(rX, rY);

                        r              = new GridRegion();
                        r.RegionID     = UUID.Random();
                        r.RegionHandle = regionhandle;
                        IHttpServer server = m_registry.RequestModuleInterface <ISimulationBase>().GetHttpServer(0);
                        r.ExternalHostName = server.HostName;
                        if (r.ExternalHostName.StartsWith("http://"))
                        {
                            r.ExternalHostName = r.ExternalHostName.Remove(0, 7);
                        }
                        else if (r.ExternalHostName.StartsWith("https://"))
                        {
                            r.ExternalHostName = r.ExternalHostName.Remove(0, 8);
                        }
                        r.InternalEndPoint = new IPEndPoint(IPAddress.Any, (int)server.Port);
                        r.Flags            = (int)Aurora.Framework.RegionFlags.Foreign;
                        r.RegionName       = c.Connection.UserName + "_Link";
                        r.RegionType       = "Link";

                        UUID SessionID;
                        gridService.RegisterRegion(r, UUID.Zero, out SessionID);
                    }
                    //Give the basic Urls that we have
                    c.Connection.SecureUrls = gridRegistration.GetUrlForRegisteringClient(c.Connection.UserName, r.RegionHandle);
                }
            }
            return(c);
        }
        public GridRegion GetRegionForGrid(string regionName, string Url)
        {
            IWCCertificate c = FindConnectionByURL(Url);

            if (c != null)
            {
                //If we are already connected, the grid services are together, so we already know of the region if it exists, therefore, it does not exist
                return(null);
            }
            else
            {
                c            = new IWCCertificate();
                c.Connection = new IWCConnection();
                //Build the certificate
                c.ValidUntil = DateTime.Now.AddDays(1);             //One day for now...

                c.ThreatLevel = m_untrustedConnectionsDefaultTrust; //Least amount of our trust for them
                //Be user friendly, add the http:// if needed as well as the final /
                Url = (Url.StartsWith("http://") || Url.StartsWith("https://")) ? Url : "http://" + Url;
                Url = Url.EndsWith("/") ? Url + "iwcconnection" : Url + "/iwcconnection";
                c.Connection.RecieverURL = Url;
                IHttpServer server = m_registry.RequestModuleInterface <ISimulationBase>().GetHttpServer(0);
                c.Connection.SenderURL = server.HostName + ":" + server.Port + "/iwcconnection";
                c.Connection.UserName  = c.Connection.SenderURL;

                //Add the certificate now
                CertificateVerification.AddCertificate(c);

                TryAddConnection(c);
                IGridService gridService = m_registry.RequestModuleInterface <IGridService>();
                if (gridService != null)
                {
                    List <GridRegion> regions = gridService.GetRegionsByName(UUID.Zero, regionName, 1);
                    if (regions != null && regions.Count > 0)
                    {
                        return(regions[0]);
                    }
                }
            }
            return(null);
        }
        /// <summary>
        /// Query the given host (by connection) and verify that we can connect to it.
        /// </summary>
        /// <param name="connector">The host to connect to</param>
        /// <returns>The connection that has been recieved from the host</returns>
        public IWCConnection QueryRemoteHost(IWCConnection connection)
        {
            OSDMap request = connection.ToOSD(false);

            request["Method"] = "Query";
            OSDMap reply = WebUtils.PostToService(connection.RecieverURL, request);

            if (reply["Success"].AsBoolean())
            {
                if (reply["_Result"].Type != OSDType.Map)
                {
                    m_log.Warn("[IWC]: Unable to connect successfully to " + connection.RecieverURL + ", connection did not have all the required data.");
                    return(null);
                }
                OSDMap innerReply = (OSDMap)reply["_Result"];
                if (innerReply["Result"].AsString() == "Successful")
                {
                    IWCConnection c = new IWCConnection();
                    c.FromOSD(innerReply);
                    IWCCertificate cert = new IWCCertificate();
                    cert.Connection             = new IWCConnection();
                    cert.Active                 = true;
                    cert.Connection.SenderURL   = c.SenderURL;
                    cert.Connection.RecieverURL = c.RecieverURL;
                    cert.Connection.UserName    = c.UserName;
                    cert.Connection.Password    = c.Password;
                    cert.Connection.SecureUrls  = c.SecureUrls;
                    m_log.Error("[IWC]: Connected successfully to " + connection.RecieverURL);
                    return(c);
                }
                m_log.Warn("[IWC]: Unable to connect successfully to " + connection.RecieverURL + ", " + innerReply["Result"]);
            }
            else
            {
                m_log.Warn("[IWC]: Unable to connect successfully to " + connection.RecieverURL);
            }
            return(null);
        }
        private void AddConnection(IWCCertificate c)
        {
            IWCCertificate old = null;

            foreach (IWCCertificate cert in Connections)
            {
                if (cert.Connection.UserName == c.Connection.UserName)
                {
                    old = cert;
                }
            }
            if (old != null)
            {
                Connections.Remove(old);
            }

            Connections.Add(c);
            IGenericsConnector genericsConnector = DataManager.DataManager.RequestPlugin <IGenericsConnector> ();

            if (genericsConnector != null)
            {
                genericsConnector.AddGeneric(UUID.Zero, "InterWorldConnections", c.Connection.RecieverURL, c.ToOSD());
            }
        }
 /// <summary>
 /// Query the given host (by connection) and verify that we can connect to it.
 /// </summary>
 /// <param name="connector">The host to connect to</param>
 /// <returns>The connection that has been recieved from the host</returns>
 public IWCCertificate QueryRemoteHost(Connection connection)
 {
     OSDMap request = connection.Certificate.ToOSD(false);
     request["Method"] = "Query";
     OSDMap reply = WebUtils.PostToService(connection.URL, request);
     if (reply["Success"].AsBoolean())
     {
         if (reply["_Result"].Type != OSDType.Map)
         {
             m_log.Warn("[IWC]: Unable to connect successfully to " + connection.URL + ", connection did not have all the required data.");
             return null;
         }
         OSDMap innerReply = (OSDMap)reply["_Result"];
         if (innerReply["Result"].AsString() == "Successful")
         {
             IWCCertificate c = new IWCCertificate();
             c.FromOSD(innerReply);
             m_log.Error("[IWC]: Connected successfully to " + connection.URL);
             return c;
         }
         m_log.Warn("[IWC]: Unable to connect successfully to " + connection.URL + ", " + innerReply["Result"]);
     }
     else
     {
         m_log.Warn("[IWC]: Unable to connect successfully to " + connection.URL);
     }
     return null;
 }
        /// <summary>
        /// Add a certificate for the given connection
        /// </summary>
        /// <param name="module"></param>
        /// <param name="cmds"></param>
        private void AddIWCConnection(string module, string[] cmds)
        {
            string Url = MainConsole.Instance.CmdPrompt("Url to the connection");
            string timeUntilExpires = MainConsole.Instance.CmdPrompt("Time until the connection expires (ends, in days)");
            string trustLevel = MainConsole.Instance.CmdPrompt("Trust level of this connection");
            int timeInDays = int.Parse(timeUntilExpires);

            Connection con = new Connection();
            
            //Build the certificate
            IWCCertificate cert = new IWCCertificate();
            cert.SessionHash = UUID.Random().ToString();
            cert.ValidUntil = DateTime.Now.AddDays(timeInDays);

            //Add the certificate now
            CertificateVerification.AddCertificate(cert);

            con.Certificate = cert;
            con.TrustLevel = (TrustLevel)Enum.Parse(typeof(TrustLevel), trustLevel);
            //Be user friendly, add the http:// if needed as well as the final /
            Url = (Url.StartsWith("http://") || Url.StartsWith("https://")) ? Url : "http://" + Url;
            Url = Url.EndsWith("/") ? Url + "iwcconnection" : Url + "/iwcconnection";
            con.URL = Url;

            cert = OutgoingPublicComms.QueryRemoteHost(con);
            if (cert != null)
            {
                con.Certificate = cert;
                IConfigurationService configService = m_registry.RequestModuleInterface<IConfigurationService>();
                //Give the Urls to the config service
                configService.AddNewUrls(cert.SessionHash, cert.SecureUrls);
                Connections.Add(con);
                m_log.Warn("Added connection to " + Url + ".");
            }
            else
            {
                m_log.Warn("Could not add connection.");
            }
        }
 /// <summary>
 /// Add (or update) a certificate
 /// </summary>
 /// <param name="cert"></param>
 public static void AddCertificate(IWCCertificate cert)
 {
     m_certificates[cert.Connection.UserName] = cert;
 }
 public void TryAddConnection(IWCCertificate c)
 {
     c = BuildSecureUrlsForConnection(c);
     IWCConnection cert = OutgoingPublicComms.QueryRemoteHost (c.Connection);
     if (cert != null)
     {
         c.Connection = cert;
         ParseIWCCertificateForURLs (c);
     }
     else
         c.Active = false;
 }
        /// <summary>
        /// This is the initial request to join this host
        /// We need to verify passwords and add sessionHashes to our database
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private byte[] Query(OSDMap requestMap)
        {
            IWCConnection incomingConnectionRequest = new IWCConnection();

            //Pull the connection info out of the request
            incomingConnectionRequest.FromOSD(requestMap);

            IWCCertificate incomingCertificate = null;

            //Lets make sure that they are allowed to connect to us
            if (!CertificateVerification.VerifyConnection(incomingConnectionRequest))
            {
                //Make sure the other host is not trying to spoof one of our certificates
                if (CertificateVerification.GetCertificateByUserName(incomingConnectionRequest.UserName) != null)
                {
                    //SPOOF! XXXXXX
                    return(FailureResult());
                }
                //This is an untrusted connection otherwise
                if (!IWC.m_allowUntrustedConnections)
                {
                    return(FailureResult()); //We don't allow them
                }
            }
            else
            {
                incomingCertificate = CertificateVerification.GetCertificateByUserName(incomingConnectionRequest.UserName);
            }

            if (incomingCertificate == null)
            {
                incomingCertificate            = new IWCCertificate();
                incomingCertificate.Connection = new IWCConnection(incomingConnectionRequest);
                //Got to flip the URLs so that we send to the right place later
                incomingCertificate.Connection.RecieverURL = incomingCertificate.Connection.SenderURL;
                //And add our SenderURL to the connection
                IHttpServer server = IWC.Registry.RequestModuleInterface <ISimulationBase> ().GetHttpServer(0);
                incomingCertificate.Connection.SenderURL = server.HostName + ":" + server.Port + "/iwcconnection";

                //If we don't know it, its the default trust level
                incomingCertificate.ThreatLevel = IWC.m_untrustedConnectionsDefaultTrust;
                incomingCertificate.Active      = true;
                incomingCertificate.ValidUntil  = DateTime.Now.AddDays(1);
            }

            //Update them in the database so that they can connect again later
            CertificateVerification.AddCertificate(incomingCertificate);

            //Read the URLs they sent to us
            IWC.ParseIWCCertificateForURLs(incomingCertificate);

            //Now send them back some URLs as well
            IWC.BuildSecureUrlsForConnection(incomingCertificate);

            //Fix the SecureURLs
            incomingConnectionRequest.SecureUrls = incomingCertificate.Connection.SecureUrls;
            OSDMap result = incomingConnectionRequest.ToOSD(false);

            result["Result"] = "Successful";

            m_log.WarnFormat("[IWC]: {0} successfully connected to us.", incomingConnectionRequest.SenderURL);

            return(Return(result));
        }
 /// <summary>
 /// Query the given host (by connection) and verify that we can connect to it.
 /// </summary>
 /// <param name="connector">The host to connect to</param>
 /// <returns>The connection that has been recieved from the host</returns>
 public IWCConnection QueryRemoteHost (IWCConnection connection)
 {
     OSDMap request = connection.ToOSD(false);
     request["Method"] = "Query";
     OSDMap reply = WebUtils.PostToService (connection.RecieverURL, request, true, true);
     if (reply["Success"].AsBoolean())
     {
         if (reply["_Result"].Type != OSDType.Map)
         {
             m_log.Warn ("[IWC]: Unable to connect successfully to " + connection.RecieverURL + ", connection did not have all the required data.");
             return null;
         }
         OSDMap innerReply = (OSDMap)reply["_Result"];
         if (innerReply["Result"].AsString() == "Successful")
         {
             IWCConnection c = new IWCConnection ();
             c.FromOSD(innerReply);
             IWCCertificate cert = new IWCCertificate ();
             cert.Connection = new IWCConnection ();
             cert.Active = true;
             cert.Connection.SenderURL = c.SenderURL;
             cert.Connection.RecieverURL = c.RecieverURL;
             cert.Connection.UserName = c.UserName;
             cert.Connection.Password = c.Password;
             cert.Connection.SecureUrls = c.SecureUrls;
             m_log.Error ("[IWC]: Connected successfully to " + connection.RecieverURL);
             return c;
         }
         m_log.Warn ("[IWC]: Unable to connect successfully to " + connection.RecieverURL + ", " + innerReply["Result"]);
     }
     else
     {
         m_log.Warn ("[IWC]: Unable to connect successfully to " + connection.RecieverURL);
     }
     return null;
 }
 /// <summary>
 /// Create secure Urls that only us and the sim that called us know of
 /// This Urls is used to add/remove agents and other information from the other sim
 /// </summary>
 /// <param name="c"></param>
 /// <returns></returns>
 private IWCCertificate BuildSecureUrlsForConnection(IWCCertificate c)
 {
     IConfigurationService service = IWC.Registry.RequestModuleInterface<IConfigurationService>();
     //Give the basic Urls that we have
     c.SecureUrls = service.GetValuesFor("default");
     c.SecureUrls["TeleportAgent"] = "";
     return c;
 }
 public override IDataTransferable Duplicate()
 {
     IWCCertificate m = new IWCCertificate();
     m.FromOSD(ToOSD());
     return m;
 }
        /// <summary>
        /// Create secure Urls that only us and the sim that called us know of
        /// This Urls is used to add/remove agents and other information from the other sim
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public IWCCertificate BuildSecureUrlsForConnection(IWCCertificate c)
        {
            IGridRegistrationService gridRegistration = Registry.RequestModuleInterface<IGridRegistrationService>();
            if (gridRegistration != null)
            {
                IGridService gridService = Registry.RequestModuleInterface<IGridService>();
                if (gridService != null)
                {
                    GridRegion r = gridService.GetRegionByName(UUID.Zero, c.Connection.UserName + "_Link");
                    if (r == null)
                    {
                        uint rX = (uint)Util.RandomClass.Next(10000, 1000000);
                        uint rY = (uint)Util.RandomClass.Next(10000, 1000000);
                        ulong regionhandle = Utils.UIntsToLong(rX, rY);

                        r = new GridRegion();
                        r.RegionID = UUID.Random();
                        r.RegionHandle = regionhandle;
                        IHttpServer server = m_registry.RequestModuleInterface<ISimulationBase>().GetHttpServer(0);
                        r.ExternalHostName = server.HostName;
                        if (r.ExternalHostName.StartsWith("http://"))
                            r.ExternalHostName = r.ExternalHostName.Remove(0, 7);
                        else if (r.ExternalHostName.StartsWith("https://"))
                            r.ExternalHostName = r.ExternalHostName.Remove(0, 8);
                        r.InternalEndPoint = new IPEndPoint(IPAddress.Any, (int)server.Port);
                        r.Flags = (int)Aurora.Framework.RegionFlags.Foreign;
                        r.RegionName = c.Connection.UserName + "_Link";
                        r.RegionType = "Link";

                        UUID SessionID;
                        gridService.RegisterRegion(r, UUID.Zero, out SessionID);
                    }
                    //Give the basic Urls that we have
                    c.Connection.SecureUrls = gridRegistration.GetUrlForRegisteringClient(c.Connection.UserName, r.RegionHandle);
                }
            }
            return c;
        }
 private void RemoveConnection(IWCCertificate c)
 {
     if (Connections.Contains(c))
     {
         Connections.Remove(c);
         IGenericsConnector genericsConnector = DataManager.DataManager.RequestPlugin<IGenericsConnector>();
         if (genericsConnector != null)
             genericsConnector.RemoveGeneric (UUID.Zero, "InterWorldConnections", c.Connection.RecieverURL);
     }
 }
 /// <summary>
 /// Check to make sure this IWC Certificate is valid
 /// </summary>
 /// <param name="cert"></param>
 /// <returns></returns>
 public static bool VerifyCertificate(IWCCertificate cert)
 {
     //Make sure we have the certificate
     if (m_certificates.ContainsKey(cert.SessionHash))
     {
         //Now verify that it hasn't expired yet
         if (DateTime.Now < m_certificates[cert.SessionHash].ValidUntil)
         {
             return true;
         }
     }
     return false;
 }
 /// <summary>
 /// Add (or update) a certificate
 /// </summary>
 /// <param name="cert"></param>
 public static void AddCertificate(IWCCertificate cert)
 {
     m_certificates[cert.Connection.UserName] = cert;
 }
        /// <summary>
        /// Add a certificate for the given connection
        /// </summary>
        /// <param name="module"></param>
        /// <param name="cmds"></param>
        private void AddIWCConnection(string module, string[] cmds)
        {
            string Url = MainConsole.Instance.CmdPrompt("Url to the connection");
            //Be user friendly, add the http:// if needed as well as the final /
            Url = (Url.StartsWith("http://") || Url.StartsWith("https://")) ? Url : "http://" + Url;
            Url = Url.EndsWith("/") ? Url + "iwcconnection" : Url + "/iwcconnection";

            IWCCertificate con = FindConnectionByURL(Url);
            if(con != null)
            {
                if (con.Active)
                {
                    m_log.Warn("A connection to this server already exists.");
                }
                else
                {
                    string activate = MainConsole.Instance.CmdPrompt("A connection to this server already exists, do you wish to active it?");
                    if (activate == "yes" || activate == "true")
                    {
                        TryAddConnection(con);
                    }
                }
                return;
            }
            con = new IWCCertificate();
            con.Connection = new IWCConnection ();
            con.Connection.RecieverURL = Url;
            IHttpServer server = m_registry.RequestModuleInterface<ISimulationBase>().GetHttpServer(0);
            con.Connection.SenderURL = server.HostName + ":" + server.Port + "/iwcconnection";
            string timeUntilExpires = MainConsole.Instance.CmdPrompt("Time until the connection expires (ends, in days)");
            string trustLevel = MainConsole.Instance.CmdPrompt("Trust level of this connection");
            int timeInDays = int.Parse(timeUntilExpires);
            string UserName = MainConsole.Instance.CmdPrompt("User Name for this connection (can be blank)");
            string Password = MainConsole.Instance.CmdPrompt("Password for this connection");
            
            //Build the certificate
            if (UserName == "")
                UserName = UUID.Random().ToString();
            con.Connection.UserName = UserName;
            con.Connection.Password = Password;
            con.ValidUntil = DateTime.Now.AddDays(timeInDays);

            //Add the certificate now
            CertificateVerification.AddCertificate(con);
            con.ThreatLevel = (ThreatLevel)Enum.Parse(typeof(ThreatLevel), trustLevel);

            TryAddConnection(con);
        }
        public GridRegion GetRegionForGrid(string regionName, string Url)
        {
            IWCCertificate c = FindConnectionByURL(Url);
            if (c != null)
            {
                //If we are already connected, the grid services are together, so we already know of the region if it exists, therefore, it does not exist
                return null;
            }
            else
            {
                c = new IWCCertificate();
                c.Connection = new IWCConnection ();
                //Build the certificate
                c.ValidUntil = DateTime.Now.AddDays(1); //One day for now...

                c.ThreatLevel = m_untrustedConnectionsDefaultTrust; //Least amount of our trust for them
                //Be user friendly, add the http:// if needed as well as the final /
                Url = (Url.StartsWith("http://") || Url.StartsWith("https://")) ? Url : "http://" + Url;
                Url = Url.EndsWith("/") ? Url + "iwcconnection" : Url + "/iwcconnection";
                c.Connection.RecieverURL = Url;
                IHttpServer server = m_registry.RequestModuleInterface<ISimulationBase>().GetHttpServer(0);
                c.Connection.SenderURL = server.HostName + ":" + server.Port + "/iwcconnection";
                c.Connection.UserName = c.Connection.SenderURL;

                //Add the certificate now
                CertificateVerification.AddCertificate(c);

                TryAddConnection(c);
                IGridService gridService = m_registry.RequestModuleInterface<IGridService>();
                if (gridService != null)
                {
                    List<GridRegion> regions = gridService.GetRegionsByName(UUID.Zero, regionName, 1);
                    if (regions != null && regions.Count > 0)
                        return regions[0];
                }
            }
            return null;
        }
        /// <summary>
        /// This is the initial request to join this host
        /// We need to verify passwords and add sessionHashes to our database
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private byte[] Query(OSDMap request)
        {
            IWCCertificate Certificate = new IWCCertificate();
            //Pull the connection info out of the request
            Certificate.FromOSD(request);

            //Lets make sure that they are allowed to connect to us
            if (!CertificateVerification.VerifyCertificate(Certificate))
            {
                //Make sure the other host is not trying to spoof one of our certificates
                if (CertificateVerification.GetCertificateBySessionHash(Certificate.SessionHash) != null)
                {
                    //SPOOF! XXXXXX
                    return FailureResult();
                }
                //This is an untrusted connection otherwise
                if (!IWC.m_allowUntrustedConnections)
                    return FailureResult(); //We don't allow them

                //Give them the default untrusted connection level
                Certificate.TrustLevel = IWC.m_untrustedConnectionsDefaultTrust;
            }

            //Update them in the database so that they can connect again later
            CertificateVerification.AddCertificate(Certificate);

            BuildSecureUrlsForConnection(Certificate);

            OSDMap result = Certificate.ToOSD(false);
            result["Result"] = "Successful";

            return Return(result);
        }
        /// <summary>
        /// This is a request to remove the remote host from our list of current connections.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private byte[] Delete(OSDMap request)
        {
            IWCCertificate Certificate = new IWCCertificate();
            //Pull the connection info out of the request
            Certificate.FromOSD(request);

            //Make sure that they are verified to connect
            if (!CertificateVerification.VerifyCertificate(Certificate))
                return FailureResult();

            //Remove them from our list of connections
            CertificateVerification.RemoveCertificate(Certificate);

            return SuccessfulResult();
        }
        /// <summary>
        /// This is the initial request to join this host
        /// We need to verify passwords and add sessionHashes to our database
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private byte[] Query(OSDMap requestMap)
        {
            IWCConnection incomingConnectionRequest = new IWCConnection ();
            //Pull the connection info out of the request
            incomingConnectionRequest.FromOSD(requestMap);

            IWCCertificate incomingCertificate = null;

            //Lets make sure that they are allowed to connect to us
            if (!CertificateVerification.VerifyConnection (incomingConnectionRequest))
            {
                //Make sure the other host is not trying to spoof one of our certificates
                if (CertificateVerification.GetCertificateByUserName (incomingConnectionRequest.UserName) != null)
                {
                    //SPOOF! XXXXXX
                    return FailureResult ();
                }
                //This is an untrusted connection otherwise
                if (!IWC.m_allowUntrustedConnections)
                    return FailureResult (); //We don't allow them
            }
            else
                incomingCertificate = CertificateVerification.GetCertificateByUserName (incomingConnectionRequest.UserName);

            if (incomingCertificate == null)
            {
                incomingCertificate = new IWCCertificate ();
                incomingCertificate.Connection = new IWCConnection (incomingConnectionRequest);
                //Got to flip the URLs so that we send to the right place later
                incomingCertificate.Connection.RecieverURL = incomingCertificate.Connection.SenderURL;
                //And add our SenderURL to the connection
                IHttpServer server = IWC.Registry.RequestModuleInterface<ISimulationBase> ().GetHttpServer (0);
                incomingCertificate.Connection.SenderURL = server.HostName + ":" + server.Port + "/iwcconnection";

                //If we don't know it, its the default trust level
                incomingCertificate.ThreatLevel = IWC.m_untrustedConnectionsDefaultTrust;
                incomingCertificate.Active = true;
                incomingCertificate.ValidUntil = DateTime.Now.AddDays (1);
            }

            //Update them in the database so that they can connect again later
            CertificateVerification.AddCertificate (incomingCertificate);

            //Read the URLs they sent to us
            IWC.ParseIWCCertificateForURLs (incomingCertificate);

            //Now send them back some URLs as well
            IWC.BuildSecureUrlsForConnection (incomingCertificate);

            //Fix the SecureURLs
            incomingConnectionRequest.SecureUrls = incomingCertificate.Connection.SecureUrls;
            OSDMap result = incomingConnectionRequest.ToOSD(false);
            result["Result"] = "Successful";

            m_log.WarnFormat("[IWC]: {0} successfully connected to us.", incomingConnectionRequest.SenderURL);

            return Return(result);
        }
 public override void FromOSD(OSDMap map)
 {
     TrustLevel = (TrustLevel)map["TrustLevel"].AsInteger();
     Certificate = new IWCCertificate();
     Certificate.FromOSD((OSDMap)OSDParser.DeserializeJson(map["Certificate"].AsString()));
     URL = map["URL"].AsString();
 }
 public void ParseIWCCertificateForURLs(IWCCertificate c)
 {
     IConfigurationService configService = m_registry.RequestModuleInterface<IConfigurationService>();
     //Give the Urls to the config service
     configService.AddNewUrls (c.Connection.UserName, c.Connection.SecureUrls);
     AddConnection(c);
     c.Active = true;
 }
 /// <summary>
 /// Add (or update) a certificate
 /// </summary>
 /// <param name="cert"></param>
 public static void AddCertificate(IWCCertificate cert)
 {
     m_certificates[cert.SessionHash] = cert;
 }
 public void DeleteRemoteHost(IWCCertificate connection)
 {
     OSDMap request = connection.ToOSD(false);
     request["Method"] = "Delete";
     OSDMap reply = WebUtils.PostToService (connection.Connection.RecieverURL, request, true, false);
     if (!reply["Success"].AsBoolean())
     {
         m_log.Warn ("[IWC]: Failed to delete remote host @ " + connection.Connection.RecieverURL);
     }
 }
 /// <summary>
 /// Remove a certificate
 /// </summary>
 /// <param name="cert"></param>
 public static void RemoveCertificate(IWCCertificate cert)
 {
     m_certificates.Remove(cert.SessionHash);
 }
        private void AddConnection(IWCCertificate c)
        {
            IWCCertificate old = null;
            foreach (IWCCertificate cert in Connections)
            {
                if (cert.Connection.UserName == c.Connection.UserName)
                    old = cert;
            }
            if (old != null)
                Connections.Remove (old);

            Connections.Add (c);
            IGenericsConnector genericsConnector = DataManager.DataManager.RequestPlugin<IGenericsConnector> ();
            if (genericsConnector != null)
                genericsConnector.AddGeneric (UUID.Zero, "InterWorldConnections", c.Connection.RecieverURL, c.ToOSD ());
        }