EmailModule.cs 17 KB

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