EmailModule.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Reflection;
  30. using System.Text.RegularExpressions;
  31. using DotNetOpenMail;
  32. using DotNetOpenMail.SmtpAuth;
  33. using log4net;
  34. using Nini.Config;
  35. using OpenMetaverse;
  36. using OpenSim.Framework;
  37. using OpenSim.Region.Framework.Interfaces;
  38. using OpenSim.Region.Framework.Scenes;
  39. namespace OpenSim.Region.CoreModules.Scripting.EmailModules
  40. {
  41. public class EmailModule : IEmailModule
  42. {
  43. //
  44. // Log
  45. //
  46. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  47. //
  48. // Module vars
  49. //
  50. private IConfigSource m_Config;
  51. private string m_HostName = string.Empty;
  52. //private string m_RegionName = string.Empty;
  53. private string SMTP_SERVER_HOSTNAME = string.Empty;
  54. private int SMTP_SERVER_PORT = 25;
  55. private string SMTP_SERVER_LOGIN = string.Empty;
  56. private string SMTP_SERVER_PASSWORD = string.Empty;
  57. private int m_MaxQueueSize = 50; // maximum size of an object mail queue
  58. private Dictionary<UUID, List<Email>> m_MailQueues = new Dictionary<UUID, List<Email>>();
  59. private Dictionary<UUID, DateTime> m_LastGetEmailCall = new Dictionary<UUID, DateTime>();
  60. private TimeSpan m_QueueTimeout = new TimeSpan(2, 0, 0); // 2 hours without llGetNextEmail drops the queue
  61. private string m_InterObjectHostname = "lsl.opensim.local";
  62. // Scenes by Region Handle
  63. private Dictionary<ulong, Scene> m_Scenes =
  64. new Dictionary<ulong, Scene>();
  65. private bool m_Enabled = false;
  66. public void InsertEmail(UUID to, Email email)
  67. {
  68. // It's tempting to create the queue here. Don't; objects which have
  69. // not yet called GetNextEmail should have no queue, and emails to them
  70. // should be silently dropped.
  71. lock (m_MailQueues)
  72. {
  73. if (m_MailQueues.ContainsKey(to))
  74. {
  75. if (m_MailQueues[to].Count >= m_MaxQueueSize)
  76. {
  77. // fail silently
  78. return;
  79. }
  80. lock (m_MailQueues[to])
  81. {
  82. m_MailQueues[to].Add(email);
  83. }
  84. }
  85. }
  86. }
  87. public void Initialise(Scene scene, IConfigSource config)
  88. {
  89. m_Config = config;
  90. IConfig SMTPConfig;
  91. //FIXME: RegionName is correct??
  92. //m_RegionName = scene.RegionInfo.RegionName;
  93. IConfig startupConfig = m_Config.Configs["Startup"];
  94. m_Enabled = (startupConfig.GetString("emailmodule", "DefaultEmailModule") == "DefaultEmailModule");
  95. //Load SMTP SERVER config
  96. try
  97. {
  98. if ((SMTPConfig = m_Config.Configs["SMTP"]) == null)
  99. {
  100. m_log.InfoFormat("[SMTP] SMTP server not configured");
  101. m_Enabled = false;
  102. return;
  103. }
  104. if (!SMTPConfig.GetBoolean("enabled", false))
  105. {
  106. m_log.InfoFormat("[SMTP] module disabled in configuration");
  107. m_Enabled = false;
  108. return;
  109. }
  110. m_HostName = SMTPConfig.GetString("host_domain_header_from", m_HostName);
  111. m_InterObjectHostname = SMTPConfig.GetString("internal_object_host", m_InterObjectHostname);
  112. SMTP_SERVER_HOSTNAME = SMTPConfig.GetString("SMTP_SERVER_HOSTNAME", SMTP_SERVER_HOSTNAME);
  113. SMTP_SERVER_PORT = SMTPConfig.GetInt("SMTP_SERVER_PORT", SMTP_SERVER_PORT);
  114. SMTP_SERVER_LOGIN = SMTPConfig.GetString("SMTP_SERVER_LOGIN", SMTP_SERVER_LOGIN);
  115. SMTP_SERVER_PASSWORD = SMTPConfig.GetString("SMTP_SERVER_PASSWORD", SMTP_SERVER_PASSWORD);
  116. }
  117. catch (Exception e)
  118. {
  119. m_log.Error("[EMAIL] DefaultEmailModule not configured: "+ e.Message);
  120. m_Enabled = false;
  121. return;
  122. }
  123. // It's a go!
  124. if (m_Enabled)
  125. {
  126. lock (m_Scenes)
  127. {
  128. // Claim the interface slot
  129. scene.RegisterModuleInterface<IEmailModule>(this);
  130. // Add to scene list
  131. if (m_Scenes.ContainsKey(scene.RegionInfo.RegionHandle))
  132. {
  133. m_Scenes[scene.RegionInfo.RegionHandle] = scene;
  134. }
  135. else
  136. {
  137. m_Scenes.Add(scene.RegionInfo.RegionHandle, scene);
  138. }
  139. }
  140. m_log.Info("[EMAIL] Activated DefaultEmailModule");
  141. }
  142. }
  143. public void PostInitialise()
  144. {
  145. }
  146. public void Close()
  147. {
  148. }
  149. public string Name
  150. {
  151. get { return "DefaultEmailModule"; }
  152. }
  153. public bool IsSharedModule
  154. {
  155. get { return true; }
  156. }
  157. /// <summary>
  158. /// Delay function using thread in seconds
  159. /// </summary>
  160. /// <param name="seconds"></param>
  161. private void DelayInSeconds(int delay)
  162. {
  163. delay = (int)((float)delay * 1000);
  164. if (delay == 0)
  165. return;
  166. System.Threading.Thread.Sleep(delay);
  167. }
  168. private bool IsLocal(UUID objectID)
  169. {
  170. string unused;
  171. return (null != findPrim(objectID, out unused));
  172. }
  173. private SceneObjectPart findPrim(UUID objectID, out string ObjectRegionName)
  174. {
  175. lock (m_Scenes)
  176. {
  177. foreach (Scene s in m_Scenes.Values)
  178. {
  179. SceneObjectPart part = s.GetSceneObjectPart(objectID);
  180. if (part != null)
  181. {
  182. ObjectRegionName = s.RegionInfo.RegionName;
  183. uint localX = (s.RegionInfo.RegionLocX * (int)Constants.RegionSize);
  184. uint localY = (s.RegionInfo.RegionLocY * (int)Constants.RegionSize);
  185. ObjectRegionName = ObjectRegionName + " (" + localX + ", " + localY + ")";
  186. return part;
  187. }
  188. }
  189. }
  190. ObjectRegionName = string.Empty;
  191. return null;
  192. }
  193. private void resolveNamePositionRegionName(UUID objectID, out string ObjectName, out string ObjectAbsolutePosition, out string ObjectRegionName)
  194. {
  195. string m_ObjectRegionName;
  196. int objectLocX;
  197. int objectLocY;
  198. int objectLocZ;
  199. SceneObjectPart part = findPrim(objectID, out m_ObjectRegionName);
  200. if (part != null)
  201. {
  202. objectLocX = (int)part.AbsolutePosition.X;
  203. objectLocY = (int)part.AbsolutePosition.Y;
  204. objectLocZ = (int)part.AbsolutePosition.Z;
  205. ObjectAbsolutePosition = "(" + objectLocX + ", " + objectLocY + ", " + objectLocZ + ")";
  206. ObjectName = part.Name;
  207. ObjectRegionName = m_ObjectRegionName;
  208. return;
  209. }
  210. objectLocX = (int)part.AbsolutePosition.X;
  211. objectLocY = (int)part.AbsolutePosition.Y;
  212. objectLocZ = (int)part.AbsolutePosition.Z;
  213. ObjectAbsolutePosition = "(" + objectLocX + ", " + objectLocY + ", " + objectLocZ + ")";
  214. ObjectName = part.Name;
  215. ObjectRegionName = m_ObjectRegionName;
  216. return;
  217. }
  218. /// <summary>
  219. /// SendMail function utilized by llEMail
  220. /// </summary>
  221. /// <param name="objectID"></param>
  222. /// <param name="address"></param>
  223. /// <param name="subject"></param>
  224. /// <param name="body"></param>
  225. public void SendEmail(UUID objectID, string address, string subject, string body)
  226. {
  227. //Check if address is empty
  228. if (address == string.Empty)
  229. return;
  230. //FIXED:Check the email is correct form in REGEX
  231. string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
  232. + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
  233. + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
  234. + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
  235. + @"[a-zA-Z]{2,}))$";
  236. Regex EMailreStrict = new Regex(EMailpatternStrict);
  237. bool isEMailStrictMatch = EMailreStrict.IsMatch(address);
  238. if (!isEMailStrictMatch)
  239. {
  240. m_log.Error("[EMAIL] REGEX Problem in EMail Address: "+address);
  241. return;
  242. }
  243. //FIXME:Check if subject + body = 4096 Byte
  244. if ((subject.Length + body.Length) > 1024)
  245. {
  246. m_log.Error("[EMAIL] subject + body > 1024 Byte");
  247. return;
  248. }
  249. string LastObjectName = string.Empty;
  250. string LastObjectPosition = string.Empty;
  251. string LastObjectRegionName = string.Empty;
  252. resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);
  253. if (!address.EndsWith(m_InterObjectHostname))
  254. {
  255. // regular email, send it out
  256. try
  257. {
  258. //Creation EmailMessage
  259. EmailMessage emailMessage = new EmailMessage();
  260. //From
  261. emailMessage.FromAddress = new EmailAddress(objectID.ToString() + "@" + m_HostName);
  262. //To - Only One
  263. emailMessage.AddToAddress(new EmailAddress(address));
  264. //Subject
  265. emailMessage.Subject = subject;
  266. //TEXT Body
  267. resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName);
  268. emailMessage.BodyText = "Object-Name: " + LastObjectName +
  269. "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
  270. LastObjectPosition + "\n\n" + body;
  271. //Config SMTP Server
  272. //Set SMTP SERVER config
  273. SmtpServer smtpServer=new SmtpServer(SMTP_SERVER_HOSTNAME,SMTP_SERVER_PORT);
  274. // Add authentication only when requested
  275. //
  276. if (SMTP_SERVER_LOGIN != String.Empty && SMTP_SERVER_PASSWORD != String.Empty)
  277. {
  278. //Authentication
  279. smtpServer.SmtpAuthToken=new SmtpAuthToken(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD);
  280. }
  281. //Send Email Message
  282. emailMessage.Send(smtpServer);
  283. //Log
  284. m_log.Info("[EMAIL] EMail sent to: " + address + " from object: " + objectID.ToString() + "@" + m_HostName);
  285. }
  286. catch (Exception e)
  287. {
  288. m_log.Error("[EMAIL] DefaultEmailModule Exception: " + e.Message);
  289. }
  290. }
  291. else
  292. {
  293. // inter object email, keep it in the family
  294. Email email = new Email();
  295. email.time = ((int)((DateTime.UtcNow - new DateTime(1970,1,1,0,0,0)).TotalSeconds)).ToString();
  296. email.subject = subject;
  297. email.sender = objectID.ToString() + "@" + m_InterObjectHostname;
  298. email.message = "Object-Name: " + LastObjectName +
  299. "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " +
  300. LastObjectPosition + "\n\n" + body;
  301. string guid = address.Substring(0, address.IndexOf("@"));
  302. UUID toID = new UUID(guid);
  303. if (IsLocal(toID)) // TODO FIX check to see if it is local
  304. {
  305. // object in this region
  306. InsertEmail(toID, email);
  307. }
  308. else
  309. {
  310. // object on another region
  311. // TODO FIX
  312. }
  313. }
  314. //DONE: Message as Second Life style
  315. //20 second delay - AntiSpam System - for now only 10 seconds
  316. DelayInSeconds(10);
  317. }
  318. /// <summary>
  319. ///
  320. /// </summary>
  321. /// <param name="objectID"></param>
  322. /// <param name="sender"></param>
  323. /// <param name="subject"></param>
  324. /// <returns></returns>
  325. public Email GetNextEmail(UUID objectID, string sender, string subject)
  326. {
  327. List<Email> queue = null;
  328. lock (m_LastGetEmailCall)
  329. {
  330. if (m_LastGetEmailCall.ContainsKey(objectID))
  331. {
  332. m_LastGetEmailCall.Remove(objectID);
  333. }
  334. m_LastGetEmailCall.Add(objectID, DateTime.Now);
  335. // Hopefully this isn't too time consuming. If it is, we can always push it into a worker thread.
  336. DateTime now = DateTime.Now;
  337. List<UUID> removal = new List<UUID>();
  338. foreach (UUID uuid in m_LastGetEmailCall.Keys)
  339. {
  340. if ((now - m_LastGetEmailCall[uuid]) > m_QueueTimeout)
  341. {
  342. removal.Add(uuid);
  343. }
  344. }
  345. foreach (UUID remove in removal)
  346. {
  347. m_LastGetEmailCall.Remove(remove);
  348. lock (m_MailQueues)
  349. {
  350. m_MailQueues.Remove(remove);
  351. }
  352. }
  353. }
  354. lock (m_MailQueues)
  355. {
  356. if (m_MailQueues.ContainsKey(objectID))
  357. {
  358. queue = m_MailQueues[objectID];
  359. }
  360. }
  361. if (queue != null)
  362. {
  363. lock (queue)
  364. {
  365. if (queue.Count > 0)
  366. {
  367. int i;
  368. for (i = 0; i < queue.Count; i++)
  369. {
  370. if ((sender == null || sender.Equals("") || sender.Equals(queue[i].sender)) &&
  371. (subject == null || subject.Equals("") || subject.Equals(queue[i].subject)))
  372. {
  373. break;
  374. }
  375. }
  376. if (i != queue.Count)
  377. {
  378. Email ret = queue[i];
  379. queue.Remove(ret);
  380. ret.numLeft = queue.Count;
  381. return ret;
  382. }
  383. }
  384. }
  385. }
  386. else
  387. {
  388. lock (m_MailQueues)
  389. {
  390. m_MailQueues.Add(objectID, new List<Email>());
  391. }
  392. }
  393. return null;
  394. }
  395. }
  396. }