public override void Login(PresenceInfo pInfo) { var post = new Dictionary <string, object> { ["UserID"] = pInfo.UserID.ID, ["SessionID"] = pInfo.SessionID, ["SecureSessionID"] = pInfo.SecureSessionID, ["RegionID"] = UUID.Zero, ["LastSeen"] = Date.Now }; using (var conn = new MySqlConnection(m_ConnectionString)) { conn.Open(); try { conn.InsertInto("presence", post); } catch (Exception e) { m_Log.Debug("Presence update failed", e); throw new PresenceUpdateFailedException(); } } }
public override List <PresenceInfo> this[UUID userID] { get { var presences = new List <PresenceInfo>(); using (var conn = new MySqlConnection(m_ConnectionString)) { conn.Open(); using (var cmd = new MySqlCommand("SELECT * FROM presence WHERE UserID = @userID", conn)) { cmd.Parameters.AddParameter("@userID", userID); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { var pi = new PresenceInfo(); pi.UserID.ID = reader.GetUUID("UserID"); pi.RegionID = reader.GetUUID("RegionID"); pi.SessionID = reader.GetUUID("SessionID"); pi.SecureSessionID = reader.GetUUID("SecureSessionID"); presences.Add(pi); } } } } return(presences); } }
public override PresenceInfo this[UUID sessionID, UUID userID] { get { using (var conn = new MySqlConnection(m_ConnectionString)) { conn.Open(); using (var cmd = new MySqlCommand("SELECT * FROM presence WHERE SessionID = @sessionID", conn)) { cmd.Parameters.AddParameter("@sessionID", sessionID); using (MySqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { var pi = new PresenceInfo(); pi.UserID.ID = reader.GetUUID("UserID"); pi.RegionID = reader.GetUUID("RegionID"); pi.SessionID = reader.GetUUID("SessionID"); pi.SecureSessionID = reader.GetUUID("SecureSessionID"); return(pi); } } } } throw new PresenceNotFoundException(); } }
byte[] GetAgent(Dictionary <string, object> request) { UUID session = UUID.Zero; if (!request.ContainsKey("SessionID")) { return(FailureResult()); } if (!UUID.TryParse(request["SessionID"].ToString(), out session)) { return(FailureResult()); } PresenceInfo pinfo = m_PresenceService.GetAgent(session); Dictionary <string, object> result = new Dictionary <string, object>(); if (pinfo == null) { result["result"] = "null"; } else { result["result"] = pinfo.ToKeyValuePairs(); } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return(Util.UTF8NoBomEncoding.GetBytes(xmlString)); }
public void Presence_001() { PresenceServicesConnector m_Connector = new PresenceServicesConnector(DemonServer.Address); UUID user1 = UUID.Random(); UUID session1 = UUID.Random(); UUID region1 = UUID.Random(); bool success = m_Connector.LoginAgent(user1.ToString(), session1, UUID.Zero); Assert.AreEqual(success, true, "Failed to add user session"); PresenceInfo pinfo = m_Connector.GetAgent(session1); Assert.AreNotEqual(pinfo, null, "Unable to retrieve session"); Assert.AreEqual(pinfo.UserID, user1.ToString(), "Retrieved session does not match expected userID"); Assert.AreNotEqual(pinfo.RegionID, region1, "Retrieved session is unexpectedly in region"); success = m_Connector.ReportAgent(session1, region1); Assert.AreEqual(success, true, "Failed to report session in region 1"); pinfo = m_Connector.GetAgent(session1); Assert.AreNotEqual(pinfo, null, "Unable to session presence"); Assert.AreEqual(pinfo.UserID, user1.ToString(), "Retrieved session does not match expected userID"); Assert.AreEqual(pinfo.RegionID, region1, "Retrieved session is not in expected region"); success = m_Connector.LogoutAgent(session1); Assert.AreEqual(success, true, "Failed to remove session"); pinfo = m_Connector.GetAgent(session1); Assert.AreEqual(pinfo, null, "Session is still there, even though it shouldn't"); success = m_Connector.ReportAgent(session1, UUID.Random()); Assert.AreEqual(success, false, "Remove non-existing session should fail"); }
public PresenceInfo GetAgent(UUID sessionID) { Dictionary <string, object> sendData = new Dictionary <string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getagent"; sendData["SessionID"] = sessionID.ToString(); string reply = string.Empty; string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/presence"; // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth); if (reply == null || (reply != null && reply == string.Empty)) { m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgent received null or empty reply"); return(null); } } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server at {0}: {1}", uri, e.Message); return(null); } Dictionary <string, object> replyData = ServerUtils.ParseXmlResponse(reply); PresenceInfo pinfo = null; if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null)) { if (replyData["result"] is Dictionary <string, object> ) { pinfo = new PresenceInfo((Dictionary <string, object>)replyData["result"]); } else { if (replyData["result"].ToString() == "null") { return(null); } m_log.DebugFormat("[PRESENCE CONNECTOR]: Invalid reply (result not dictionary) received from presence server when querying for sessionID {0}", sessionID.ToString()); } } else { m_log.DebugFormat("[PRESENCE CONNECTOR]: Invalid reply received from presence server when querying for sessionID {0}", sessionID.ToString()); } return(pinfo); }
public PresenceInfo[] GetAgents(string[] userIDs) { List <PresenceInfo> info = new List <PresenceInfo>(); foreach (string userIDStr in userIDs) { PresenceData[] data = m_Database.Get("UserID", userIDStr); foreach (PresenceData d in data) { PresenceInfo ret = new PresenceInfo(); ret.UserID = d.UserID; ret.RegionID = d.RegionID; info.Add(ret); } // m_log.DebugFormat( // "[PRESENCE SERVICE]: GetAgents for {0} found {1} presences", userIDStr, data.Length); } return(info.ToArray()); }
/// <summary> /// Occurs when we've been told that a cliend has left a subscription. /// </summary> /// <param name="clientId">The client id.</param> /// <param name="username">The username of the connection.</param> private void OnClientLeave(string key) { // If there's no subscribers for presence, ignore if (this.PresenceSubscribers.Length == 0) { return; } var who = new PresenceInfo(); who.Id = key; // Prepare a notification var serialized = JsonConvert.SerializeObject(new PresenceNotification(PresenceEvent.Unsubscribe, this.Channel, who, this.Occupancy), Formatting.Indented); if (serialized == null) { return; } // Since we have a subscription, iterate and notify presence change foreach (var client in this.PresenceSubscribers) { client.Send(this.ContractKey, "emitter/presence/", serialized.AsUTF8().AsSegment()); } }
public void FillSum(PresenceInfo info) { PresenceCount = info.PresenceCount.ToString(); LeaveCount = info.LeaveCount.ToString(); AbsenceCount = info.AbsenceCount.ToString(); GivingCount = info.GivingCount.ToString(); TotleCount = info.Details.Count.ToString(); }
/// <summary> /// Converts repliccated state to a presence info. /// </summary> /// <returns></returns> internal PresenceInfo AsInfo() { var info = new PresenceInfo(); info.Id = this.Key; info.Username = this.Username; return(info); }
/// <summary> /// Deserializes the JSON key-gen response. /// </summary> /// <param name="json">The json string to deserialize from.</param> /// <returns></returns> public static PresenceEvent FromJson(string json) { var map = JsonConvert.DeserializeObject(json) as Hashtable; // Check for error. ErrorEvent.ThrowIfError(map); var response = new Uno.Emitter.Messages.PresenceEvent(); if (map.ContainsKey("req")) { response.RequestId = (long)map["req"]; } response.Channel = (string)map["channel"]; response.Time = (long)map["time"]; switch ((string)map["event"]) { case "status": response.Event = PresenceEventType.Status; break; case "subscribe": response.Event = PresenceEventType.Subscribe; break; case "unsubscribe": response.Event = PresenceEventType.Unsubscribe; break; } response.Who = new List <PresenceInfo>(); if (map["who"] is ArrayList arrayWho) { foreach (Hashtable who in arrayWho) { var info = new PresenceInfo(); info.Id = (string)who["id"]; if (who.ContainsKey("username")) { info.Username = (string)who["username"]; } response.Who.Add(info); } } else if (map["who"] is Hashtable who) { var info = new PresenceInfo(); info.Id = (string)who["id"]; if (who.ContainsKey("username")) { info.Username = (string)who["username"]; } response.Who.Add(info); } return(response); }
public static PresenceInfo FromJson(string json) { var map = JsonConvert.DeserializeObject(json) as Hashtable; var info = new PresenceInfo(); info.Id = (string)map["id"]; info.Username = (string)map["username"]; return(info); }
public bool LogoutAgent(UUID sessionID) { PresenceInfo presence = GetAgent(sessionID); m_log.DebugFormat("[PRESENCE SERVICE]: LogoutAgent: session {0}, user {1}, region {2}", sessionID, (presence == null) ? null : presence.UserID, (presence == null) ? null : presence.RegionID.ToString()); return(m_Database.Delete("SessionID", sessionID.ToString())); }
bool SendIMToRegion(PresenceInfo upd, GridInstantMessage im, UUID toAgentID, bool foreigner) { bool imresult = false; GridRegion reginfo = null; if (!m_RegionCache.TryGetValue(upd.RegionID, out reginfo)) { reginfo = m_GridService.GetRegionByUUID(UUID.Zero /*!!!*/, upd.RegionID); if (reginfo != null) { m_RegionCache.AddOrUpdate(upd.RegionID, reginfo, CACHE_EXPIRATION_SECONDS); } } if (reginfo != null) { imresult = InstantMessageServiceConnector.SendInstantMessage(reginfo.ServerURI, im, m_messageKey); } else { m_log.DebugFormat("[HG IM SERVICE]: Failed to deliver message to {0}", reginfo.ServerURI); return(false); } if (imresult) { // IM delivery successful, so store the Agent's location in our local cache. lock (m_UserLocationMap) { if (m_UserLocationMap.ContainsKey(toAgentID)) { m_UserLocationMap[toAgentID] = upd; } else { m_UserLocationMap.Add(toAgentID, upd); } } return(true); } else { // try again, but lookup user this time. // Warning, this must call the Async version // of this method or we'll be making thousands of threads // The version within the spawned thread is SendGridInstantMessageViaXMLRPCAsync // The version that spawns the thread is SendGridInstantMessageViaXMLRPC // This is recursive!!!!! return(TrySendInstantMessage(im, upd, false, foreigner)); } }
public override void Report(PresenceInfo pInfo) { using (var conn = new MySqlConnection(m_ConnectionString)) { conn.Open(); using (var cmd = new MySqlCommand("UPDATE presence SET RegionID = @regionID WHERE SessionID = @sessionID", conn)) { cmd.Parameters.AddParameter("@regionID", pInfo.RegionID); cmd.Parameters.AddParameter("@sessionID", pInfo.SessionID); cmd.ExecuteNonQuery(); } } }
public bool OutgoingInstantMessage(GridInstantMessage im, string url, bool foreigner) { // m_log.DebugFormat("[HG IM SERVICE]: Sending message from {0} to {1}@{2}", im.fromAgentID, im.toAgentID, url); if (url != string.Empty) { return(TrySendInstantMessage(im, url, true, foreigner)); } else { PresenceInfo upd = new PresenceInfo(); upd.RegionID = UUID.Zero; return(TrySendInstantMessage(im, upd, true, foreigner)); } }
private bool ForwardToSim(string op, UUID fromID, string name, String fromUUI, UUID toID, string message) { PresenceInfo session = null; GridRegion region = null; PresenceInfo[] sessions = m_PresenceService.GetAgents(new string[] { toID.ToString() }); if (sessions != null && sessions.Length > 0) { session = sessions[0]; } if (session != null) { region = m_GridService.GetRegionByUUID(UUID.Zero, session.RegionID); } switch (op) { case "FriendshipOffered": // Let's store backwards string secret = UUID.Random().ToString().Substring(0, 8); m_FriendsService.StoreFriend(toID.ToString(), fromUUI + ";" + secret, 0); if (m_FriendsLocalSimConnector != null) // standalone { GridInstantMessage im = new GridInstantMessage(null, fromID, name, toID, (byte)InstantMessageDialog.FriendshipOffered, message, false, Vector3.Zero); // !! HACK im.imSessionID = im.fromAgentID; return(m_FriendsLocalSimConnector.LocalFriendshipOffered(toID, im)); } else if (region != null) // grid { return(m_FriendsSimConnector.FriendshipOffered(region, fromID, toID, message, name)); } break; case "ApproveFriendshipRequest": if (m_FriendsLocalSimConnector != null) // standalone { return(m_FriendsLocalSimConnector.LocalFriendshipApproved(fromID, name, toID)); } else if (region != null) //grid { return(m_FriendsSimConnector.FriendshipApproved(region, fromID, name, toID)); } break; } return(false); }
public PresenceInfo GetAgent(UUID sessionID) { PresenceInfo ret = new PresenceInfo(); PresenceData data = m_Database.Get(sessionID); if (data == null) { return(null); } ret.UserID = data.UserID; ret.RegionID = data.RegionID; return(ret); }
public async Task <PresenceInfo> GetPresence() { string requestUrl = "https://graph.microsoft.com/beta/me/presence"; // Create the request message and add the content. HttpRequestMessage hrm = new HttpRequestMessage(HttpMethod.Get, requestUrl); // Authenticate (add access token) our HttpRequestMessage await theGraphClient.AuthenticationProvider.AuthenticateRequestAsync(hrm); // Send the request and get the response. HttpResponseMessage response = await theGraphClient.HttpProvider.SendAsync(hrm); var content = await response.Content.ReadAsStringAsync(); PresenceInfo presence = theGraphClient.HttpProvider.Serializer.DeserializeObject <PresenceInfo>(content); return(presence); }
public PresenceInfo[] GetAgents(string[] userIDs) { var info = new List <PresenceInfo>(userIDs.Length); PresenceInfo ret; foreach (string userIDStr in userIDs) { if (ByUserCache.TryGetValue(userIDStr, out PresenceData pd)) { ByUserCache.Add(pd.UserID, pd, EXPIREMS); BySessionCache.Add(pd.SessionID, pd, EXPIREMS); ret = new PresenceInfo() { UserID = pd.UserID, RegionID = pd.RegionID }; info.Add(ret); } else { PresenceData[] data = m_Database.Get("UserID", userIDStr); if (data.Length == 0) { continue; } PresenceData d = data[0]; ByUserCache.Add(d.UserID, d, EXPIREMS); BySessionCache.Add(d.SessionID, d, EXPIREMS); ret = new PresenceInfo() { UserID = d.UserID, RegionID = d.RegionID }; info.Add(ret); } //m_log.DebugFormat( // "[PRESENCE SERVICE]: GetAgents for {0} found {1} presences", userIDStr, data.Length); } return(info.ToArray()); }
internal void Update(PresenceInfo model) { if (model.User != null) { Update(model.User as UserReference); } if (model.Roles != null) { UpdateRoles(model.Roles.Select(x => _client.Roles[x])); } if (model.Status != null && Status != model.Status) { Status = UserStatus.FromString(model.Status); if (Status == UserStatus.Offline) { _lastOnline = DateTime.UtcNow; } } GameId = model.GameId; //Allows null }
public PresenceInfo GetAgent(UUID sessionID) { if (!BySessionCache.TryGetValue(sessionID, out PresenceData data)) { data = m_Database.Get(sessionID); } if (data == null) { return(null); } BySessionCache.Add(sessionID, data, EXPIREMS); ByUserCache.Add(data.UserID, data, EXPIREMS); var ret = new PresenceInfo() { UserID = data.UserID, RegionID = data.RegionID }; return(ret); }
bool SendIMToRegion(PresenceInfo upd, GridInstantMessage im, UUID toAgentID, bool foreigner) { GridRegion reginfo = null; if (!m_RegionCache.TryGetValue(upd.RegionID, REGIONCACHE_EXPIRATION, out reginfo)) { reginfo = m_GridService.GetRegionByUUID(UUID.Zero /*!!!*/, upd.RegionID); m_RegionCache.AddOrUpdate(upd.RegionID, reginfo, reginfo == null ? 60000 : REGIONCACHE_EXPIRATION); } if (reginfo == null) { return(false); } bool imresult = InstantMessageServiceConnector.SendInstantMessage(reginfo.ServerURI, im, m_messageKey); if (imresult) { // IM delivery successful, so store the Agent's location in our local cache. lock (m_UserLocationMap) m_UserLocationMap[toAgentID] = upd; return(true); } else { // try again, but lookup user this time. // Warning, this must call the Async version // of this method or we'll be making thousands of threads // The version within the spawned thread is SendGridInstantMessageViaXMLRPCAsync // The version that spawns the thread is SendGridInstantMessageViaXMLRPC // This is recursive!!!!! return(TrySendInstantMessage(im, upd, false, foreigner)); } }
private void OnPresenceInfoChanged(PresenceInfo info) { ItemCollection.Clear(); int presenceCount = 0; if (info.Details != null) { foreach (PresenceDetail item in info.Details) { if (item.State == CallingState.Presence) { presenceCount++; } ItemCollection.Add(new PresenceItemViewModel(item)); if (item.State == CallingState.Presence && presenceCount > 20) { ItemCollection.Last().ChangeToOverdue(); } } } Sum.FillSum(info); }
public List <UUID> StatusNotification(List <string> friends, UUID foreignUserID, bool online) { if (m_FriendsService == null || m_PresenceService == null) { m_log.WarnFormat("[USER AGENT SERVICE]: Unable to perform status notifications because friends or presence services are missing"); return(new List <UUID>()); } List <UUID> localFriendsOnline = new List <UUID>(); m_log.DebugFormat("[USER AGENT SERVICE]: Status notification: foreign user {0} wants to notify {1} local friends", foreignUserID, friends.Count); // First, let's double check that the reported friends are, indeed, friends of that user // And let's check that the secret matches List <string> usersToBeNotified = new List <string>(); foreach (string uui in friends) { UUID localUserID; string secret = string.Empty, tmp = string.Empty; if (Util.ParseUniversalUserIdentifier(uui, out localUserID, out tmp, out tmp, out tmp, out secret)) { FriendInfo[] friendInfos = m_FriendsService.GetFriends(localUserID); foreach (FriendInfo finfo in friendInfos) { if (finfo.Friend.StartsWith(foreignUserID.ToString()) && finfo.Friend.EndsWith(secret)) { // great! usersToBeNotified.Add(localUserID.ToString()); } } } } // Now, let's send the notifications m_log.DebugFormat("[USER AGENT SERVICE]: Status notification: user has {0} local friends", usersToBeNotified.Count); // First, let's send notifications to local users who are online in the home grid PresenceInfo[] friendSessions = m_PresenceService.GetAgents(usersToBeNotified.ToArray()); if (friendSessions != null && friendSessions.Length > 0) { PresenceInfo friendSession = null; foreach (PresenceInfo pinfo in friendSessions) { if (pinfo.RegionID != UUID.Zero) // let's guard against traveling agents { friendSession = pinfo; break; } } if (friendSession != null) { ForwardStatusNotificationToSim(friendSession.RegionID, foreignUserID, friendSession.UserID, online); usersToBeNotified.Remove(friendSession.UserID.ToString()); UUID id; if (UUID.TryParse(friendSession.UserID, out id)) { localFriendsOnline.Add(id); } } } //// Lastly, let's notify the rest who may be online somewhere else //foreach (string user in usersToBeNotified) //{ // UUID id = new UUID(user); // if (m_Database.ContainsKey(id) && m_Database[id].GridExternalName != m_GridName) // { // string url = m_Database[id].GridExternalName; // // forward // m_log.WarnFormat("[USER AGENT SERVICE]: User {0} is visiting {1}. HG Status notifications still not implemented.", user, url); // } //} // and finally, let's send the online friends if (online) { return(localFriendsOnline); } else { return(new List <UUID>()); } }
public void Init() { instance = new PresenceInfo(); }
public static void Main(string[] args) { ConsoleAppender consoleAppender = new ConsoleAppender(); consoleAppender.Layout = new PatternLayout("%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"); log4net.Config.BasicConfigurator.Configure(consoleAppender); string serverURI = "http://127.0.0.1:8003"; PresenceServicesConnector m_Connector = new PresenceServicesConnector(serverURI); UUID user1 = UUID.Random(); UUID session1 = UUID.Random(); UUID region1 = UUID.Random(); bool success = m_Connector.LoginAgent(user1.ToString(), session1, UUID.Zero); if (success) { m_log.InfoFormat("[PRESENCE CLIENT]: Successfully logged in user {0} with session {1}", user1, session1); } else { m_log.InfoFormat("[PRESENCE CLIENT]: failed to login user {0}", user1); } System.Console.WriteLine("\n"); PresenceInfo pinfo = m_Connector.GetAgent(session1); if (pinfo == null) { m_log.InfoFormat("[PRESENCE CLIENT]: Unable to retrieve presence for {0}", user1); } else { m_log.InfoFormat("[PRESENCE CLIENT]: Presence retrieved correctly: userID={0}; regionID={1}", pinfo.UserID, pinfo.RegionID); } System.Console.WriteLine("\n"); success = m_Connector.ReportAgent(session1, region1); if (success) { m_log.InfoFormat("[PRESENCE CLIENT]: Successfully reported session {0} in region {1}", user1, region1); } else { m_log.InfoFormat("[PRESENCE CLIENT]: failed to report session {0}", session1); } pinfo = m_Connector.GetAgent(session1); if (pinfo == null) { m_log.InfoFormat("[PRESENCE CLIENT]: Unable to retrieve presence for {0} for second time", user1); } else { m_log.InfoFormat("[PRESENCE CLIENT]: Presence retrieved correctly: userID={0}; regionID={2}", pinfo.UserID, pinfo.RegionID); } System.Console.WriteLine("\n"); success = m_Connector.LogoutAgent(session1); if (success) { m_log.InfoFormat("[PRESENCE CLIENT]: Successfully logged out user {0}", user1); } else { m_log.InfoFormat("[PRESENCE CLIENT]: failed to logout user {0}", user1); } pinfo = m_Connector.GetAgent(session1); if (pinfo == null) { m_log.InfoFormat("[PRESENCE CLIENT]: Unable to retrieve presence for {0} for fourth time", user1); } else { m_log.InfoFormat("[PRESENCE CLIENT]: Presence retrieved correctly: userID={0}; regionID={1}", pinfo.UserID, pinfo.RegionID); } System.Console.WriteLine("\n"); success = m_Connector.ReportAgent(session1, UUID.Random()); if (success) { m_log.InfoFormat("[PRESENCE CLIENT]: Report agent succeeded, but this is wrong"); } else { m_log.InfoFormat("[PRESENCE CLIENT]: failed to report agent, as it should because user is not logged in"); } }
public PresenceInfo[] GetAgents(string[] userIDs) { Dictionary <string, object> sendData = new Dictionary <string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getagents"; sendData["uuids"] = new List <string>(userIDs); string reply = string.Empty; string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/presence"; //m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth); } catch (Exception e) { m_log.Error("[PRESENCE CONNECTOR]: GetAgents exception when contacting presence server at " + uri, e); return(new PresenceInfo[0]); } if ((reply == null) || (reply == string.Empty)) { m_log.Error("[PRESENCE CONNECTOR]: GetAgents received null or empty reply"); return(new PresenceInfo[0]); } List <PresenceInfo> rinfos = new List <PresenceInfo>(); Dictionary <string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { if (replyData.ContainsKey("result") && (replyData["result"].ToString() == "null" || replyData["result"].ToString() == "Failure")) { return(new PresenceInfo[0]); } Dictionary <string, object> .ValueCollection pinfosList = replyData.Values; //m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents returned {0} elements", pinfosList.Count); foreach (object presence in pinfosList) { if (presence is Dictionary <string, object> ) { PresenceInfo pinfo = new PresenceInfo((Dictionary <string, object>)presence); rinfos.Add(pinfo); } else { m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents received invalid response type {0}", presence.GetType()); } } } else { m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents received null response"); } return(rinfos.ToArray()); }
private bool CheckViewer(PresenceInfo info, out string reason) { //Check for banned viewers if (IsViewerBanned(info.LastKnownViewer)) { reason = "Viewer is banned"; return false; } //Overkill, and perm-bans people who only log in with a bad viewer once //foreach (string mac in info.KnownMacs) { if (info.LastKnownMac.Contains("000")) { //Ban this asshole reason = "Viewer is blocked (MAC)"; return false; } } //foreach (string id0 in info.KnownID0s) { if (info.LastKnownID0.Contains("000")) { //Ban this asshole reason = "Viewer is blocked (IO)"; return false; } } reason = ""; return true; }
private PresenceInfo UpdatePresenceInfo(UUID AgentID, PresenceInfo oldInfo, string ip, string version, string platform, string mac, string id0) { PresenceInfo info = new PresenceInfo(); info.AgentID = AgentID; info.LastKnownIP = ip; info.LastKnownViewer = version; info.Platform = platform; info.LastKnownMac = mac; info.LastKnownID0 = id0; if (!oldInfo.KnownID0s.Contains(info.LastKnownID0)) oldInfo.KnownID0s.Add(info.LastKnownID0); if (!oldInfo.KnownIPs.Contains(info.LastKnownIP)) oldInfo.KnownIPs.Add(info.LastKnownIP); if (!oldInfo.KnownMacs.Contains(info.LastKnownMac)) oldInfo.KnownMacs.Add(info.LastKnownMac); if (!oldInfo.KnownViewers.Contains(info.LastKnownViewer)) oldInfo.KnownViewers.Add(info.LastKnownViewer); info.KnownViewers = oldInfo.KnownViewers; info.KnownMacs = oldInfo.KnownMacs; info.KnownIPs = oldInfo.KnownIPs; info.KnownID0s = oldInfo.KnownID0s; info.KnownAlts = oldInfo.KnownAlts; info.Flags = oldInfo.Flags; presenceInfo.UpdatePresenceInfo(info); return info; }
protected bool TrySendInstantMessage(GridInstantMessage im, object previousLocation, bool firstTime, bool foreigner) { UUID toAgentID = new UUID(im.toAgentID); PresenceInfo upd = null; string url = string.Empty; bool lookupAgent = false; lock (m_UserLocationMap) { if (m_UserLocationMap.ContainsKey(toAgentID)) { object o = m_UserLocationMap[toAgentID]; if (o is PresenceInfo) { upd = (PresenceInfo)o; } else if (o is string) { url = (string)o; } // We need to compare the current location with the previous // or the recursive loop will never end because it will never try to lookup the agent again if (!firstTime) { lookupAgent = true; upd = null; } } else { lookupAgent = true; } } //m_log.DebugFormat("[XXX] Neeed lookup ? {0}", (lookupAgent ? "yes" : "no")); // Are we needing to look-up an agent? if (lookupAgent) { // Non-cached user agent lookup. PresenceInfo[] presences = m_PresenceService.GetAgents(new string[] { toAgentID.ToString() }); if (presences != null && presences.Length > 0) { foreach (PresenceInfo p in presences) { if (p.RegionID != UUID.Zero) { //m_log.DebugFormat("[XXX]: Found presence in {0}", p.RegionID); upd = p; break; } } } if (upd == null && !foreigner) { // Let's check with the UAS if the user is elsewhere m_log.DebugFormat("[HG IM SERVICE]: User is not present. Checking location with User Agent service"); try { url = m_UserAgentService.LocateUser(toAgentID); } catch (Exception e) { m_log.Warn("[HG IM SERVICE]: LocateUser call failed ", e); url = string.Empty; } } // check if we've tried this before.. // This is one way to end the recursive loop // if (!firstTime && ((previousLocation is PresenceInfo && upd != null && upd.RegionID == ((PresenceInfo)previousLocation).RegionID) || (previousLocation is string && upd == null && previousLocation.Equals(url)))) { // m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message"); m_log.DebugFormat("[HG IM SERVICE]: Fail 2 {0} {1}", previousLocation, url); return(false); } } if (upd != null) { // ok, the user is around somewhere. Let's send back the reply with "success" // even though the IM may still fail. Just don't keep the caller waiting for // the entire time we're trying to deliver the IM return(SendIMToRegion(upd, im, toAgentID, foreigner)); } else if (url != string.Empty) { // ok, the user is around somewhere. Let's send back the reply with "success" // even though the IM may still fail. Just don't keep the caller waiting for // the entire time we're trying to deliver the IM return(ForwardIMToGrid(url, im, toAgentID, foreigner)); } else if (firstTime && previousLocation is string && (string)previousLocation != string.Empty) { return(ForwardIMToGrid((string)previousLocation, im, toAgentID, foreigner)); } else { m_log.DebugFormat("[HG IM SERVICE]: Unable to locate user {0}", toAgentID); } return(false); }
public void SetCachedWearables(PresenceInfo.WearableCache[] wearables) { if (wearables.Length == 0) return; m_wearableCache.Clear(); foreach (var w in wearables) m_wearableCache.Add(w.TextureIndex.ToString(), w.CacheID); }
public bool LoginAgent(GridRegion source, AgentCircuitData aCircuit, GridRegion destination, out string reason) { reason = string.Empty; string authURL = string.Empty; if (aCircuit.ServiceURLs.ContainsKey("HomeURI")) { authURL = aCircuit.ServiceURLs["HomeURI"].ToString(); } m_log.InfoFormat("[GATEKEEPER SERVICE]: Login request for {0} {1} @ {2} ({3}) at {4} using viewer {5}, channel {6}, IP {7}, Mac {8}, Id0 {9}, Teleport Flags: {10}. From region {11}", aCircuit.firstname, aCircuit.lastname, authURL, aCircuit.AgentID, destination.RegionID, aCircuit.Viewer, aCircuit.Channel, aCircuit.IPAddress, aCircuit.Mac, aCircuit.Id0, (TeleportFlags)aCircuit.teleportFlags, (source == null) ? "Unknown" : string.Format("{0} ({1}){2}", source.RegionName, source.RegionID, (source.RawServerURI == null) ? "" : " @ " + source.ServerURI)); string curViewer = Util.GetViewerName(aCircuit); // // Check client // if (m_AllowedClients != string.Empty) { Regex arx = new Regex(m_AllowedClients); Match am = arx.Match(curViewer); if (!am.Success) { reason = "Login failed: client " + curViewer + " is not allowed"; m_log.InfoFormat("[GATEKEEPER SERVICE]: Login failed, reason: client {0} is not allowed", curViewer); return(false); } } if (m_DeniedClients != string.Empty) { Regex drx = new Regex(m_DeniedClients); Match dm = drx.Match(curViewer); if (dm.Success) { reason = "Login failed: client " + curViewer + " is denied"; m_log.InfoFormat("[GATEKEEPER SERVICE]: Login failed, reason: client {0} is denied", curViewer); return(false); } } // // Authenticate the user // if (!Authenticate(aCircuit)) { reason = "Unable to verify identity"; m_log.InfoFormat("[GATEKEEPER SERVICE]: Unable to verify identity of agent {0} {1}. Refusing service.", aCircuit.firstname, aCircuit.lastname); return(false); } m_log.DebugFormat("[GATEKEEPER SERVICE]: Identity verified for {0} {1} @ {2}", aCircuit.firstname, aCircuit.lastname, authURL); // // Check for impersonations // UserAccount account = null; if (m_UserAccountService != null) { // Check to see if we have a local user with that UUID account = m_UserAccountService.GetUserAccount(m_ScopeID, aCircuit.AgentID); if (account != null) { // Make sure this is the user coming home, and not a foreign user with same UUID as a local user if (m_UserAgentService != null) { if (!m_UserAgentService.IsAgentComingHome(aCircuit.SessionID, m_ExternalName)) { // Can't do, sorry reason = "Unauthorized"; m_log.InfoFormat("[GATEKEEPER SERVICE]: Foreign agent {0} {1} has same ID as local user. Refusing service.", aCircuit.firstname, aCircuit.lastname); return(false); } } } } // // Foreign agents allowed? Exceptions? // if (account == null) { bool allowed = m_ForeignAgentsAllowed; if (m_ForeignAgentsAllowed && IsException(aCircuit, m_ForeignsAllowedExceptions)) { allowed = false; } if (!m_ForeignAgentsAllowed && IsException(aCircuit, m_ForeignsDisallowedExceptions)) { allowed = true; } if (!allowed) { reason = "Destination does not allow visitors from your world"; m_log.InfoFormat("[GATEKEEPER SERVICE]: Foreign agents are not permitted {0} {1} @ {2}. Refusing service.", aCircuit.firstname, aCircuit.lastname, aCircuit.ServiceURLs["HomeURI"]); return(false); } } // // Is the user banned? // This uses a Ban service that's more powerful than the configs // string uui = (account != null ? aCircuit.AgentID.ToString() : Util.ProduceUserUniversalIdentifier(aCircuit)); if (m_BansService != null && m_BansService.IsBanned(uui, aCircuit.IPAddress, aCircuit.Id0, authURL)) { reason = "You are banned from this world"; m_log.InfoFormat("[GATEKEEPER SERVICE]: Login failed, reason: user {0} is banned", uui); return(false); } m_log.DebugFormat("[GATEKEEPER SERVICE]: User {0} is ok", aCircuit.Name); bool isFirstLogin = false; // // Login the presence, if it's not there yet (by the login service) // PresenceInfo presence = m_PresenceService.GetAgent(aCircuit.SessionID); if (presence != null) // it has been placed there by the login service { isFirstLogin = true; } else { if (!m_PresenceService.LoginAgent(aCircuit.AgentID.ToString(), aCircuit.SessionID, aCircuit.SecureSessionID)) { reason = "Unable to login presence"; m_log.InfoFormat("[GATEKEEPER SERVICE]: Presence login failed for foreign agent {0} {1}. Refusing service.", aCircuit.firstname, aCircuit.lastname); return(false); } m_log.DebugFormat("[GATEKEEPER SERVICE]: Login presence {0} is ok", aCircuit.Name); // Also login foreigners with GridUser service if (m_GridUserService != null && account == null) { string userId = aCircuit.AgentID.ToString(); string first = aCircuit.firstname, last = aCircuit.lastname; if (last.StartsWith("@")) { string[] parts = aCircuit.firstname.Split('.'); if (parts.Length >= 2) { first = parts[0]; last = parts[1]; } } userId += ";" + aCircuit.ServiceURLs["HomeURI"] + ";" + first + " " + last; m_GridUserService.LoggedIn(userId); } } // // Get the region // destination = m_GridService.GetRegionByUUID(m_ScopeID, destination.RegionID); if (destination == null) { reason = "Destination region not found"; return(false); } m_log.DebugFormat( "[GATEKEEPER SERVICE]: Destination {0} is ok for {1}", destination.RegionName, aCircuit.Name); // // Adjust the visible name // if (account != null) { aCircuit.firstname = account.FirstName; aCircuit.lastname = account.LastName; } if (account == null) { if (!aCircuit.lastname.StartsWith("@")) { aCircuit.firstname = aCircuit.firstname + "." + aCircuit.lastname; } try { Uri uri = new Uri(aCircuit.ServiceURLs["HomeURI"].ToString()); aCircuit.lastname = "@" + uri.Authority; } catch { m_log.WarnFormat("[GATEKEEPER SERVICE]: Malformed HomeURI (this should never happen): {0}", aCircuit.ServiceURLs["HomeURI"]); aCircuit.lastname = "@" + aCircuit.ServiceURLs["HomeURI"].ToString(); } } // // Finally launch the agent at the destination // Constants.TeleportFlags loginFlag = isFirstLogin ? Constants.TeleportFlags.ViaLogin : Constants.TeleportFlags.ViaHGLogin; // Preserve our TeleportFlags we have gathered so-far loginFlag |= (Constants.TeleportFlags)aCircuit.teleportFlags; m_log.DebugFormat("[GATEKEEPER SERVICE]: Launching {0}, Teleport Flags: {1}", aCircuit.Name, loginFlag); EntityTransferContext ctx = new EntityTransferContext(); if (!m_SimulationService.QueryAccess( destination, aCircuit.AgentID, aCircuit.ServiceURLs["HomeURI"].ToString(), true, aCircuit.startpos, new List <UUID>(), ctx, out reason)) { return(false); } return(m_SimulationService.CreateAgent(source, destination, aCircuit, (uint)loginFlag, ctx, out reason)); }
private void CheckForSimilarities(PresenceInfo info) { presenceInfo.Check(info, m_useIncludeList ? m_allowedViewers : m_bannedViewers, m_useIncludeList); }
public void SetUserLevel(UUID AgentID, PresenceInfo.PresenceInfoFlags presenceInfoFlags) { if (!m_enabled) return; //Get PresenceInfo info = GetInformation(AgentID); //Set the flags info.Flags = presenceInfoFlags; //Save presenceInfo.UpdatePresenceInfo(info); }
private bool CheckThreatLevel(PresenceInfo info, out string message) { message = ""; if ((info.Flags & PresenceInfo.PresenceInfoFlags.Banned) == PresenceInfo.PresenceInfoFlags.Banned) { message = "Banned agent."; return false; } if (GrieferAllowLevel == AllowLevel.AllowKnown) return true; //Allow all else if (GrieferAllowLevel == AllowLevel.AllowCleanOnly) { //Allow people with only clean flag or suspected alt if ((info.Flags & PresenceInfo.PresenceInfoFlags.Clean) == PresenceInfo.PresenceInfoFlags.Clean) return true; else { message = "Not a Clean agent and have been denied access."; return false; } } else if (GrieferAllowLevel == AllowLevel.AllowSuspected) { //Block all alts of knowns, and suspected alts of knowns if ((info.Flags & PresenceInfo.PresenceInfoFlags.Known) == PresenceInfo.PresenceInfoFlags.Known || (info.Flags & PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfKnown) == PresenceInfo.PresenceInfoFlags.SuspectedAltAccountOfKnown || (info.Flags & PresenceInfo.PresenceInfoFlags.KnownAltAccountOfKnown) == PresenceInfo.PresenceInfoFlags.KnownAltAccountOfKnown) { message = "Not a Clean agent and have been denied access."; return false; } else return true; } return true; }
private bool CheckViewer(PresenceInfo info) { //Check for banned viewers if (IsViewerBanned(info.LastKnownViewer)) return false; foreach (string mac in info.KnownMacs) { if (mac.Contains("000")) { //Ban this asshole return false; } //if (mac.Length != 32) // return false; //Valid length! } foreach (string id0 in info.KnownID0s) { if (id0.Contains("000")) { //Ban this asshole return false; } //if (id0.Length != 32) // return false; //Valid length! } return true; }
private void DisplayUserInfo(PresenceInfo info) { MainConsole.Instance.Info("User Info for " + info.AgentID); MainConsole.Instance.Info(" AgentID: " + info.AgentID); MainConsole.Instance.Info(" Flags: " + info.Flags); /*MainConsole.Instance.Info(" ID0: " + info.LastKnownID0); MainConsole.Instance.Info(" IP: " + info.LastKnownIP); MainConsole.Instance.Info(" Mac: " + info.LastKnownMac); MainConsole.Instance.Info(" Viewer: " + info.LastKnownViewer); MainConsole.Instance.Info(" Platform: " + info.Platform);*/ }
private PresenceInfo GetInformation(UUID AgentID) { PresenceInfo oldInfo = presenceInfo.GetPresenceInfo(AgentID); if (oldInfo == null) { PresenceInfo info = new PresenceInfo(); info.AgentID = AgentID; info.Flags = PresenceInfo.PresenceInfoFlags.Clean; presenceInfo.UpdatePresenceInfo(info); oldInfo = presenceInfo.GetPresenceInfo(AgentID); } return oldInfo; }
private void DisplayUserInfo(PresenceInfo info) { UserAccount account = m_accountService.GetUserAccount(null, info.AgentID); if (account != null) MainConsole.Instance.Info("User Info for " + account.Name); else MainConsole.Instance.Info("User Info for " + info.AgentID); MainConsole.Instance.Info(" AgentID: " + info.AgentID); MainConsole.Instance.Info(" Flags: " + info.Flags); MainConsole.Instance.Info(" ID0: " + info.LastKnownID0); MainConsole.Instance.Info(" IP: " + info.LastKnownIP); //MainConsole.Instance.Info(" Mac: " + info.LastKnownMac); MainConsole.Instance.Info(" Viewer: " + info.LastKnownViewer); MainConsole.Instance.Info(" Platform: " + info.Platform); if (info.KnownAlts.Count > 0) { MainConsole.Instance.Info(" Known Alt Accounts: "); foreach (var acc in info.KnownAlts) { account = m_accountService.GetUserAccount(null, UUID.Parse(acc)); if (account != null) MainConsole.Instance.Info(" " + account.Name); else MainConsole.Instance.Info(" " + acc); } } }
private bool CheckViewer(PresenceInfo info, out string reason) { //Check for banned viewers if (IsViewerBanned(info.LastKnownViewer)) { reason = "Viewer is banned"; return false; } reason = ""; return true; }