MailServer_Service.cs
上传用户:horngjaan
上传日期:2009-12-12
资源大小:2882k
文件大小:27k
源码类别:

Email服务器

开发平台:

C#

  1. using System;
  2. using System.IO;
  3. using System.Collections;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Diagnostics;
  7. using System.ServiceProcess;
  8. using System.Threading;
  9. using LumiSoft.MailServer;
  10. namespace LumiSoft.MailServer
  11. {
  12. /// <summary>
  13. /// Mail server service.
  14. /// </summary>
  15. public class MailServer : System.ServiceProcess.ServiceBase
  16. {
  17. private LumiSoft.MailServer.POP3.POP3_Server POP3_Server;
  18. private LumiSoft.MailServer.SMTP.SMTP_Server SMTP_Server;
  19. private System.Timers.Timer timer1;
  20. private System.ComponentModel.IContainer components;
  21. private  static  ServerAPI m_pAPI  = null;
  22. private DataSet  dsSettings        = null;
  23. internal string  m_SartUpPath      = ""; // Path where (this)service relies.
  24. internal string  m_PostmasterUName = "";    // Holds postmaster UserName.
  25. internal string  m_PostmasterPwd   = "";    // Holds postmaster Password.
  26. private DB_Type  m_DB_Type         = DB_Type.XML;
  27. internal string  m_connStr         = "";    // Sql connection string to Mail DB.
  28. private DateTime m_SettingsDate;            // Holds server Settings.xml date.
  29. private DateTime m_UsersDate;               // Holds server Users.xml date.
  30. private DateTime m_AliasesDate;             // Holds server Aliases.xml date.
  31. private DateTime m_RoutingDate;             // Holds server Routing.xml date.
  32. private DateTime m_DomainsDate;     // Holds server Domains.xml date.
  33. private DateTime m_SecurityDate;     // Holds server Secuirty.xml date.
  34. private DateTime m_RelayTime;
  35. private DateTime m_RelayRetryTime;
  36. /// <summary>
  37. /// Default constructor.
  38. /// </summary>
  39. public MailServer()
  40. {
  41. // This call is required by the Windows.Forms Component Designer.
  42. InitializeComponent();
  43. // TODO: Add any initialization after the InitComponent call
  44. }
  45. #region static Main
  46. // The main entry point for the process
  47. static void Main()
  48. {
  49. System.ServiceProcess.ServiceBase[] ServicesToRun;
  50. // More than one user Service may run within the same process. To add
  51. // another service to this process, change the following line to
  52. // create a second service object. For example,
  53. //
  54. //   ServicesToRun = New System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};
  55. //
  56. ServicesToRun = new System.ServiceProcess.ServiceBase[] { new MailServer() };
  57. System.ServiceProcess.ServiceBase.Run(ServicesToRun);
  58. }
  59. #endregion
  60. #region Designer Generated code
  61. /// <summary> 
  62. /// Required method for Designer support - do not modify 
  63. /// the contents of this method with the code editor.
  64. /// </summary>
  65. private void InitializeComponent()
  66. {
  67. this.components = new System.ComponentModel.Container();
  68. this.POP3_Server = new LumiSoft.MailServer.POP3.POP3_Server(this.components);
  69. this.timer1 = new System.Timers.Timer();
  70. this.SMTP_Server = new LumiSoft.MailServer.SMTP.SMTP_Server(this.components);
  71. ((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
  72. // 
  73. // POP3_Server
  74. // 
  75. this.POP3_Server.CommandIdleTimeOut = 60000;
  76. this.POP3_Server.LogCommands = false;
  77. this.POP3_Server.SessionIdleTimeOut = 80000;
  78. this.POP3_Server.GetTopLines += new LumiSoft.MailServer.POP3.GetTopLinesHandler(this.POP3_Server_GetTopLines);
  79. this.POP3_Server.GetMailEvent += new LumiSoft.MailServer.POP3.GetMessageHandler(this.pop3_Server_GetMailEvent);
  80. this.POP3_Server.DeleteMessageEvent += new LumiSoft.MailServer.POP3.DeleteMessageHandler(this.pop3_Server_DeleteMessageEvent);
  81. this.POP3_Server.SysError += new LumiSoft.MailServer.ErrorEventHandler(this.OnServer_SysError);
  82. this.POP3_Server.AuthUser += new LumiSoft.MailServer.AuthUserEventHandler(this.Server_AuthenticateUser);
  83. this.POP3_Server.GetMessgesList += new LumiSoft.MailServer.POP3.GetMessagesInfoHandler(this.pop3_Server_GetMessgesList);
  84. this.POP3_Server.SessionLog += new LumiSoft.MailServer.LogEventHandler(this.POP3_Server_SessionLog);
  85. this.POP3_Server.ValidateIPAddress += new LumiSoft.MailServer.ValidateIPHandler(this.POP3_Server_ValidateIPAddress);
  86. // 
  87. // timer1
  88. // 
  89. this.timer1.Interval = 15000;
  90. this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
  91. // 
  92. // SMTP_Server
  93. // 
  94. this.SMTP_Server.CommandIdleTimeOut = 60000;
  95. this.SMTP_Server.LogCommands = false;
  96. this.SMTP_Server.MaxBadCommands = 8;
  97. this.SMTP_Server.MaxMessageSize = 1000000;
  98. this.SMTP_Server.MaxRecipients = 100;
  99. this.SMTP_Server.SessionIdleTimeOut = 80000;
  100. this.SMTP_Server.AuthUser += new LumiSoft.MailServer.AuthUserEventHandler(this.Server_AuthenticateUser);
  101. this.SMTP_Server.SessionLog += new LumiSoft.MailServer.LogEventHandler(this.SMTP_Server_SessionLog);
  102. this.SMTP_Server.ValidateMailFrom += new LumiSoft.MailServer.SMTP.ValidateMailFromHandler(this.smtp_Server_ValidateSender);
  103. this.SMTP_Server.SysError += new LumiSoft.MailServer.ErrorEventHandler(this.OnServer_SysError);
  104. this.SMTP_Server.NewMailEvent += new LumiSoft.MailServer.SMTP.NewMailEventHandler(this.smtp_Server_NewMailEvent);
  105. this.SMTP_Server.ValidateMailTo += new LumiSoft.MailServer.SMTP.ValidateMailToHandler(this.smtp_Server_ValidateRecipient);
  106. this.SMTP_Server.ValidateMailboxSize += new LumiSoft.MailServer.SMTP.ValidateMailboxSize(this.SMTP_Server_ValidateMailBoxSize);
  107. this.SMTP_Server.ValidateIPAddress += new LumiSoft.MailServer.ValidateIPHandler(this.SMTP_Server_ValidateIPAddress);
  108. // 
  109. // MailServer
  110. // 
  111. this.ServiceName = "Service1";
  112. ((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
  113. }
  114. #endregion
  115. #region function Dispose
  116. /// <summary>
  117. /// Clean up any resources being used.
  118. /// </summary>
  119. protected override void Dispose( bool disposing )
  120. {
  121. if( disposing )
  122. {
  123. if (components != null) 
  124. {
  125. components.Dispose();
  126. }
  127. }
  128. base.Dispose( disposing );
  129. }
  130. #endregion
  131. #region function OnStart
  132. /// <summary>
  133. /// Set things in motion so your service can do its work.
  134. /// </summary>
  135. protected override void OnStart(string[] args)
  136. {
  137. try
  138. {
  139. string filePath     = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
  140. m_SartUpPath        = filePath.Substring(0,filePath.LastIndexOf('\')) + "\";
  141. Error.ErrorFilePath = m_SartUpPath;
  142. LoadSettings();
  143. m_pAPI = new ServerAPI(m_SartUpPath + "Settings\",MailStore.MailStorePath,m_connStr,m_DB_Type);
  144. // If don't use sql, load Users and Domains from xml
  145. if(m_DB_Type == DB_Type.XML){
  146. LoadLocalDomains();
  147. LoadLocalUsers();
  148. LoadLocalAliases();
  149. LoadRoutes();
  150. LoadLocalSecurity();
  151. }
  152. // Start Servers
  153. SMTP_Server.Enabled = true;
  154. POP3_Server.Enabled = true;
  155. timer1.Enabled = true;
  156. m_RelayTime      = DateTime.Today;
  157. m_RelayRetryTime = DateTime.Today;
  158. // Logging stuff
  159.                 SCore.WriteLog(m_SartUpPath + "Logs\Server\server.log","//---- Server started " + DateTime.Now);
  160. }
  161. catch(Exception x)
  162. {
  163. Error.DumpError(x,new System.Diagnostics.StackTrace());
  164. }
  165. }
  166. #endregion
  167. #region function OnStop
  168.  
  169. /// <summary>
  170. /// Stop this service.
  171. /// </summary>
  172. protected override void OnStop()
  173. {
  174. SMTP_Server.Enabled = false;
  175. POP3_Server.Enabled = false;
  176. timer1.Enabled = false;
  177. // Logging stuff
  178. SCore.WriteLog(m_SartUpPath + "Logs\Server\server.log","//---- Server stopped " + DateTime.Now);
  179. }
  180. #endregion
  181. #region SMTP Events
  182. //------ SMTP Events -----------------------//
  183. #region function SMTP_Server_ValidateIPAddress
  184. private void SMTP_Server_ValidateIPAddress(object sender, LumiSoft.MailServer.ValidateIP_EventArgs e)
  185. {
  186. try
  187. {
  188. string IP = Ip_to_longStr(e.ConnectedIP);
  189. e.Validated = m_pAPI.IsSmtpAccessAllowed(IP);
  190. }
  191. catch(Exception x)
  192. {
  193. e.Validated = false;
  194. Error.DumpError(x,new System.Diagnostics.StackTrace());
  195. }
  196. }
  197. #endregion
  198. #region function smtp_Server_ValidateSender
  199. private void smtp_Server_ValidateSender(object sender, LumiSoft.MailServer.SMTP.ValidateSender_EventArgs e)
  200. {
  201. e.Validated = true;
  202. }
  203. #endregion
  204. #region function smtp_Server_ValidateRecipient
  205. private void smtp_Server_ValidateRecipient(object sender, LumiSoft.MailServer.SMTP.ValidateRecipient_EventArgs e)
  206. {
  207. try
  208. {
  209. e.Validated = false;
  210. string mailTo = e.MailTo;
  211. mailTo = mailTo.Replace("%",""); //remove '%'
  212. mailTo = mailTo.Replace("!",""); //remove '!'
  213. mailTo = mailTo.Replace("[",""); //remove '['
  214. mailTo = mailTo.Replace("]",""); //remove ']'
  215. //1) is local domain or relay needed
  216. //2) can map email address to mailbox
  217. //3) [is alias. NOTE: only authenticated user can access alias !]
  218. //4) if matches any routing pattern
  219. // check e-domain, if it's local.
  220. if(m_pAPI.DomainExists(mailTo)){
  221. if(m_pAPI.MapUser(mailTo) == null){
  222. // Check if alias. NOTE: only authenticated user can access alias !
  223. if(e.Authenticated && m_pAPI.GetAliasMembers(mailTo) != null){
  224. e.Validated = true;
  225. }
  226. // At least check if matches any routing pattern.
  227. else if(m_pAPI.GetMailboxFromPattern(mailTo) != null){
  228. e.Validated = true;
  229. }
  230. }
  231. else{
  232. e.Validated = true;
  233. }
  234. }
  235. else{
  236. e.LocalRecipient = false;
  237. // This isn't domain what we want.
  238. // 1)If user Authenticated, allow relay.
  239. // 2)Check if relay is allowed for this ip.
  240. if(e.Authenticated || IsRelayAllowed(e.ConnectedIP)){
  241. e.Validated = true;
  242. }
  243. }
  244. }
  245. catch(Exception x)
  246. {
  247. Error.DumpError(x,new System.Diagnostics.StackTrace());
  248. }
  249. }
  250. #endregion
  251. #region function SMTP_Server_ValidateMailBoxSize
  252. private void SMTP_Server_ValidateMailBoxSize(object sender, LumiSoft.MailServer.SMTP.ValidateMailboxSize_EventArgs e)
  253. {
  254. e.IsValid = false;
  255. try
  256. {
  257. // If relay or alias address, don't check size
  258. if(!m_pAPI.DomainExists(e.eAddress) || m_pAPI.GetAliasMembers(e.eAddress) != null){
  259. e.IsValid = true;
  260. return;
  261. }
  262. //--------------------------------//
  263. string user = m_pAPI.MapUser(e.eAddress);
  264. if(user == null){
  265. user = m_pAPI.GetMailboxFromPattern(e.eAddress);
  266. }
  267. if(user != null){
  268. e.IsValid = !m_pAPI.ValidateMailboxSize(user);
  269. }
  270. }
  271. catch(Exception x)
  272. {
  273. Error.DumpError(x,new System.Diagnostics.StackTrace());
  274. }
  275. }
  276. #endregion
  277. #region function smtp_Server_NewMailEvent
  278. private void smtp_Server_NewMailEvent(object sender, LumiSoft.MailServer.SMTP.NewMail_EventArgs e)
  279. {
  280. try
  281. {
  282. Hashtable forward_pathList = new Hashtable();
  283. //--------------------------------------------------------------//
  284. // Construct new forward-path list.(because of aliases)
  285. foreach(string forward_path in e.MailTo){
  286. string emailAddress   = Core.ParseEmailFromPath(forward_path);
  287. string[] aliasMembers = m_pAPI.GetAliasMembers(emailAddress);
  288. if(aliasMembers != null){
  289. foreach(string member in aliasMembers){
  290. if(!forward_pathList.Contains(member)){
  291. forward_pathList.Add(member,member);
  292. }
  293. }
  294. }
  295. else{
  296. if(!forward_pathList.Contains(emailAddress)){
  297. forward_pathList.Add(emailAddress,forward_path);
  298. }
  299. }
  300. }
  301. //------------------------------------------------------------//
  302. // Store individual msg for each Recipient
  303. foreach(string forward_path in forward_pathList.Values){
  304. string eAddress = Core.ParseEmailFromPath(forward_path);
  305. string mailbox  = m_pAPI.MapUser(eAddress);
  306. bool   relay    = false;
  307. // if not valid mailbox
  308. if(mailbox == null){
  309. // check e-domain, if it's local.
  310. if(m_pAPI.DomainExists(eAddress)){
  311. // Check if eAddress matches routing pattern
  312. mailbox = m_pAPI.GetMailboxFromPattern(eAddress);
  313. // If there isn't valid mailbox, some error has happened.
  314. // (One known reason is when user,alias,routing is deleted between RCPT and DATA)
  315. // Forward message to postmaster.
  316. if(mailbox == null){
  317. mailbox = "postmaster";
  318. }
  319. }
  320. // This isn't domain what we want, relay message.
  321. else{
  322. relay = true;
  323. }
  324. }
  325. // stores mail 
  326. MailStore.StoreMessage(mailbox,e.MessageStream,forward_path,e.MailFrom,relay);
  327. }
  328. }
  329. catch(Exception x)
  330. {
  331. Error.DumpError(x,new System.Diagnostics.StackTrace());
  332. }
  333. }
  334. #endregion
  335. #region function SMTP_Server_SessionLog
  336. private void SMTP_Server_SessionLog(object sender, LumiSoft.MailServer.Log_EventArgs e)
  337. {
  338. DateTime today = DateTime.Today;
  339. string fileName = "smtpCmds_" + today.Year.ToString() + "_" + today.Month.ToString() + "_" + today.Day.ToString() + ".log";
  340. SCore.WriteLog(m_SartUpPath + "Logs\SMTP\" + fileName,e.LogText);
  341. }
  342. #endregion
  343. //------ End of SMTP Events ----------------//
  344. #endregion
  345. #region POP3 Events
  346. //------ POP3 Events ----------------------//
  347. #region function POP3_Server_ValidateIPAddress
  348. private void POP3_Server_ValidateIPAddress(object sender, LumiSoft.MailServer.ValidateIP_EventArgs e)
  349. {
  350. try
  351. {
  352. string IP = Ip_to_longStr(e.ConnectedIP);
  353. e.Validated = m_pAPI.IsPop3AccessAllowed(IP);
  354. }
  355. catch(Exception x)
  356. {
  357. e.Validated = false;
  358. Error.DumpError(x,new System.Diagnostics.StackTrace());
  359. }
  360. }
  361. #endregion
  362. #region function pop3_Server_GetMessgesList
  363. private void pop3_Server_GetMessgesList(object sender, LumiSoft.MailServer.POP3.GetMessagesInfo_EventArgs e)
  364. {
  365. try
  366. {
  367. string userName = e.UserName;
  368. // If postmaster, mailbox name is always 'postmaster'.
  369. if(m_PostmasterUName == e.UserName){
  370. userName = "postmaster";
  371. }
  372. MailStore.GetMessageList(userName,e);
  373. }
  374. catch(Exception x)
  375. {
  376. Error.DumpError(x,new System.Diagnostics.StackTrace());
  377. }
  378. }
  379. #endregion
  380. #region function pop3_Server_GetMailEvent
  381. private void pop3_Server_GetMailEvent(object sender, LumiSoft.MailServer.POP3.GetMessage_EventArgs e)
  382. {
  383. try
  384. {
  385. string mailbox = e.UserName;
  386. string msgFile = e.MessageID;
  387. // If postmaster, mailbox name is always 'postmaster'.
  388. if(m_PostmasterUName == e.UserName){
  389. mailbox = "postmaster";
  390. }
  391. e.Message = MailStore.GetMessage(mailbox,msgFile);
  392. }
  393. catch(Exception x)
  394. {
  395. Error.DumpError(x,new System.Diagnostics.StackTrace());
  396. }
  397. }
  398. #endregion
  399. #region function pop3_Server_DeleteMessageEvent
  400. private void pop3_Server_DeleteMessageEvent(object sender, LumiSoft.MailServer.POP3.DeleteMessage_EventArgs e)
  401. {
  402. try
  403. {
  404. string mailbox = e.UserName;
  405. string msgFile = e.MessageID;
  406. MailStore.DeleteMessage(mailbox,msgFile);
  407. }
  408. catch(Exception x)
  409. {
  410. Error.DumpError(x,new System.Diagnostics.StackTrace());
  411. }
  412. }
  413. #endregion
  414. #region function POP3_Server_GetTopLines
  415. private void POP3_Server_GetTopLines(object sender, LumiSoft.MailServer.POP3.GetTopLines_Eventargs e)
  416. {
  417. try
  418. {
  419. e.LinesData = m_pAPI.GetMessageTopLines(e.Mailbox,e.MessageID,e.Lines);
  420. }
  421. catch(Exception x)
  422. {
  423. Error.DumpError(x,new System.Diagnostics.StackTrace());
  424. }
  425. }
  426. #endregion
  427. #region function POP3_Server_SessionLog
  428. private void POP3_Server_SessionLog(object sender, LumiSoft.MailServer.Log_EventArgs e)
  429. {
  430. DateTime today = DateTime.Today;
  431. string fileName = "pop3Cmds_" + today.Year.ToString() + "_" + today.Month.ToString() + "_" + today.Day.ToString() + ".log";
  432. SCore.WriteLog(m_SartUpPath + "Logs\POP3\" + fileName,e.LogText);
  433. }
  434. #endregion
  435. //------ End of POP3 Events ---------------//
  436. #endregion
  437. #region Common Events
  438. #region function Server_AuthenticateUser
  439. private void Server_AuthenticateUser(object sender, LumiSoft.MailServer.AuthUser_EventArgs e)
  440. {
  441. try
  442. {
  443. e.Validated = m_pAPI.AuthUser(e.UserName,e.PasswData,e.AuthData,e.AuthType);
  444. }
  445. catch(Exception x)
  446. {
  447. e.Validated = false;
  448. Error.DumpError(x,new System.Diagnostics.StackTrace());
  449. }
  450. }
  451. #endregion
  452. #region function OnServer_SysError
  453. private void OnServer_SysError(object sender,LumiSoft.MailServer.Error_EventArgs e)
  454. {
  455. Error.DumpError(e.Exception,e.StackTrace);
  456. }
  457. #endregion
  458. #endregion
  459. #region function IsRelayAllowed
  460. /// <summary>
  461. /// Checks if relaying is allowed to specified IP.
  462. /// </summary>
  463. /// <param name="ipAddress"></param>
  464. /// <returns></returns>
  465. private bool IsRelayAllowed(string ipAddress)
  466. {
  467. try
  468. {
  469. string IP = Ip_to_longStr(ipAddress);
  470. return m_pAPI.IsRelayAllowed(IP);
  471. }
  472. catch(Exception x)
  473. {
  474. Error.DumpError(x,new System.Diagnostics.StackTrace());
  475. }
  476. return false;
  477. }
  478. #endregion
  479. #region Service Timer
  480. private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
  481. {
  482. try
  483. {
  484. //------------ local settings --------------------------------------------------------------//
  485. DateTime dateSettings = File.GetLastWriteTime(m_SartUpPath + "\Settings\Settings.xml");
  486. if(DateTime.Compare(dateSettings,m_SettingsDate) != 0){
  487. LoadSettings();
  488. }
  489. if(m_DB_Type == DB_Type.XML){
  490. DateTime dateUsers    = File.GetLastWriteTime(m_SartUpPath + "\Settings\Users.xml");
  491. DateTime dateAliases  = File.GetLastWriteTime(m_SartUpPath + "\Settings\Aliases.xml");
  492. DateTime dateDomains  = File.GetLastWriteTime(m_SartUpPath + "\Settings\Domains.xml");
  493. DateTime dateRouting  = File.GetLastWriteTime(m_SartUpPath + "\Settings\Routing.xml");
  494. DateTime dateSecurity = File.GetLastWriteTime(m_SartUpPath + "\Settings\Security.xml");
  495. if(DateTime.Compare(dateDomains,m_DomainsDate) != 0){
  496. LoadLocalDomains();
  497. }
  498. if(DateTime.Compare(dateUsers,m_UsersDate) != 0){
  499. LoadLocalUsers();
  500. }
  501. if(DateTime.Compare(dateAliases,m_AliasesDate) != 0){
  502. LoadLocalAliases();
  503. }
  504. if(DateTime.Compare(dateRouting,m_RoutingDate) != 0){
  505. LoadRoutes();
  506. }
  507. if(DateTime.Compare(dateSecurity,m_SecurityDate) != 0){
  508. LoadLocalSecurity();
  509. }
  510. }
  511. //------------------------------------------------------------------------------------------//
  512. //---- Relay stuff ----------------------------------------------------------------------------//
  513. if(DateTime.Now.CompareTo(m_RelayTime.AddSeconds(Relay.RelayInterval)) >= 0 && !Relay.IsDelivering){
  514. Relay relay = new Relay(this);
  515. // Create New Thread for Mail Delivery handling
  516. ThreadStart tStart = new ThreadStart(relay.Deliver);
  517. Thread      tr     = new Thread(tStart);
  518. tr.Priority        = ThreadPriority.Lowest;
  519. tr.Start();
  520. m_RelayTime = DateTime.Now;
  521. }
  522. if(DateTime.Now.CompareTo(m_RelayRetryTime.AddSeconds(Relay.RelayRetryInterval)) >= 0 && !Relay.IsDeliveringRetry){
  523. Relay relay = new Relay(this);
  524. // Create New Thread for Mail Delivery handling
  525. ThreadStart tStart = new ThreadStart(relay.DeliverRetry);
  526. Thread      tr     = new Thread(tStart);
  527. tr.Priority        = ThreadPriority.Lowest;
  528. tr.Start();
  529. m_RelayRetryTime = DateTime.Now;
  530. }
  531. //----------------------------------------------------------------------------------------------//
  532. }
  533. catch(Exception x)
  534. {
  535. Error.DumpError(x,new System.Diagnostics.StackTrace());
  536. }
  537. }
  538. #endregion
  539. #region Local settings loading stuff
  540. #region function LoadSettings
  541. private void LoadSettings()
  542. {
  543. try
  544. {
  545. lock(this){
  546. dsSettings = new DataSet();
  547. dsSettings.ReadXml(m_SartUpPath + "\Settings\Settings.xml");
  548. m_SettingsDate = File.GetLastWriteTime(m_SartUpPath + "\Settings\Settings.xml");
  549. DataRow dr = dsSettings.Tables["Settings"].Rows[0];
  550. m_connStr             = dr["ConnectionString"].ToString();
  551. m_DB_Type             = (DB_Type)Enum.Parse(typeof(DB_Type),dr["DataBaseType"].ToString());
  552. string mailStorePath  = dr["MailRoot"].ToString();
  553. if(!mailStorePath.EndsWith("\")){
  554. mailStorePath += "\";
  555. }
  556. if(mailStorePath.Length < 3){
  557. mailStorePath = m_SartUpPath + "MailStore\";
  558. }
  559. MailStore.MailStorePath = mailStorePath;
  560. //------- SMTP Settings ---------------------------------------------//
  561. SMTP_Server.IpAddress          = dr["SMTP_IPAddress"].ToString();
  562. SMTP_Server.Port               = Convert.ToInt32(dr["SMTP_Port"]);
  563. SMTP_Server.Threads            = Convert.ToInt32(dr["SMTP_Threads"]);
  564. SMTP_Server.SessionIdleTimeOut = Convert.ToInt32(dr["SMTP_SessionIdleTimeOut"]) * 1000; // Seconds to milliseconds
  565. SMTP_Server.CommandIdleTimeOut = Convert.ToInt32(dr["SMTP_CommandIdleTimeOut"]) * 1000; // Seconds to milliseconds
  566. SMTP_Server.MaxMessageSize     = Convert.ToInt32(dr["MaxMessageSize"]) * 1000000;       // Mb to byte.
  567. SMTP_Server.MaxRecipients      = Convert.ToInt32(dr["MaxRecipients"]);
  568. SMTP_Server.MaxBadCommands     = Convert.ToInt32(dr["SMTP_MaxBadCommands"]);
  569. m_PostmasterUName = dr["PostMasterUserName"].ToString();
  570. m_PostmasterPwd   = dr["PostMasterPassword"].ToString();
  571. //-------------------------------------------------------------------//
  572. //------- POP3 Settings -------------------------------------//
  573. POP3_Server.IpAddress = dr["POP3_IPAddress"].ToString();
  574. POP3_Server.Port      = Convert.ToInt32(dr["POP3_Port"]);
  575. POP3_Server.Threads   = Convert.ToInt32(dr["POP3_Threads"]);
  576. POP3_Server.SessionIdleTimeOut = Convert.ToInt32(dr["POP3_SessionIdleTimeOut"]) * 1000; // Seconds to milliseconds
  577. POP3_Server.CommandIdleTimeOut = Convert.ToInt32(dr["POP3_CommandIdleTimeOut"]) * 1000; // Seconds to milliseconds
  578. POP3_Server.MaxBadCommands     = Convert.ToInt32(dr["POP3_MaxBadCommands"]);
  579. //-----------------------------------------------------------//
  580. //------- Delivery ------------------------------------------//
  581. Relay.SmartHost            = dr["SmartHost"].ToString();
  582. Relay.UseSmartHost         = Convert.ToBoolean(dr["UseSmartHost"]);
  583. Relay.Dns1                 = dr["Dns1"].ToString();
  584. Relay.Dns2                 = dr["Dns2"].ToString();
  585. Relay.RelayInterval        = Convert.ToInt32(dr["RelayInterval"]);
  586. Relay.RelayRetryInterval   = Convert.ToInt32(dr["RelayRetryInterval"]);
  587. Relay.RelayUndelWarning    = Convert.ToInt32(dr["RelayUndeliveredWarning"]);
  588. Relay.RelayUndelivered     = Convert.ToInt32(dr["RelayUndelivered"]);
  589. Relay.MaxRelayThreads      = Convert.ToInt32(dr["MaxRelayThreads"]);
  590. Relay.UndeliveredTemplate  = dr["UndeliveredTemplate"].ToString();
  591. Relay.UndelWarningTemplate = dr["UndeliveredWarningTemplate"].ToString();
  592. //-----------------------------------------------------------//
  593. //----- Logging settings -------------------------------------//
  594. SMTP_Server.LogCommands = Convert.ToBoolean(dr["LogSMTPCmds"]);
  595. POP3_Server.LogCommands = Convert.ToBoolean(dr["LogPOP3Cmds"]);
  596. //------------------------------------------------------------//
  597. SCore.WriteLog(m_SartUpPath + "Logs\Server\server.log","//---- Server settings loaded " + DateTime.Now);
  598. }
  599. }
  600. catch(Exception x)
  601. {
  602. Error.DumpError(x,new System.Diagnostics.StackTrace());
  603. }
  604. }
  605. #endregion
  606. #region function LoadLocalDomains
  607. private void LoadLocalDomains()
  608. {
  609. try
  610. {
  611. lock(this){
  612. m_pAPI.LoadDomains();
  613. m_DomainsDate = File.GetLastWriteTime(m_SartUpPath + "\Settings\Domains.xml");
  614. SCore.WriteLog(m_SartUpPath + "Logs\Server\server.log","//---- Local Domains loaded " + DateTime.Now);
  615. }
  616. }
  617. catch(Exception x)
  618. {
  619. Error.DumpError(x,new System.Diagnostics.StackTrace());
  620. }
  621. }
  622. #endregion
  623. #region function LoadLocalUsers
  624. private void LoadLocalUsers()
  625. {
  626. try
  627. {
  628. lock(this){
  629. m_pAPI.LoadUsers();
  630. m_UsersDate = File.GetLastWriteTime(m_SartUpPath + "\Settings\Users.xml");
  631. SCore.WriteLog(m_SartUpPath + "Logs\Server\server.log","//---- Local Users loaded " + DateTime.Now);
  632. }
  633. }
  634. catch(Exception x)
  635. {
  636. Error.DumpError(x,new System.Diagnostics.StackTrace());
  637. }
  638. }
  639. #endregion
  640. #region function LoadLocalAliases
  641. private void LoadLocalAliases()
  642. {
  643. try
  644. {
  645. lock(this){
  646. m_pAPI.LoadAliases();
  647. m_AliasesDate = File.GetLastWriteTime(m_SartUpPath + "\Settings\Aliases.xml");
  648. SCore.WriteLog(m_SartUpPath + "Logs\Server\server.log","//---- Local Aliaeses loaded " + DateTime.Now);
  649. }
  650. }
  651. catch(Exception x)
  652. {
  653. Error.DumpError(x,new System.Diagnostics.StackTrace());
  654. }
  655. }
  656. #endregion
  657. #region function LoadRoutes
  658. private void LoadRoutes()
  659. {
  660. try
  661. {
  662. lock(this){
  663. m_pAPI.LoadRouting();
  664. m_RoutingDate = File.GetLastWriteTime(m_SartUpPath + "\Settings\Routing.xml");
  665. SCore.WriteLog(m_SartUpPath + "Logs\Server\server.log","//---- Local Routes loaded " + DateTime.Now);
  666. }
  667. }
  668. catch(Exception x)
  669. {
  670. Error.DumpError(x,new System.Diagnostics.StackTrace());
  671. }
  672. }
  673. #endregion
  674. #region function LoadLocalSecurity
  675. private void LoadLocalSecurity()
  676. {
  677. try
  678. {
  679. lock(this){
  680. m_pAPI.LoadSecurity();
  681. m_SecurityDate = File.GetLastWriteTime(m_SartUpPath + "\Settings\Security.xml");
  682. SCore.WriteLog(m_SartUpPath + "Logs\Server\server.log","//---- Local Security loaded " + DateTime.Now);
  683. }
  684. }
  685. catch(Exception x)
  686. {
  687. Error.DumpError(x,new System.Diagnostics.StackTrace());
  688. }
  689. }
  690. #endregion
  691. #endregion
  692. #region function Ip_to_longStr
  693. /// <summary>
  694. /// Removes points from ip and fill all blocks eg.(10.0.0.1 = 10 000 000 001).
  695. /// </summary>
  696. /// <param name="ip"></param>
  697. /// <returns></returns>
  698. private string Ip_to_longStr(string ip)
  699. {
  700. try
  701. {
  702. string retVal = "";
  703. string[] str = ip.Split(new char[]{'.'});
  704. // loop through all ip blocks.
  705. foreach(string ipBlock in str){
  706. string buff = ipBlock;
  707. // If block size is smaller than 3, append '0' at the beginning of string.
  708. if(ipBlock.Length < 3){
  709. for(int i=0;i<3;i++){
  710. if(buff.Length >= 3){
  711. break;
  712. }
  713. buff = "0" + buff;
  714. }
  715. }
  716. retVal += buff;
  717. }
  718. return retVal;
  719. }
  720. catch(Exception x)
  721. {
  722. Error.DumpError(x,new System.Diagnostics.StackTrace());
  723. return "";
  724. }
  725. }
  726. #endregion
  727. #region Properties Implementation
  728. /// <summary>
  729. /// 
  730. /// </summary>
  731. internal static ServerAPI API
  732. {
  733. get{ return m_pAPI; }
  734. }
  735. #endregion
  736. }
  737. }