Exemplo n.º 1
0
        private void MakeHttpRequest(string url, UUID requestID)
        {
            ServicePointManagerTimeoutSupport.ResetHosts();
            WebRequest request = HttpWebRequest.Create(url);

            if (!string.IsNullOrEmpty(m_proxyurl))
            {
                if (!string.IsNullOrEmpty(m_proxyexcepts))
                {
                    string[] elist = m_proxyexcepts.Split(';');
                    request.Proxy = new WebProxy(m_proxyurl, true, elist);
                }
                else
                {
                    request.Proxy = new WebProxy(m_proxyurl, true);
                }
            }

            RequestState state = new RequestState((HttpWebRequest)request, requestID);

            // IAsyncResult result = request.BeginGetResponse(new AsyncCallback(HttpRequestReturn), state);
            request.BeginGetResponse(new AsyncCallback(HttpRequestReturn), state);

            TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));

            state.TimeOfRequest = (int)t.TotalSeconds;
        }
Exemplo n.º 2
0
        public Hashtable ForwardProxyRequest(Hashtable request)
        {
            m_log.Debug("[PROXYING]: -------------------------------proxying request");
            Hashtable response = new Hashtable();

            response["content_type"]        = "text/xml";
            response["str_response_string"] = "";
            response["int_response_code"]   = 200;

            string forwardaddress = "https://www.bhr.vivox.com/api2/";
            string body           = (string)request["body"];
            string method         = (string)request["http-method"];
            string contenttype    = (string)request["content-type"];
            string uri            = (string)request["uri"];

            uri             = uri.Replace("/api/", "");
            forwardaddress += uri;


            string fwdresponsestr         = "";
            int    fwdresponsecode        = 200;
            string fwdresponsecontenttype = "text/xml";

            ServicePointManagerTimeoutSupport.ResetHosts();
            HttpWebRequest forwardreq = (HttpWebRequest)WebRequest.Create(forwardaddress);

            forwardreq.Method      = method;
            forwardreq.ContentType = contenttype;
            forwardreq.KeepAlive   = false;

            if (method == "POST")
            {
                byte[] contentreq = Util.UTF8.GetBytes(body);
                forwardreq.ContentLength = contentreq.Length;
                Stream reqStream = forwardreq.GetRequestStream();
                reqStream.Write(contentreq, 0, contentreq.Length);
                reqStream.Close();
            }

            using (HttpWebResponse fwdrsp = (HttpWebResponse)forwardreq.GetResponse())
            {
                Encoding encoding = Util.UTF8;

                using (Stream s = fwdrsp.GetResponseStream())
                {
                    using (StreamReader fwdresponsestream = new StreamReader(s))
                    {
                        fwdresponsestr         = fwdresponsestream.ReadToEnd();
                        fwdresponsecontenttype = fwdrsp.ContentType;
                        fwdresponsecode        = (int)fwdrsp.StatusCode;
                    }
                }
            }

            response["content_type"]        = fwdresponsecontenttype;
            response["str_response_string"] = fwdresponsestr;
            response["int_response_code"]   = fwdresponsecode;

            return(response);
        }
Exemplo n.º 3
0
        public static void BeginPostObject <TRequest>(string verb, string requestUrl, TRequest obj)
        {
            Type type = typeof(TRequest);

            ServicePointManagerTimeoutSupport.ResetHosts();
            WebRequest request = WebRequest.Create(requestUrl);

            request.Method      = verb;
            request.ContentType = "text/xml";

            MemoryStream buffer = new MemoryStream();

            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Encoding = Encoding.UTF8;

            using (XmlWriter writer = XmlWriter.Create(buffer, settings))
            {
                XmlSerializer serializer = new XmlSerializer(type);
                serializer.Serialize(writer, obj);
                writer.Flush();
            }

            int length = (int)buffer.Length;

            request.ContentLength = length;

            Stream requestStream = request.GetRequestStream();

            requestStream.Write(buffer.ToArray(), 0, length);
            // IAsyncResult result = request.BeginGetResponse(AsyncCallback, request);
            request.BeginGetResponse(AsyncCallback, request);
        }
Exemplo n.º 4
0
        public static Stream URIFetch(Uri uri)
        {
            ServicePointManagerTimeoutSupport.ResetHosts();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            // request.Credentials = credentials;

            request.ContentLength = 0;
            request.KeepAlive     = false;

            WebResponse response = request.GetResponse();
            Stream      file     = response.GetResponseStream();

            // justincc: gonna ignore the content type for now and just try anything
            //if (response.ContentType != "application/x-oar")
            //    throw new Exception(String.Format("{0} does not identify an OAR file", uri.ToString()));

            if (response.ContentLength == 0)
            {
                throw new Exception(String.Format("{0} returned an empty file", uri.ToString()));
            }

            // return new BufferedStream(file, (int) response.ContentLength);
            return(new BufferedStream(file, 1000000));
        }
Exemplo n.º 5
0
        public virtual string Helo()
        {
            if (String.IsNullOrEmpty(m_ServerURI))
            {
                m_log.WarnFormat("[HELO SERVICE]: Unable to invoke HELO due to malformed URL");
                return(String.Empty);
            }

            try
            {
                ServicePointManagerTimeoutSupport.ResetHosts();
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(m_ServerURI);
                // Eventually we need to switch to HEAD
                /* req.Method = "HEAD"; */

                using (WebResponse response = req.GetResponse())
                {
                    if (response.Headers.Get("X-Handlers-Provided") == null) // just in case this ever returns a null
                    {
                        return(string.Empty);
                    }
                    return(response.Headers.Get("X-Handlers-Provided"));
                }
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[HELO SERVICE]: Unable to perform HELO request to {0}: {1}", m_ServerURI, e.Message);
            }

            // fail
            return(string.Empty);
        }
Exemplo n.º 6
0
        protected void UpdateBroker(Scene scene)
        {
            if (String.IsNullOrEmpty(m_brokerURI))
            {
                return;
            }

            string uri = String.Format(m_brokerURI, scene.RegionInfo.RegionName, scene.RegionInfo.RegionID);

            // create XML sniplet
            StringBuilder list = new StringBuilder();

            list.Append(String.Format("<avatars count=\"{0}\" region_name=\"{1}\" region_uuid=\"{2}\" timestamp=\"{3}\">\n",
                                      scene.GetRootAgentCount(), scene.RegionInfo.RegionName,
                                      scene.RegionInfo.RegionID,
                                      DateTime.UtcNow.ToString("s")));

            scene.ForEachRootScenePresence(delegate(ScenePresence sp)
            {
                list.Append(String.Format("    <avatar name=\"{0}\" uuid=\"{1}\" />\n", sp.Name, sp.UUID));
            });

            list.Append("</avatars>");
            string payload = list.ToString();

            // post via REST to broker
            ServicePointManagerTimeoutSupport.ResetHosts();
            HttpWebRequest updatePost = WebRequest.Create(uri) as HttpWebRequest;

            updatePost.Method        = "POST";
            updatePost.ContentType   = "text/xml";
            updatePost.ContentLength = payload.Length;
            updatePost.UserAgent     = "OpenSim.Concierge";


            BrokerState bs = new BrokerState(uri, payload, updatePost);

            bs.Timer = new Timer(delegate(object state)
            {
                BrokerState b = state as BrokerState;
                b.Poster.Abort();
                b.Timer.Dispose();
                m_log.Debug("[Concierge]: async broker POST abort due to timeout");
            }, bs, m_brokerUpdateTimeout * 1000, Timeout.Infinite);

            try
            {
                updatePost.BeginGetRequestStream(UpdateBrokerSend, bs);
                m_log.DebugFormat("[Concierge] async broker POST to {0} started", uri);
            }
            catch (WebException we)
            {
                m_log.ErrorFormat("[Concierge] async broker POST to {0} failed: {1}", uri, we.Status);
            }
        }
Exemplo n.º 7
0
        public static TResponse BeginPostObject(string verb, string requestUrl, TRequest obj, string sid, string aid)
        {
            RestSessionObject <TRequest> sobj = new RestSessionObject <TRequest>();

            sobj.SessionID = sid;
            sobj.AvatarID  = aid;
            sobj.Body      = obj;

            Type type = typeof(RestSessionObject <TRequest>);

            ServicePointManagerTimeoutSupport.ResetHosts();
            WebRequest request = WebRequest.Create(requestUrl);

            request.Method      = verb;
            request.ContentType = "text/xml";
            request.Timeout     = 20000;

            MemoryStream buffer = new MemoryStream();

            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Encoding = Encoding.UTF8;

            using (XmlWriter writer = XmlWriter.Create(buffer, settings))
            {
                XmlSerializer serializer = new XmlSerializer(type);
                serializer.Serialize(writer, sobj);
                writer.Flush();
            }

            int length = (int)buffer.Length;

            request.ContentLength = length;

            Stream requestStream = request.GetRequestStream();

            requestStream.Write(buffer.ToArray(), 0, length);
            buffer.Close();
            requestStream.Close();

            TResponse deserial = default(TResponse);

            using (WebResponse resp = request.GetResponse())
            {
                XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));

                using (Stream respStream = resp.GetResponseStream())
                    deserial = (TResponse)deserializer.Deserialize(respStream);
            }

            return(deserial);
        }
        public void RRAlert(string status)
        {
            string request_method = "POST";
            string content_type   = "application/json";
            OSDMap RRAlert        = new OSDMap();

            RRAlert["alert"]       = "region_ready";
            RRAlert["login"]       = status;
            RRAlert["region_name"] = m_scene.RegionInfo.RegionName;
            RRAlert["region_id"]   = m_scene.RegionInfo.RegionID;

            string strBuffer = "";

            byte[] buffer = new byte[1];
            try
            {
                strBuffer = OSDParser.SerializeJsonString(RRAlert);
                Encoding str = Util.UTF8;
                buffer = str.GetBytes(strBuffer);
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[RegionReady]: Exception thrown on alert: {0}", e.Message);
            }

            ServicePointManagerTimeoutSupport.ResetHosts();
            WebRequest request = WebRequest.Create(m_uri);

            request.Method      = request_method;
            request.ContentType = content_type;

            Stream os = null;

            try
            {
                request.ContentLength = buffer.Length;
                os = request.GetRequestStream();
                os.Write(buffer, 0, strBuffer.Length);
            }
            catch (Exception e)
            {
                m_log.WarnFormat("[RegionReady]: Exception thrown sending alert: {0}", e.Message);
            }
            finally
            {
                if (os != null)
                {
                    os.Dispose();
                }
            }
        }
        /// <summary>Send the request to the server.</summary>
        /// <param name="url"><c>String</c> The url of the XML-RPC server.</param>
        /// <returns><c>XmlRpcResponse</c> The response generated.</returns>
        public XmlRpcResponse Send(String url)
        {
            ServicePointManagerTimeoutSupport.ResetHosts();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            if (request == null)
            {
                throw new XmlRpcException(XmlRpcErrorCodes.TRANSPORT_ERROR,
                                          XmlRpcErrorCodes.TRANSPORT_ERROR_MSG + ": Could not create request with " + url);
            }
            request.Method      = "POST";
            request.ContentType = "text/xml";
            request.AllowWriteStreamBuffering = true;
            request.KeepAlive = !_disableKeepAlive;

            using (Stream stream = request.GetRequestStream())
            {
                using (XmlTextWriter xml = new XmlTextWriter(stream, Encoding.ASCII))
                {
                    _serializer.Serialize(xml, this);
                    xml.Flush();
                }
            }

            XmlRpcResponse resp;

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (Stream s = response.GetResponseStream())
                {
                    using (StreamReader input = new StreamReader(s))
                    {
                        string inputXml = input.ReadToEnd();

                        try
                        {
                            resp = (XmlRpcResponse)_deserializer.Deserialize(inputXml);
                        }
                        catch (Exception e)
                        {
                            RequestResponse = inputXml;
                            throw e;
                        }
                    }
                }
            }

            return(resp);
        }
Exemplo n.º 10
0
        public XmlRpcResponse certSend(String url, X509Certificate2 clientCert, Int32 timeout)
        {
            m_log.InfoFormat("[MONEY NSL RPC]: XmlRpcResponse certSend: connect to {0}", url);

            ServicePointManagerTimeoutSupport.ResetHosts();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            if (request == null)
            {
                throw new XmlRpcException(XmlRpcErrorCodes.TRANSPORT_ERROR, XmlRpcErrorCodes.TRANSPORT_ERROR_MSG + ": Could not create request with " + url);
            }

            request.Method      = "POST";
            request.ContentType = "text/xml";
            request.AllowWriteStreamBuffering = true;
            request.Timeout   = timeout;
            request.UserAgent = "NSLXmlRpcRequest";

            if (clientCert != null)
            {
                request.ClientCertificates.Add(clientCert);                                     // 自身の証明書
            }
            Stream        stream = request.GetRequestStream();
            XmlTextWriter xml    = new XmlTextWriter(stream, _encoding);

            _serializer.Serialize(xml, this);
            xml.Flush();
            xml.Close();

            HttpWebResponse response = null;

            //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            try {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception ex) {
                m_log.ErrorFormat("[MONEY NSL RPC]: XmlRpcResponse certSend: GetResponse Error: {0}", ex);
                throw;
            }
            StreamReader input = new StreamReader(response.GetResponseStream());

            string         inputXml = input.ReadToEnd();
            XmlRpcResponse resp     = (XmlRpcResponse)_deserializer.Deserialize(inputXml);

            input.Close();
            response.Close();
            return(resp);
        }
Exemplo n.º 11
0
        public static void MakeRequest(string requestUrl, string data,
                                       ReplyDelegate action)
        {
            ServicePointManagerTimeoutSupport.ResetHosts();
            WebRequest request = WebRequest.Create(requestUrl);

            request.Method = "POST";

            request.ContentType = "application/x-www-form-urlencoded";

            byte[] buffer = Encoding.ASCII.GetBytes(data);
            int    length = (int)buffer.Length;

            request.ContentLength = length;

            request.BeginGetRequestStream(delegate(IAsyncResult res)
            {
                Stream requestStream = request.EndGetRequestStream(res);

                requestStream.Write(buffer, 0, length);

                request.BeginGetResponse(delegate(IAsyncResult ar)
                {
                    string reply = String.Empty;

                    using (WebResponse response = request.EndGetResponse(ar))
                    {
                        try
                        {
                            using (Stream s = response.GetResponseStream())
                                using (StreamReader r = new StreamReader(s))
                                    reply = r.ReadToEnd();
                        }
                        catch (System.InvalidOperationException)
                        {
                        }
                    }

                    action(requestUrl, data, reply);
                }, null);
            }, null);
        }
Exemplo n.º 12
0
        public void BeginPostObject(string verb, string requestUrl, TRequest obj, string sid, string aid)
        {
            RestSessionObject <TRequest> sobj = new RestSessionObject <TRequest>();

            sobj.SessionID = sid;
            sobj.AvatarID  = aid;
            sobj.Body      = obj;

            Type type = typeof(RestSessionObject <TRequest>);

            ServicePointManagerTimeoutSupport.ResetHosts();
            WebRequest request = WebRequest.Create(requestUrl);

            request.Method      = verb;
            request.ContentType = "text/xml";
            request.Timeout     = 10000;

            MemoryStream buffer = new MemoryStream();

            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Encoding = Encoding.UTF8;

            using (XmlWriter writer = XmlWriter.Create(buffer, settings))
            {
                XmlSerializer serializer = new XmlSerializer(type);
                serializer.Serialize(writer, sobj);
                writer.Flush();
            }
            buffer.Close();

            int length = (int)buffer.Length;

            request.ContentLength = length;

            Stream requestStream = request.GetRequestStream();

            requestStream.Write(buffer.ToArray(), 0, length);
            requestStream.Close();
            // IAsyncResult result = request.BeginGetResponse(AsyncCallback, request);
            request.BeginGetResponse(AsyncCallback, request);
        }
Exemplo n.º 13
0
        public Stream Request(Stream src, IServiceAuth auth)
        {
            ServicePointManagerTimeoutSupport.ResetHosts();
            _request               = (HttpWebRequest)WebRequest.Create(buildUri());
            _request.KeepAlive     = false;
            _request.ContentType   = "application/xml";
            _request.Timeout       = 900000;
            _request.Method        = RequestMethod;
            _asyncException        = null;
            _request.ContentLength = src.Length;
            if (auth != null)
            {
                auth.AddAuthorization(_request.Headers);
            }

            src.Seek(0, SeekOrigin.Begin);

            Stream dst = _request.GetRequestStream();

            byte[] buf    = new byte[1024];
            int    length = src.Read(buf, 0, 1024);

            while (length > 0)
            {
                dst.Write(buf, 0, length);
                length = src.Read(buf, 0, 1024);
            }

            _response = (HttpWebResponse)_request.GetResponse();

//            IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);

            // TODO! Implement timeout, without killing the server
            // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
            //ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);

            return(null);
        }
        private Bitmap ImageHttpRequest(string url)
        {
            try
            {
                ServicePointManagerTimeoutSupport.ResetHosts();
                WebRequest request = HttpWebRequest.Create(url);

                using (HttpWebResponse response = (HttpWebResponse)(request).GetResponse())
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        using (Stream s = response.GetResponseStream())
                        {
                            Bitmap image = new Bitmap(s);
                            return(image);
                        }
                    }
                }
            }
            catch { }

            return(null);
        }
Exemplo n.º 15
0
        private Hashtable CallServer(string methodName, Hashtable hash)
        {
            IList paramList = new ArrayList();

            paramList.Add(hash);

            ServicePointManagerTimeoutSupport.ResetHosts();
            XmlRpcRequest request = new XmlRpcRequest(methodName, paramList);

            // Send and get reply
            XmlRpcResponse response = null;

            try
            {
                response = request.Send(m_ServerURL, 10000);
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[USER AGENT CONNECTOR]: {0} call to {1} failed: {2}", methodName, m_ServerURLHost, e.Message);
                throw;
            }

            if (response.IsFault)
            {
                throw new Exception(string.Format("[USER AGENT CONNECTOR]: {0} call to {1} returned an error: {2}", methodName, m_ServerURLHost, response.FaultString));
            }

            hash = (Hashtable)response.Value;

            if (hash == null)
            {
                throw new Exception(string.Format("[USER AGENT CONNECTOR]: {0} call to {1} returned null", methodName, m_ServerURLHost));
            }

            return(hash);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Perform a synchronous request
        /// </summary>
        public Stream Request(IServiceAuth auth)
        {
            ServicePointManagerTimeoutSupport.ResetHosts();
            lock (_lock)
            {
                _request             = (HttpWebRequest)WebRequest.Create(buildUri());
                _request.ContentType = "application/xml";
                _request.Timeout     = 200000;
                _request.Method      = RequestMethod;
                _asyncException      = null;
                if (auth != null)
                {
                    auth.AddAuthorization(_request.Headers);
                }

                if (WebUtil.DebugLevel >= 3)
                {
                    m_log.DebugFormat("[LOGHTTP]: HTTP OUT REST {0} to {1}", _request.Method, _request.RequestUri);
                }

//                IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);
                try
                {
                    _response = (HttpWebResponse)_request.GetResponse();
                }
                catch (WebException e)
                {
                    HttpWebResponse errorResponse = e.Response as HttpWebResponse;
                    if (null != errorResponse && HttpStatusCode.NotFound == errorResponse.StatusCode)
                    {
                        // This is often benign. E.g., requesting a missing asset will return 404.
                        m_log.DebugFormat("[REST CLIENT] Resource not found (404): {0}", _request.Address.ToString());
                    }
                    else
                    {
                        m_log.Error(string.Format("[REST CLIENT] Error fetching resource from server: {0} ", _request.Address.ToString()), e);
                    }

                    return(null);
                }

                Stream src    = _response.GetResponseStream();
                int    length = src.Read(_readbuf, 0, BufferSize);
                while (length > 0)
                {
                    _resource.Write(_readbuf, 0, length);
                    length = src.Read(_readbuf, 0, BufferSize);
                }


                // TODO! Implement timeout, without killing the server
                // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
                //ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);

//                _allDone.WaitOne();
                if (_response != null)
                {
                    _response.Close();
                }
                if (_asyncException != null)
                {
                    throw _asyncException;
                }

                if (_resource != null)
                {
                    _resource.Flush();
                    _resource.Seek(0, SeekOrigin.Begin);
                }

                return(_resource);
            }
        }
Exemplo n.º 17
0
        public RegionInfo[] LoadRegions()
        {
            if (m_configSource == null)
            {
                m_log.Error("[WEBLOADER]: Unable to load configuration source!");
                return(null);
            }
            else
            {
                IConfig startupConfig   = (IConfig)m_configSource.Configs["Startup"];
                string  url             = startupConfig.GetString("regionload_webserver_url", String.Empty).Trim();
                bool    allowRegionless = startupConfig.GetBoolean("allow_regionless", false);

                if (url == String.Empty)
                {
                    m_log.Error("[WEBLOADER]: Unable to load webserver URL - URL was empty.");
                    return(null);
                }
                else
                {
                    RegionInfo[] regionInfos = new RegionInfo[] {};
                    int          regionCount = 0;
                    ServicePointManagerTimeoutSupport.ResetHosts();
                    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                    webRequest.Timeout = 30000; //30 Second Timeout
                    m_log.DebugFormat("[WEBLOADER]: Sending download request to {0}", url);

                    try
                    {
                        string xmlSource = String.Empty;

                        using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
                        {
                            m_log.Debug("[WEBLOADER]: Downloading region information...");

                            using (Stream s = webResponse.GetResponseStream())
                            {
                                using (StreamReader reader = new StreamReader(s))
                                {
                                    string tempStr = reader.ReadLine();
                                    while (tempStr != null)
                                    {
                                        xmlSource = xmlSource + tempStr;
                                        tempStr   = reader.ReadLine();
                                    }
                                }
                            }
                        }

                        m_log.Debug("[WEBLOADER]: Done downloading region information from server. Total Bytes: " +
                                    xmlSource.Length);
                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.LoadXml(xmlSource);
                        if (xmlDoc.FirstChild.Name == "Nini")
                        {
                            regionCount = xmlDoc.FirstChild.ChildNodes.Count;

                            if (regionCount > 0)
                            {
                                regionInfos = new RegionInfo[regionCount];
                                int i;
                                for (i = 0; i < xmlDoc.FirstChild.ChildNodes.Count; i++)
                                {
                                    m_log.Debug(xmlDoc.FirstChild.ChildNodes[i].OuterXml);
                                    regionInfos[i] =
                                        new RegionInfo("REGION CONFIG #" + (i + 1), xmlDoc.FirstChild.ChildNodes[i], false, m_configSource);
                                }
                            }
                        }
                    }
                    catch (WebException ex)
                    {
                        using (HttpWebResponse response = (HttpWebResponse)ex.Response)
                        {
                            if (response.StatusCode == HttpStatusCode.NotFound)
                            {
                                if (!allowRegionless)
                                {
                                    throw ex;
                                }
                            }
                            else
                            {
                                throw ex;
                            }
                        }
                    }

                    if (regionCount > 0 | allowRegionless)
                    {
                        return(regionInfos);
                    }
                    else
                    {
                        m_log.Error("[WEBLOADER]: No region configs were available.");
                        return(null);
                    }
                }
            }
        }
Exemplo n.º 18
0
        public GridRegion GetHyperlinkRegion(GridRegion gatekeeper, UUID regionID, UUID agentID, string agentHomeURI, out string message)
        {
            Hashtable hash = new Hashtable();

            hash["region_uuid"] = regionID.ToString();
            if (agentID != UUID.Zero)
            {
                hash["agent_id"] = agentID.ToString();
                if (agentHomeURI != null)
                {
                    hash["agent_home_uri"] = agentHomeURI;
                }
            }

            IList paramList = new ArrayList();

            paramList.Add(hash);

            ServicePointManagerTimeoutSupport.ResetHosts();
            XmlRpcRequest request = new XmlRpcRequest("get_region", paramList);

            m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: contacting " + gatekeeper.ServerURI);
            XmlRpcResponse response = null;

            try
            {
                response = request.Send(gatekeeper.ServerURI, 10000);
            }
            catch (Exception e)
            {
                message = "Error contacting grid.";
                m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: Exception " + e.Message);
                return(null);
            }

            if (response.IsFault)
            {
                message = "Error contacting grid.";
                m_log.ErrorFormat("[GATEKEEPER SERVICE CONNECTOR]: remote call returned an error: {0}", response.FaultString);
                return(null);
            }

            hash = (Hashtable)response.Value;
            //foreach (Object o in hash)
            //    m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value);
            try
            {
                bool success = false;
                Boolean.TryParse((string)hash["result"], out success);

                if (hash["message"] != null)
                {
                    message = (string)hash["message"];
                }
                else if (success)
                {
                    message = null;
                }
                else
                {
                    message = "The teleport destination could not be found.";   // probably the dest grid is old and doesn't send 'message', but the most common problem is that the region is unavailable
                }
                if (success)
                {
                    GridRegion region = new GridRegion();

                    UUID.TryParse((string)hash["uuid"], out region.RegionID);
                    //m_log.Debug(">> HERE, uuid: " + region.RegionID);
                    int n = 0;
                    if (hash["x"] != null)
                    {
                        Int32.TryParse((string)hash["x"], out n);
                        region.RegionLocX = n;
                        //m_log.Debug(">> HERE, x: " + region.RegionLocX);
                    }
                    if (hash["y"] != null)
                    {
                        Int32.TryParse((string)hash["y"], out n);
                        region.RegionLocY = n;
                        //m_log.Debug(">> HERE, y: " + region.RegionLocY);
                    }
                    if (hash["size_x"] != null)
                    {
                        Int32.TryParse((string)hash["size_x"], out n);
                        region.RegionSizeX = n;
                        //m_log.Debug(">> HERE, x: " + region.RegionLocX);
                    }
                    if (hash["size_y"] != null)
                    {
                        Int32.TryParse((string)hash["size_y"], out n);
                        region.RegionSizeY = n;
                        //m_log.Debug(">> HERE, y: " + region.RegionLocY);
                    }
                    if (hash["region_name"] != null)
                    {
                        region.RegionName = (string)hash["region_name"];
                        //m_log.Debug(">> HERE, region_name: " + region.RegionName);
                    }
                    if (hash["hostname"] != null)
                    {
                        region.ExternalHostName = (string)hash["hostname"];
                        //m_log.Debug(">> HERE, hostname: " + region.ExternalHostName);
                    }
                    if (hash["http_port"] != null)
                    {
                        uint p = 0;
                        UInt32.TryParse((string)hash["http_port"], out p);
                        region.HttpPort = p;
                        //m_log.Debug(">> HERE, http_port: " + region.HttpPort);
                    }
                    if (hash["internal_port"] != null)
                    {
                        int p = 0;
                        Int32.TryParse((string)hash["internal_port"], out p);
                        region.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), p);
                        //m_log.Debug(">> HERE, internal_port: " + region.InternalEndPoint);
                    }

                    if (hash["server_uri"] != null)
                    {
                        region.ServerURI = (string)hash["server_uri"];
                        //m_log.Debug(">> HERE, server_uri: " + region.ServerURI);
                    }

                    // Successful return
                    return(region);
                }
            }
            catch (Exception e)
            {
                message = "Error parsing response from grid.";
                m_log.Error("[GATEKEEPER SERVICE CONNECTOR]: Got exception while parsing hyperlink response " + e.StackTrace);
                return(null);
            }

            return(null);
        }
Exemplo n.º 19
0
        public bool LinkRegion(GridRegion info, out UUID regionID, out ulong realHandle, out string externalName, out string imageURL, out string reason)
        {
            regionID     = UUID.Zero;
            imageURL     = string.Empty;
            realHandle   = 0;
            externalName = string.Empty;
            reason       = string.Empty;

            Hashtable hash = new Hashtable();

            hash["region_name"] = info.RegionName;

            IList paramList = new ArrayList();

            paramList.Add(hash);

            ServicePointManagerTimeoutSupport.ResetHosts();
            XmlRpcRequest request = new XmlRpcRequest("link_region", paramList);

            m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: Linking to " + info.ServerURI);
            XmlRpcResponse response = null;

            try
            {
                response = request.Send(info.ServerURI, 10000);
            }
            catch (Exception e)
            {
                m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: Exception " + e.Message);
                reason = "Error contacting remote server";
                return(false);
            }

            if (response.IsFault)
            {
                reason = response.FaultString;
                m_log.ErrorFormat("[GATEKEEPER SERVICE CONNECTOR]: remote call returned an error: {0}", response.FaultString);
                return(false);
            }

            hash = (Hashtable)response.Value;
            //foreach (Object o in hash)
            //    m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value);
            try
            {
                bool success = false;
                Boolean.TryParse((string)hash["result"], out success);
                if (success)
                {
                    UUID.TryParse((string)hash["uuid"], out regionID);
                    //m_log.Debug(">> HERE, uuid: " + regionID);
                    if ((string)hash["handle"] != null)
                    {
                        realHandle = Convert.ToUInt64((string)hash["handle"]);
                        //m_log.Debug(">> HERE, realHandle: " + realHandle);
                    }
                    if (hash["region_image"] != null)
                    {
                        imageURL = (string)hash["region_image"];
                        //m_log.Debug(">> HERE, imageURL: " + imageURL);
                    }
                    if (hash["external_name"] != null)
                    {
                        externalName = (string)hash["external_name"];
                        //m_log.Debug(">> HERE, externalName: " + externalName);
                    }
                }
            }
            catch (Exception e)
            {
                reason = "Error parsing return arguments";
                m_log.Error("[GATEKEEPER SERVICE CONNECTOR]: Got exception while parsing hyperlink response " + e.StackTrace);
                return(false);
            }

            return(true);
        }
        public bool DoHelloNeighbourCall(GridRegion region, RegionInfo thisRegion)
        {
            string uri = region.ServerURI + "region/" + thisRegion.RegionID + "/";
//            m_log.Debug("   >>> DoHelloNeighbourCall <<< " + uri);

            WebRequest helloNeighbourRequest;

            try
            {
                ServicePointManagerTimeoutSupport.ResetHosts();
                helloNeighbourRequest = WebRequest.Create(uri);
            }
            catch (Exception e)
            {
                m_log.Warn(string.Format(
                               "[NEIGHBOUR SERVICES CONNECTOR]: Unable to parse uri {0} to send HelloNeighbour from {1} to {2}.  Exception {3} ",
                               uri, thisRegion.RegionName, region.RegionName, e.Message), e);

                return(false);
            }

            helloNeighbourRequest.Method      = "POST";
            helloNeighbourRequest.ContentType = "application/json";
            helloNeighbourRequest.Timeout     = 10000;

            // Fill it in
            OSDMap args = null;

            try
            {
                args = thisRegion.PackRegionInfoData();
            }
            catch (Exception e)
            {
                m_log.Warn(string.Format(
                               "[NEIGHBOUR SERVICES CONNECTOR]: PackRegionInfoData failed for HelloNeighbour from {0} to {1}.  Exception {2} ",
                               thisRegion.RegionName, region.RegionName, e.Message), e);

                return(false);
            }

            // Add the regionhandle of the destination region
            args["destination_handle"] = OSD.FromString(region.RegionHandle.ToString());

            string strBuffer = "";

            byte[] buffer = new byte[1];

            try
            {
                strBuffer = OSDParser.SerializeJsonString(args);
                buffer    = Util.UTF8NoBomEncoding.GetBytes(strBuffer);
            }
            catch (Exception e)
            {
                m_log.Warn(string.Format(
                               "[NEIGHBOUR SERVICES CONNECTOR]: Exception thrown on serialization of HelloNeighbour from {0} to {1}.  Exception {2} ",
                               thisRegion.RegionName, region.RegionName, e.Message), e);

                return(false);
            }

            Stream os = null;

            try
            {                                                        // send the Post
                helloNeighbourRequest.ContentLength = buffer.Length; //Count bytes to send
                os = helloNeighbourRequest.GetRequestStream();
                os.Write(buffer, 0, strBuffer.Length);               //Send it
                //m_log.InfoFormat("[REST COMMS]: Posted HelloNeighbour request to remote sim {0}", uri);
            }
            catch (Exception e)
            {
                m_log.Warn(string.Format(
                               "[NEIGHBOUR SERVICES CONNECTOR]: Unable to send HelloNeighbour from {0} to {1} (uri {2}).  Exception {3} ",
                               thisRegion.RegionName, region.RegionName, uri, e.Message), e);

                return(false);
            }
            finally
            {
                if (os != null)
                {
                    os.Dispose();
                }
            }

            // Let's wait for the response
            //m_log.Info("[REST COMMS]: Waiting for a reply after DoHelloNeighbourCall");

            try
            {
                using (WebResponse webResponse = helloNeighbourRequest.GetResponse())
                {
                    if (webResponse == null)
                    {
                        m_log.DebugFormat(
                            "[NEIGHBOUR SERVICES CONNECTOR]: Null reply on DoHelloNeighbourCall post from {0} to {1}",
                            thisRegion.RegionName, region.RegionName);
                    }

                    using (Stream s = webResponse.GetResponseStream())
                    {
                        using (StreamReader sr = new StreamReader(s))
                        {
                            //reply = sr.ReadToEnd().Trim();
                            sr.ReadToEnd().Trim();
                            //m_log.InfoFormat("[REST COMMS]: DoHelloNeighbourCall reply was {0} ", reply);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                m_log.Warn(string.Format(
                               "[NEIGHBOUR SERVICES CONNECTOR]: Exception on reply of DoHelloNeighbourCall from {0} back to {1}.  Exception {2} ",
                               region.RegionName, thisRegion.RegionName, e.Message), e);

                return(false);
            }

            return(true);
        }
Exemplo n.º 21
0
        public void SendRequest()
        {
            try
            {
                ServicePointManagerTimeoutSupport.ResetHosts();
                Request             = (HttpWebRequest)WebRequest.Create(Url);
                Request.Method      = HttpMethod;
                Request.ContentType = HttpMIMEType;

                if (!HttpVerifyCert)
                {
                    // We could hijack Connection Group Name to identify
                    // a desired security exception.  But at the moment we'll use a dummy header instead.
//                    Request.ConnectionGroupName = "NoVerify";
                    Request.Headers.Add("NoVerifyCert", "true");
                }
//                else
//                {
//                    Request.ConnectionGroupName="Verify";
//                }
                if (!HttpPragmaNoCache)
                {
                    Request.Headers.Add("Pragma", "no-cache");
                }
                if (HttpCustomHeaders != null)
                {
                    for (int i = 0; i < HttpCustomHeaders.Count; i += 2)
                    {
                        Request.Headers.Add(HttpCustomHeaders[i],
                                            HttpCustomHeaders[i + 1]);
                    }
                }
                if (!string.IsNullOrEmpty(proxyurl))
                {
                    if (!string.IsNullOrEmpty(proxyexcepts))
                    {
                        string[] elist = proxyexcepts.Split(';');
                        Request.Proxy = new WebProxy(proxyurl, true, elist);
                    }
                    else
                    {
                        Request.Proxy = new WebProxy(proxyurl, true);
                    }
                }

                if (ResponseHeaders != null)
                {
                    foreach (KeyValuePair <string, string> entry in ResponseHeaders)
                    {
                        if (entry.Key.Equals("user-agent", StringComparison.OrdinalIgnoreCase))
                        {
                            Request.UserAgent = entry.Value;
                        }
                        else
                        {
                            Request.Headers[entry.Key] = entry.Value;
                        }
                    }
                }

                // Encode outbound data
                if (!string.IsNullOrEmpty(OutboundBody))
                {
                    byte[] data = Util.UTF8.GetBytes(OutboundBody);
                    if (data.Length < 4096)
                    {
                        Request.ServicePoint.Expect100Continue = false;
                    }
                    Request.ContentLength = data.Length;
                    using (Stream bstream = Request.GetRequestStream())
                        bstream.Write(data, 0, data.Length);
                }

                try
                {
                    IAsyncResult result = Request.BeginGetResponse(ResponseCallback, null);

                    ThreadPool.RegisterWaitForSingleObject(
                        result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), null, HttpTimeout, true);
                }
                catch (WebException e)
                {
                    if (e.Status != WebExceptionStatus.ProtocolError)
                    {
                        throw;
                    }

                    HttpWebResponse response = (HttpWebResponse)e.Response;

                    Status       = (int)response.StatusCode;
                    ResponseBody = response.StatusDescription;
                    _finished    = true;
                }
            }
            catch (Exception e)
            {
//                m_log.Debug(
//                    string.Format("[SCRIPTS HTTP REQUESTS]: Exception on request to {0} for {1}  ", Url, ItemID), e);

                Status       = (int)OSHttpStatusCode.ClientErrorJoker;
                ResponseBody = e.Message;
                _finished    = true;
            }
        }
        public void SendInstantMessage(GridInstantMessage im, MessageResultNotification result)
        {
            UUID toAgentID = new UUID(im.toAgentID);

            try
            {
                // Try root avatar only first
                m_Scenes.ForEach(delegate(Scene scene)
                {
                    //                m_log.DebugFormat(
                    //                    "[HG INSTANT MESSAGE]: Looking for root agent {0} in {1}",
                    //                    toAgentID.ToString(), scene.RegionInfo.RegionName);
                    ScenePresence sp = scene.GetScenePresence(toAgentID);
                    if (sp != null && !sp.IsChildAgent)
                    {
                        // Local message
                        //                  m_log.DebugFormat("[HG INSTANT MESSAGE]: Delivering IM to root agent {0} {1}", user.Name, toAgentID);
                        sp.ControllingClient.SendInstantMessage(im);

                        // Message sent
                        result(true);
                        throw new ThreadedClasses.ReturnValueException <bool>(true);
                    }
                });

                // try child avatar second
                m_Scenes.ForEach(delegate(Scene scene)
                {
                    //                m_log.DebugFormat(
                    //                    "[HG INSTANT MESSAGE]: Looking for child of {0} in {1}",
                    //                    toAgentID, scene.RegionInfo.RegionName);
                    ScenePresence sp = scene.GetScenePresence(toAgentID);
                    if (sp != null)
                    {
                        // Local message
                        //                    m_log.DebugFormat("[HG INSTANT MESSAGE]: Delivering IM to child agent {0} {1}", user.Name, toAgentID);
                        sp.ControllingClient.SendInstantMessage(im);

                        // Message sent
                        result(true);
                        throw new ThreadedClasses.ReturnValueException <bool>(true);
                    }
                });
            }
            catch (ThreadedClasses.ReturnValueException <bool> )
            {
                return;
            }

//            m_log.DebugFormat("[HG INSTANT MESSAGE]: Delivering IM to {0} via XMLRPC", im.toAgentID);
            // Is the user a local user?
            string url       = string.Empty;
            bool   foreigner = false;

            byte dialog = im.dialog;

            if (dialog == (byte)InstantMessageDialog.MessageFromObject && !m_EnableObjectIM)
            {
                return;
            }

            if (UserManagementModule != null && !UserManagementModule.IsLocalGridUser(toAgentID)) // foreign user
            {
                url       = UserManagementModule.GetUserServerURL(toAgentID, "IMServerURI");
                foreigner = true;
            }

            Util.FireAndForget(delegate
            {
                bool success = false;
                if (foreigner && url == string.Empty) // we don't know about this user
                {
                    string recipientUUI = TryGetRecipientUUI(new UUID(im.fromAgentID), toAgentID);
                    m_log.DebugFormat("[HG MESSAGE TRANSFER]: Got UUI {0}", recipientUUI);
                    if (recipientUUI != string.Empty)
                    {
                        UUID id; string u = string.Empty, first = string.Empty, last = string.Empty, secret = string.Empty;
                        if (Util.ParseUniversalUserIdentifier(recipientUUI, out id, out u, out first, out last, out secret))
                        {
                            ServicePointManagerTimeoutSupport.ResetHosts();
                            success = m_IMService.OutgoingInstantMessage(im, u, true);
                            if (success)
                            {
                                UserManagementModule.AddUser(toAgentID, u + ";" + first + " " + last);
                            }
                        }
                    }
                }
                else
                {
                    ServicePointManagerTimeoutSupport.ResetHosts();
                    success = m_IMService.OutgoingInstantMessage(im, url, foreigner);
                }

                if (!success && !foreigner)
                {
                    HandleUndeliveredMessage(im, result);
                }
                else
                {
                    result(success);
                }
            });

            return;
        }