public override byte[] Handle(string path, Stream requestData,
                                      IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            // It's a POST, so we need to read the data on the stream, the lines after the blank line
            StreamReader sr   = new StreamReader(requestData);
            string       body = sr.ReadToEnd();

            sr.Close();
            body = body.Trim();

            httpResponse.ContentType = "text/html";

            string resource = GetParam(path);

            //m_log.DebugFormat("[XXX]: query String: {0}; resource: {1}", body, resource);

            try
            {
                // Here the data on the stream is transformed into a nice dictionary of keys & values
                Dictionary <string, object> postdata =
                    ServerUtils.ParseQueryString(body);

                Request req = WifiUtils.CreateRequest(resource, httpRequest);
                Diva.Wifi.Environment env = new Diva.Wifi.Environment(req);

                string result = string.Empty;
                if (resource.Equals("/") || resource.Equals(string.Empty))
                {
                    // The client invoked /wifi/admin/users/
                    string terms = String.Empty;
                    if (postdata.ContainsKey("terms"))
                    {
                        terms = postdata["terms"].ToString();
                    }

                    result = m_WebApp.Services.UserSearchPostRequest(env, terms);
                }
                else if (resource.StartsWith("/edit"))
                {
                    // The client invoked /wifi/admin/users/edit, possibly with the UUID parameter after
                    UUID     userID = UUID.Zero;
                    string[] pars   = SplitParams(path);
                    if ((pars.Length >= 2) && UUID.TryParse(pars[1], out userID))
                    {
                        // Indeed the client invoked /wifi/admin/users/edit/<uuid>, and we got it already in userID (above)
                        string form = string.Empty;
                        if (postdata.ContainsKey("form"))
                        {
                            form = postdata["form"].ToString();
                        }
                        if (form == "1")
                        {
                            string first = string.Empty, last = string.Empty, email = string.Empty, title = string.Empty;
                            int    level = 0, flags = 0;
                            if (postdata.ContainsKey("first") && WifiUtils.IsValidName(postdata["first"].ToString()))
                            {
                                first = postdata["first"].ToString();
                            }
                            if (postdata.ContainsKey("last") && WifiUtils.IsValidName(postdata["last"].ToString()))
                            {
                                last = postdata["last"].ToString();
                            }
                            if (postdata.ContainsKey("email") && WifiUtils.IsValidEmail(postdata["email"].ToString()))
                            {
                                email = postdata["email"].ToString();
                            }
                            if (postdata.ContainsKey("title"))
                            {
                                title = postdata["title"].ToString();
                            }
                            if (postdata.ContainsKey("level"))
                            {
                                Int32.TryParse(postdata["level"].ToString(), out level);
                            }
                            if (postdata.ContainsKey("flags"))
                            {
                                Int32.TryParse(postdata["flags"].ToString(), out flags);
                            }

                            result = m_WebApp.Services.UserEditPostRequest(env, userID, first, last, email, level, flags, title);
                        }
                        else if (form == "2")
                        {
                            string password = string.Empty;
                            if (postdata.ContainsKey("password"))
                            {
                                password = postdata["password"].ToString();
                                result   = m_WebApp.Services.UserEditPostRequest(env, userID, password);
                            }
                        }
                    }
                }
                else if (resource.StartsWith("/delete"))
                {
                    // The client invoked /wifi/admin/users/edit, possibly with the UUID parameter after
                    UUID     userID = UUID.Zero;
                    string[] pars   = SplitParams(path);
                    if ((pars.Length >= 2) && UUID.TryParse(pars[1], out userID))
                    {
                        // Indeed the client invoked /wifi/admin/users/edit/<uuid>, and we got it already in userID (above)
                        string form = string.Empty;
                        if (postdata.ContainsKey("form"))
                        {
                            form = postdata["form"].ToString();
                        }
                        if (form == "1")
                        {
                            result = m_WebApp.Services.UserDeletePostRequest(env, userID);
                        }
                    }
                }

                return(WifiUtils.StringToBytes(result));
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[USER ACCOUNT POST HANDLER]: Exception {0}", e);
            }

            return(WifiUtils.FailureResult());
        }
예제 #2
0
        protected override void ProcessRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            httpResponse.KeepAlive = false;
            if (httpRequest.HttpMethod != "POST")
            {
                httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
                return;
            }

            httpResponse.StatusCode = (int)HttpStatusCode.OK;

            // m_log.DebugFormat("[XESTATE HANDLER]: query String: {0}", body);

            try
            {
                string body;
                using (StreamReader sr = new StreamReader(httpRequest.InputStream))
                    body = sr.ReadToEnd();

                body = body.Trim();
                lock (m_RequestLock)
                {
                    Dictionary <string, object> request = ServerUtils.ParseQueryString(body);

                    bool fail = true;
                    while (true)
                    {
                        if (!request.ContainsKey("METHOD"))
                        {
                            break;
                        }

                        if (!request.ContainsKey("TOKEN"))
                        {
                            break;
                        }

                        string reqToken = request["TOKEN"].ToString();

                        if (token != reqToken)
                        {
                            break;
                        }

                        fail = false;
                        break;
                    }
                    if (fail)
                    {
                        httpResponse.RawBuffer = FailureResult();
                        return;
                    }

                    string method = request["METHOD"].ToString();
                    request.Remove("METHOD");
                    request.Remove("TOKEN");

                    try
                    {
                        m_EstateModule.InInfoUpdate = false;
                        switch (method)
                        {
                        case "update_covenant":
                            httpResponse.RawBuffer = UpdateCovenant(request);
                            return;

                        case "update_estate":
                            httpResponse.RawBuffer = UpdateEstate(request);
                            return;

                        case "estate_message":
                            httpResponse.RawBuffer = EstateMessage(request);
                            return;

                        case "teleport_home_one_user":
                            httpResponse.RawBuffer = TeleportHomeOneUser(request);
                            return;

                        case "teleport_home_all_users":
                            httpResponse.RawBuffer = TeleportHomeAllUsers(request);
                            return;
                        }
                    }
                    finally
                    {
                        m_EstateModule.InInfoUpdate = false;
                    }
                }
            }
            catch (Exception e)
            {
                m_log.Debug("[XESTATE]: Exception {0}" + e.ToString());
            }

            httpResponse.RawBuffer = FailureResult();
        }
예제 #3
0
        protected override byte[] ProcessRequest(string path, Stream requestData,
                                                 IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            string body;

            using (StreamReader sr = new StreamReader(requestData))
                body = sr.ReadToEnd();
            body = body.Trim();

            // We need to check the authorization header
            //httpRequest.Headers["authorization"] ...

            //m_log.DebugFormat("[XXX]: query String: {0}", body);
            string method = string.Empty;

            try
            {
                Dictionary <string, object> request =
                    ServerUtils.ParseQueryString(body);

                if (!request.ContainsKey("METHOD"))
                {
                    return(FailureResult());
                }

                method = request["METHOD"].ToString();

                switch (method)
                {
                case "createuser":
                    if (m_AllowCreateUser)
                    {
                        return(CreateUser(request));
                    }
                    else
                    {
                        return(FailureResult());
                    }

                case "getaccount":
                    return(GetAccount(request));

                case "getaccounts":
                    return(GetAccounts(request));

                case "getmultiaccounts":
                    return(GetMultiAccounts(request));

                case "setaccount":
                    if (m_AllowSetAccount)
                    {
                        return(StoreAccount(request));
                    }
                    else
                    {
                        return(FailureResult());
                    }

                case "setdisplayname":
                    return(SetDisplayName(request));
                }

                m_log.DebugFormat("[USER SERVICE HANDLER]: unknown method request: {0}", method);
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[USER SERVICE HANDLER]: Exception in method {0}: {1}", method, e);
            }

            return(FailureResult());
        }
        private List <UserAccount> doGetMultiUserAccounts(UUID scopeID, List <string> IDs, out bool suported)
        {
            suported = true;
            Dictionary <string, object> sendData = new Dictionary <string, object>();

            //sendData["SCOPEID"] = scopeID.ToString();
            sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
            sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
            sendData["METHOD"]     = "getmultiaccounts";

            sendData["ScopeID"] = scopeID.ToString();
            sendData["IDS"]     = new List <string>(IDs);

            string reply     = string.Empty;
            string reqString = ServerUtils.BuildQueryString(sendData);
            string uri       = m_ServerURI + "/accounts";

            // m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString);
            try
            {
                reply = SynchronousRestFormsRequester.MakeRequest("POST",
                                                                  uri,
                                                                  reqString,
                                                                  m_Auth);
                if (reply == null || (reply != null && reply == string.Empty))
                {
                    m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetMultiUserAccounts received null or empty reply");
                    return(null);
                }
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[ACCOUNT CONNECTOR]: Exception when contacting user accounts server at {0}: {1}", uri, e.Message);
            }

            List <UserAccount> accounts = new List <UserAccount>();

            Dictionary <string, object> replyData = ServerUtils.ParseXmlResponse(reply);

            if (replyData != null)
            {
                if (replyData.ContainsKey("result"))
                {
                    if (replyData["result"].ToString() == "null")
                    {
                        return(accounts);
                    }

                    if (replyData["result"].ToString() == "Failure")
                    {
                        suported = false;
                        return(accounts);
                    }
                }

                Dictionary <string, object> .ValueCollection accountList = replyData.Values;
                //m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetAgents returned {0} elements", pinfosList.Count);
                foreach (object acc in accountList)
                {
                    if (acc is Dictionary <string, object> )
                    {
                        UserAccount pinfo = new UserAccount((Dictionary <string, object>)acc);
                        accounts.Add(pinfo);
                    }
                    else
                    {
                        m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetMultiUserAccounts received invalid response type {0}",
                                          acc.GetType());
                    }
                }
            }
            else
            {
                m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetMultiUserAccounts received null response");
            }

            return(accounts);
        }
예제 #5
0
        public GridService(IConfigSource config)
            : base(config)
        {
            m_log.DebugFormat("[GRID SERVICE]: Starting...");

            m_config = config;
            IConfig gridConfig = config.Configs["GridService"];

            bool suppressConsoleCommands = false;

            if (gridConfig != null)
            {
                m_DeleteOnUnregister = gridConfig.GetBoolean("DeleteOnUnregister", true);

                string authService = gridConfig.GetString("AuthenticationService", String.Empty);

                if (authService != String.Empty)
                {
                    Object[] args = new Object[] { config };
                    m_AuthenticationService = ServerUtils.LoadPlugin <IAuthenticationService>(authService, args);
                }
                m_AllowDuplicateNames     = gridConfig.GetBoolean("AllowDuplicateNames", m_AllowDuplicateNames);
                m_AllowHypergridMapSearch = gridConfig.GetBoolean("AllowHypergridMapSearch", m_AllowHypergridMapSearch);

                // This service is also used locally by a simulator running in grid mode.  This switches prevents
                // inappropriate console commands from being registered
                suppressConsoleCommands = gridConfig.GetBoolean("SuppressConsoleCommands", suppressConsoleCommands);
            }

            if (m_RootInstance == null)
            {
                m_RootInstance = this;

                if (!suppressConsoleCommands && MainConsole.Instance != null)
                {
                    MainConsole.Instance.Commands.AddCommand("Regions", true,
                                                             "deregister region id",
                                                             "deregister region id <region-id>+",
                                                             "Deregister a region manually.",
                                                             String.Empty,
                                                             HandleDeregisterRegion);

                    MainConsole.Instance.Commands.AddCommand("Regions", true,
                                                             "show regions",
                                                             "show regions",
                                                             "Show details on all regions",
                                                             String.Empty,
                                                             HandleShowRegions);

                    MainConsole.Instance.Commands.AddCommand("Regions", true,
                                                             "show region name",
                                                             "show region name <Region name>",
                                                             "Show details on a region",
                                                             String.Empty,
                                                             HandleShowRegion);

                    MainConsole.Instance.Commands.AddCommand("Regions", true,
                                                             "show region at",
                                                             "show region at <x-coord> <y-coord>",
                                                             "Show details on a region at the given co-ordinate.",
                                                             "For example, show region at 1000 1000",
                                                             HandleShowRegionAt);

                    MainConsole.Instance.Commands.AddCommand("General", true,
                                                             "show grid size",
                                                             "show grid size",
                                                             "Show the current grid size (excluding hyperlink references)",
                                                             String.Empty,
                                                             HandleShowGridSize);

                    MainConsole.Instance.Commands.AddCommand("Regions", true,
                                                             "set region flags",
                                                             "set region flags <Region name> <flags>",
                                                             "Set database flags for region",
                                                             String.Empty,
                                                             HandleSetFlags);
                }

                if (!suppressConsoleCommands)
                {
                    SetExtraServiceURLs(config);
                }

                m_HypergridLinker = new HypergridLinker(m_config, this, m_Database);
            }
        }
예제 #6
0
        public GatekeeperService(IConfigSource config, ISimulationService simService)
        {
            if (!m_Initialized)
            {
                m_Initialized = true;

                IConfig serverConfig = config.Configs["GatekeeperService"];
                if (serverConfig == null)
                {
                    throw new Exception(String.Format("No section GatekeeperService in config file"));
                }

                string accountService    = serverConfig.GetString("UserAccountService", string.Empty);
                string homeUsersService  = serverConfig.GetString("UserAgentService", string.Empty);
                string gridService       = serverConfig.GetString("GridService", string.Empty);
                string presenceService   = serverConfig.GetString("PresenceService", string.Empty);
                string simulationService = serverConfig.GetString("SimulationService", string.Empty);
                string gridUserService   = serverConfig.GetString("GridUserService", string.Empty);
                string bansService       = serverConfig.GetString("BansService", string.Empty);
                // These are mandatory, the others aren't
                if (gridService == string.Empty || presenceService == string.Empty)
                {
                    throw new Exception("Incomplete specifications, Gatekeeper Service cannot function.");
                }

                string scope = serverConfig.GetString("ScopeID", UUID.Zero.ToString());
                UUID.TryParse(scope, out m_ScopeID);
                //m_WelcomeMessage = serverConfig.GetString("WelcomeMessage", "Welcome to OpenSim!");
                m_AllowTeleportsToAnyRegion = serverConfig.GetBoolean("AllowTeleportsToAnyRegion", true);

                string[] sections     = new string[] { "Const, Startup", "Hypergrid", "GatekeeperService" };
                string   externalName = Util.GetConfigVarFromSections <string>(config, "GatekeeperURI", sections, string.Empty);
                if (string.IsNullOrEmpty(externalName))
                {
                    externalName = serverConfig.GetString("ExternalName", string.Empty);
                }

                m_gatekeeperHost = new OSHHTPHost(externalName, true);
                if (!m_gatekeeperHost.IsResolvedHost)
                {
                    m_log.Error((m_gatekeeperHost.IsValidHost ? "Could not resolve GatekeeperURI" : "GatekeeperURI is a invalid host ") + externalName ?? "");
                    throw new Exception("GatekeeperURI is invalid");
                }
                m_gatekeeperURL = m_gatekeeperHost.URIwEndSlash;

                string gatekeeperURIAlias = Util.GetConfigVarFromSections <string>(config, "GatekeeperURIAlias", sections, string.Empty);

                if (!string.IsNullOrWhiteSpace(gatekeeperURIAlias))
                {
                    string[] alias = gatekeeperURIAlias.Split(',');
                    for (int i = 0; i < alias.Length; ++i)
                    {
                        OSHHTPHost tmp = new OSHHTPHost(alias[i].Trim(), false);
                        if (tmp.IsValidHost)
                        {
                            if (m_gateKeeperAlias == null)
                            {
                                m_gateKeeperAlias = new HashSet <OSHHTPHost>();
                            }
                            m_gateKeeperAlias.Add(tmp);
                        }
                    }
                }

                object[] args = new object[] { config };
                m_GridService     = ServerUtils.LoadPlugin <IGridService>(gridService, args);
                m_PresenceService = ServerUtils.LoadPlugin <IPresenceService>(presenceService, args);

                if (accountService != string.Empty)
                {
                    m_UserAccountService = ServerUtils.LoadPlugin <IUserAccountService>(accountService, args);
                }
                if (homeUsersService != string.Empty)
                {
                    m_UserAgentService = ServerUtils.LoadPlugin <IUserAgentService>(homeUsersService, args);
                }
                if (gridUserService != string.Empty)
                {
                    m_GridUserService = ServerUtils.LoadPlugin <IGridUserService>(gridUserService, args);
                }
                if (bansService != string.Empty)
                {
                    m_BansService = ServerUtils.LoadPlugin <IBansService>(bansService, args);
                }

                if (simService != null)
                {
                    m_SimulationService = simService;
                }
                else if (simulationService != string.Empty)
                {
                    m_SimulationService = ServerUtils.LoadPlugin <ISimulationService>(simulationService, args);
                }

                string[] possibleAccessControlConfigSections = new string[] { "AccessControl", "GatekeeperService" };
                m_AllowedClients = Util.GetConfigVarFromSections <string>(
                    config, "AllowedClients", possibleAccessControlConfigSections, string.Empty);
                m_DeniedClients = Util.GetConfigVarFromSections <string>(
                    config, "DeniedClients", possibleAccessControlConfigSections, string.Empty);
                m_DeniedMacs = Util.GetConfigVarFromSections <string>(
                    config, "DeniedMacs", possibleAccessControlConfigSections, string.Empty);
                m_ForeignAgentsAllowed = serverConfig.GetBoolean("ForeignAgentsAllowed", true);

                LoadDomainExceptionsFromConfig(serverConfig, "AllowExcept", m_ForeignsAllowedExceptions);
                LoadDomainExceptionsFromConfig(serverConfig, "DisallowExcept", m_ForeignsDisallowedExceptions);

                if (m_GridService == null || m_PresenceService == null || m_SimulationService == null)
                {
                    throw new Exception("Unable to load a required plugin, Gatekeeper Service cannot function.");
                }

                IConfig presenceConfig = config.Configs["PresenceService"];
                if (presenceConfig != null)
                {
                    m_allowDuplicatePresences = presenceConfig.GetBoolean("AllowDuplicatePresences", m_allowDuplicatePresences);
                }

                IConfig messagingConfig = config.Configs["Messaging"];
                if (messagingConfig != null)
                {
                    m_messageKey = messagingConfig.GetString("MessageKey", String.Empty);
                }
                m_log.Debug("[GATEKEEPER SERVICE]: Starting...");
            }
        }
        byte[] StatusNotification(Dictionary <string, object> request)
        {
            UUID principalID = UUID.Zero;

            if (request.ContainsKey("userID"))
            {
                UUID.TryParse(request["userID"].ToString(), out principalID);
            }
            else
            {
                m_log.WarnFormat("[HGFRIENDS HANDLER]: no userID in request to notify");
                return(FailureResult());
            }

            bool online = true;

            if (request.ContainsKey("online"))
            {
                Boolean.TryParse(request["online"].ToString(), out online);
            }
            else
            {
                m_log.WarnFormat("[HGFRIENDS HANDLER]: no online in request to notify");
                return(FailureResult());
            }

            List <string> friends = new List <string>();
            int           i       = 0;

            foreach (KeyValuePair <string, object> kvp in request)
            {
                if (kvp.Key.Equals("friend_" + i.ToString()))
                {
                    friends.Add(kvp.Value.ToString());
                    i++;
                }
            }

            List <UUID> onlineFriends = m_TheService.StatusNotification(friends, principalID, online);

            Dictionary <string, object> result = new Dictionary <string, object>();

            if ((onlineFriends == null) || ((onlineFriends != null) && (onlineFriends.Count == 0)))
            {
                result["RESULT"] = "NULL";
            }
            else
            {
                i = 0;
                foreach (UUID f in onlineFriends)
                {
                    result["friend_" + i] = f.ToString();
                    i++;
                }
            }

            string xmlString = ServerUtils.BuildXmlResponse(result);

            //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
            return(Util.UTF8NoBomEncoding.GetBytes(xmlString));
        }
        protected override byte[] ProcessRequest(string path, Stream requestData,
                                                 IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            StreamReader sr   = new StreamReader(requestData);
            string       body = sr.ReadToEnd();

            sr.Close();
            body = body.Trim();

            //m_log.DebugFormat("[XXX]: query String: {0}", body);

            try
            {
                Dictionary <string, object> request =
                    ServerUtils.ParseQueryString(body);

                if (!request.ContainsKey("METHOD"))
                {
                    return(FailureResult());
                }

                string method = request["METHOD"].ToString();

                switch (method)
                {
                case "register":
                    return(Register(request));

                case "deregister":
                    return(Deregister(request));

                case "get_neighbours":
                    return(GetNeighbours(request));

                case "get_region_by_uuid":
                    return(GetRegionByUUID(request));

                case "get_region_by_position":
                    return(GetRegionByPosition(request));

                case "get_region_by_name":
                    return(GetRegionByName(request));

                case "get_regions_by_name":
                    return(GetRegionsByName(request));

                case "get_region_range":
                    return(GetRegionRange(request));

                case "get_default_regions":
                    return(GetDefaultRegions(request));

                case "get_fallback_regions":
                    return(GetFallbackRegions(request));

                case "get_hyperlinks":
                    return(GetHyperlinks(request));

                case "get_region_flags":
                    return(GetRegionFlags(request));
                }

                m_log.DebugFormat("[GRID HANDLER]: unknown method request {0}", method);
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[GRID HANDLER]: Exception {0} {1}", e.Message, e.StackTrace);
            }

            return(FailureResult());
        }
예제 #9
0
        public HypergridLinker(IConfigSource config, GridService gridService, IRegionData db)
        {
            IConfig gridConfig = config.Configs["GridService"];

            if (gridConfig == null)
            {
                return;
            }

            if (!gridConfig.GetBoolean("HypergridLinker", false))
            {
                return;
            }

            m_Database    = db;
            m_GridService = gridService;
            m_log.DebugFormat("[HYPERGRID LINKER]: Starting with db {0}", db.GetType());

            string assetService = gridConfig.GetString("AssetService", string.Empty);

            Object[] args = new Object[] { config };

            if (assetService != string.Empty)
            {
                m_AssetService = ServerUtils.LoadPlugin <IAssetService>(assetService, args);
            }

            string scope = gridConfig.GetString("ScopeID", string.Empty);

            if (scope != string.Empty)
            {
                UUID.TryParse(scope, out m_ScopeID);
            }

//                m_Check4096 = gridConfig.GetBoolean("Check4096", true);

            m_MapTileDirectory = gridConfig.GetString("MapTileDirectory", "maptiles");

            m_ThisGatekeeperURI = Util.GetConfigVarFromSections <string>(config, "GatekeeperURI",
                                                                         new string[] { "Startup", "Hypergrid", "GridService" }, String.Empty);
            m_ThisGatekeeperURI = gridConfig.GetString("Gatekeeper", m_ThisGatekeeperURI);

            if (!Util.checkServiceURI(m_ThisGatekeeperURI, out m_ThisGatekeeperURI, out m_ThisGatekeeperHost, out m_ThisGateKeeperIP))
            {
                m_log.ErrorFormat("[HYPERGRID LINKER]: Malformed URL in [GridService], variable Gatekeeper = {0}", m_ThisGatekeeperURI);
                throw new Exception("Failed to resolve gatekeeper external IP, please check GatekeeperURI configuration");
            }

            string gatekeeperURIAlias = Util.GetConfigVarFromSections <string>(config, "GatekeeperURIAlias",
                                                                               new string[] { "Startup", "Hypergrid", "GridService" }, String.Empty);

            if (!string.IsNullOrWhiteSpace(gatekeeperURIAlias))
            {
                string[] alias = gatekeeperURIAlias.Split(',');
                for (int i = 0; i < alias.Length; ++i)
                {
                    if (!string.IsNullOrWhiteSpace(alias[i]))
                    {
                        m_ThisGateKeeperAlias.Add(alias[i].Trim().ToLower());
                    }
                }
            }

            m_GatekeeperConnector = new GatekeeperServiceConnector(m_AssetService);

            m_log.Debug("[HYPERGRID LINKER]: Loaded all services...");

            if (!string.IsNullOrEmpty(m_MapTileDirectory))
            {
                try
                {
                    Directory.CreateDirectory(m_MapTileDirectory);
                }
                catch (Exception e)
                {
                    m_log.WarnFormat("[HYPERGRID LINKER]: Could not create map tile storage directory {0}: {1}", m_MapTileDirectory, e);
                    m_MapTileDirectory = string.Empty;
                }
            }

            if (MainConsole.Instance != null)
            {
                MainConsole.Instance.Commands.AddCommand("Hypergrid", false, "link-region",
                                                         "link-region <Xloc> <Yloc> <ServerURI> [<RemoteRegionName>]",
                                                         "Link a HyperGrid Region. Examples for <ServerURI>: http://grid.net:8002/ or http://example.org/path/foo.php", RunCommand);
                MainConsole.Instance.Commands.AddCommand("Hypergrid", false, "link-region",
                                                         "link-region <Xloc> <Yloc> <RegionIP> <RegionPort> [<RemoteRegionName>]",
                                                         "Link a hypergrid region (deprecated)", RunCommand);
                MainConsole.Instance.Commands.AddCommand("Hypergrid", false, "unlink-region",
                                                         "unlink-region <local name>",
                                                         "Unlink a hypergrid region", RunCommand);
                MainConsole.Instance.Commands.AddCommand("Hypergrid", false, "link-mapping", "link-mapping [<x> <y>]",
                                                         "Set local coordinate to map HG regions to", RunCommand);
                MainConsole.Instance.Commands.AddCommand("Hypergrid", false, "show hyperlinks", "show hyperlinks",
                                                         "List the HG regions", HandleShow);
            }
        }
        protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
//            m_log.DebugFormat("[MAP SERVICE IMAGE HANDLER]: Received {0}", path);
            StreamReader sr   = new StreamReader(requestData);
            string       body = sr.ReadToEnd();

            sr.Close();
            body = body.Trim();

            try
            {
                Dictionary <string, object> request = ServerUtils.ParseQueryString(body);

                if (!request.ContainsKey("X") || !request.ContainsKey("Y") || !request.ContainsKey("DATA"))
                {
                    httpResponse.StatusCode = (int)OSHttpStatusCode.ClientErrorBadRequest;
                    return(FailureResult("Bad request."));
                }
                int x = 0, y = 0;
                Int32.TryParse(request["X"].ToString(), out x);
                Int32.TryParse(request["Y"].ToString(), out y);

                m_log.DebugFormat("[MAP ADD SERVER CONNECTOR]: Received map data for region at {0}-{1}", x, y);

//                string type = "image/jpeg";
//
//                if (request.ContainsKey("TYPE"))
//                    type = request["TYPE"].ToString();

                if (m_GridService != null)
                {
                    System.Net.IPAddress ipAddr = GetCallerIP(httpRequest);
                    GridRegion           r      = m_GridService.GetRegionByPosition(UUID.Zero, x * (int)Constants.RegionSize, y * (int)Constants.RegionSize);
                    if (r != null)
                    {
                        if (r.ExternalEndPoint.Address.ToString() != ipAddr.ToString())
                        {
                            m_log.WarnFormat("[MAP IMAGE HANDLER]: IP address {0} may be trying to impersonate region in IP {1}", ipAddr, r.ExternalEndPoint.Address);
                            return(FailureResult("IP address of caller does not match IP address of registered region"));
                        }
                    }
                    else
                    {
                        m_log.WarnFormat("[MAP IMAGE HANDLER]: IP address {0} may be rogue. Region not found at coordinates {1}-{2}",
                                         ipAddr, x, y);
                        return(FailureResult("Region not found at given coordinates"));
                    }
                }

                byte[] data = Convert.FromBase64String(request["DATA"].ToString());

                string reason = string.Empty;
                bool   result = m_MapService.AddMapTile(x, y, data, out reason);

                if (result)
                {
                    return(SuccessResult());
                }
                else
                {
                    return(FailureResult(reason));
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[MAP SERVICE IMAGE HANDLER]: Exception {0} {1}", e.Message, e.StackTrace);
            }

            return(FailureResult("Unexpected server error"));
        }
        byte[] GetRegionRange(Dictionary <string, object> request)
        {
            //m_log.DebugFormat("[GRID HANDLER]: GetRegionRange");
            UUID scopeID = UUID.Zero;

            if (request.ContainsKey("SCOPEID"))
            {
                UUID.TryParse(request["SCOPEID"].ToString(), out scopeID);
            }
            else
            {
                m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region range");
            }

            int xmin = 0, xmax = 0, ymin = 0, ymax = 0;

            if (request.ContainsKey("XMIN"))
            {
                Int32.TryParse(request["XMIN"].ToString(), out xmin);
            }
            else
            {
                m_log.WarnFormat("[GRID HANDLER]: no XMIN in request to get region range");
            }
            if (request.ContainsKey("XMAX"))
            {
                Int32.TryParse(request["XMAX"].ToString(), out xmax);
            }
            else
            {
                m_log.WarnFormat("[GRID HANDLER]: no XMAX in request to get region range");
            }
            if (request.ContainsKey("YMIN"))
            {
                Int32.TryParse(request["YMIN"].ToString(), out ymin);
            }
            else
            {
                m_log.WarnFormat("[GRID HANDLER]: no YMIN in request to get region range");
            }
            if (request.ContainsKey("YMAX"))
            {
                Int32.TryParse(request["YMAX"].ToString(), out ymax);
            }
            else
            {
                m_log.WarnFormat("[GRID HANDLER]: no YMAX in request to get region range");
            }


            List <GridRegion> rinfos           = m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax);

            Dictionary <string, object> result = new Dictionary <string, object>();

            if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0)))
            {
                result["result"] = "null";
            }
            else
            {
                int i = 0;
                foreach (GridRegion rinfo in rinfos)
                {
                    Dictionary <string, object> rinfoDict = rinfo.ToKeyValuePairs();
                    result["region" + i] = rinfoDict;
                    i++;
                }
            }
            string xmlString                   = ServerUtils.BuildXmlResponse(result);

            //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
            return(Util.UTF8NoBomEncoding.GetBytes(xmlString));
        }
예제 #12
0
        public void Initialise(IConfigSource source)
        {
            IConfig moduleConfig = source.Configs["Modules"];

            if (moduleConfig != null)
            {
                string name = moduleConfig.GetString("InventoryServices", "");
                if (name == Name)
                {
                    IConfig inventoryConfig = source.Configs["InventoryService"];
                    if (inventoryConfig == null)
                    {
                        m_log.Error("[HG INVENTORY CONNECTOR]: InventoryService missing from OpenSim.ini");
                        return;
                    }

                    string localDll = inventoryConfig.GetString("LocalGridInventoryService",
                                                                String.Empty);
                    string HGDll = inventoryConfig.GetString("HypergridInventoryService",
                                                             String.Empty);

                    if (localDll == String.Empty)
                    {
                        m_log.Error("[HG INVENTORY CONNECTOR]: No LocalGridInventoryService named in section InventoryService");
                        //return;
                        throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's");
                    }

                    if (HGDll == String.Empty)
                    {
                        m_log.Error("[HG INVENTORY CONNECTOR]: No HypergridInventoryService named in section InventoryService");
                        //return;
                        throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's");
                    }

                    Object[] args = new Object[] { source };
                    m_GridService =
                        ServerUtils.LoadPlugin <IInventoryService>(localDll,
                                                                   args);

                    m_HGService =
                        ServerUtils.LoadPlugin <ISessionAuthInventoryService>(HGDll,
                                                                              args);

                    if (m_GridService == null)
                    {
                        m_log.Error("[HG INVENTORY CONNECTOR]: Can't load local inventory service");
                        return;
                    }
                    if (m_HGService == null)
                    {
                        m_log.Error("[HG INVENTORY CONNECTOR]: Can't load hypergrid inventory service");
                        return;
                    }

                    m_LocalGridInventoryURI = inventoryConfig.GetString("InventoryServerURI", string.Empty);

                    m_Enabled = true;
                    m_log.Info("[HG INVENTORY CONNECTOR]: HG inventory broker enabled");
                }
            }
        }
예제 #13
0
        public UserAgentService(IConfigSource config, IFriendsSimConnector friendsConnector)
            : base(config)
        {
            // Let's set this always, because we don't know the sequence
            // of instantiations
            if (friendsConnector != null)
            {
                m_FriendsLocalSimConnector = friendsConnector;
            }

            if (!m_Initialized)
            {
                m_Initialized = true;

                m_log.DebugFormat("[HOME USERS SECURITY]: Starting...");

                m_FriendsSimConnector = new FriendsSimConnector();

                IConfig serverConfig = config.Configs["UserAgentService"];
                if (serverConfig == null)
                {
                    throw new Exception(String.Format("No section UserAgentService in config file"));
                }

                string gridService        = serverConfig.GetString("GridService", String.Empty);
                string gridUserService    = serverConfig.GetString("GridUserService", String.Empty);
                string gatekeeperService  = serverConfig.GetString("GatekeeperService", String.Empty);
                string friendsService     = serverConfig.GetString("FriendsService", String.Empty);
                string presenceService    = serverConfig.GetString("PresenceService", String.Empty);
                string userAccountService = serverConfig.GetString("UserAccountService", String.Empty);

                m_BypassClientVerification = serverConfig.GetBoolean("BypassClientVerification", false);

                if (gridService == string.Empty || gridUserService == string.Empty || gatekeeperService == string.Empty)
                {
                    throw new Exception(String.Format("Incomplete specifications, UserAgent Service cannot function."));
                }

                Object[] args = new Object[] { config };
                m_GridService         = ServerUtils.LoadPlugin <IGridService>(gridService, args);
                m_GridUserService     = ServerUtils.LoadPlugin <IGridUserService>(gridUserService, args);
                m_GatekeeperConnector = new GatekeeperServiceConnector();
                m_GatekeeperService   = ServerUtils.LoadPlugin <IGatekeeperService>(gatekeeperService, args);
                m_FriendsService      = ServerUtils.LoadPlugin <IFriendsService>(friendsService, args);
                m_PresenceService     = ServerUtils.LoadPlugin <IPresenceService>(presenceService, args);
                m_UserAccountService  = ServerUtils.LoadPlugin <IUserAccountService>(userAccountService, args);

                m_LevelOutsideContacts = serverConfig.GetInt("LevelOutsideContacts", 0);

                LoadTripPermissionsFromConfig(serverConfig, "ForeignTripsAllowed");
                LoadDomainExceptionsFromConfig(serverConfig, "AllowExcept", m_TripsAllowedExceptions);
                LoadDomainExceptionsFromConfig(serverConfig, "DisallowExcept", m_TripsDisallowedExceptions);

                m_GridName = Util.GetConfigVarFromSections <string>(config, "GatekeeperURI",
                                                                    new string[] { "Startup", "Hypergrid", "UserAgentService" }, String.Empty);
                if (string.IsNullOrEmpty(m_GridName)) // Legacy. Remove soon.
                {
                    m_GridName = serverConfig.GetString("ExternalName", string.Empty);
                    if (m_GridName == string.Empty)
                    {
                        serverConfig = config.Configs["GatekeeperService"];
                        m_GridName   = serverConfig.GetString("ExternalName", string.Empty);
                    }
                }

                if (!m_GridName.EndsWith("/"))
                {
                    m_GridName = m_GridName + "/";
                }

                // Finally some cleanup
                m_Database.DeleteOld();
            }
        }
예제 #14
0
        /// <summary>
        /// Performs startup specific to the region server, including initialization of the scene
        /// such as loading configuration from disk.
        /// </summary>
        protected override void StartupSpecific()
        {
            IConfig startupConfig = Config.Configs["Startup"];

            if (startupConfig != null)
            {
                string pidFile = startupConfig.GetString("PIDFile", String.Empty);
                if (pidFile != String.Empty)
                {
                    CreatePIDFile(pidFile);
                }

                userStatsURI    = startupConfig.GetString("Stats_URI", String.Empty);
                managedStatsURI = startupConfig.GetString("ManagedStatsRemoteFetchURI", String.Empty);
            }

            // Load the simulation data service
            IConfig simDataConfig = Config.Configs["SimulationDataStore"];

            if (simDataConfig == null)
            {
                throw new Exception("Configuration file is missing the [SimulationDataStore] section.  Have you copied OpenSim.ini.example to OpenSim.ini to reference config-include/ files?");
            }

            string module = simDataConfig.GetString("LocalServiceModule", String.Empty);

            if (String.IsNullOrEmpty(module))
            {
                throw new Exception("Configuration file is missing the LocalServiceModule parameter in the [SimulationDataStore] section.");
            }

            m_simulationDataService = ServerUtils.LoadPlugin <ISimulationDataService>(module, new object[] { Config });
            if (m_simulationDataService == null)
            {
                throw new Exception(
                          string.Format(
                              "Could not load an ISimulationDataService implementation from {0}, as configured in the LocalServiceModule parameter of the [SimulationDataStore] config section.",
                              module));
            }

            // Load the estate data service
            module = Util.GetConfigVarFromSections <string>(Config, "LocalServiceModule", new string[] { "EstateDataStore", "EstateService" }, String.Empty);
            if (String.IsNullOrEmpty(module))
            {
                throw new Exception("Configuration file is missing the LocalServiceModule parameter in the [EstateDataStore] or [EstateService] section");
            }

            if (LoadEstateDataService)
            {
                m_estateDataService = ServerUtils.LoadPlugin <IEstateDataService>(module, new object[] { Config });
                if (m_estateDataService == null)
                {
                    throw new Exception(
                              string.Format(
                                  "Could not load an IEstateDataService implementation from {0}, as configured in the LocalServiceModule parameter of the [EstateDataStore] config section.",
                                  module));
                }
            }

            base.StartupSpecific();

            if (EnableInitialPluginLoad)
            {
                LoadPlugins();
            }

            // We still want to post initalize any plugins even if loading has been disabled since a test may have
            // inserted them manually.
            foreach (IApplicationPlugin plugin in m_plugins)
            {
                plugin.PostInitialise();
            }

            if (m_console != null)
            {
                AddPluginCommands(m_console);
            }
        }
        /// <summary>
        /// Publishes a value.
        /// </summary>
        private void Publish(
            OperationContext context,
            DataValue value,
            ServiceResult error,
            Queue <MonitoredItemNotification> notifications,
            Queue <DiagnosticInfo> diagnostics)
        {
            // set semantics changed bit.
            if (m_semanticsChanged)
            {
                if (value != null)
                {
                    value.StatusCode = value.StatusCode.SetSemanticsChanged(true);
                }

                if (error != null)
                {
                    error = new ServiceResult(
                        error.StatusCode.SetSemanticsChanged(true),
                        error.SymbolicId,
                        error.NamespaceUri,
                        error.LocalizedText,
                        error.AdditionalInfo,
                        error.InnerResult);
                }

                m_semanticsChanged = false;
            }

            // set structure changed bit.
            if (m_structureChanged)
            {
                if (value != null)
                {
                    value.StatusCode = value.StatusCode.SetStructureChanged(true);
                }

                if (error != null)
                {
                    error = new ServiceResult(
                        error.StatusCode.SetStructureChanged(true),
                        error.SymbolicId,
                        error.NamespaceUri,
                        error.LocalizedText,
                        error.AdditionalInfo,
                        error.InnerResult);
                }

                m_structureChanged = false;
            }

            // copy data value.
            MonitoredItemNotification item = new MonitoredItemNotification();

            item.ClientHandle = m_clientHandle;
            item.Value        = value;

            // apply timestamp filter.
            if (m_timestampsToReturn != TimestampsToReturn.Server && m_timestampsToReturn != TimestampsToReturn.Both)
            {
                item.Value.ServerTimestamp = DateTime.MinValue;
            }

            if (m_timestampsToReturn != TimestampsToReturn.Source && m_timestampsToReturn != TimestampsToReturn.Both)
            {
                item.Value.SourceTimestamp = DateTime.MinValue;
            }

            notifications.Enqueue(item);

            // update diagnostic info.
            DiagnosticInfo diagnosticInfo = null;

            if (m_lastError != null)
            {
                if ((m_diagnosticsMasks & DiagnosticsMasks.OperationAll) != 0)
                {
                    diagnosticInfo = ServerUtils.CreateDiagnosticInfo(m_source.Server, context, m_lastError);
                }
            }

            diagnostics.Enqueue(diagnosticInfo);
        }
        public GridRegion GetRegionByName(UUID scopeID, string regionName)
        {
            Dictionary <string, object> sendData = new Dictionary <string, object>();

            sendData["SCOPEID"] = scopeID.ToString();
            sendData["NAME"]    = regionName;

            sendData["METHOD"] = "get_region_by_name";
            string reply = string.Empty;
            string uri   = m_ServerURI + "/grid";

            try
            {
                reply = SynchronousRestFormsRequester.MakeRequest("POST",
                                                                  uri,
                                                                  ServerUtils.BuildQueryString(sendData), m_Auth);
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
                return(null);
            }

            GridRegion rinfo = null;

            if (reply != string.Empty)
            {
                Dictionary <string, object> replyData = ServerUtils.ParseXmlResponse(reply);

                if ((replyData != null) && (replyData["result"] != null))
                {
                    if (replyData["result"] is Dictionary <string, object> )
                    {
                        rinfo = new GridRegion((Dictionary <string, object>)replyData["result"]);
                    }
                }
                else
                {
                    m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1} received null response",
                                      scopeID, regionName);
                }
            }
            else
            {
                m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByName received null reply");
            }

            if (rinfo != null)
            {
                try
                {
                    if (!Uri.IsWellFormedUriString(rinfo.ServerURI, UriKind.Absolute) ||
                        rinfo.ExternalEndPoint.Port == 0 ||
                        rinfo.HttpPort == 0)
                    {
                        return(null);
                    }
                }
                catch
                {
                    return(null);
                }
            }

            return(rinfo);
        }
        protected override byte[] ProcessRequest(string path, Stream requestData,
                                                 IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            StreamReader sr   = new StreamReader(requestData);
            string       body = sr.ReadToEnd();

            sr.Close();
            body = body.Trim();

            //m_log.DebugFormat("[XXX]: query String: {0}", body);

            try
            {
                Dictionary <string, object> request =
                    ServerUtils.ParseQueryString(body);

                if (!request.ContainsKey("METHOD"))
                {
                    return(FailureResult());
                }

                string method = request["METHOD"].ToString();
                request.Remove("METHOD");

                switch (method)
                {
                case "CREATEUSERINVENTORY":
                    return(HandleCreateUserInventory(request));

                case "GETINVENTORYSKELETON":
                    return(HandleGetInventorySkeleton(request));

                case "GETUSERINVENTORY":
                    return(HandleGetUserInventory(request));

                case "GETROOTFOLDER":
                    return(HandleGetRootFolder(request));

                case "GETFOLDERFORTYPE":
                    return(HandleGetFolderForType(request));

                case "GETFOLDERCONTENT":
                    return(HandleGetFolderContent(request));

                case "GETFOLDERITEMS":
                    return(HandleGetFolderItems(request));

                case "ADDFOLDER":
                    return(HandleAddFolder(request));

                case "UPDATEFOLDER":
                    return(HandleUpdateFolder(request));

                case "MOVEFOLDER":
                    return(HandleMoveFolder(request));

                case "DELETEFOLDERS":
                    return(HandleDeleteFolders(request));

                case "PURGEFOLDER":
                    return(HandlePurgeFolder(request));

                case "ADDITEM":
                    return(HandleAddItem(request));

                case "UPDATEITEM":
                    return(HandleUpdateItem(request));

                case "MOVEITEMS":
                    return(HandleMoveItems(request));

                case "DELETEITEMS":
                    return(HandleDeleteItems(request));

                case "GETITEM":
                    return(HandleGetItem(request));

                case "GETFOLDER":
                    return(HandleGetFolder(request));

                case "GETACTIVEGESTURES":
                    return(HandleGetActiveGestures(request));

                case "GETASSETPERMISSIONS":
                    return(HandleGetAssetPermissions(request));
                }
                m_log.DebugFormat("[XINVENTORY HANDLER]: unknown method request: {0}", method);
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[XINVENTORY HANDLER]: Exception {0}", e.StackTrace);
            }

            return(FailureResult());
        }
        public List <GridRegion> GetHyperlinks(UUID scopeID)
        {
            Dictionary <string, object> sendData = new Dictionary <string, object>();

            sendData["SCOPEID"] = scopeID.ToString();

            sendData["METHOD"] = "get_hyperlinks";

            List <GridRegion> rinfos = new List <GridRegion>();
            string            reply  = string.Empty;
            string            uri    = m_ServerURI + "/grid";

            try
            {
                reply = SynchronousRestFormsRequester.MakeRequest("POST",
                                                                  uri,
                                                                  ServerUtils.BuildQueryString(sendData), m_Auth);

                //m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
                return(rinfos);
            }

            if (reply != string.Empty)
            {
                Dictionary <string, object> replyData = ServerUtils.ParseXmlResponse(reply);

                if (replyData != null)
                {
                    Dictionary <string, object> .ValueCollection rinfosList = replyData.Values;
                    foreach (object r in rinfosList)
                    {
                        if (r is Dictionary <string, object> )
                        {
                            GridRegion rinfo = new GridRegion((Dictionary <string, object>)r);
                            try
                            {
                                if (Uri.IsWellFormedUriString(rinfo.ServerURI, UriKind.Absolute) &&
                                    rinfo.ExternalEndPoint.Port != 0 &&
                                    rinfo.HttpPort != 0)
                                {
                                    rinfos.Add(rinfo);
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                }
                else
                {
                    m_log.DebugFormat("[GRID CONNECTOR]: GetHyperlinks {0} received null response",
                                      scopeID);
                }
            }
            else
            {
                m_log.DebugFormat("[GRID CONNECTOR]: GetHyperlinks received null reply");
            }

            return(rinfos);
        }
예제 #19
0
        public string RegisterRegion(UUID scopeID, GridRegion regionInfo)
        {
            Dictionary <string, object> rinfo    = regionInfo.ToKeyValuePairs();
            Dictionary <string, object> sendData = new Dictionary <string, object>();

            foreach (KeyValuePair <string, object> kvp in rinfo)
            {
                sendData[kvp.Key] = (string)kvp.Value;
            }

            sendData["SCOPEID"]    = scopeID.ToString();
            sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
            sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
            sendData["METHOD"]     = "register";

            string reqString = ServerUtils.BuildQueryString(sendData);
            string uri       = m_ServerURI + "/grid";

            // m_log.DebugFormat("[GRID CONNECTOR]: queryString = {0}", reqString);
            try
            {
                string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth);
                if (reply != string.Empty)
                {
                    Dictionary <string, object> replyData = ServerUtils.ParseXmlResponse(reply);

                    if (replyData.ContainsKey("Result") && (replyData["Result"].ToString().ToLower() == "success"))
                    {
                        return(String.Empty);
                    }
                    else if (replyData.ContainsKey("Result") && (replyData["Result"].ToString().ToLower() == "failure"))
                    {
                        m_log.ErrorFormat(
                            "[GRID CONNECTOR]: Registration failed: {0} when contacting {1}", replyData["Message"], uri);

                        return(replyData["Message"].ToString());
                    }
                    else if (!replyData.ContainsKey("Result"))
                    {
                        m_log.ErrorFormat(
                            "[GRID CONNECTOR]: reply data does not contain result field when contacting {0}", uri);
                    }
                    else
                    {
                        m_log.ErrorFormat(
                            "[GRID CONNECTOR]: unexpected result {0} when contacting {1}", replyData["Result"], uri);

                        return("Unexpected result " + replyData["Result"].ToString());
                    }
                }
                else
                {
                    m_log.ErrorFormat(
                        "[GRID CONNECTOR]: RegisterRegion received null reply when contacting grid server at {0}", uri);
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[GRID CONNECTOR]: Exception when contacting grid server at {0}: {1}", uri, e.Message);
            }

            return(string.Format("Error communicating with the grid service at {0}", uri));
        }
예제 #20
0
 public static Type GetTypeByTypeName(string typeName)
 {
     return(ServerUtils.Single(i => i.TypeName.Equals(typeName)).ServerType);
 }
        protected override byte[] ProcessRequest(string path, Stream requestData,
                                                 IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            StreamReader sr   = new StreamReader(requestData);
            string       body = sr.ReadToEnd();

            sr.Close();
            body = body.Trim();

            //m_log.DebugFormat("[XXX]: query String: {0}", body);

            try
            {
                Dictionary <string, object> request =
                    ServerUtils.ParseQueryString(body);

                if (!request.ContainsKey("METHOD"))
                {
                    return(FailureResult());
                }

                string method = request["METHOD"].ToString();

                switch (method)
                {
                case "getfriendperms":
                    return(GetFriendPerms(request));

                case "newfriendship":
                    return(NewFriendship(request));

                case "deletefriendship":
                    return(DeleteFriendship(request));

                /* Same as inter-sim */
                case "friendship_offered":
                    return(FriendshipOffered(request));

                case "validate_friendship_offered":
                    return(ValidateFriendshipOffered(request));

                case "statusnotification":
                    return(StatusNotification(request));

                    /*
                     * case "friendship_approved":
                     *  return FriendshipApproved(request);
                     *
                     * case "friendship_denied":
                     *  return FriendshipDenied(request);
                     *
                     * case "friendship_terminated":
                     *  return FriendshipTerminated(request);
                     *
                     * case "grant_rights":
                     *  return GrantRights(request);
                     */
                }

                m_log.DebugFormat("[HGFRIENDS HANDLER]: unknown method {0}", method);
            }
            catch (Exception e)
            {
                m_log.DebugFormat("[HGFRIENDS HANDLER]: Exception {0}", e);
            }

            return(FailureResult());
        }
예제 #22
0
        public void Initialise(IConfigSource source)
        {
            IConfig moduleConfig = source.Configs["Modules"];

            if (moduleConfig != null)
            {
                string name = moduleConfig.GetString("AssetServices", "");
                if (name == Name)
                {
                    IConfig assetConfig = source.Configs["AssetService"];
                    if (assetConfig == null)
                    {
                        m_log.Error("[HG ASSET CONNECTOR]: AssetService missing from OpenSim.ini");
                        return;
                    }

                    string localDll = assetConfig.GetString("LocalGridAssetService",
                                                            String.Empty);
                    string HGDll = assetConfig.GetString("HypergridAssetService",
                                                         String.Empty);

                    if (localDll == String.Empty)
                    {
                        m_log.Error("[HG ASSET CONNECTOR]: No LocalGridAssetService named in section AssetService");
                        return;
                    }

                    if (HGDll == String.Empty)
                    {
                        m_log.Error("[HG ASSET CONNECTOR]: No HypergridAssetService named in section AssetService");
                        return;
                    }

                    Object[] args = new Object[] { source };
                    m_GridService =
                        ServerUtils.LoadPlugin <IAssetService>(localDll,
                                                               args);

                    m_HGService =
                        ServerUtils.LoadPlugin <IAssetService>(HGDll,
                                                               args);

                    if (m_GridService == null)
                    {
                        m_log.Error("[HG ASSET CONNECTOR]: Can't load local asset service");
                        return;
                    }
                    if (m_HGService == null)
                    {
                        m_log.Error("[HG ASSET CONNECTOR]: Can't load hypergrid asset service");
                        return;
                    }

                    m_LocalAssetServiceURI = assetConfig.GetString("AssetServerURI", string.Empty);
                    if (m_LocalAssetServiceURI == string.Empty)
                    {
                        IConfig netConfig = source.Configs["Network"];
                        m_LocalAssetServiceURI = netConfig.GetString("asset_server_url", string.Empty);
                    }

                    if (m_LocalAssetServiceURI != string.Empty)
                    {
                        m_LocalAssetServiceURI = m_LocalAssetServiceURI.Trim('/');
                    }

                    IConfig hgConfig = source.Configs["HGAssetService"];
                    m_AssetPerms = new AssetPermissions(hgConfig); // it's ok if arg is null

                    m_Enabled = true;
                    m_log.Info("[HG ASSET CONNECTOR]: HG asset broker enabled");
                }
            }
        }
        public void InitialiseService(IConfigSource source)
        {
            ConfigName = "UserProfilesService";

            // Instantiate the request handler
            IHttpServer Server = MainServer.Instance;

            IConfig config = source.Configs[ConfigName];

            if (config == null)
            {
                //m_log.Error("[LOCAL USERPROFILES SERVICE CONNECTOR]: UserProfilesService missing from OpenSim.ini");
                return;
            }

            if (!config.GetBoolean("Enabled", false))
            {
                Enabled = false;
                return;
            }

            Enabled = true;

            string serviceDll = config.GetString("LocalServiceModule", String.Empty);

            if (serviceDll == String.Empty)
            {
                m_log.Error("[LOCAL USERPROFILES SERVICE CONNECTOR]: No LocalServiceModule named in section UserProfilesService");
                return;
            }

            Object[] args = new Object[] { source, ConfigName };
            ServiceModule = ServerUtils.LoadPlugin <IUserProfilesService>(serviceDll, args);

            if (ServiceModule == null)
            {
                m_log.Error("[LOCAL USERPROFILES SERVICE CONNECTOR]: Can't load user profiles service");
                return;
            }

            Enabled = true;

            JsonRpcProfileHandlers handler = new JsonRpcProfileHandlers(ServiceModule);

            Server.AddJsonRPCHandler("avatarclassifiedsrequest", handler.AvatarClassifiedsRequest);
            Server.AddJsonRPCHandler("classified_update", handler.ClassifiedUpdate);
            Server.AddJsonRPCHandler("classifieds_info_query", handler.ClassifiedInfoRequest);
            Server.AddJsonRPCHandler("classified_delete", handler.ClassifiedDelete);
            Server.AddJsonRPCHandler("avatarpicksrequest", handler.AvatarPicksRequest);
            Server.AddJsonRPCHandler("pickinforequest", handler.PickInfoRequest);
            Server.AddJsonRPCHandler("picks_update", handler.PicksUpdate);
            Server.AddJsonRPCHandler("picks_delete", handler.PicksDelete);
            Server.AddJsonRPCHandler("avatarnotesrequest", handler.AvatarNotesRequest);
            Server.AddJsonRPCHandler("avatar_notes_update", handler.NotesUpdate);
            Server.AddJsonRPCHandler("avatar_properties_request", handler.AvatarPropertiesRequest);
            Server.AddJsonRPCHandler("avatar_properties_update", handler.AvatarPropertiesUpdate);
            Server.AddJsonRPCHandler("avatar_interests_update", handler.AvatarInterestsUpdate);
            Server.AddJsonRPCHandler("user_preferences_update", handler.UserPreferenecesUpdate);
            Server.AddJsonRPCHandler("user_preferences_request", handler.UserPreferencesRequest);
            Server.AddJsonRPCHandler("image_assets_request", handler.AvatarImageAssetsRequest);
            Server.AddJsonRPCHandler("user_data_request", handler.RequestUserAppData);
            Server.AddJsonRPCHandler("user_data_update", handler.UpdateUserAppData);
        }
예제 #24
0
        protected override byte[] ProcessRequest(string path, Stream requestData,
                                                 IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            string body;

            using (StreamReader sr = new StreamReader(requestData))
                body = sr.ReadToEnd();

            body = body.Trim();

            //m_log.DebugFormat("[XXX]: query String: {0}", body);

            try
            {
                Dictionary <string, object> request =
                    ServerUtils.ParseQueryString(body);

                if (!request.ContainsKey("METHOD"))
                {
                    return(FailureResult());
                }

                string method = request["METHOD"].ToString();
                request.Remove("METHOD");

                m_log.DebugFormat("[Groups.RobustHGConnector]: {0}", method);
                switch (method)
                {
                case "POSTGROUP":
                    return(HandleAddGroupProxy(request));

                case "REMOVEAGENTFROMGROUP":
                    return(HandleRemoveAgentFromGroup(request));

                case "GETGROUP":
                    return(HandleGetGroup(request));

                case "ADDNOTICE":
                    return(HandleAddNotice(request));

                case "VERIFYNOTICE":
                    return(HandleVerifyNotice(request));

                case "GETGROUPMEMBERS":
                    return(HandleGetGroupMembers(request));

                case "GETGROUPROLES":
                    return(HandleGetGroupRoles(request));

                case "GETROLEMEMBERS":
                    return(HandleGetRoleMembers(request));
                }
                m_log.DebugFormat("[Groups.RobustHGConnector]: unknown method request: {0}", method);
            }
            catch (Exception e)
            {
                m_log.Error(string.Format("[Groups.RobustHGConnector]: Exception {0} ", e.Message), e);
            }

            return(FailureResult());
        }
        public bool AddMapTile(int x, int y, byte[] jpgData, UUID scopeID, out string reason)
        {
            reason = string.Empty;
            int tickstart = Util.EnvironmentTickCount();
            Dictionary <string, object> sendData = new Dictionary <string, object>();

            sendData["X"]     = x.ToString();
            sendData["Y"]     = y.ToString();
            sendData["SCOPE"] = scopeID.ToString();
            sendData["TYPE"]  = "image/jpeg";
            sendData["DATA"]  = Convert.ToBase64String(jpgData);

            string reqString = ServerUtils.BuildQueryString(sendData);
            string uri       = m_ServerURI + "/map";

            try
            {
                string reply = SynchronousRestFormsRequester.MakeRequest("POST",
                                                                         uri,
                                                                         reqString,
                                                                         30,
                                                                         m_Auth);
                if (reply != string.Empty)
                {
                    Dictionary <string, object> replyData = ServerUtils.ParseXmlResponse(reply);

                    if (replyData.ContainsKey("Result") && (replyData["Result"].ToString().ToLower() == "success"))
                    {
                        return(true);
                    }
                    else if (replyData.ContainsKey("Result") && (replyData["Result"].ToString().ToLower() == "failure"))
                    {
                        reason = string.Format("Map post to {0} failed: {1}", uri, replyData["Message"].ToString());
                        m_log.WarnFormat("[MAP IMAGE CONNECTOR]: {0}", reason);

                        return(false);
                    }
                    else if (!replyData.ContainsKey("Result"))
                    {
                        reason = string.Format("Reply data from {0} does not contain result field", uri);
                        m_log.WarnFormat("[MAP IMAGE CONNECTOR]: {0}", reason);
                    }
                    else
                    {
                        reason = string.Format("Unexpected result {0} from {1}" + replyData["Result"].ToString(), uri);
                        m_log.WarnFormat("[MAP IMAGE CONNECTOR]: {0}", reason);
                    }
                }
                else
                {
                    reason = string.Format("Map post received null reply from {0}", uri);
                    m_log.WarnFormat("[MAP IMAGE CONNECTOR]: {0}", reason);
                }
            }
            catch (Exception e)
            {
                reason = string.Format("Exception when posting to map server at {0}: {1}", uri, e.Message);
                m_log.WarnFormat("[MAP IMAGE CONNECTOR]: {0}", reason);
            }
            finally
            {
                // This just dumps a warning for any operation that takes more than 100 ms
                int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
                m_log.DebugFormat("[MAP IMAGE CONNECTOR]: map tile upload time {0}ms", tickdiff);
            }

            return(false);
        }
예제 #26
0
        public void Initialise(IConfigSource config)
        {
            m_Config = config.Configs["FreeSwitchVoice"];

            if (m_Config == null)
            {
                return;
            }

            if (!m_Config.GetBoolean("Enabled", false))
            {
                return;
            }

            try
            {
                string serviceDll = m_Config.GetString("LocalServiceModule",
                                                       String.Empty);

                if (serviceDll == String.Empty)
                {
                    m_log.Error("[FreeSwitchVoice]: No LocalServiceModule named in section FreeSwitchVoice.  Not starting.");
                    return;
                }

                Object[] args = new Object[] { config };
                m_FreeswitchService = ServerUtils.LoadPlugin <IFreeswitchService>(serviceDll, args);

                string jsonConfig = m_FreeswitchService.GetJsonConfig();
                //m_log.Debug("[FreeSwitchVoice]: Configuration string: " + jsonConfig);
                OSDMap map = (OSDMap)OSDParser.DeserializeJson(jsonConfig);

                m_freeSwitchAPIPrefix          = map["APIPrefix"].AsString();
                m_freeSwitchRealm              = map["Realm"].AsString();
                m_freeSwitchSIPProxy           = map["SIPProxy"].AsString();
                m_freeSwitchAttemptUseSTUN     = map["AttemptUseSTUN"].AsBoolean();
                m_freeSwitchEchoServer         = map["EchoServer"].AsString();
                m_freeSwitchEchoPort           = map["EchoPort"].AsInteger();
                m_freeSwitchDefaultWellKnownIP = map["DefaultWellKnownIP"].AsString();
                m_freeSwitchDefaultTimeout     = map["DefaultTimeout"].AsInteger();
                m_freeSwitchUrlResetPassword   = String.Empty;
//                m_freeSwitchContext = map["Context"].AsString();

                if (String.IsNullOrEmpty(m_freeSwitchRealm) ||
                    String.IsNullOrEmpty(m_freeSwitchAPIPrefix))
                {
                    m_log.Error("[FreeSwitchVoice]: Freeswitch service mis-configured.  Not starting.");
                    return;
                }

                // set up http request handlers for
                // - prelogin: viv_get_prelogin.php
                // - signin: viv_signin.php
                // - buddies: viv_buddy.php
                // - ???: viv_watcher.php
                // - signout: viv_signout.php
                MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_get_prelogin.php", m_freeSwitchAPIPrefix),
                                                   FreeSwitchSLVoiceGetPreloginHTTPHandler);

                MainServer.Instance.AddHTTPHandler(String.Format("{0}/freeswitch-config", m_freeSwitchAPIPrefix), FreeSwitchConfigHTTPHandler);

                // RestStreamHandler h = new
                // RestStreamHandler("GET",
                // String.Format("{0}/viv_get_prelogin.php", m_freeSwitchAPIPrefix), FreeSwitchSLVoiceGetPreloginHTTPHandler);
                //  MainServer.Instance.AddStreamHandler(h);

                MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_signin.php", m_freeSwitchAPIPrefix),
                                                   FreeSwitchSLVoiceSigninHTTPHandler);

                MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_buddy.php", m_freeSwitchAPIPrefix),
                                                   FreeSwitchSLVoiceBuddyHTTPHandler);

                MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_watcher.php", m_freeSwitchAPIPrefix),
                                                   FreeSwitchSLVoiceWatcherHTTPHandler);

                m_log.InfoFormat("[FreeSwitchVoice]: using FreeSwitch server {0}", m_freeSwitchRealm);

                m_Enabled = true;

                m_log.Info("[FreeSwitchVoice]: plugin enabled");
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[FreeSwitchVoice]: plugin initialization failed: {0} {1}", e.Message, e.StackTrace);
                return;
            }

            // This here is a region module trying to make a global setting.
            // Not really a good idea but it's Windows only, so I can't test.
            try
            {
                ServicePointManager.ServerCertificateValidationCallback += CustomCertificateValidation;
            }
            catch (NotImplementedException)
            {
                try
                {
#pragma warning disable 0612, 0618
                    // Mono does not implement the ServicePointManager.ServerCertificateValidationCallback yet!  Don't remove this!
                    ServicePointManager.CertificatePolicy = new MonoCert();
#pragma warning restore 0612, 0618
                }
                catch (Exception)
                {
                    // COmmented multiline spam log message
                    //m_log.Error("[FreeSwitchVoice]: Certificate validation handler change not supported.  You may get ssl certificate validation errors teleporting from your region to some SSL regions.");
                }
            }
        }
예제 #27
0
        private byte[] ResultToBytes(Dictionary <string, object> result)
        {
            string xmlString = ServerUtils.BuildXmlResponse(result);

            return(Util.UTF8NoBomEncoding.GetBytes(xmlString));
        }
        public GatekeeperService(IConfigSource config, ISimulationService simService)
        {
            if (!m_Initialized)
            {
                m_Initialized = true;

                IConfig serverConfig = config.Configs["GatekeeperService"];
                if (serverConfig == null)
                {
                    throw new Exception(String.Format("No section GatekeeperService in config file"));
                }

                string accountService    = serverConfig.GetString("UserAccountService", String.Empty);
                string homeUsersService  = serverConfig.GetString("UserAgentService", string.Empty);
                string gridService       = serverConfig.GetString("GridService", String.Empty);
                string presenceService   = serverConfig.GetString("PresenceService", String.Empty);
                string simulationService = serverConfig.GetString("SimulationService", String.Empty);
                string gridUserService   = serverConfig.GetString("GridUserService", String.Empty);
                string bansService       = serverConfig.GetString("BansService", String.Empty);

                // These are mandatory, the others aren't
                if (gridService == string.Empty || presenceService == string.Empty)
                {
                    throw new Exception("Incomplete specifications, Gatekeeper Service cannot function.");
                }

                string scope = serverConfig.GetString("ScopeID", UUID.Zero.ToString());
                UUID.TryParse(scope, out m_ScopeID);
                //m_WelcomeMessage = serverConfig.GetString("WelcomeMessage", "Welcome to OpenSim!");
                m_AllowTeleportsToAnyRegion = serverConfig.GetBoolean("AllowTeleportsToAnyRegion", true);
                m_ExternalName = Util.GetConfigVarFromSections <string>(config, "GatekeeperURI",
                                                                        new string[] { "Startup", "Hypergrid", "GatekeeperService" }, String.Empty);
                m_ExternalName = serverConfig.GetString("ExternalName", m_ExternalName);
                if (m_ExternalName != string.Empty && !m_ExternalName.EndsWith("/"))
                {
                    m_ExternalName = m_ExternalName + "/";
                }

                try
                {
                    m_Uri = new Uri(m_ExternalName);
                }
                catch
                {
                    m_log.WarnFormat("[GATEKEEPER SERVICE]: Malformed gatekeeper address {0}", m_ExternalName);
                }

                Object[] args = new Object[] { config };
                m_GridService     = ServerUtils.LoadPlugin <IGridService>(gridService, args);
                m_PresenceService = ServerUtils.LoadPlugin <IPresenceService>(presenceService, args);

                if (accountService != string.Empty)
                {
                    m_UserAccountService = ServerUtils.LoadPlugin <IUserAccountService>(accountService, args);
                }
                if (homeUsersService != string.Empty)
                {
                    m_UserAgentService = ServerUtils.LoadPlugin <IUserAgentService>(homeUsersService, args);
                }
                if (gridUserService != string.Empty)
                {
                    m_GridUserService = ServerUtils.LoadPlugin <IGridUserService>(gridUserService, args);
                }
                if (bansService != string.Empty)
                {
                    m_BansService = ServerUtils.LoadPlugin <IBansService>(bansService, args);
                }

                if (simService != null)
                {
                    m_SimulationService = simService;
                }
                else if (simulationService != string.Empty)
                {
                    m_SimulationService = ServerUtils.LoadPlugin <ISimulationService>(simulationService, args);
                }

                m_AllowedClients       = serverConfig.GetString("AllowedClients", string.Empty);
                m_DeniedClients        = serverConfig.GetString("DeniedClients", string.Empty);
                m_ForeignAgentsAllowed = serverConfig.GetBoolean("ForeignAgentsAllowed", true);

                LoadDomainExceptionsFromConfig(serverConfig, "AllowExcept", m_ForeignsAllowedExceptions);
                LoadDomainExceptionsFromConfig(serverConfig, "DisallowExcept", m_ForeignsDisallowedExceptions);

                if (m_GridService == null || m_PresenceService == null || m_SimulationService == null)
                {
                    throw new Exception("Unable to load a required plugin, Gatekeeper Service cannot function.");
                }

                m_log.Debug("[GATEKEEPER SERVICE]: Starting...");
            }
        }
예제 #29
0
        ///<summary>
        ///
        ///</summary>
        public void Initialise(IConfigSource source)
        {
            IConfig moduleConfig = source.Configs["Modules"];

            if (moduleConfig != null)
            {
                string name = moduleConfig.GetString("MapImageService", "");
                if (name != Name)
                {
                    return;
                }
            }

            IConfig config = source.Configs["MapImageService"];

            if (config == null)
            {
                return;
            }

            int refreshminutes = Convert.ToInt32(config.GetString("RefreshTime"));

            // if refresh is less than zero, disable the module
            if (refreshminutes < 0)
            {
                m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: Negative refresh time given in config. Module disabled.");
                return;
            }

            string service = config.GetString("LocalServiceModule", string.Empty);

            if (service == string.Empty)
            {
                m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: No service dll given in config. Unable to proceed.");
                return;
            }

            Object[] args = new Object[] { source };
            m_MapService = ServerUtils.LoadPlugin <IMapImageService>(service, args);
            if (m_MapService == null)
            {
                m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: Unable to load LocalServiceModule from {0}. MapService module disabled. Please fix the configuration.", service);
                return;
            }

            // we don't want the timer if the interval is zero, but we still want this module enables
            if (refreshminutes > 0)
            {
                m_refreshtime = refreshminutes * 60 * 1000; // convert from minutes to ms

                m_refreshTimer           = new System.Timers.Timer();
                m_refreshTimer.Enabled   = true;
                m_refreshTimer.AutoReset = true;
                m_refreshTimer.Interval  = m_refreshtime;
                m_refreshTimer.Elapsed  += new ElapsedEventHandler(HandleMaptileRefresh);

                m_log.InfoFormat("[MAP IMAGE SERVICE MODULE]: enabled with refresh time {0} min and service object {1}",
                                 refreshminutes, service);
            }
            else
            {
                m_log.InfoFormat("[MAP IMAGE SERVICE MODULE]: enabled with no refresh and service object {0}", service);
            }
            m_enabled = true;
        }
예제 #30
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.MediaViewerActivity);

            string json       = Intent.GetStringExtra("JSON") ?? "";
            int    activityId = Intent.GetIntExtra("ACT_ID", -1);

            resIndex = Intent.GetIntExtra("RES_INDEX", -1);

            if (string.IsNullOrWhiteSpace(json))
            {
                return;
            }

            AppTask thisTask = JsonConvert.DeserializeObject <AppTask>(json);

            taskId = thisTask.Id;

            SupportActionBar.Show();
            SupportActionBar.Title = thisTask.Description;

            string[] results = null;

            if (thisTask.CompletionData?.JsonData != null)
            {
                results = JsonConvert.DeserializeObject <string[]>(thisTask.CompletionData?.JsonData);
            }

            taskType = thisTask.TaskType.IdName;

            Dictionary <string, string> properties = new Dictionary <string, string>
            {
                { "TaskId", taskId.ToString() },
                { "TaskType", taskType }
            };

            Analytics.TrackEvent("MediaViewerActivity", properties);

            if (new string[] { "TAKE_VIDEO", "REC_AUDIO", "LISTEN_AUDIO" }.Contains(taskType))
            {
                if (taskType == "LISTEN_AUDIO" || taskType == "REC_AUDIO")
                {
                    ImageViewAsync imageView = FindViewById <ImageViewAsync>(Resource.Id.speakerImage);
                    imageView.Visibility = ViewStates.Visible;
                }

                global::Android.Net.Uri uri = null;

                if (taskType == "LISTEN_AUDIO")
                {
                    string localRes = Storage.GetCacheFilePath(
                        thisTask.JsonData,
                        activityId,
                        ServerUtils.GetFileExtension(taskType));
                    uri = global::Android.Net.Uri.Parse(localRes);
                }
                else
                {
                    if (results != null)
                    {
                        uri = global::Android.Net.Uri.Parse(results[resIndex]);
                    }
                }

                // easiest way to get audio playback controls is to use a videoview
                videoView            = FindViewById <VideoView>(Resource.Id.videoView);
                videoView.Visibility = ViewStates.Visible;
                videoView.SetOnPreparedListener(this);
                videoView.SetVideoURI(uri);

                mediaController = new AlwaysVisibleMediaController(this, Finish);
                mediaController.SetAnchorView(videoView);
                videoView.SetMediaController(mediaController);
            }
            else if (new string[] { "DRAW", "DRAW_PHOTO", "TAKE_PHOTO", "MATCH_PHOTO" }.Contains(taskType))
            {
                ImageViewAsync imageView = FindViewById <ImageViewAsync>(Resource.Id.imageView);
                imageView.Visibility = ViewStates.Visible;
                if (results != null)
                {
                    ImageService.Instance.LoadFile(results[resIndex]).FadeAnimation(true).Into(imageView);
                }
            }
        }