/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Threading; using log4net; using MailKit.Net.Smtp; using MailKit.Security; using MimeKit; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Client; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.OfflineIM { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "OfflineIMConnectorModule")] public class OfflineIMRegionModule : ISharedRegionModule, IOfflineIMService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private bool m_Enabled = false; private List m_SceneList = new List(); IMessageTransferModule m_TransferModule = null; private bool m_ForwardOfflineGroupMessages = true; private bool m_EmailEnabled; private string m_EmailRelayDomain = "im.stadt-nexverse.de"; private string m_EmailSubjectTemplate = "Offline-IM Nachricht von {SENDER}"; private string m_EmailRelaySigningKey = string.Empty; private int m_EmailReplyLifetimeDays = 5; private string m_EmailSmtpHost = "mail.nexvortex.de"; private int m_EmailSmtpPort = 587; private bool m_EmailUseStartTls = true; private bool m_EmailUseSslOnConnect; private string m_EmailSmtpUsername = "relay@im.stadt-nexverse.de"; private string m_EmailSmtpPassword = string.Empty; private int m_EmailPerSenderPerHour = 30; private int m_EmailPerRecipientPerHour = 60; private int m_EmailGlobalPerHour = 500; private readonly object m_EmailRateLock = new object(); private readonly Dictionary> m_EmailSenderRate = new Dictionary>(); private readonly Dictionary> m_EmailRecipientRate = new Dictionary>(); private readonly Queue m_EmailGlobalRate = new Queue(); private IOfflineIMService m_OfflineIMService; public void Initialise(IConfigSource config) { IConfig cnf = config.Configs["Messaging"]; if (cnf == null) return; if (cnf != null && cnf.GetString("OfflineMessageModule", string.Empty) != Name) return; m_Enabled = true; string serviceLocation = cnf.GetString("OfflineMessageURL", string.Empty); if (serviceLocation.Length == 0) m_OfflineIMService = new OfflineIMService(config); else m_OfflineIMService = new OfflineIMServiceRemoteConnector(config); m_ForwardOfflineGroupMessages = cnf.GetBoolean("ForwardOfflineGroupMessages", m_ForwardOfflineGroupMessages); IConfig emailConfig = config.Configs["OfflineIMEmail"]; if (emailConfig is not null) { m_EmailEnabled = emailConfig.GetBoolean("Enabled", false); m_EmailRelayDomain = emailConfig.GetString("RelayDomain", m_EmailRelayDomain).Trim().Trim('.'); m_EmailSubjectTemplate = emailConfig.GetString("SubjectTemplate", m_EmailSubjectTemplate); m_EmailRelaySigningKey = emailConfig.GetString("RelaySigningKey", string.Empty); m_EmailReplyLifetimeDays = Math.Max(1, Math.Min(30, emailConfig.GetInt("ReplyLifetimeDays", 5))); m_EmailSmtpHost = emailConfig.GetString("SMTPHost", m_EmailSmtpHost).Trim(); m_EmailSmtpPort = emailConfig.GetInt("SMTPPort", m_EmailSmtpPort); m_EmailUseStartTls = emailConfig.GetBoolean("UseStartTls", m_EmailUseStartTls); m_EmailUseSslOnConnect = emailConfig.GetBoolean("UseSslOnConnect", false); m_EmailSmtpUsername = emailConfig.GetString("SMTPUsername", m_EmailSmtpUsername).Trim(); m_EmailSmtpPassword = emailConfig.GetString("SMTPPassword", string.Empty); m_EmailPerSenderPerHour = Math.Max(1, emailConfig.GetInt("PerSenderPerHour", m_EmailPerSenderPerHour)); m_EmailPerRecipientPerHour = Math.Max(1, emailConfig.GetInt("PerRecipientPerHour", m_EmailPerRecipientPerHour)); m_EmailGlobalPerHour = Math.Max(1, emailConfig.GetInt("GlobalPerHour", m_EmailGlobalPerHour)); if (m_EmailUseStartTls && m_EmailUseSslOnConnect) { m_log.Warn("[OfflineIM.V2.EMAIL]: UseStartTls und UseSslOnConnect dürfen nicht gleichzeitig aktiviert sein. Offline-IM-E-Mail wurde deaktiviert."); m_EmailEnabled = false; } if (m_EmailEnabled && (string.IsNullOrWhiteSpace(m_EmailSmtpHost) || m_EmailSmtpPort < 1 || m_EmailSmtpPort > 65535 || !IsValidRelayDomain(m_EmailRelayDomain))) { m_log.Warn("[OfflineIM.V2.EMAIL]: Ungültiger SMTP-Server, SMTP-Port oder RelayDomain. Offline-IM-E-Mail wurde deaktiviert."); m_EmailEnabled = false; } if (m_EmailEnabled && !string.IsNullOrEmpty(m_EmailSmtpUsername) && string.IsNullOrEmpty(m_EmailSmtpPassword)) { m_log.Warn( "[OfflineIM.V2.EMAIL]: SMTP-Benutzer ist konfiguriert, aber NEXVERSE_OFFLINE_IM_SMTP_PASSWORD fehlt oder ist leer. Offline-IM-E-Mail wurde deaktiviert."); m_EmailEnabled = false; } if (m_EmailEnabled && !OfflineImMailRelayToken.IsSigningKeyStrongEnough(m_EmailRelaySigningKey)) { m_log.Warn("[OfflineIM.V2.EMAIL]: RelaySigningKey fehlt oder ist kürzer als 32 Byte. Sichere E-Mail-Antworten bleiben deaktiviert, bis NEXVERSE_IM_RELAY_SIGNING_KEY konfiguriert ist."); } } m_log.DebugFormat("[OfflineIM.V2]: Offline-Nachrichten wurden durch {0} aktiviert", Name); if (m_EmailEnabled) { string smtpSecurity = m_EmailUseSslOnConnect ? "SSL/TLS" : m_EmailUseStartTls ? "STARTTLS" : "keine"; m_log.InfoFormat( "[OfflineIM.V2.EMAIL]: SMTP-Konfiguration aktiv: Server {0}:{1}, Verschlüsselung {2}, Benutzer {3}, Relay-Domain {4}. Passwortquelle: geschützte NexVerse-Runtime-Konfiguration.", m_EmailSmtpHost, m_EmailSmtpPort, smtpSecurity, string.IsNullOrWhiteSpace(m_EmailSmtpUsername) ? "(keiner)" : m_EmailSmtpUsername, m_EmailRelayDomain); } } public void AddRegion(Scene scene) { if (!m_Enabled) return; scene.RegisterModuleInterface(this); lock (m_SceneList) m_SceneList.Add(scene); scene.EventManager.OnNewClient += OnNewClient; } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; if (m_TransferModule == null) { m_TransferModule = scene.RequestModuleInterface(); if (m_TransferModule == null) { scene.EventManager.OnNewClient -= OnNewClient; lock (m_SceneList) m_SceneList.Clear(); m_log.Error("[OfflineIM.V2]: Kein Nachrichtenübertragungsmodul ist aktiviert. Offline-Nachrichten werden deaktiviert."); } m_TransferModule.OnUndeliveredMessage += UndeliveredMessage; } } public void RemoveRegion(Scene scene) { if (!m_Enabled) return; lock (m_SceneList) m_SceneList.Remove(scene); scene.EventManager.OnNewClient -= OnNewClient; m_TransferModule.OnUndeliveredMessage -= UndeliveredMessage; scene.ForEachClient(delegate(IClientAPI client) { client.OnRetrieveInstantMessages -= RetrieveInstantMessages; }); } public void PostInitialise() { } public string Name { get { return "Offline Message Module V2"; } } public Type ReplaceableInterface { get { return null; } } public void Close() { lock (m_SceneList) m_SceneList.Clear(); } private Scene[] SnapshotScenes() { lock (m_SceneList) return m_SceneList.ToArray(); } private Scene FindScene(UUID agentID) { foreach (Scene s in SnapshotScenes()) { ScenePresence presence = s.GetScenePresence(agentID); if (presence != null && !presence.IsChildAgent) return s; } return null; } private IClientAPI FindClient(UUID agentID) { foreach (Scene s in SnapshotScenes()) { ScenePresence presence = s.GetScenePresence(agentID); if (presence != null && !presence.IsChildAgent) return presence.ControllingClient; } return null; } private void OnNewClient(IClientAPI client) { client.OnRetrieveInstantMessages += RetrieveInstantMessages; } private void RetrieveInstantMessages(IClientAPI client) { m_log.DebugFormat("[OfflineIM.V2]: Gespeicherte Nachrichten für {0} werden abgerufen", client.AgentId); List msglist = m_OfflineIMService.GetMessages(client.AgentId); if (msglist == null) m_log.DebugFormat("[OfflineIM.V2]: WARNUNG: Nachrichtenliste ist null."); foreach (GridInstantMessage im in msglist) { if (im.dialog == (byte)InstantMessageDialog.InventoryOffered) // send it directly or else the item will be given twice client.SendInstantMessage(im); else { // Send through scene event manager so all modules get a chance // to look at this message before it gets delivered. // // Needed for proper state management for stored group // invitations // Scene s = client.Scene as Scene; if (s != null) { im.offline = 1; s.EventManager.TriggerIncomingInstantMessage(im); } } } } private void UndeliveredMessage(GridInstantMessage im) { if (im.dialog != (byte)InstantMessageDialog.MessageFromObject && im.dialog != (byte)InstantMessageDialog.MessageFromAgent && im.dialog != (byte)InstantMessageDialog.GroupNotice && im.dialog != (byte)InstantMessageDialog.GroupInvitation && im.dialog != (byte)InstantMessageDialog.InventoryOffered) { return; } if (!m_ForwardOfflineGroupMessages) { if (im.dialog == (byte)InstantMessageDialog.GroupNotice || im.dialog == (byte)InstantMessageDialog.GroupInvitation) return; } string reason = string.Empty; bool success = m_OfflineIMService.StoreMessage(im, out reason); if (success && m_EmailEnabled && im.dialog == (byte)InstantMessageDialog.MessageFromAgent && !im.fromGroup) { QueueOfflineImEmail(im); } if (im.dialog == (byte)InstantMessageDialog.MessageFromAgent) { IClientAPI client = FindClient(new UUID(im.fromAgentID)); if (client == null) return; client.SendInstantMessage(new GridInstantMessage( null, new UUID(im.toAgentID), "System", new UUID(im.fromAgentID), (byte)InstantMessageDialog.MessageFromAgent, "User is not logged in. " + (success ? "Message saved." : "Message not saved: " + reason), false, new Vector3())); } } private void QueueOfflineImEmail(GridInstantMessage im) { UUID senderID = new UUID(im.fromAgentID); UUID recipientID = new UUID(im.toAgentID); if (!ConsumeEmailRate(senderID, recipientID)) { m_log.WarnFormat( "[OfflineIM.V2.EMAIL]: Ratenlimit hat die Offline-IM-E-Mail von {0} an {1} unterdrückt.", senderID, recipientID); return; } GridInstantMessage snapshot = new GridInstantMessage(im, false); ThreadPool.QueueUserWorkItem(_ => SendOfflineImEmail(snapshot)); } private bool ConsumeEmailRate(UUID senderID, UUID recipientID) { double now = Util.GetTimeStamp(); double cutoff = now - 3600.0; lock (m_EmailRateLock) { TrimRateQueue(m_EmailGlobalRate, cutoff); if (!m_EmailSenderRate.TryGetValue(senderID, out Queue senderQueue)) { senderQueue = new Queue(); m_EmailSenderRate[senderID] = senderQueue; } if (!m_EmailRecipientRate.TryGetValue(recipientID, out Queue recipientQueue)) { recipientQueue = new Queue(); m_EmailRecipientRate[recipientID] = recipientQueue; } TrimRateQueue(senderQueue, cutoff); TrimRateQueue(recipientQueue, cutoff); if (m_EmailGlobalRate.Count >= m_EmailGlobalPerHour || senderQueue.Count >= m_EmailPerSenderPerHour || recipientQueue.Count >= m_EmailPerRecipientPerHour) { return false; } m_EmailGlobalRate.Enqueue(now); senderQueue.Enqueue(now); recipientQueue.Enqueue(now); return true; } } private static void TrimRateQueue(Queue queue, double cutoff) { while (queue.Count > 0 && queue.Peek() < cutoff) queue.Dequeue(); } private UserAccount FindLocalAccount(UUID principalID) { foreach (Scene scene in SnapshotScenes()) { try { IUserAccountService accounts = scene?.UserAccountService; if (accounts is null) continue; UserAccount account = accounts.GetUserAccount(scene.RegionInfo.ScopeID, principalID) ?? accounts.GetUserAccount(UUID.Zero, principalID); if (account is not null && account.LocalToGrid && account.PrincipalID == principalID) return account; } catch (Exception e) { m_log.DebugFormat( "[OfflineIM.V2.EMAIL]: Benutzerkonto {0} konnte in Szene {1} nicht ermittelt werden: {2}", principalID, scene?.Name ?? "(unbekannt)", e.Message); } } return null; } private void SendOfflineImEmail(GridInstantMessage im) { UUID recipientID = new UUID(im.toAgentID); UserAccount recipient = FindLocalAccount(recipientID); if (recipient is null || string.IsNullOrWhiteSpace(recipient.Email)) return; if (!MailboxAddress.TryParse(recipient.Email.Trim(), out MailboxAddress recipientAddress)) { m_log.WarnFormat( "[OfflineIM.V2.EMAIL]: Ungültige E-Mail-Adresse für lokales Konto {0}; Benachrichtigung wird übersprungen.", recipientID); return; } string senderName = SanitizeHeaderValue(im.fromAgentName); if (string.IsNullOrWhiteSpace(senderName)) senderName = new UUID(im.fromAgentID).ToString(); string subject = SanitizeHeaderValue( (m_EmailSubjectTemplate ?? "Offline-IM Nachricht von {SENDER}") .Replace("{SENDER}", senderName, StringComparison.Ordinal)); bool replyEnabled = OfflineImMailRelayToken.IsSigningKeyStrongEnough(m_EmailRelaySigningKey); string plainBody = BuildOfflineImEmailBody(recipient, senderName, im, replyEnabled, m_EmailReplyLifetimeDays); string htmlBody = BuildOfflineImEmailHtml(recipient, senderName, im, replyEnabled, m_EmailReplyLifetimeDays); try { UUID senderID = new UUID(im.fromAgentID); string relayEmail = senderID.ToString() + "@" + m_EmailRelayDomain; MailboxAddress relayAddress = new MailboxAddress(senderName, relayEmail); MimeMessage message = new MimeMessage(); message.From.Add(relayAddress); if (replyEnabled) { string replyLocalPart = OfflineImMailRelayToken.Create( senderID, recipientID, recipientAddress.Address, DateTimeOffset.UtcNow.AddDays(m_EmailReplyLifetimeDays), m_EmailRelaySigningKey); message.ReplyTo.Add( new MailboxAddress( senderName + " via NexVerse", replyLocalPart + "@" + m_EmailRelayDomain)); } message.To.Add(new MailboxAddress(recipient.Name, recipientAddress.Address)); message.Subject = subject; message.Headers["X-NexVerse-IM-From-Agent"] = senderID.ToString(); message.Headers["X-NexVerse-IM-To-Agent"] = recipientID.ToString(); message.Headers["X-NexVerse-IM-Reply-Enabled"] = replyEnabled ? "true" : "false"; BodyBuilder bodyBuilder = new BodyBuilder { TextBody = plainBody, HtmlBody = htmlBody }; message.Body = bodyBuilder.ToMessageBody(); using SmtpClient client = new SmtpClient(); SecureSocketOptions socketOptions = m_EmailUseSslOnConnect ? SecureSocketOptions.SslOnConnect : m_EmailUseStartTls ? SecureSocketOptions.StartTls : SecureSocketOptions.None; client.Connect(m_EmailSmtpHost, m_EmailSmtpPort, socketOptions); if (!string.IsNullOrWhiteSpace(m_EmailSmtpUsername)) client.Authenticate(m_EmailSmtpUsername, m_EmailSmtpPassword ?? string.Empty); client.Send(message); client.Disconnect(true); m_log.InfoFormat( "[OfflineIM.V2.EMAIL]: Offline-IM-E-Mail an lokales Konto {0} von {1} wurde versendet.", recipientID, senderName); } catch (AuthenticationException e) { m_log.WarnFormat( "[OfflineIM.V2.EMAIL]: SMTP-Authentifizierung für Benutzer {0} auf {1}:{2} fehlgeschlagen. Bitte NEXVERSE_OFFLINE_IM_SMTP_PASSWORD prüfen. Servermeldung: {3}", string.IsNullOrWhiteSpace(m_EmailSmtpUsername) ? "(keiner)" : m_EmailSmtpUsername, m_EmailSmtpHost, m_EmailSmtpPort, e.Message); } catch (Exception e) { m_log.WarnFormat( "[OfflineIM.V2.EMAIL]: SMTP-Versand für lokales Konto {0} fehlgeschlagen: {1}", recipientID, e.Message); } } private static string BuildOfflineImEmailBody( UserAccount recipient, string senderName, GridInstantMessage im, bool replyEnabled, int replyLifetimeDays) { StringBuilder body = new StringBuilder(); body.AppendLine("NexVerse - Offline-IM"); body.AppendLine(); body.AppendLine("Hallo " + (string.IsNullOrWhiteSpace(recipient.FirstName) ? "NexVerse Resident" : recipient.FirstName) + ","); body.AppendLine(); body.AppendLine("du hast in NexVerse eine Nachricht erhalten, waehrend du offline warst."); body.AppendLine(); body.AppendLine("Absender: " + senderName); if (im.timestamp > 0) { DateTimeOffset sentAt = DateTimeOffset.FromUnixTimeSeconds(im.timestamp); body.AppendLine("Zeit: " + sentAt.UtcDateTime.ToString("dd.MM.yyyy HH:mm:ss") + " UTC"); } body.AppendLine(); body.AppendLine("Nachricht:"); body.AppendLine(im.message ?? string.Empty); body.AppendLine(); if (replyEnabled) body.AppendLine("Du kannst innerhalb von " + replyLifetimeDays + " Tagen direkt auf diese E-Mail antworten. Deine Antwort wird als Inworld-IM an " + senderName + " zugestellt."); else body.AppendLine("Die direkte E-Mail-Antwortfunktion ist derzeit nicht aktiviert."); body.AppendLine(); body.AppendLine("Stadt NexVerse - ...Beyond the Reality"); return body.ToString(); } private static string BuildOfflineImEmailHtml( UserAccount recipient, string senderName, GridInstantMessage im, bool replyEnabled, int replyLifetimeDays) { string firstName = System.Net.WebUtility.HtmlEncode( string.IsNullOrWhiteSpace(recipient.FirstName) ? "NexVerse Resident" : recipient.FirstName); string safeSender = System.Net.WebUtility.HtmlEncode(senderName); string safeMessage = System.Net.WebUtility.HtmlEncode(im.message ?? string.Empty) .Replace("\r\n", "
") .Replace("\n", "
") .Replace("\r", "
"); string sentAt = string.Empty; if (im.timestamp > 0) { DateTimeOffset time = DateTimeOffset.FromUnixTimeSeconds(im.timestamp); sentAt = System.Net.WebUtility.HtmlEncode(time.UtcDateTime.ToString("dd.MM.yyyy HH:mm:ss") + " UTC"); } string replyText = replyEnabled ? "Du kannst innerhalb von " + replyLifetimeDays + " Tagen direkt auf diese E-Mail antworten. Deine Antwort wird als Inworld-IM an " + safeSender + " zugestellt." : "Die direkte E-Mail-Antwortfunktion ist derzeit nicht aktiviert."; return "" + "" + "
" + "" + "" + "
" + "
Stadt NexVerse
" + "
Offline-IM Nachricht
" + "
...Beyond the Reality
" + "

Hallo " + firstName + ",
du hast eine Nachricht erhalten, waehrend du offline warst.

" + "" + "" + (string.IsNullOrEmpty(sentAt) ? string.Empty : "") + "
Absender" + safeSender + "
Zeit" + sentAt + "
" + "
Nachricht
" + "
" + safeMessage + "
" + "
" + replyText + "
" + "

Diese Nachricht wurde automatisch vom NexVerse IM-Relay erzeugt. Verwende fuer Antworten die Antwortfunktion deines E-Mail-Programms; die technische Relay-Adresse ist nur fuer diese Unterhaltung bestimmt.

" + "
"; } private static bool IsValidRelayDomain(string value) { if (string.IsNullOrWhiteSpace(value) || value.Length > 253) return false; string[] labels = value.Split('.'); if (labels.Length < 2) return false; foreach (string label in labels) { if (string.IsNullOrEmpty(label) || label.Length > 63) return false; if (label[0] == '-' || label[label.Length - 1] == '-') return false; foreach (char ch in label) { if (!(char.IsLetterOrDigit(ch) || ch == '-')) return false; } } return true; } private static string SanitizeHeaderValue(string value) { if (string.IsNullOrEmpty(value)) return string.Empty; return value.Replace("\r", " ", StringComparison.Ordinal) .Replace("\n", " ", StringComparison.Ordinal) .Trim(); } #region IOfflineIM public List GetMessages(UUID principalID) { return m_OfflineIMService.GetMessages(principalID); } public bool StoreMessage(GridInstantMessage im, out string reason) { return m_OfflineIMService.StoreMessage(im, out reason); } public void DeleteMessages(UUID userID) { m_OfflineIMService.DeleteMessages(userID); } #endregion } }