Exemplo n.º 1
0
        // Reads a first int giving the global message's lenght, then reads the message.
        public ByteMessage(System.Net.Security.SslStream stream)
        {
            byte[] b_dataLenght = new byte[4];
            stream.Read(b_dataLenght, 0, 4);
            int dataLenght = BitConverter.ToInt32(b_dataLenght, 0);

            bytes = new byte[dataLenght];

            stream.Read(bytes, 0, dataLenght);
        }
Exemplo n.º 2
0
        public string Read(bool connect)
        {
            if (secure)
            {
                if (connect)
                {
                    sb     = new StringBuilder();
                    buffer = new byte[2048];
                    ssl.Read(buffer, 0, 2048);
                    sb.Append(UTF8Encoding.UTF8.GetString(buffer));
                }
                else
                {
                    sb     = new StringBuilder();
                    buffer = new byte[2048];
                    int bytes = -1;
                    do
                    {
                        bytes = ssl.Read(buffer, 0, buffer.Length);

                        // Use Decoder class to convert from bytes to UTF8
                        // in case a character spans two buffers.
                        Decoder decoder = Encoding.UTF8.GetDecoder();
                        char[]  chars   = new char[decoder.GetCharCount(buffer, 0, bytes)];
                        decoder.GetChars(buffer, 0, bytes, chars, 0);
                        sb.Append(chars);
                        // Check for EOF.
                        if (sb.ToString().IndexOf("TAGGED" + tagNumber.ToString()) != -1)
                        {
                            break;
                        }
                    } while (bytes != 0);
                }
                Thread.Sleep(3);
            }
            else
            {
                sb     = new StringBuilder();
                buffer = new byte[4000];
                bytes  = tcpc.GetStream().Read(buffer, 0, 4000);
                sb.Append(UTF8Encoding.UTF8.GetString(buffer));
            }

            string res = sb.ToString();

            //MessageBox.Show(res);

            return(res);
        }
 /// <summary>
 /// Communication with server
 /// </summary>
 /// <param name="command">The command beeing sent</param>
 private static void SendCommandAndReceiveResponse(string command)
 {
     try
     {
         if (command != "")
         {
             if (tcpc.Connected)
             {
                 dummy = System.Text.Encoding.ASCII.GetBytes(command);
                 ssl.Write(dummy, 0, dummy.Length);
             }
             else
             {
                 throw new System.ApplicationException("TCP CONNECTION DISCONNECTED");
             }
         }
         ssl.Flush();
         buffer = new byte[2048];
         bytes  = ssl.Read(buffer, 0, 2048);
         sb.Append(System.Text.Encoding.ASCII.GetString(buffer));
         System.Diagnostics.Debug.WriteLine(sb.ToString());
         sw.WriteLine(sb.ToString());
         sb = new System.Text.StringBuilder();
     }
     catch (System.Exception ex)
     {
         throw new System.ApplicationException(ex.Message);
     }
 }
Exemplo n.º 4
0
        static string receiveResponse(string command)
        {
            try
            {
                //Console.WriteLine("<<<" + command);
                if (command != "")
                {
                    if (tcpc.Connected)
                    {
                        dummy = Encoding.UTF8.GetBytes(command);
                        ssl.Write(dummy, 0, dummy.Length);
                    }
                    else
                    {
                        throw new ApplicationException("TCP CONNECTION DISCONNECTED");
                    }
                }

                ssl.Flush();

                buffer = new byte[2048];
                bytes  = ssl.Read(buffer, 0, 2048);

                // Decode to utf8
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[]  chars   = new char[decoder.GetCharCount(buffer, 0, bytes)];
                decoder.GetChars(buffer, 0, bytes, chars, 0);
                StringBuilder messageData = new StringBuilder();
                messageData.Append(chars);

                //Console.WriteLine(messageData.ToString());
                //sb.Append(Encoding.ASCII.GetString(buffer), 0, bytes - 1);
                //Console.WriteLine(">>>" + sb.ToString());
                //sb = new StringBuilder();
                //}
                return(messageData.ToString());
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.Message);
            }
        }
Exemplo n.º 5
0
 private StringBuilder Request(string command)
 {
     try
     {
         if (command != "")
         {
             request = Encoding.ASCII.GetBytes(command);
             ssl.Write(request, 0, request.Length);
         }
         ssl.Flush();
         sb     = new StringBuilder();
         buffer = new byte[2048];
         bytes  = ssl.Read(buffer, 0, 2048);
         sb.Append(Encoding.ASCII.GetString(buffer));
         return(sb);
     }
     catch
     {
         return(null);
     }
 }
Exemplo n.º 6
0
        private void receiveResponse(string command)
        {
            try
            {
                if (command != "")
                {
                    if (tcpc.Connected)
                    {
                        writeBuffer = Encoding.ASCII.GetBytes(command);
                        ssl.Write(writeBuffer, 0, writeBuffer.Length);
                    }
                    else
                    {
                        throw new ApplicationException("TCP CONNECTION DISCONNECTED");
                    }
                }
                ssl.Flush();

                byte[]        buffer      = new byte[2048];
                StringBuilder messageData = new StringBuilder();
                int           bytes       = -1;
                do
                {
                    bytes = ssl.Read(buffer, 0, buffer.Length);

                    Console.WriteLine($"bytes: {bytes}");

                    Decoder decoder = Encoding.UTF8.GetDecoder();
                    char[]  chars   = new char[decoder.GetCharCount(buffer, 0, bytes, true)];
                    Console.WriteLine($"array length: {chars.Length}");
                    decoder.GetChars(buffer, 0, bytes, chars, 0, true);
                    messageData.Append(chars);
                } while (bytes == 2048);
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.Message);
            }
        }
Exemplo n.º 7
0
        static string receiveResponse(string command)
        {
            try
            {
                if (command != "")
                {
                    if (tcpc.Connected)
                    {
                        dummy = Encoding.ASCII.GetBytes(command);
                        //dummy = Encoding.UTF8.GetBytes(command);
                        //Console.WriteLine(Encoding.UTF8.GetString(dummy));
                        ssl.Write(dummy, 0, dummy.Length);
                    }
                    else
                    {
                        throw new ApplicationException("TCP CONNECTION DISCONNECTED");
                    }
                }
                ssl.Flush();


                buffer = new byte[2048];
                bytes  = ssl.Read(buffer, 0, 2048);
                //sb.Append(Encoding.ASCII.GetString(buffer));

                //Console.WriteLine(sb.ToString());
                //sw.WriteLine(sb.ToString());
                //sb = new StringBuilder();
                Console.WriteLine(Encoding.ASCII.GetString(buffer));
                return(Encoding.ASCII.GetString(buffer));
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.Message);
            }
        }
Exemplo n.º 8
0
        private static String RequestGet(String url)
        {
            var str = "";

            try
            {
                if (url.StartsWith("https://"))
                {
                    #region HTTPS请求
                    var uri        = new Uri(url);
                    var hostSocket = Wlniao.Net.WlnSocket.GetSocket(uri.Host, uri.Port);
                    var reqStr     = "";
                    reqStr += "GET " + uri.PathAndQuery + " HTTP/1.1";
                    reqStr += "\r\nHost: " + uri.Host;
                    reqStr += "\r\nDate: " + DateTools.ConvertToGMT(DateTools.GetUnix());
                    reqStr += "\r\nAccept: application/json";
                    reqStr += "\r\n";
                    reqStr += "\r\n";
                    var request = System.Text.Encoding.UTF8.GetBytes(reqStr);
                    using (var ssl = new System.Net.Security.SslStream(new System.Net.Sockets.NetworkStream(hostSocket, true), false, new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate), null))
                    {
                        ssl.AuthenticateAsClientAsync(uri.Host).ContinueWith((_rlt) =>
                        {
                            if (ssl.IsAuthenticated)
                            {
                                ssl.Write(request);
                                ssl.Flush();
                                var length  = 0;
                                var end     = false;
                                var start   = false;
                                var chunked = false;
                                while (true)
                                {
                                    var rev   = new byte[65535];
                                    var index = ssl.Read(rev, 0, rev.Length);
                                    if (index == 0)
                                    {
                                        break;
                                    }
                                    var beffur = new byte[index];
                                    Buffer.BlockCopy(rev, 0, beffur, 0, index);
                                    var tempstr = strUtil.GetUTF8String(beffur);
                                    var lines   = tempstr.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                                    index       = 0;
                                    #region Headers处理
                                    if (!start && lines[0].StartsWith("HTTP"))
                                    {
                                        var ts = lines[0].Split(' ');
                                        if (ts[1] == "200")
                                        {
                                            for (index = 1; index < lines.Length; index++)
                                            {
                                                if (lines[index].ToLower().StartsWith("content-length"))
                                                {
                                                    ts     = lines[index].Split(' ');
                                                    length = cvt.ToInt(ts[1]);
                                                }
                                                else if (lines[index].ToLower().StartsWith("transfer-encoding"))
                                                {
                                                    chunked = lines[index].EndsWith("chunked");
                                                }
                                                if (string.IsNullOrEmpty(lines[index]))
                                                {
                                                    index++;
                                                    start = true;
                                                    break;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            index = lines.Length;
                                            break;
                                        }
                                    }
                                    #endregion
                                    #region 取文本内容
                                    for (; index < lines.Length; index++)
                                    {
                                        var line = lines[index];
                                        if (chunked)
                                        {
                                            index++;
                                            if (index < lines.Length)
                                            {
                                                var tempLength = cvt.DeHex(line, "0123456789abcdef");
                                                if (tempLength > 0)
                                                {
                                                    length += (int)tempLength;
                                                    line    = lines[index];
                                                }
                                                else if (lines.Length == index + 2 && string.IsNullOrEmpty(lines[index + 1]))
                                                {
                                                    end = true;
                                                    break;
                                                }
                                                else
                                                {
                                                    break;
                                                }
                                            }
                                            else
                                            {
                                                break;
                                            }
                                        }
                                        if (index == 0 || (chunked && index == 1) || str.Length == 0)
                                        {
                                            str += line;
                                        }
                                        else
                                        {
                                            str += "\r\n" + line;
                                        }
                                        if (!chunked && System.Text.Encoding.UTF8.GetBytes(str).Length >= length)
                                        {
                                            end = true;
                                        }
                                    }
                                    if (end)
                                    {
                                        break;
                                    }
                                    #endregion
                                }
                            }
                        }).Wait();
                    }
                    hostSocket.Using = false;
                    #endregion
                }
                else
                {
                    #region HTTP请求
                    var response = new System.Net.Http.HttpClient().GetAsync(url).GetAwaiter().GetResult();
                    str = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                    #endregion
                }
                if (string.IsNullOrEmpty(str))
                {
                    str = "{\"success\":false,\"message\":\"empty response\",\"data\":\"\"}";
                }
                else
                {
                    log.Info(str);
                }
            }
            catch (Exception ex)
            {
                str = "{\"success\":false,\"message\":\"request exception\",\"data\":\"" + ex.Message + "\"}";
            }
            return(str);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Sends the message via a socket connection to an SMTP relay host. 
        /// </summary>
        /// <param name="hostname">Friendly-name or IP address of SMTP relay host</param>
        /// <param name="port">Port on which to connect to SMTP relay host</param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        private void SendSSL(string HostName, int Port, string UserName, string Password, string FromEmail, string ToEmail, byte[] MIMEMessage)
        {
            //This Doesn't Work Yet... :(

            const int bufsize = 1000;
            TcpClient smtp;
            System.Net.Security.SslStream ns;
            int cb, startOfBlock;
            byte[] recv = new byte[bufsize];
            byte[] data;
            string message, block;

            try
            {

                smtp = new TcpClient(HostName, Port);
                ns = new System.Net.Security.SslStream(smtp.GetStream(), true);
                cb = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                message = "EHLO\r\n";
                System.Diagnostics.Debug.WriteLine(message, "Client");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
            }
            catch(Exception ex)
            {
                throw new Exception(string.Format("Unable to establish SMTP session with {0}:{1}", HostName, Port), ex);
            }

            try
            {

                //figure out the line containing 250-AUTH
                cb = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                startOfBlock = message.IndexOf("250-AUTH");
                block = message.Substring(startOfBlock, message.IndexOf("\n", startOfBlock) - startOfBlock);
                //check the auth protocols
                if (-1 == block.IndexOf("LOGIN"))
                    throw new Exception("Mailhost does not support LOGIN authentication");

                message = "AUTH LOGIN\r\n";
                System.Diagnostics.Debug.WriteLine(message, "Client");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (!message.StartsWith("334"))
                    throw new Exception(string.Format("Unexpected reply to AUTH LOGIN:\n{0}", message));

                message = string.Format("{0}\r\n", Convert.ToBase64String(Encoding.ASCII.GetBytes(UserName)));
                System.Diagnostics.Debug.WriteLine(message, "Client (username)");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (!message.StartsWith("334"))
                    throw new Exception(string.Format("Unexpected reply to username:\n{0}", message));

                message = string.Format("{0}\r\n", Convert.ToBase64String(Encoding.ASCII.GetBytes(Password)));
                System.Diagnostics.Debug.WriteLine(message, "Client (password)");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (message.StartsWith("535"))
                    throw new Exception("Authentication unsuccessful");
                if (!message.StartsWith("2"))
                    throw new Exception(string.Format("Unexpected reply to password:\n{0}", message));

                message = string.Format("MAIL FROM: <{0}>\r\n", FromEmail);
                System.Diagnostics.Debug.WriteLine(message, "Client");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (!message.StartsWith("250"))
                    throw new Exception(string.Format("Unexpected reply to MAIL FROM:\n{0}", message));

                message = string.Format("RCPT TO: <{0}>\r\n", ToEmail);
                System.Diagnostics.Debug.WriteLine(message, "Client");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (!message.StartsWith("250"))
                    throw new Exception(string.Format("Unexpected reply to RCPT TO:\n{0}", message));

                message = "DATA\r\n";
                System.Diagnostics.Debug.WriteLine(message, "Client");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (!message.StartsWith("354"))
                    throw new Exception(string.Format("Unexpected reply to DATA:\n{0}", message));

                data = MIMEMessage;
                ns.Write(data, 0, data.Length);
                message = "\r\n.\r\n";
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);

                clearBuf(recv);
                cb = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (!message.StartsWith("250"))
                    throw new Exception(string.Format("Unexpected reply to end of data marker (\\r\\n.\\r\\n):\n{0}", message));

                message = "QUIT\r\n";
                System.Diagnostics.Debug.WriteLine(message, "Client");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);

            }
            catch (Exception ex)
            {
                General.Debugging.Report.SendError("SMTP Communication Error", ex);
                throw new Exception(string.Format("SMTP Communication Error: {0}", message), ex);
            }
            finally
            {
                if (null != smtp) smtp.Close();
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Sends the message via a socket connection to an SMTP relay host.
        /// </summary>
        /// <param name="hostname">Friendly-name or IP address of SMTP relay host</param>
        /// <param name="port">Port on which to connect to SMTP relay host</param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        private void SendSSL(string HostName, int Port, string UserName, string Password, string FromEmail, string ToEmail, byte[] MIMEMessage)
        {
            //This Doesn't Work Yet... :(
            const int bufsize = 1000;
            TcpClient smtp;

            System.Net.Security.SslStream ns;
            int cb, startOfBlock;

            byte[] recv = new byte[bufsize];
            byte[] data;
            string message, block;

            try
            {
                smtp    = new TcpClient(HostName, Port);
                ns      = new System.Net.Security.SslStream(smtp.GetStream(), true);
                cb      = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                message = "EHLO\r\n";
                System.Diagnostics.Debug.WriteLine(message, "Client");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Unable to establish SMTP session with {0}:{1}", HostName, Port), ex);
            }
            try
            {
                //figure out the line containing 250-AUTH
                cb      = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                startOfBlock = message.IndexOf("250-AUTH");
                block        = message.Substring(startOfBlock, message.IndexOf("\n", startOfBlock) - startOfBlock);
                //check the auth protocols
                if (-1 == block.IndexOf("LOGIN"))
                {
                    throw new Exception("Mailhost does not support LOGIN authentication");
                }
                message = "AUTH LOGIN\r\n";
                System.Diagnostics.Debug.WriteLine(message, "Client");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb      = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (!message.StartsWith("334"))
                {
                    throw new Exception(string.Format("Unexpected reply to AUTH LOGIN:\n{0}", message));
                }
                message = string.Format("{0}\r\n", Convert.ToBase64String(Encoding.ASCII.GetBytes(UserName)));
                System.Diagnostics.Debug.WriteLine(message, "Client (username)");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb      = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (!message.StartsWith("334"))
                {
                    throw new Exception(string.Format("Unexpected reply to username:\n{0}", message));
                }
                message = string.Format("{0}\r\n", Convert.ToBase64String(Encoding.ASCII.GetBytes(Password)));
                System.Diagnostics.Debug.WriteLine(message, "Client (password)");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb      = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (message.StartsWith("535"))
                {
                    throw new Exception("Authentication unsuccessful");
                }
                if (!message.StartsWith("2"))
                {
                    throw new Exception(string.Format("Unexpected reply to password:\n{0}", message));
                }
                message = string.Format("MAIL FROM: <{0}>\r\n", FromEmail);
                System.Diagnostics.Debug.WriteLine(message, "Client");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb      = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (!message.StartsWith("250"))
                {
                    throw new Exception(string.Format("Unexpected reply to MAIL FROM:\n{0}", message));
                }
                message = string.Format("RCPT TO: <{0}>\r\n", ToEmail);
                System.Diagnostics.Debug.WriteLine(message, "Client");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb      = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (!message.StartsWith("250"))
                {
                    throw new Exception(string.Format("Unexpected reply to RCPT TO:\n{0}", message));
                }
                message = "DATA\r\n";
                System.Diagnostics.Debug.WriteLine(message, "Client");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb      = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (!message.StartsWith("354"))
                {
                    throw new Exception(string.Format("Unexpected reply to DATA:\n{0}", message));
                }
                data = MIMEMessage;
                ns.Write(data, 0, data.Length);
                message = "\r\n.\r\n";
                data    = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
                clearBuf(recv);
                cb      = ns.Read(recv, 0, recv.Length);
                message = Encoding.ASCII.GetString(recv);
                System.Diagnostics.Debug.WriteLine(message, "Server");
                if (!message.StartsWith("250"))
                {
                    throw new Exception(string.Format("Unexpected reply to end of data marker (\\r\\n.\\r\\n):\n{0}", message));
                }
                message = "QUIT\r\n";
                System.Diagnostics.Debug.WriteLine(message, "Client");
                data = Encoding.ASCII.GetBytes(message);
                ns.Write(data, 0, data.Length);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("SMTP Communication Error: {0}", message), ex);
            }
            finally
            {
                if (null != smtp)
                {
                    smtp.Close();
                }
            }
        }
        //----- Talking to the server -------------------------------------------------
        private void ReceiveResponse(string command)
        {
            try
            {
                if (command != "")
                {
                    if (tcpc.Connected)
                    {
                        commandTemplate = Encoding.ASCII.GetBytes(command);
                        ssl.Write(commandTemplate, 0, commandTemplate.Length);
                    }
                    else
                    {
                        throw new ApplicationException("TCP CONNECTION DISCONNECTED");
                    }
                }
                ssl.Flush();

                ListBoxEvents.Items.Add(command);
                sw.WriteLine(command);
                bytes = -1;

                while (bytes != 0)
                {
                    previousAnswer = answer;

                    buffer = new byte[2048];
                    bytes  = ssl.Read(buffer, 0, 2048);

                    answer = Encoding.ASCII.GetString(buffer);

                    ListBoxEvents.Items.Add(answer.Substring(0, bytes));
                    sw.WriteLine(answer.Substring(0, bytes));

                    bool endMessage = answer.Contains("\r\n");

                    if (commandNumber <= 1)
                    {
                        pTaggedMessage = false;
                    }
                    else
                    {
                        pTaggedMessage = previousAnswer.Contains(prefix);
                    }

                    if (command != "")
                    {
                        bool taggedEndMessage = answer.Contains(prefix);

                        if ((endMessage && taggedEndMessage) || bytes == 0 || (pTaggedMessage && endMessage))
                        {
                            break;
                        }
                    }
                    else
                    {
                        if (endMessage || bytes == 0)
                        {
                            break;
                        }
                    }
                }

                if (command != "")
                {
                    commandNumber += 1;
                    prefix         = "A" + commandNumber;
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                Environment.Exit(0);
            }
        }
Exemplo n.º 12
0
        // ASCII format 3 erase: 15
        void LoopThread()
        {
            byte[] chat_buffer = new byte[MSG_BUFFER];
            int    buffer_used = 0;

            while (cli.Connected && running)
            {
                int free_chars = chat_buffer.Length - buffer_used;
                int rec_len    = 0;
                if (cli.Available > 0 && free_chars > 0)
                {
                    rec_len      = stream.Read(chat_buffer, buffer_used, free_chars);
                    buffer_used += rec_len;
                }

                Thread.Sleep(50);
                if (rec_len > 1)
                {
                    last_ping = 360;                     // Refill last ping
                }
                while (true)
                {
                    // Search for newline in buffer
                    int found_line = Array.IndexOf(chat_buffer, (byte)'\n', 0, buffer_used);

                    if (found_line == -1)
                    {
                        // Reset buffer, discard.
                        if (buffer_used == chat_buffer.Length)
                        {
                            L.Log("E::LoopThread, Line too long, reset.", true);
                            chat_buffer = new byte[MSG_BUFFER];
                            buffer_used = 0;
                        }
                        break;
                    }
                    found_line++;

                    // Add message to the chat buffer, remove '\n' and beginning ':'
                    int offset = (chat_buffer[0] == ':') ? 1 : 0;
                    int length = found_line - 2 - offset;

                    string query = enc.GetString(chat_buffer, offset, length);

                    // Shift back in array
                    for (int i = 0; i < buffer_used - found_line; i++)
                    {
                        chat_buffer[i] = chat_buffer[found_line + i];
                    }

                    buffer_used -= found_line;

                    try {
                        FetchChat(query);
                    } catch (Exception e) {
                        Console.WriteLine(query);
                        Console.WriteLine(e.ToString());
                        L.Dump("E::FetchChat", query, e.ToString());
                    }
                    manager.SetActiveChannel(null);
                }
            }
            L.Log("E::LoopThread, Disconnected", true);
        }
Exemplo n.º 13
0
        static public string SendSSLMsg(string host, int port, string msg)
        {
            lock (syncRoot)
            {
                System.Net.Sockets.TcpClient  client    = new System.Net.Sockets.TcpClient(host, port);
                System.Net.Security.SslStream sslStream = new System.Net.Security.SslStream(
                    client.GetStream(),
                    false,
                    new System.Net.Security.RemoteCertificateValidationCallback(
                        (object sender,
                         System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                         System.Security.Cryptography.X509Certificates.X509Chain chain,
                         System.Net.Security.SslPolicyErrors sslPolicyErrors) =>
                {
                    if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors ||
                        sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
                    {
                        return(true);
                    }
                    return(false);
                }
                        ),
                    null);
                sslStream.WriteTimeout = 2000;
                sslStream.ReadTimeout  = 2000;

                try
                {
                    sslStream.AuthenticateAsClient("VoiceCyber.PF", null, System.Security.Authentication.SslProtocols.Tls, false);
                    byte[] messsage = Encoding.UTF8.GetBytes(msg + "\r\n");
                    sslStream.Write(messsage);
                    sslStream.Flush();

                    byte[]        buffer      = new byte[2048];
                    StringBuilder messageData = new StringBuilder();
                    int           bytes       = -1;
                    try
                    {
                        do
                        {
                            bytes = sslStream.Read(buffer, 0, buffer.Length);
                            Decoder decoder = Encoding.UTF8.GetDecoder();
                            char[]  chars   = new char[decoder.GetCharCount(buffer, 0, bytes)];
                            decoder.GetChars(buffer, 0, bytes, chars, 0);
                            messageData.Append(chars);
                            if (messageData.ToString().IndexOf("\r\n") != -1)
                            {
                                messageData.Replace("\r\n", "");
                                break;
                            }
                        } while (bytes != 0);
                    }
                    catch (System.Exception ex)
                    {
                        messageData.Clear();
                        throw ex;
                    }
                    return(messageData.ToString());
                }
                catch (System.Security.Authentication.AuthenticationException e)
                {
                    client.Close();
                    throw e;
                }
                catch (System.Exception ex)
                {
                    throw ex;
                }
            }
        }
Exemplo n.º 14
0
        public int Authenticate()
        {
            int s = 0, n;
            try
            {
                if (StartTls)
                {
                    string text = "STARTTLS\r\n";
                    ns_client.Write(UTF8.GetBytes(text), 0, UTF8.GetByteCount(text));
                    Chunk c = CreateChunk(512);
                    n = ns_client.Read(c.buffer, 0, c.size);
                    text = UTF8.GetString(c.buffer, 0, n);
                    //Console.WriteLine(text);

                    ssl_stream = new System.Net.Security.SslStream(ns_client);
                    ssl_stream.AuthenticateAsClient(Host, null, System.Security.Authentication.SslProtocols.Tls12, false);

                    text = "EHLO " + Host + "\r\n";
                    ssl_stream.Write(UTF8.GetBytes(text), 0, UTF8.GetByteCount(text));
                    ResetChunk(ref c, 512);
                    n = ssl_stream.Read(c.buffer, 0, c.size);
                    text = UTF8.GetString(c.buffer, 0, n);

                    IsAuthenticationRequired = false;
                    AuthenticationMethod = new List<string>();

                    string[] cond = text.Split('\n');
                    for (int i = 0; i < cond.Length; i++)
                    {
                        if (cond[i].Contains("SIZE"))
                        {
                            int m = 0;
                            int.TryParse(cond[i].Substring(cond[i].IndexOf("SIZE") + 4, cond[i].Length - cond[i].IndexOf("SIZE") - 4 - 1).Trim(), out m);
                            MaximumSize = m;
                        }
                        if (cond[i].Contains("AUTH"))
                        {
                            IsAuthenticationRequired = true;
                            text = cond[i].Substring(cond[i].IndexOf("AUTH") + 4, cond[i].Length - cond[i].IndexOf("AUTH") - 4 - 1).Trim();
                            foreach (string item in text.Split(' '))
                                AuthenticationMethod.Add(item);
                        }
                    }

                    if (AuthenticationMethod.Contains("PLAIN"))
                    {
                        text = "AUTH PLAIN\r\n";
                        ssl_stream.Write(UTF8.GetBytes(text), 0, UTF8.GetByteCount(text));
                        ResetChunk(ref c);
                        n = ssl_stream.Read(c.buffer, 0, c.size);
                        text = UTF8.GetString(c.buffer, 0, n);
                        if (!text.StartsWith("334"))
                            return s = 1;

                        text = UserID + '\0' + UserName + '\0' + Password;
                        text = Convert.ToBase64String(UTF8.GetBytes(text)) + "\r\n";
                        ssl_stream.Write(UTF8.GetBytes(text), 0, UTF8.GetByteCount(text));
                        ResetChunk(ref c);
                        n = ssl_stream.Read(c.buffer, 0, c.size);
                        text = UTF8.GetString(c.buffer, 0, n);
                        if (!text.StartsWith("235"))
                            return s = 2;
                    }
                }
            }
            catch (Exception)
            {
                s = -1;
            }

            return s;
        }