Exemplo n.º 1
0
        public void TestServiceAsyncCall()
        {
            const ushort ServerPort = 13337;

            var endPoint = new HostEndPoint("localhost", ServerPort);

            // Start the server and setup our service.
            var server = new Server(endPoint);
            var serverThread = new Thread(Process);
            serverThread.Start(server);

            // Start the client and connect to the service.
            var client = new Client();
            var clientThread = new Thread(Process);
            clientThread.Start(client);

            var connectTask = client.Connect(endPoint);
            connectTask.Wait();
            Assert.IsTrue(connectTask.Result);

            var service = new ServiceTest();
            var serviceImpl = server.ServiceManager.ServiceManager.GetCreateImplementation<IServiceTest>(service);

            var serviceProxy = client.ServiceManager.GetService<IServiceTest>(new SessionRPCPeer(client.Session), serviceImpl.LocalId);
            var pingTask = serviceProxy.Ping();

            Assert.IsTrue(pingTask.Wait(1000));
            Assert.AreEqual("Pong", pingTask.Result);

            serverThread.Abort();
            clientThread.Abort();
         }
Exemplo n.º 2
0
        public void TestServiceAsyncCall()
        {
            const ushort ServerPort = 13337;

            var endPoint = new HostEndPoint("localhost", ServerPort);

            // Start the server and setup our service.
            var server       = new Server(endPoint);
            var serverThread = new Thread(Process);

            serverThread.Start(server);

            // Start the client and connect to the service.
            var client       = new Client();
            var clientThread = new Thread(Process);

            clientThread.Start(client);

            var connectTask = client.Connect(endPoint);

            connectTask.Wait();
            Assert.IsTrue(connectTask.Result);

            var service     = new ServiceTest();
            var serviceImpl = server.ServiceManager.GetCreateImplementation <IServiceTest>(service);

            var serviceProxy = client.ServiceManager.GetCreateProxy <IServiceTest>(new SessionRPCPeer(client.Session), serviceImpl.Id);
            var pingTask     = serviceProxy.Ping();

            Assert.IsTrue(pingTask.Wait(1000));
            Assert.AreEqual("Pong", pingTask.Result);

            serverThread.Abort();
            clientThread.Abort();
        }
Exemplo n.º 3
0
 /// <summary>
 /// Defualt constructor.
 /// </summary>
 public SIP_t_ViaParm()
 {
     m_ProtocolName      = "SIP";
     m_ProtocolVersion   = "2.0";
     m_ProtocolTransport = "UDP";
     m_pSentBy           = new HostEndPoint("localhost", -1);
 }
        public void SingleThreadGoodHostGoodPort()
        {
            var h  = new HostEndPoint("example.com", 2000);
            var ip = h.GetIPEndPoint(out _);

            Assert.IsNotNull(ip);
        }
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="envelopeID">Envelope ID_(MAIL FROM: ENVID).</param>
        /// <param name="sender">Senders email address.</param>
        /// <param name="recipient">Recipients email address.</param>
        /// <param name="originalRecipient">Original recipient(RCPT TO: ORCPT).</param>
        /// <param name="notify">DSN notify condition.</param>
        /// <param name="ret">Specifies what parts of message are returned in DSN report.</param>
        /// <param name="date">Message date.</param>
        /// <param name="delayedDeliveryNotifySent">Specifies if delayed delivery notify has been sent.</param>
        /// <param name="hostEndPoint">Host end point where message must be sent. Value null means DNS is used to get message target host.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>sender</b> or <b>recipient</b> is null.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
        public RelayMessageInfo(string envelopeID, string sender, string recipient, string originalRecipient, SMTP_DSN_Notify notify, SMTP_DSN_Ret ret, DateTime date, bool delayedDeliveryNotifySent, HostEndPoint hostEndPoint)
        {
            if (sender == null)
            {
                throw new ArgumentNullException("sender");
            }
            if (recipient == null)
            {
                throw new ArgumentNullException("recipient");
            }
            if (recipient == "")
            {
                throw new ArgumentException("Argument 'recipient' value must be specified.");
            }

            m_EnvelopeID        = envelopeID;
            m_Sender            = sender;
            m_Recipient         = recipient;
            m_OriginalRecipient = originalRecipient;
            m_DSN_Notify        = notify;
            m_DSN_Ret           = ret;
            m_Date = date;
            m_DelayedDeliveryNotifySent = delayedDeliveryNotifySent;
            m_pHostEndPoint             = hostEndPoint;
        }
 public void SingleThreadGoodHostBadPort()
 {
     foreach (var port in _badPorts)
     {
         var h = new HostEndPoint("example.com", port);
         Assert.IsNull(h.GetIPEndPoint(out _));
     }
 }
 public void SingleThreadBadHostGoodPort()
 {
     foreach (var host in _badHosts)
     {
         var h = new HostEndPoint(host, 2000);
         Assert.IsNull(h.GetIPEndPoint(out _));
     }
 }
        private void TestMultiThreadedUpdateSpacing(int ttl)
        {
            var       targetRuntime   = ttl * 1;
            const int numberOfThreads = 20;

            var      l = new Mutex();
            DateTime timeOfLastUpdate;

            var h = new HostEndPoint("example.com", 2000, ttl);

            h.GetIPEndPoint(out _);
            var start = DateTime.Now;

            timeOfLastUpdate = start;

            var proc = new ThreadStart(() =>
            {
                while (DateTime.Now.Subtract(start).TotalSeconds < targetRuntime)
                {
                    Assert.IsNotNull(h.GetIPEndPoint(out var updatePerformed));

                    if (!updatePerformed)
                    {
                        continue;
                    }

                    var now = DateTime.Now;
                    DateTime lastUpdated;

                    l.WaitOne();
                    lastUpdated      = timeOfLastUpdate;
                    timeOfLastUpdate = now;
                    l.ReleaseMutex();

                    var timeBetweenUpdates = now.Subtract(lastUpdated).TotalSeconds;
                    Console.WriteLine(timeBetweenUpdates);

                    Assert.IsTrue(timeBetweenUpdates > ttl, string.Format("Frequency of cache updates exceeded, expected at most one every {0} seconds, but two occured with {1} seconds apart!", ttl, timeBetweenUpdates));
                }
            });

            var threads = new Thread[numberOfThreads];

            for (var i = 0; i < threads.Length; i++)
            {
                threads[i] = new Thread(proc);
            }
            Console.WriteLine("Time between cache updates with cache ttl = {0}", ttl);
            foreach (var t in threads)
            {
                t.Start();
            }
            foreach (var t in threads)
            {
                t.Join();
            }
        }
Exemplo n.º 9
0
        public void TestWithHostname()
        {
            var testHost   = new HostEndPoint("localhost", 3001);
            var expectedIP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3001);

            var ep = EndPoint.Of(testHost);

            Assert.AreEqual(expectedIP, ep.GetIPEndPoint());
        }
Exemplo n.º 10
0
        protected Server(HostEndPoint endPeer)
        {
            Host = new Network.Server(endPeer);

            #if USE_RAVENDB
            Database = new RavenDatabaseManager();
            #else
            Database = new NullDatabaseManager();
            #endif
        }
Exemplo n.º 11
0
        protected Server(HostEndPoint endPeer)
        {
            Host = new Network.Server(endPeer);

#if USE_RAVENDB
            Database = new RavenDatabaseManager();
#else
            Database = new NullDatabaseManager();
#endif
        }
Exemplo n.º 12
0
        // Main listener thread.  Starts an indefinite loop listening for
        // new socket clients.  As Each client comes in, it is handed off
        // to OnClientConnect asynchronously on its own ThreadPool thread.
        private void StartListening()
        {
            Log.Info("Inside Listener Thread.");

            _listener = CreateListenerSocket();
            try
            {
                _listener.Bind(HostEndPoint);
                _listener.Listen(PENDING_CONNECTION_QUEUE_SIZE);

                if (Log.IsInfoEnabled)
                {
                    Log.Info("Socket Listener Started Listening on " + HostEndPoint.ToString());
                }

                // This loops indefinitely listening for client connections.
                while (_isRunning)
                {
                    // Set event to nonsignaled state.
                    _clientConnected.Reset();

                    Log.Info("Ready to Accept Incoming Connection.");

                    // Perform a blocking call to accept requests.
                    // You could also user server.AcceptSocket() here.
                    _listener.BeginAccept(new AsyncCallback(AcceptIncomingConnection), _listener);

                    if (Log.IsInfoEnabled)
                    {
                        Log.Info("Waiting For a Connection...");
                    }
                    // Wait for the connection to be made before continuing.
                    // But do so in a non-blocking manner.
                    while (true)
                    {
                        if (_clientConnected.WaitOne(1000, false))
                        {
                            Log.Info("Breaking out of the infinite loop because we have a new connection.");
                            break;
                        }
                        if (!_isRunning)
                        {
                            Log.Warn("Breaking out of the infinite loop because the server is stopping.");
                            break;
                        }
                    }
                }
                Log.Info("Exiting Listener Thread Gracefully.");
            }
            catch (Exception e)
            {
                //TODO: Consider starting up again.
                Log.Error("Exception thrown in StartListening() thread.  Server is shutting down.", e);
            }
        }
Exemplo n.º 13
0
        public EditorServer(HostEndPoint endPoint)
            : base(endPoint)
        {
            var serviceManager = Host.ServiceManager;

            UserManager = new UserManager();
            //serviceManager.AddImplementation<IUserManager>(UserManager);

            ProjectManager = new ProjectManager(Database);
            //serviceManager.AddImplementation<IProjectManager>(ProjectManager);
        }
Exemplo n.º 14
0
        public EditorServer(HostEndPoint endPoint)
            : base(endPoint)
        {
            var serviceManager = Host.ServiceManager;

            UserManager = new UserManager();
            //serviceManager.AddImplementation<IUserManager>(UserManager);

            ProjectManager = new ProjectManager(Database);
            //serviceManager.AddImplementation<IProjectManager>(ProjectManager);
        }
Exemplo n.º 15
0
        public void CreateBuiltinServer()
        {
            Log.Info("Initializing the built-in editor server...");

            serverCreatedEvent = new ManualResetEventSlim();

            var endPoint = new HostEndPoint(Settings.Host, Settings.RPCPort);

            Server = new EditorServer(endPoint);

            System.Threading.Tasks.Task.Run((Action)RunBuiltinServer);
            serverCreatedEvent.Wait();
        }
        public void AvgPerformanceSingleThreadGoodHostGoodPort()
        {
            const int    timesToTest            = 10_000;
            const double maxMillisecondsPerTest = 0.005;
            var          h = new HostEndPoint("example.com", 2000);

            h.GetIPEndPoint(out _); // Call to initialise cache

            var startTime = DateTime.Now;

            for (var i = 0; i < timesToTest; i++)
            {
                h.GetIPEndPoint(out _);
            }

            var finnishTime = DateTime.Now;

            var totalTime = finnishTime.Subtract(startTime).TotalMilliseconds;

            Assert.IsTrue(totalTime < timesToTest * maxMillisecondsPerTest);
        }
        /// <summary>
        /// Executes specified actions.
        /// </summary>
        /// <param name="dvActions">Dataview what contains actions to be executed.</param>
        /// <param name="server">Reference to owner virtual server.</param>
        /// <param name="message">Recieved message.</param>
        /// <param name="sender">MAIL FROM: command value.</param>
        /// <param name="to">RCPT TO: commands values.</param>
        public GlobalMessageRuleActionResult DoActions(DataView dvActions, VirtualServer server, Stream message, string sender, string[] to)
        {
            // TODO: get rid of MemoryStream, move to Stream

            //    bool   messageChanged = false;
            bool   deleteMessage = false;
            string storeFolder   = null;
            string errorText     = null;

            // Loop actions
            foreach (DataRowView drV in dvActions)
            {
                GlobalMessageRuleAction_enum action = (GlobalMessageRuleAction_enum)drV["ActionType"];
                byte[] actionData = (byte[])drV["ActionData"];

                // Reset stream position
                message.Position = 0;

                #region AutoResponse

                /* Description: Sends specified autoresponse message to sender.
                 *  Action data structure:
                 *      <ActionData>
                 *          <From></From>
                 *          <Message></Message>
                 *      </ActionData>
                 */

                if (action == GlobalMessageRuleAction_enum.AutoResponse)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    string smtp_from   = table.GetValue("From");
                    string responseMsg = table.GetValue("Message");

                    // See if we have header field X-LS-MailServer-AutoResponse, never answer to auto response.
                    MIME_h_Collection header = new MIME_h_Collection(new MIME_h_Provider());
                    header.Parse(new SmartStream(message, false));
                    if (header.Contains("X-LS-MailServer-AutoResponse"))
                    {
                        // Just skip
                    }
                    else
                    {
                        Mail_Message autoresponseMessage = Mail_Message.ParseFromByte(System.Text.Encoding.Default.GetBytes(responseMsg));

                        // Add header field 'X-LS-MailServer-AutoResponse:'
                        autoresponseMessage.Header.Add(new MIME_h_Unstructured("X-LS-MailServer-AutoResponse", ""));
                        // Update message date
                        autoresponseMessage.Date = DateTime.Now;

                        // Set To: if not explicity set
                        if (autoresponseMessage.To == null || autoresponseMessage.To.Count == 0)
                        {
                            if (autoresponseMessage.To == null)
                            {
                                Mail_t_AddressList t = new Mail_t_AddressList();
                                t.Add(new Mail_t_Mailbox(null, sender));
                                autoresponseMessage.To = t;
                            }
                            else
                            {
                                autoresponseMessage.To.Add(new Mail_t_Mailbox(null, sender));
                            }
                        }
                        // Update Subject: variables, if any
                        if (autoresponseMessage.Subject != null)
                        {
                            if (header.Contains("Subject"))
                            {
                                autoresponseMessage.Subject = autoresponseMessage.Subject.Replace("#SUBJECT", header.GetFirst("Subject").ValueToString().Trim());
                            }
                        }

                        // Sender missing, we can't send auto response.
                        if (string.IsNullOrEmpty(sender))
                        {
                            continue;
                        }

                        server.ProcessAndStoreMessage(smtp_from, new string[] { sender }, new MemoryStream(autoresponseMessage.ToByte(new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8)), null);
                    }
                }

                #endregion

                #region Delete Message

                /* Description: Deletes message.
                 *  Action data structure:
                 *      <ActionData>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.DeleteMessage)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    deleteMessage = true;
                }

                #endregion

                #region ExecuteProgram

                /* Description: Executes specified program.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Program></Program>
                 *          <Arguments></Arguments>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.ExecuteProgram)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    System.Diagnostics.ProcessStartInfo pInfo = new System.Diagnostics.ProcessStartInfo();
                    pInfo.FileName       = table.GetValue("Program");
                    pInfo.Arguments      = table.GetValue("Arguments");
                    pInfo.CreateNoWindow = true;
                    System.Diagnostics.Process.Start(pInfo);
                }

                #endregion

                #region ForwardToEmail

                /* Description: Forwards email to specified email.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Email></Email>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.ForwardToEmail)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    // See If message has X-LS-MailServer-ForwardedTo: and equals to "Email".
                    // If so, then we have cross reference forward, don't forward that message
                    MIME_h_Collection header = new MIME_h_Collection(new MIME_h_Provider());
                    header.Parse(new SmartStream(message, false));
                    bool forwardedAlready = false;
                    if (header.Contains("X-LS-MailServer-ForwardedTo"))
                    {
                        foreach (MIME_h headerField in header["X-LS-MailServer-ForwardedTo"])
                        {
                            if (headerField.ValueToString().Trim() == table.GetValue("Email"))
                            {
                                forwardedAlready = true;
                                break;
                            }
                        }
                    }

                    // Reset stream position
                    message.Position = 0;

                    if (forwardedAlready)
                    {
                        // Just skip
                    }
                    else
                    {
                        // Add header field 'X-LS-MailServer-ForwardedTo:'
                        MemoryStream msFwMessage = new MemoryStream();
                        byte[]       fwField     = System.Text.Encoding.Default.GetBytes("X-LS-MailServer-ForwardedTo: " + table.GetValue("Email") + "\r\n");
                        msFwMessage.Write(fwField, 0, fwField.Length);
                        SCore.StreamCopy(message, msFwMessage);

                        server.ProcessAndStoreMessage(sender, new string[] { table.GetValue("Email") }, msFwMessage, null);
                    }
                }

                #endregion

                #region ForwardToHost

                /* Description: Forwards email to specified host.
                 *              All RCPT TO: recipients are preserved.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Host></Host>
                 *          <Port></Port>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.ForwardToHost)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    foreach (string t in to)
                    {
                        message.Position = 0;
                        server.RelayServer.StoreRelayMessage(
                            Guid.NewGuid().ToString(),
                            null,
                            message,
                            HostEndPoint.Parse(table.GetValue("Host") + ":" + table.GetValue("Port")),
                            sender,
                            t,
                            null,
                            SMTP_DSN_Notify.NotSpecified,
                            SMTP_DSN_Ret.NotSpecified
                            );
                    }
                    message.Position = 0;
                }

                #endregion

                #region StoreToDiskFolder

                /* Description: Stores message to specified disk folder.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Folder></Folder>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.StoreToDiskFolder)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    string folder = table.GetValue("Folder");
                    if (!folder.EndsWith("\\"))
                    {
                        folder += "\\";
                    }

                    if (Directory.Exists(folder))
                    {
                        using (FileStream fs = File.Create(folder + DateTime.Now.ToString("ddMMyyyyHHmmss") + "_" + Guid.NewGuid().ToString().Replace('-', '_').Substring(0, 8) + ".eml")){
                            SCore.StreamCopy(message, fs);
                        }
                    }
                    else
                    {
                        // TODO: log error somewhere
                    }
                }

                #endregion

                #region StoreToIMAPFolder

                /* Description: Stores message to specified IMAP folder.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Folder></Folder>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.StoreToIMAPFolder)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);
                    storeFolder = table.GetValue("Folder");
                }

                #endregion

                #region AddHeaderField

                /* Description: Add specified header field to message main header.
                 *  Action data structure:
                 *      <ActionData>
                 *          <HeaderFieldName></HeaderFieldName>
                 *          <HeaderFieldValue></HeaderFieldValue>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.AddHeaderField)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    Mail_Message mime = Mail_Message.ParseFromStream(message);
                    mime.Header.Add(new MIME_h_Unstructured(table.GetValue("HeaderFieldName"), table.GetValue("HeaderFieldValue")));
                    message.SetLength(0);
                    mime.ToStream(message, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8);

                    //  messageChanged = true;
                }

                #endregion

                #region RemoveHeaderField

                /* Description: Removes specified header field from message mian header.
                 *  Action data structure:
                 *      <ActionData>
                 *          <HeaderFieldName></HeaderFieldName>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.RemoveHeaderField)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    Mail_Message mime = Mail_Message.ParseFromStream(message);
                    mime.Header.RemoveAll(table.GetValue("HeaderFieldName"));
                    message.SetLength(0);
                    mime.ToStream(message, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8);

                    //    messageChanged = true;
                }

                #endregion

                #region SendErrorToClient

                /* Description: Sends error to currently connected client. NOTE: Error text may contain ASCII printable chars only and maximum length is 500.
                 *  Action data structure:
                 *      <ActionData>
                 *          <ErrorText></ErrorText>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.SendErrorToClient)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    errorText = table.GetValue("ErrorText");
                }

                #endregion

                #region StoreToFTPFolder

                /* Description: Stores message to specified FTP server folder.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Server></Server>
                 *          <Port></Server>
                 *          <User></User>
                 *          <Password></Password>
                 *          <Folder></Folder>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.StoreToFTPFolder)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    _MessageRuleAction_FTP_AsyncSend ftpSend = new _MessageRuleAction_FTP_AsyncSend(
                        table.GetValue("Server"),
                        Convert.ToInt32(table.GetValue("Port")),
                        table.GetValue("User"),
                        table.GetValue("Password"),
                        table.GetValue("Folder"),
                        message,
                        DateTime.Now.ToString("ddMMyyyyHHmmss") + "_" + Guid.NewGuid().ToString().Replace('-', '_').Substring(0, 8) + ".eml"
                        );
                }

                #endregion

                #region PostToNNTPNewsGroup

                /* Description: Posts message to specified NNTP newsgroup.
                 *  Action data structure:
                 *      <ActionData>
                 *          <Server></Server>
                 *          <Port></Server>
                 *          <User></User>
                 *          <Password></Password>
                 *          <Newsgroup></Newsgroup>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.PostToNNTPNewsGroup)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    // Add header field "Newsgroups: newsgroup", NNTP server demands it.
                    Mail_Message mime = Mail_Message.ParseFromStream(message);
                    if (!mime.Header.Contains("Newsgroups:"))
                    {
                        mime.Header.Add(new MIME_h_Unstructured("Newsgroups:", table.GetValue("Newsgroup")));
                    }

                    _MessageRuleAction_NNTP_Async nntp = new _MessageRuleAction_NNTP_Async(
                        table.GetValue("Server"),
                        Convert.ToInt32(table.GetValue("Port")),
                        table.GetValue("Newsgroup"),
                        new MemoryStream(mime.ToByte(new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8))
                        );
                }

                #endregion

                #region PostToHTTP

                /* Description: Posts message to specified page via HTTP.
                 *  Action data structure:
                 *      <ActionData>
                 *          <URL></URL>
                 *          <FileName></FileName>
                 *      </ActionData>
                 */

                else if (action == GlobalMessageRuleAction_enum.PostToHTTP)
                {
                    XmlTable table = new XmlTable("ActionData");
                    table.Parse(actionData);

                    _MessageRuleAction_HTTP_Async http = new _MessageRuleAction_HTTP_Async(
                        table.GetValue("URL"),
                        message
                        );
                }

                #endregion
            }

            return(new GlobalMessageRuleActionResult(deleteMessage, storeFolder, errorText));
        }
Exemplo n.º 18
0
        /// <summary>
        /// Parses "via-parm" from specified reader.
        /// </summary>
        /// <param name="reader">Reader from where to parse.</param>
        /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception>
        /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception>
        public override void Parse(StringReader reader)
        {
            /*
             *  via-parm          =  sent-protocol LWS sent-by *( SEMI via-params )
             *  via-params        =  via-ttl / via-maddr / via-received / via-branch / via-extension
             *  via-ttl           =  "ttl" EQUAL ttl
             *  via-maddr         =  "maddr" EQUAL host
             *  via-received      =  "received" EQUAL (IPv4address / IPv6address)
             *  via-branch        =  "branch" EQUAL token
             *  via-extension     =  generic-param
             *  sent-protocol     =  protocol-name SLASH protocol-version
             *                       SLASH transport
             *  protocol-name     =  "SIP" / token
             *  protocol-version  =  token
             *  transport         =  "UDP" / "TCP" / "TLS" / "SCTP" / other-transport
             *  sent-by           =  host [ COLON port ]
             *  ttl               =  1*3DIGIT ; 0 to 255
             *
             *  Via extentions:
             *  // RFC 3486
             *  via-compression  =  "comp" EQUAL ("sigcomp" / other-compression)
             *  // RFC 3581
             *  response-port  =  "rport" [EQUAL 1*DIGIT]
             *
             *  Examples:
             *  Via: SIP/2.0/UDP 127.0.0.1:58716;branch=z9hG4bK-d87543-4d7e71216b27df6e-1--d87543-
             *  // Specifically, LWS on either side of the ":" or "/" is allowed.
             *  Via: SIP / 2.0 / UDP 127.0.0.1:58716;branch=z9hG4bK-d87543-4d7e71216b27df6e-1--d87543-
             */

            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            // protocol-name
            string word = reader.QuotedReadToDelimiter('/');

            if (word == null)
            {
                throw new SIP_ParseException("Via header field protocol-name is missing !");
            }
            ProtocolName = word.Trim();
            // protocol-version
            word = reader.QuotedReadToDelimiter('/');
            if (word == null)
            {
                throw new SIP_ParseException("Via header field protocol-version is missing !");
            }
            ProtocolVersion = word.Trim();
            // transport
            word = reader.ReadWord();
            if (word == null)
            {
                throw new SIP_ParseException("Via header field transport is missing !");
            }
            ProtocolTransport = word.Trim();
            // sent-by
            word = reader.QuotedReadToDelimiter(new[] { ';', ',' }, false);
            if (word == null)
            {
                throw new SIP_ParseException("Via header field sent-by is missing !");
            }
            SentBy = HostEndPoint.Parse(word.Trim());

            // Parse parameters
            ParseParameters(reader);
        }
Exemplo n.º 19
0
 /// <summary>
 /// Stores message for relay.
 /// </summary>
 /// <param name="id">Message ID. Guid value is suggested.</param>
 /// <param name="envelopeID">Envelope ID_(MAIL FROM: ENVID).</param>
 /// <param name="message">Message to store. Message will be readed from current position of stream.</param>
 /// <param name="targetHost">Target host or IP where to send message. This value can be null, then DNS MX o A record is used to deliver message.</param>
 /// <param name="sender">Sender address to report to target server.</param>
 /// <param name="to">Message recipient address.</param>
 /// <param name="originalRecipient">Original recipient(RCPT TO: ORCPT).</param>
 /// <param name="notify">DSN notify condition.</param>
 /// <param name="ret">Specifies what parts of message are returned in DSN report.</param>
 /// <exception cref="ArgumentNullException">Is raised when <b>id</b>,<b>message</b> or <b>to</b> is null.</exception>
 /// <exception cref="ArgumentException">Is raised when any of the argumnets has invalid value.</exception>
 public void StoreRelayMessage(string id, String envelopeID, Stream message, HostEndPoint targetHost, string sender, string to, string originalRecipient, SMTP_DSN_Notify notify, SMTP_DSN_Ret ret)
 {
     StoreRelayMessage("Relay", id, envelopeID, DateTime.Now, message, targetHost, sender, to, originalRecipient, notify, ret);
 }
Exemplo n.º 20
0
        /// <summary>
        /// Stores message for relay.
        /// </summary>
        /// <param name="queueName">Queue name where to store message.</param>
        /// <param name="id">Message ID. Guid value is suggested.</param>
        /// <param name="envelopeID">Envelope ID_(MAIL FROM: ENVID).</param>
        /// <param name="date">Message date.</param>
        /// <param name="message">Message to store. Message will be readed from current position of stream.</param>
        /// <param name="targetHost">Target host or IP where to send message. This value can be null, then DNS MX o A record is used to deliver message.</param>
        /// <param name="sender">Sender address to report to target server.</param>
        /// <param name="to">Message recipient address.</param>
        /// <param name="originalRecipient">Original recipient(RCPT TO: ORCPT).</param>
        /// <param name="notify">DSN notify condition.</param>
        /// <param name="ret">Specifies what parts of message are returned in DSN report.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>queueName</b>,<b>id</b>,<b>message</b> or <b>to</b> is null.</exception>
        /// <exception cref="ArgumentException">Is raised when any of the argumnets has invalid value.</exception>
        private void StoreRelayMessage(string queueName, string id, string envelopeID, DateTime date, Stream message, HostEndPoint targetHost, string sender, string to, string originalRecipient, SMTP_DSN_Notify notify, SMTP_DSN_Ret ret)
        {
            if (queueName == null)
            {
                throw new ArgumentNullException("queueName");
            }
            if (queueName == "")
            {
                throw new ArgumentException("Argumnet 'queueName' value must be specified.");
            }
            if (id == null)
            {
                throw new ArgumentNullException("id");
            }
            if (id == "")
            {
                throw new ArgumentException("Argument 'id' value must be specified.");
            }
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            if (to == null)
            {
                throw new ArgumentNullException("to");
            }
            if (to == "")
            {
                throw new ArgumentException("Argument 'to' value must be specified.");
            }

            string path = m_pVirtualServer.MailStorePath + queueName;

            // Check if Directory exists, if not Create
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            // Create relay message.
            using (FileStream fs = File.Create(API_Utlis.PathFix(path + "\\" + id + ".eml"))){
                SCore.StreamCopy(message, fs);

                // Create message info file for the specified relay message.
                RelayMessageInfo messageInfo = new RelayMessageInfo(
                    envelopeID,
                    sender,
                    to,
                    originalRecipient,
                    notify,
                    ret,
                    date,
                    false,
                    targetHost
                    );
                File.WriteAllBytes(API_Utlis.PathFix(path + "\\" + id + ".info"), messageInfo.ToByte());
            }
        }
Exemplo n.º 21
0
        private void StoreRelayMessage(string queueName, string id, string envelopeID, DateTime date, Stream message, HostEndPoint targetHost, string sender, string to, string originalRecipient, SMTP_DSN_Notify notify, SMTP_DSN_Ret ret)
        {
            if (queueName == null)
            {
                throw new ArgumentNullException("queueName");
            }
            if (queueName == "")
            {
                throw new ArgumentException("Argumnet 'queueName' value must be specified.");
            }
            if (id == null)
            {
                throw new ArgumentNullException("id");
            }
            if (id == "")
            {
                throw new ArgumentException("Argument 'id' value must be specified.");
            }
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            if (to == null)
            {
                throw new ArgumentNullException("to");
            }
            if (to == "")
            {
                throw new ArgumentException("Argument 'to' value must be specified.");
            }
            string text = this.m_pVirtualServer.MailStorePath + queueName;

            if (!Directory.Exists(text))
            {
                Directory.CreateDirectory(text);
            }
            using (FileStream fileStream = File.Create(PathHelper.PathFix(text + "\\" + id + ".eml")))
            {
                SCore.StreamCopy(message, fileStream);
                RelayMessageInfo relayMessageInfo = new RelayMessageInfo(envelopeID, sender, to, originalRecipient, notify, ret, date, false, targetHost);
                File.WriteAllBytes(PathHelper.PathFix(text + "\\" + id + ".info"), relayMessageInfo.ToByte());
            }
        }
        public GlobalMessageRuleActionResult DoActions(DataView dvActions, VirtualServer server, Stream message, string sender, string[] to)
        {
            bool   deleteMessage = false;
            string storeFolder   = null;
            string errorText     = null;

            foreach (DataRowView dataRowView in dvActions)
            {
                GlobalMessageRuleActionType globalMessageRuleAction_enum = (GlobalMessageRuleActionType)dataRowView["ActionType"];
                byte[] data = (byte[])dataRowView["ActionData"];
                message.Position = 0L;
                if (globalMessageRuleAction_enum == (GlobalMessageRuleActionType)1)
                {
                    XmlTable xmlTable = new XmlTable("ActionData");
                    xmlTable.Parse(data);
                    string            value             = xmlTable.GetValue("From");
                    string            value2            = xmlTable.GetValue("Message");
                    MIME_h_Collection mIME_h_Collection = new MIME_h_Collection(new MIME_h_Provider());
                    mIME_h_Collection.Parse(new SmartStream(message, false));
                    if (!mIME_h_Collection.Contains("X-LS-MailServer-AutoResponse"))
                    {
                        Mail_Message mail_Message = Mail_Message.ParseFromByte(Encoding.UTF8.GetBytes(value2));
                        mail_Message.Header.Add(new MIME_h_Unstructured("X-LS-MailServer-AutoResponse", ""));
                        mail_Message.Date = DateTime.Now;
                        if (mail_Message.To == null || mail_Message.To.Count == 0)
                        {
                            if (mail_Message.To == null)
                            {
                                mail_Message.To = new Mail_t_AddressList
                                {
                                    new Mail_t_Mailbox(null, sender)
                                };
                            }
                            else
                            {
                                mail_Message.To.Add(new Mail_t_Mailbox(null, sender));
                            }
                        }
                        if (mail_Message.Subject != null && mIME_h_Collection.Contains("Subject"))
                        {
                            mail_Message.Subject = mail_Message.Subject.Replace("#SUBJECT", mIME_h_Collection.GetFirst("Subject").ValueToString().Trim());
                        }
                        if (!string.IsNullOrEmpty(sender))
                        {
                            server.ProcessAndStoreMessage(value, new string[]
                            {
                                sender
                            }, new MemoryStream(mail_Message.ToByte(new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8)), null);
                        }
                    }
                }
                else if (globalMessageRuleAction_enum == GlobalMessageRuleActionType.DeleteMessage)
                {
                    XmlTable xmlTable2 = new XmlTable("ActionData");
                    xmlTable2.Parse(data);
                    deleteMessage = true;
                }
                else if (globalMessageRuleAction_enum == GlobalMessageRuleActionType.ExecuteProgram)
                {
                    XmlTable xmlTable3 = new XmlTable("ActionData");
                    xmlTable3.Parse(data);
                    Process.Start(new ProcessStartInfo
                    {
                        FileName       = xmlTable3.GetValue("Program"),
                        Arguments      = xmlTable3.GetValue("Arguments"),
                        CreateNoWindow = true
                    });
                }
                else if (globalMessageRuleAction_enum == GlobalMessageRuleActionType.ForwardToEmail)
                {
                    XmlTable xmlTable4 = new XmlTable("ActionData");
                    xmlTable4.Parse(data);
                    MIME_h_Collection mIME_h_Collection2 = new MIME_h_Collection(new MIME_h_Provider());
                    mIME_h_Collection2.Parse(new SmartStream(message, false));
                    bool flag = false;
                    if (mIME_h_Collection2.Contains("X-LS-MailServer-ForwardedTo"))
                    {
                        MIME_h[] array = mIME_h_Collection2["X-LS-MailServer-ForwardedTo"];
                        for (int i = 0; i < array.Length; i++)
                        {
                            MIME_h mIME_h = array[i];
                            if (mIME_h.ValueToString().Trim() == xmlTable4.GetValue("Email"))
                            {
                                flag = true;
                                break;
                            }
                        }
                    }
                    message.Position = 0L;
                    if (!flag)
                    {
                        MemoryStream memoryStream = new MemoryStream();
                        byte[]       bytes        = Encoding.UTF8.GetBytes("X-LS-MailServer-ForwardedTo: " + xmlTable4.GetValue("Email") + "\r\n");
                        memoryStream.Write(bytes, 0, bytes.Length);
                        SCore.StreamCopy(message, memoryStream);
                        server.ProcessAndStoreMessage(sender, new string[]
                        {
                            xmlTable4.GetValue("Email")
                        }, memoryStream, null);
                    }
                }
                else if (globalMessageRuleAction_enum == GlobalMessageRuleActionType.ForwardToHost)
                {
                    XmlTable xmlTable5 = new XmlTable("ActionData");
                    xmlTable5.Parse(data);
                    for (int j = 0; j < to.Length; j++)
                    {
                        string to2 = to[j];
                        message.Position = 0L;
                        server.RelayServer.StoreRelayMessage(Guid.NewGuid().ToString(), null, message, HostEndPoint.Parse(xmlTable5.GetValue("Host") + ":" + xmlTable5.GetValue("Port")), sender, to2, null, SMTP_DSN_Notify.NotSpecified, SMTP_DSN_Ret.NotSpecified);
                    }
                    message.Position = 0L;
                }
                else
                {
                    if (globalMessageRuleAction_enum == GlobalMessageRuleActionType.StoreToDiskFolder)
                    {
                        XmlTable xmlTable6 = new XmlTable("ActionData");
                        xmlTable6.Parse(data);
                        string text = xmlTable6.GetValue("Folder");
                        if (!text.EndsWith("\\"))
                        {
                            text += "\\";
                        }
                        if (!Directory.Exists(text))
                        {
                            continue;
                        }
                        using (FileStream fileStream = File.Create(string.Concat(new string[]
                        {
                            text,
                            DateTime.Now.ToString("ddMMyyyyHHmmss"),
                            "_",
                            Guid.NewGuid().ToString().Replace('-', '_').Substring(0, 8),
                            ".eml"
                        })))
                        {
                            SCore.StreamCopy(message, fileStream);
                            continue;
                        }
                    }
                    if (globalMessageRuleAction_enum == GlobalMessageRuleActionType.StoreToIMAPFolder)
                    {
                        XmlTable xmlTable7 = new XmlTable("ActionData");
                        xmlTable7.Parse(data);
                        storeFolder = xmlTable7.GetValue("Folder");
                    }
                    else if (globalMessageRuleAction_enum == (GlobalMessageRuleActionType)8)
                    {
                        XmlTable xmlTable8 = new XmlTable("ActionData");
                        xmlTable8.Parse(data);
                        Mail_Message mail_Message2 = Mail_Message.ParseFromStream(message);
                        mail_Message2.Header.Add(new MIME_h_Unstructured(xmlTable8.GetValue("HeaderFieldName"), xmlTable8.GetValue("HeaderFieldValue")));
                        message.SetLength(0L);
                        mail_Message2.ToStream(message, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8);
                    }
                    else if (globalMessageRuleAction_enum == (GlobalMessageRuleActionType)9)
                    {
                        XmlTable xmlTable9 = new XmlTable("ActionData");
                        xmlTable9.Parse(data);
                        Mail_Message mail_Message3 = Mail_Message.ParseFromStream(message);
                        mail_Message3.Header.RemoveAll(xmlTable9.GetValue("HeaderFieldName"));
                        message.SetLength(0L);
                        mail_Message3.ToStream(message, new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8);
                    }
                    else if (globalMessageRuleAction_enum == (GlobalMessageRuleActionType)10)
                    {
                        XmlTable xmlTable10 = new XmlTable("ActionData");
                        xmlTable10.Parse(data);
                        errorText = xmlTable10.GetValue("ErrorText");
                    }
                    else if (globalMessageRuleAction_enum == (GlobalMessageRuleActionType)11)
                    {
                        XmlTable xmlTable11 = new XmlTable("ActionData");
                        xmlTable11.Parse(data);
                        new _MessageRuleAction_FTP_AsyncSend(xmlTable11.GetValue("Server"), Convert.ToInt32(xmlTable11.GetValue("Port")), xmlTable11.GetValue("User"), xmlTable11.GetValue("Password"), xmlTable11.GetValue("Folder"), message, DateTime.Now.ToString("ddMMyyyyHHmmss") + "_" + Guid.NewGuid().ToString().Replace('-', '_').Substring(0, 8) + ".eml");
                    }
                    else if (globalMessageRuleAction_enum == (GlobalMessageRuleActionType)12)
                    {
                        XmlTable xmlTable12 = new XmlTable("ActionData");
                        xmlTable12.Parse(data);
                        Mail_Message mail_Message4 = Mail_Message.ParseFromStream(message);
                        if (!mail_Message4.Header.Contains("Newsgroups:"))
                        {
                            mail_Message4.Header.Add(new MIME_h_Unstructured("Newsgroups:", xmlTable12.GetValue("Newsgroup")));
                        }
                        new _MessageRuleAction_NNTP_Async(xmlTable12.GetValue("Server"), Convert.ToInt32(xmlTable12.GetValue("Port")), xmlTable12.GetValue("Newsgroup"), new MemoryStream(mail_Message4.ToByte(new MIME_Encoding_EncodedWord(MIME_EncodedWordEncoding.Q, Encoding.UTF8), Encoding.UTF8)));
                    }
                    else if (globalMessageRuleAction_enum == (GlobalMessageRuleActionType)13)
                    {
                        XmlTable xmlTable13 = new XmlTable("ActionData");
                        xmlTable13.Parse(data);
                        new _MessageRuleAction_HTTP_Async(xmlTable13.GetValue("URL"), message);
                    }
                }
            }
            return(new GlobalMessageRuleActionResult(deleteMessage, storeFolder, errorText));
        }
Exemplo n.º 23
0
        /// <summary>
        /// Parses RelayMessageInfo from byte[] data.
        /// </summary>
        /// <param name="value">RelayMessageInfo data.</param>
        /// <returns>Returns parsed RelayMessageInfo.</returns>
        /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
        public static RelayMessageInfo Parse(byte[] value)
        {
            try
            {
                XmlTable messageInfo = new XmlTable("RelayMessageInfo");
                messageInfo.Parse(value);

                return(new RelayMessageInfo(
                           string.IsNullOrEmpty(messageInfo.GetValue("EnvelopeID")) ? null : messageInfo.GetValue("EnvelopeID"),
                           messageInfo.GetValue("Sender"),
                           messageInfo.GetValue("Recipient"),
                           string.IsNullOrEmpty(messageInfo.GetValue("OriginalRecipient")) ? null : messageInfo.GetValue("OriginalRecipient"),
                           string.IsNullOrEmpty(messageInfo.GetValue("DSN-Notify")) ? SMTP_DSN_Notify.NotSpecified : (SMTP_DSN_Notify)Enum.Parse(typeof(SMTP_DSN_Notify), messageInfo.GetValue("DSN-Notify")),
                           string.IsNullOrEmpty(messageInfo.GetValue("DSN-RET")) ? SMTP_DSN_Ret.NotSpecified : (SMTP_DSN_Ret)Enum.Parse(typeof(SMTP_DSN_Ret), messageInfo.GetValue("DSN-RET")),
                           DateTime.ParseExact(messageInfo.GetValue("Date"), "r", System.Globalization.DateTimeFormatInfo.InvariantInfo),
                           Convert.ToBoolean(messageInfo.GetValue("DelayedDeliveryNotifySent")),
                           !string.IsNullOrEmpty(messageInfo.GetValue("HostEndPoint")) ? HostEndPoint.Parse(messageInfo.GetValue("HostEndPoint"), 25) : null
                           ));
            }
            catch
            {
                throw new ArgumentException("Argument 'value' has invalid RelayMessageInfo value.");
            }
        }