Exemple #1
0
        private void HandleBatchPacket(BatchPacket packet)
        {
            byte[] data = CompressionManager.DecompressionZlib(new BinaryStream(packet.Payload), true);
            using (NetworkStream stream = new NetworkStream(data))
            {
                while (!stream.IsEndOfStream())
                {
                    int    len     = stream.ReadVarInt();
                    byte[] payload = stream.ReadBytes(len);
                    _logger.Info(payload[0].ToString("X"));

                    DataPacket pk = Protocol.GetDefinedPacket(payload[0]).ValueOrFailure();

                    pk.SetBuffer(payload);

                    pk.DecodeHeader();
                    pk.DecodePayload();

                    _players.TryGetValue(packet.EndPoint, out IServerPlayer player);
                    player?.HandleDataPacket(pk);
                }
            }

            packet.Dispose();
        }
Exemple #2
0
        private void CompressFile(string fileName)
        {
            try
            {
                byte[] uncompressedData = StreamHelper.ReadFile(fileName);
                byte[] compressedData;
                if (this.type11ToolStripMenuItem.Checked)
                {
                    compressedData = CompressionManager.CompressOnz(uncompressedData);
                }
                else
                {
                    compressedData = CompressionManager.CompressLzss(uncompressedData);
                }

                string outFileName = fileName;
                if (!this.overwriteToolStripMenuItem.Checked)
                {
                    outFileName += ".compressed";
                }

                StreamHelper.WriteFile(outFileName, compressedData);
            }
            catch (SystemException exc)
            {
                this.errors.Add(string.Format(CultureInfo.CurrentCulture, "[{0}]: {1}", fileName, exc.Message));
            }
        }
Exemple #3
0
    public ServerConnection(NetPeer peer)
    {
        this.peer = peer;
        NetworkId = peer.Id;

        compressionManager = new CompressionManager();
    }
Exemple #4
0
 public CompressionViewModel(string dialogHostName,
                             string zip,
                             string folder,
                             bool autoClose,
                             bool deleteZip       = false,
                             bool clearDestFolder = false)
     : base(dialogHostName, autoClose)
 {
     _autoClose            = autoClose;
     _manager              = new CompressionManager(zip, folder, deleteZip, clearDestFolder);
     _manager.OnComplited += OnComplited;
 }
Exemple #5
0
        protected override IScsMessage DeserializeMessage(byte[] bytes)
        {
            if (encrypt)
            {
                bytes = XXTEA.Decrypt(bytes, keys);
            }
            if (compress)
            {
                bytes = CompressionManager.DecompressGZip(bytes);
            }

            return(base.DeserializeMessage(bytes));
        }
Exemple #6
0
        public void TestCompression()
        {
            string inStr   = SerializationManager.Serialize(gateway.FindArray <Order>());
            string outGZip = CompressionManager.Compress(inStr);
            string out7Zip = CompressionManager.Compress7Zip(inStr);

            Console.WriteLine("Input Size: " + inStr.Length.ToString());
            Console.WriteLine("GZip Output Size: " + outGZip.Length.ToString());
            Console.WriteLine("7Zip Output Size: " + out7Zip.Length.ToString());

            Assert.AreEqual(inStr.Length, CompressionManager.Decompress7Zip(out7Zip).Length);
            Assert.AreEqual(inStr.Length, CompressionManager.Decompress(outGZip).Length);
        }
Exemple #7
0
        public void GZipTest()
        {
            BinaryStream stream = new BinaryStream();

            stream.WriteStringUtf8("abcdefg");

            byte[]       compressionZlib = CompressionManager.CompressGZIP(stream, CompressionLevel.Fastest, true);
            BinaryStream stream2         = new BinaryStream(compressionZlib);

            byte[]       decompressionZlib = CompressionManager.DecompressGZIP(stream2, true);
            BinaryStream stream3           = new BinaryStream(decompressionZlib);

            Assert.True(stream3.ReadStringUtf8() == "abcdefg");
        }
Exemple #8
0
        protected override byte[] SerializeMessage(IScsMessage message)
        {
            var bytes = base.SerializeMessage(message);

            if (compress)
            {
                bytes = CompressionManager.CompressGZip(bytes);
            }
            if (encrypt)
            {
                bytes = XXTEA.Encrypt(bytes, keys);
            }

            return(bytes);
        }
        public void SendDataPacket(DataPacket packet, bool needAck   = false,
                                   Reliability reliability           = Reliability.Reliable,
                                   CompressionLevel compressionLevel = CompressionLevel.Fastest)
        {
            packet.EncodeHeader();
            packet.EncodePayload();

            NetworkStream stream = new NetworkStream();

            stream.WriteVarInt((int)packet.Length);
            stream.WriteBytes(packet.GetBuffer());
            byte[] payload = CompressionManager.CompressionZlib(stream, compressionLevel, true);

            BatchPacket batch = new BatchPacket();

            batch.Payload  = payload;
            batch.EndPoint = ClientPeer.PeerEndPoint;

            ClientPeer.SendEncapsulatedPacket(batch, reliability, packet.Channel);
        }
Exemple #10
0
        private void DecompressFile(string fileName)
        {
            try
            {
                byte[] compressedData = StreamHelper.ReadFile(fileName);
                byte[] decompressedData;
                if (compressedData.Length > 0)
                {
                    this.type11ToolStripMenuItem.Checked = compressedData[0] == 0x11;
                    this.type10ToolStripMenuItem.Checked = !this.type11ToolStripMenuItem.Checked;
                }

                if (this.type11ToolStripMenuItem.Checked)
                {
                    decompressedData = CompressionManager.DecompressOnz(compressedData);
                }
                else
                {
                    decompressedData = CompressionManager.Decompress(compressedData);
                }

                if (decompressedData == null)
                {
                    throw new FormatException("Not a compressed file!");
                }

                string outFileName = fileName;
                if (!this.overwriteToolStripMenuItem.Checked)
                {
                    outFileName += ".decompressed";
                }

                StreamHelper.WriteFile(outFileName, decompressedData);
            }
            catch (SystemException exc)
            {
                this.errors.Add(string.Format(CultureInfo.CurrentCulture, "[{0}]: {1}", fileName, exc.Message));
            }
        }
Exemple #11
0
        static void Main(string[] args)
        {
            //string msg = "This is a sentence to be compressed, converted to Base64 encoding,\r\nthen converted back to compressed form, then decompressed.";
            string msg = FoeServerCatalog.GetRssCache("CKXX");
            //PrintTitle("Testing CompressionManager");

            // Show original message
            //Console.WriteLine("Original message:");
            //Console.WriteLine(msg);
            //Console.WriteLine();

            // Show Base64 without compression
            string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(msg));

            //Console.WriteLine("Base64 without compression:");
            //Console.WriteLine(base64);
            //Console.WriteLine();

            // Show compressed base64
            byte[] compressed = CompressionManager.Compress(Encoding.UTF8.GetBytes(msg));
            base64 = Convert.ToBase64String(compressed);
            //Console.WriteLine("Compressed + Base64:");
            //Console.WriteLine(base64);
            //Console.WriteLine();

            // Show decompressed
            //compressed = Convert.FromBase64String(base64);
            compressed = Convert.FromBase64String("XQAAgAAQAAAAAAAAAAArlMVWcCtFDcKRGJnu/tFfaO6aVg==");
            //compressed = Convert.FromBase64String(base64);
            byte[] decompressed = CompressionManager.Decompress(compressed);
            string originalMsg  = Encoding.UTF8.GetString(decompressed);
            //Console.WriteLine("Decompressed:");
            //Console.WriteLine(originalMsg);
            //Console.WriteLine();

            //PrintFooter();
        }
Exemple #12
0
        /// <summary>
        /// Download and process email messages from the POP3 server.
        /// </summary>
        /// <param name="server">POP3 server information</param>
        public static void DownloadMessages()
        {
            // Get POP3 server info
            PopServer server = GetPopServer();

            // connect to POP3 server and download messages
            //FoeDebug.Print("Connecting to POP3 server...");
            POPClient popClient = new POPClient();

            popClient.IsUsingSsl = server.SslEnabled;

            popClient.Disconnect();
            popClient.Connect(server.ServerName, server.Port);
            popClient.Authenticate(server.UserName, server.Password);

            FoeDebug.Print("Connected to POP3.");

            // get mail count
            int count = popClient.GetMessageCount();

            // go through each message, from newest to oldest
            for (int i = count; i >= 1; i -= 1)
            {
                OpenPOP.MIMEParser.Message msg = popClient.GetMessage(i, true);
                if (msg != null)
                {
                    string subject   = msg.Subject;
                    string fromEmail = msg.FromEmail;

                    // Check if fromEmail is the same as processor's email on file
                    if (fromEmail.ToLower() == FoeClientRegistry.GetEntry("processoremail").Value.ToLower())
                    {
                        // parse subject line
                        string[] tokens = subject.Trim().Split(new char[] { ' ' });

                        // There should be 5 tokens
                        if (tokens.Length == 5)
                        {
                            // Get the request ID for this reply
                            string requestId = tokens[2];

                            // Check if request ID matches any request the client sent
                            FoeClientRequestItem req = FoeClientRequest.Get(requestId);
                            if (req != null)
                            {
                                // Found the matching request
                                // Download the full reply
                                OpenPOP.MIMEParser.Message wholeMsg = popClient.GetMessage(i, false);
                                string msgBody = (string)wholeMsg.MessageBody[0];

                                try
                                {
                                    // decompress it
                                    byte[] compressedMsg   = Convert.FromBase64String(msgBody);
                                    byte[] decompressedMsg = CompressionManager.Decompress(compressedMsg);
                                    string foeXml          = Encoding.UTF8.GetString(decompressedMsg);

                                    // Check what is the original request type
                                    if (req.Type.ToLower() == "reg")
                                    {
                                        ProcessRegistrationReply(foeXml);
                                    }
                                    else if (req.Type.ToLower() == "content")
                                    {
                                        ProcessContentReply(foeXml);
                                    }
                                    else if (req.Type.ToLower() == "catalog")
                                    {
                                        ProcessCatalogReply(foeXml);
                                    }
                                }
                                catch (Exception)
                                {
                                    // the message is likely malformed
                                    // so just ignore it
                                }
                            }
                        }
                    }
                }
                // Delete the current message
                popClient.DeleteMessage(i);
            }
            popClient.Disconnect();
        }
Exemple #13
0
        public static string leer(string archivoHex)
        {
            FileStream    fs = new FileStream(archivoHex, FileMode.Open);
            int           hexIn;
            string        hex  = "";
            StringBuilder hex2 = new StringBuilder();

            while ((hexIn = fs.ReadByte()) != -1)
            {
                hex2.Append(string.Format("{0:X2}", hexIn));
            }

            hex = hex2.ToString();
            fs.Dispose();

            byte[] compressedFile   = strToByte.StringToByteArray(hex);
            byte[] decompressedFile = CompressionManager.Decompress(compressedFile);

            hex = strToByte.ByteArrayToString(decompressedFile);

            //Console.WriteLine(decompressedData);


            //string cabeceraDatos = (archivoHex.Contains("ds_event.cmp")) ? hex[212].ToString() + hex[213].ToString() + hex[210].ToString() + hex[211].ToString() + hex[208].ToString() + hex[209].ToString() : cabeceraDatos = hex[210].ToString() + hex[211].ToString() + hex[208].ToString() + hex[209].ToString();

            string cabeceraDatos = "";

            if (archivoHex.Contains("ds_event.cmp"))
            {
                cabeceraDatos = hex[212].ToString() + hex[213].ToString() + hex[210].ToString() + hex[211].ToString() + hex[208].ToString() + hex[209].ToString();
            }
            else if (archivoHex.Contains("ds_eventm"))
            {
                cabeceraDatos = "0";
            }
            else
            {
                cabeceraDatos = hex[210].ToString() + hex[211].ToString() + hex[208].ToString() + hex[209].ToString();
            }

            //Console.WriteLine(cabeceraDatos);

            int cabeceraDatosInt = Convert.ToInt32(cabeceraDatos, 16);
            //Console.WriteLine(cabeceraDatosInt);
            string punterosyTexto = "";

            for (int i = cabeceraDatosInt * 2; i < hex.Length; i++)
            {
                punterosyTexto += string.Format("{0:X2}", hex[i]);
            }

            //Console.WriteLine(cabeceraDatosInt);
            //Console.WriteLine(punterosyTexto);

            MatchCollection punterosMatch;

            if (archivoHex.Contains("ds_eventm"))
            {
                punterosMatch = Regex.Matches(punterosyTexto, "(?:....0000)", RegexOptions.RightToLeft);
            }
            else
            {
                punterosMatch = Regex.Matches(punterosyTexto, "....0{4}(0{2})(?!0*?$)", RegexOptions.RightToLeft);
            }

            string punteros = punterosyTexto.Substring(0, punterosMatch[0].Groups[0].Index);

            //Console.WriteLine(punteros);

            string texto = "";

            if (archivoHex.Contains("ds_eventm") == true)
            {
                texto = punterosyTexto.Substring(punterosMatch[0].Groups[0].Index + 4);
            }
            else if (archivoHex.Contains("ds_event.cmp") == true)
            {
                texto = punterosyTexto.Substring(punterosMatch[0].Groups[0].Index + 10);
            }
            else
            {
                texto = punterosyTexto.Substring(punterosMatch[0].Groups[1].Index + 2);
            }


            var    conversionRegex = new Regex(string.Join("|", conversion.Keys));
            string textoConvertido = conversionRegex.Replace(texto, m => conversion[m.Value]);

            //Console.WriteLine(textoConvertido);

            return(textoConvertido);
        }
Exemple #14
0
 private void button2_Click(object sender, EventArgs e)
 {
     byte[] compressed = Convert.FromBase64String(tbxTarget.Text);
     tbxSource.Text = Encoding.UTF8.GetString(CompressionManager.Decompress(compressed));
 }
 public ClientConnection(NetPeer peer)
 {
     this.peer          = peer;
     compressionManager = new CompressionManager();
 }
Exemple #16
0
        /// <summary>
        /// Calls the service.
        /// </summary>
        /// <param name="subServiceName">Name of the sub service.</param>
        /// <param name="returnType">Type of the return.</param>
        /// <param name="paramValues">The param values.</param>
        /// <returns>The result.</returns>
        protected object CallService(string subServiceName, Type returnType, params object[] paramValues)
        {
            object errorReturnValue = null;

            if (returnType != typeof(void))
            {
                errorReturnValue = Util.DefaultValue(returnType);
            }

            RequestMessage reqMsg = new RequestMessage();

            reqMsg.Expiration     = DateTime.Now.AddMinutes(DefaultExpireMinutes);
            reqMsg.MessageId      = Guid.NewGuid();
            reqMsg.ServiceName    = serviceInterfaceType.FullName;
            reqMsg.SubServiceName = subServiceName;
            reqMsg.Timestamp      = DateTime.Now;
            reqMsg.TransactionId  = Guid.NewGuid();

            MethodInfo mi = null;

            foreach (MethodInfo item in serviceInterfaceType.GetMethods())
            {
                if (item.ToString() == subServiceName)
                {
                    mi = item;
                    break;
                }
            }

            if (mi == null)
            {
                foreach (Type inheritedInterface in serviceInterfaceType.GetInterfaces())
                {
                    foreach (MethodInfo item in inheritedInterface.GetMethods())
                    {
                        if (item.ToString() == subServiceName)
                        {
                            mi = item;
                            break;
                        }
                    }
                }
            }

            if (mi == null)
            {
                return(errorReturnValue);
            }

            ParameterInfo[] pis = mi.GetParameters();

            if ((pis.Length == 0 && paramValues != null && paramValues.Length > 0) || (paramValues != null && pis.Length != paramValues.Length))
            {
                return(errorReturnValue);
            }

            if (pis.Length > 0)
            {
                for (int i = 0; i < paramValues.Length; i++)
                {
                    if (paramValues[i] == null)
                    {
                        continue;
                    }

                    string val = SerializationManager.Serialize(paramValues[i]);

                    reqMsg.Parameters[pis[i].Name] = val;
                }
            }

            ResponseMessage resMsg = container.CallService(serviceInterfaceType.FullName, reqMsg);

            if (resMsg == null || returnType == typeof(void))
            {
                return(errorReturnValue);
            }

            try
            {
                if (!container.Compress)
                {
                    if (returnType == typeof(System.Data.DataSet))
                    {
                        return(resMsg.Data);
                    }
                    else if (resMsg.Text != null)
                    {
                        return(SerializationManager.Deserialize(returnType, resMsg.Text));
                    }
                }
                else
                {
                    string retText = CompressionManager.Decompress7Zip(resMsg.Text);
                    if (retText != null)
                    {
                        return(SerializationManager.Deserialize(returnType, retText));
                    }
                }
            }
            catch
            {
            }

            return(errorReturnValue);
        }
Exemple #17
0
        /// <summary>
        /// Runs the specified MSG.
        /// </summary>
        /// <param name="msg">The MSG.</param>
        /// <returns>The msg.</returns>
        protected override ResponseMessage Run(RequestMessage msg)
        {
            if (container == null || msg == null)
            {
                return(null);
            }

            object service = default(object);

            try
            {
                service = container[serviceInterfaceType];
            }
            catch
            {
            }

            if (service == null)
            {
                return(null);
            }

            MethodInfo mi = null;

            foreach (MethodInfo item in serviceInterfaceType.GetMethods())
            {
                if (msg.SubServiceName == item.ToString())
                {
                    mi = item;
                    break;
                }
            }

            if (mi == null)
            {
                foreach (Type inheritedInterface in serviceInterfaceType.GetInterfaces())
                {
                    foreach (MethodInfo item in inheritedInterface.GetMethods())
                    {
                        if (item.ToString() == msg.SubServiceName)
                        {
                            mi = item;
                            break;
                        }
                    }
                }
            }

            if (mi == null)
            {
                return(null);
            }

            ParameterInfo[] pis   = mi.GetParameters();
            object[]        parms = new object[pis.Length];

            for (int i = 0; i < pis.Length; i++)
            {
                Type type = pis[i].ParameterType;

                object val = SerializationManager.Deserialize(type, msg.Parameters[pis[i].Name]);

                parms[i] = val;
            }

            ResponseMessage resMsg = new ResponseMessage();

            resMsg.Request        = msg;
            resMsg.Expiration     = DateTime.Now.AddMinutes(DefaultExpireMinutes);
            resMsg.MessageId      = Guid.NewGuid();
            resMsg.ServiceName    = serviceInterfaceType.FullName;
            resMsg.SubServiceName = mi.Name;
            resMsg.Timestamp      = DateTime.Now;
            resMsg.TransactionId  = msg.TransactionId;

            object returnValue = null;

            try
            {
                returnValue = mi.Invoke(service, parms);
            }
            catch
            {
                return(null);
            }

            if (returnValue != null)
            {
                Type returnType = mi.ReturnType;

                if (!container.Compress)
                {
                    if (returnType == typeof(System.Data.DataSet))
                    {
                        resMsg.Data = (DataSet)returnValue;
                    }
                    else
                    {
                        resMsg.Text = SerializationManager.Serialize(returnValue);
                    }
                }
                else
                {
                    string retText;
                    if (returnType == typeof(System.Data.DataSet))
                    {
                        retText = SerializationManager.Serialize(returnValue);
                    }
                    else
                    {
                        retText = SerializationManager.Serialize(returnValue);
                    }

                    resMsg.Text = CompressionManager.Compress7Zip(retText);
                }
            }

            return(resMsg);
        }
Exemple #18
0
        /// <summary>
        /// Download and process email messages from the POP3 server.
        /// </summary>
        /// <param name="server">POP3 server information</param>
        public static void DownloadMessages()
        {
            Trace.WriteLine("Entered DownloadMessages().");

            // Get POP3 server info
            PopServer server = GetPopServer();

            Trace.WriteLine("  Retrieved POP server info.");

            // connect to POP3 server and download messages
            //FoeDebug.Print("Connecting to POP3 server...");
            POPClient popClient = new POPClient();

            popClient.IsUsingSsl = server.SslEnabled;

            popClient.Disconnect();
            popClient.Connect(server.ServerName, server.Port);
            popClient.Authenticate(server.UserName, server.Password);

            Trace.WriteLine("  Connected to POP3.");

            // get mail count
            int count = popClient.GetMessageCount();

            Trace.WriteLine("  There are " + count.ToString() + " messages in inbox.");

            // go through each message, from newest to oldest
            for (int i = count; i >= 1; i -= 1)
            {
                Trace.WriteLine("  Opening message #" + i.ToString());

                OpenPOP.MIMEParser.Message msg = popClient.GetMessage(i, true);
                if (msg != null)
                {
                    string subject   = msg.Subject;
                    string fromEmail = msg.FromEmail;

                    Trace.WriteLine("  Message came from " + msg.FromEmail + " with subject \"" + msg.Subject + "\"");

                    // Check if fromEmail is the same as processor's email on file
                    if (fromEmail.ToLower() == FoeClientRegistry.GetEntry("processoremail").Value.ToLower())
                    {
                        Trace.WriteLine("  Message came from the processor.");

                        // parse subject line
                        string[] tokens = subject.Trim().Split(new char[] { ' ' });

                        // There should be 5 or 6 tokens
                        if (tokens.Length == 5)
                        {
                            Trace.WriteLine("  There are 5 tokens.");

                            // Get the request ID for this reply
                            string requestId = tokens[2];

                            // Check if request ID matches any request the client sent
                            FoeClientRequestItem req = FoeClientRequest.Get(requestId);

                            if (req != null)
                            {
                                Trace.WriteLine("  Message Request ID matched.");

                                // Found the matching request
                                // Download the full reply
                                OpenPOP.MIMEParser.Message wholeMsg = popClient.GetMessage(i, false);
                                string msgBody = (string)wholeMsg.MessageBody[0];

                                Trace.WriteLine("  Downloaded full message body.");

                                try
                                {
                                    // decompress it
                                    byte[] compressedMsg = Convert.FromBase64String(msgBody);
                                    Trace.WriteLine("  Decoded Base64 message.");

                                    byte[] decompressedMsg = CompressionManager.Decompress(compressedMsg);
                                    Trace.WriteLine("  Decompressed message.");

                                    string foe = Encoding.UTF8.GetString(decompressedMsg);
                                    Trace.WriteLine("  Retrieved original FOE message.");

                                    // Check what is the original request type
                                    if (req.Type.ToLower() == "registe")
                                    {
                                        Trace.WriteLine("  Registration reply. Processing message.");
                                        ProcessRegistrationReply(foe);
                                        Trace.WriteLine("  Registration reply processed.");
                                    }
                                    else if (req.Type.ToLower() == "catalog")
                                    {
                                        Trace.WriteLine("  Catalog reply. Processing message.");
                                        ProcessCatalogReply(foe);
                                        Trace.WriteLine("  Catalog reply processed.");
                                    }
                                    else if (req.Type.ToLower() == "feed")
                                    {
                                        Trace.WriteLine("  feed reply. Processing message.");
                                        ProcessCatalogReply(foe);
                                        Trace.WriteLine("  feed reply processed.");
                                    }
                                }
                                catch (Exception except)
                                {
                                    // the message is likely malformed
                                    // so just ignore it
                                    Trace.WriteLine("  Exception detected: \r\n" + except.ToString());
                                }
                            }
                            else
                            {
                                Trace.WriteLine("  Message ID mismatched.");
                            }
                        }
                        //content request's reply
                        else if (tokens.Length == 6)
                        {
                            Trace.WriteLine("  There are 6 tokens.");

                            // Get the request ID for this reply
                            string catalog   = tokens[1];
                            string requestId = tokens[3];

                            // Check if request ID matches any request the client sent
                            FoeClientRequestItem req = FoeClientRequest.Get(requestId);

                            if (req != null)
                            {
                                Trace.WriteLine("  Message Request ID matched.");

                                // Found the matching request
                                // Download the full reply
                                OpenPOP.MIMEParser.Message wholeMsg = popClient.GetMessage(i, false);
                                string msgBody = (string)wholeMsg.MessageBody[0];

                                Trace.WriteLine("  Downloaded full message body.");

                                try
                                {
                                    byte[] compressed   = Convert.FromBase64String(msgBody);
                                    byte[] decompressed = CompressionManager.Decompress(compressed);
                                    string foe          = Encoding.UTF8.GetString(decompressed);

                                    // Check what is the original request type
                                    if (req.Type.ToLower() == "content")
                                    {
                                        Trace.WriteLine("  Content reply. Processing message.");
                                        ProcessContentReply(catalog, foe);
                                        Trace.WriteLine("  Content reply processed.");
                                    }
                                }
                                catch (Exception except)
                                {
                                    // the message is likely malformed
                                    // so just ignore it
                                    Trace.WriteLine("  Exception detected: \r\n" + except.ToString());
                                }
                            }
                            else
                            {
                                Trace.WriteLine("  Message ID mismatched.");
                            }
                        }
                        else
                        {
                            Trace.WriteLine("  Message does not have 5 tokens.");
                        }
                    }
                    else
                    {
                        Trace.WriteLine("  Message did not come from processor.");
                    }
                }
                // Delete the current message
                popClient.DeleteMessage(i);
                Trace.WriteLine("  Deleted current message in inbox.");
            }
            popClient.Disconnect();
            Trace.WriteLine("  Disconnected from POP server.");

            Trace.WriteLine("  Exiting DownloadMessages().");
        }
        /// <summary>
        /// Download email messages from the POP3 server for a given Foe message processor.
        /// </summary>
        /// <param name="server">POP3 server information</param>
        /// <param name="processorEmail">The current Foe message processor's email address.</param>
        public static void DownloadMessages(PopServer server, string processorEmail)
        {
            // connect to POP3 server and download messages
            //FoeDebug.Print("Connecting to POP3 server...");
            POPClient popClient = new POPClient();

            popClient.IsUsingSsl = server.SslEnabled;

            popClient.Disconnect();
            popClient.Connect(server.ServerName, server.Port);
            popClient.Authenticate(server.UserName, server.Password);

            FoeDebug.Print("Connected to POP3.");

            // get mail count
            int count = popClient.GetMessageCount();

            FoeDebug.Print("Server reported " + count.ToString() + " messages.");

            // go through each message, from newest to oldest
            for (int i = count; i >= 1; i -= 1)
            {
                //FoeDebug.Print("Opening mail message...");

                OpenPOP.MIMEParser.Message msg = popClient.GetMessage(i, true);
                if (msg != null)
                {
                    // Get subject and verify sender identity
                    // Subject line in the mail header should look like one of the followings:
                    //
                    // Normal request (for news feed and content):
                    //   Subject: Request <Request ID> by <User ID>
                    //
                    // Registration request:
                    //   Subject: Register <Request ID> by Newbie
                    //
                    // where:
                    // Request ID is the request ID generated by the Foe client
                    // User ID is the user's ID as assigned by the server

                    //FoeDebug.Print("Message is not null. Getting message details.");

                    string subject   = msg.Subject;
                    string fromEmail = msg.FromEmail;

                    //FoeDebug.Print("Subject: " + subject);
                    //FoeDebug.Print("From: " + fromEmail);

                    // parse subject line
                    string[] tokens = subject.Trim().Split(new char[] { ' ' });
                    if (tokens.Length == 4)
                    {
                        // check what type of request is it
                        string requestType = tokens[0].ToUpper();
                        string requestId   = tokens[1];
                        string userId      = tokens[3];

                        FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message,
                                         "subject: " + subject + "requestType: " + requestType);
                        if (requestType.ToUpper().CompareTo("REGISTE") == 0)
                        {
                            //FoeDebug.Print("This is a registration message.");
                            // It's a registration request
                            SaveRegistrationRequest(requestId, fromEmail, processorEmail);

                            FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message,
                                             "Received registration request from " + fromEmail);
                        }
                        else if (requestType.ToUpper().CompareTo("CATALOG") == 0)
                        {
                            // get user info by email address
                            FoeUser user = FoeServerUser.GetUser(fromEmail);

                            // verify user's email against the user ID
                            if ((user != null) && (userId == user.UserId) && (processorEmail == user.ProcessorEmail))
                            {
                                FoeDebug.Print("User verified.");

                                // the user's identity is verified
                                SaveCatalogRequest(requestId, user.Email, processorEmail);
                            }
                            else
                            {
                                //FoeDebug.Print("User is not registered. Request not processed.");
                                FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning,
                                                 "Received content request from unregistered user " + fromEmail);
                            }
                        }
                        else if (requestType.ToUpper().CompareTo("CONTENT") == 0)
                        {
                            //FoeDebug.Print("This is a content request message.");

                            // It's a content request.
                            // We need to verify the user's identify first.

                            //FoeDebug.Print("Verifying user identity...");

                            // get user info by email address
                            FoeUser user = FoeServerUser.GetUser(fromEmail);

                            // verify user's email against the user ID
                            if ((user != null) && (userId == user.UserId) && (processorEmail == user.ProcessorEmail))
                            {
                                FoeDebug.Print("User verified.");

                                // the user's identity is verified
                                // get the full message body
                                OpenPOP.MIMEParser.Message wholeMsg = popClient.GetMessage(i, false);
                                string msgBody = (string)wholeMsg.MessageBody[0];

                                try
                                {
                                    // decompress it
                                    byte[] compressedMsg   = Convert.FromBase64String(msgBody);
                                    byte[] decompressedMsg = CompressionManager.Decompress(compressedMsg);
                                    string foe             = Encoding.UTF8.GetString(decompressedMsg);

                                    string[] catalogs = foe.Trim().Split(new char[] { ',' });
                                    // save request
                                    if (catalogs.Length == 0)
                                    {
                                        return;
                                    }
                                    SaveContentRequest(requestId, user.Email, catalogs, processorEmail);

                                    //FoeDebug.Print("Request saved and pending processing.");
                                    FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message,
                                                     "Received content request from verified user " + fromEmail);
                                }
                                catch (Exception except)
                                {
                                    // the message is likely malformed
                                    // so just ignore it
                                    FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning,
                                                     "Received malformed content request from verified user " + fromEmail + "\r\n" +
                                                     except.ToString() +
                                                     "Raw message:\r\n" + msgBody + "\r\n");

                                    //throw except;
                                }
                            }
                            else
                            {
                                //FoeDebug.Print("User is not registered. Request not processed.");
                                FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning,
                                                 "Received content request from unregistered user " + fromEmail);
                            }
                        }
                        else if (requestType.ToUpper().CompareTo("FEED") == 0)
                        {
                            //FoeDebug.Print("This is a content request message.");

                            // It's a content request.
                            // We need to verify the user's identify first.

                            //FoeDebug.Print("Verifying user identity...");

                            // get user info by email address
                            FoeUser user = FoeServerUser.GetUser(fromEmail);

                            // verify user's email against the user ID
                            if ((user != null) && (userId == user.UserId) && (processorEmail == user.ProcessorEmail))
                            {
                                FoeDebug.Print("User verified.");

                                // the user's identity is verified
                                // get the full message body
                                OpenPOP.MIMEParser.Message wholeMsg = popClient.GetMessage(i, false);
                                string msgBody = (string)wholeMsg.MessageBody[0];

                                try
                                {
                                    // decompress it
                                    byte[] compressedMsg   = Convert.FromBase64String(msgBody);
                                    byte[] decompressedMsg = CompressionManager.Decompress(compressedMsg);
                                    string foe             = Encoding.UTF8.GetString(decompressedMsg);

                                    string[] array = foe.Trim().Split(new char[] { ',' });
                                    // save request
                                    if (array.Length == 0)
                                    {
                                        return;
                                    }
                                    SaveFeedRequest(requestId, user.Email, array, processorEmail);

                                    //FoeDebug.Print("Request saved and pending processing.");
                                    FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message,
                                                     "Received feed request from verified user " + fromEmail);
                                }
                                catch (Exception except)
                                {
                                    // the message is likely malformed
                                    // so just ignore it
                                    FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning,
                                                     "Received malformed feed request from verified user " + fromEmail + "\r\n" +
                                                     except.ToString() +
                                                     "Raw message:\r\n" + msgBody + "\r\n");

                                    //throw except;
                                }
                            }
                            else
                            {
                                //FoeDebug.Print("User is not registered. Request not processed.");
                                FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning,
                                                 "Received content request from unregistered user " + fromEmail);
                            }
                        }
                        else
                        {
                            // Non-Foe message
                            FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message,
                                             "Received non-Foe message from " + fromEmail);
                        }
                    }
                    else
                    {
                        // Non-Foe message
                        FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message,
                                         "Received non-Foe message from " + fromEmail);
                    }

                    // Delete the current message
                    popClient.DeleteMessage(i);
                }
            }
            popClient.Disconnect();
        }
Exemple #20
0
 private void button1_Click(object sender, EventArgs e)
 {
     byte[] compressed = CompressionManager.Compress(Encoding.UTF8.GetBytes(tbxSource.Text));
     tbxTarget.Text = Convert.ToBase64String(compressed);
 }
Exemple #21
0
        public static void generate(string path)
        {
            switch (Properties.Settings.Default.selectedLang)
            {
            case 0:
                conversion = conversionES;
                break;

            case 1:
                conversion = conversionRU;
                break;
            }

            List <string> filesTranslated = new List <string>();

            filesTranslated.AddRange(Directory.GetFiles("./DSSE-files/translation/", "*.xml"));
            fileNumber = filesTranslated.Count();
            List <string> filesTranslatedNames = new List <string>();

            for (int i = 0; i < fileNumber; i++)
            {
                filesTranslatedNames.Add(Path.GetFileNameWithoutExtension(filesTranslated[i]));
            }

            //Console.WriteLine(filesTranslatedNames[0]);

            for (int i = 0; i < fileNumber; i++)
            {
                FileStream    fs = new FileStream(path + filesTranslatedNames[i] + ".cmp", FileMode.Open);
                int           hexIn;
                string        hex  = "";
                StringBuilder hex2 = new StringBuilder();
                for (int j = 0; (hexIn = fs.ReadByte()) != -1; j++)
                {
                    hex2.Append(string.Format("{0:X2}", hexIn));
                }
                hex = hex2.ToString();
                fs.Dispose();

                byte[] compressedFile   = strToByte.StringToByteArray(hex);
                byte[] decompressedFile = CompressionManager.Decompress(compressedFile);

                hex = strToByte.ByteArrayToString(decompressedFile);

                string cabeceraDatos = "";
                if (filesTranslatedNames[i].Equals("ds_event"))
                {
                    cabeceraDatos = hex[212].ToString() + hex[213].ToString() + hex[210].ToString() + hex[211].ToString() + hex[208].ToString() + hex[209].ToString();
                }
                else if (filesTranslatedNames[i].Contains("ds_eventm"))
                {
                    cabeceraDatos = "0";
                }
                else
                {
                    cabeceraDatos = hex[210].ToString() + hex[211].ToString() + hex[208].ToString() + hex[209].ToString();
                }

                int cabeceraDatosInt = Convert.ToInt32(cabeceraDatos, 16);

                string        binaryData  = "";
                StringBuilder binaryData2 = new StringBuilder();
                int           k           = 0;
                while (k < cabeceraDatosInt * 2)
                {
                    binaryData2.Append(string.Format("{0:X2}", hex[k]));
                    k++;
                }
                binaryData = binaryData2.ToString();

                //Console.WriteLine("Datos binarios:" + binaryData);

                XDocument document = XDocument.Load("./DSSE-files/translation/" + filesTranslatedNames[i] + ".xml");
                XElement  root     = document.Root;

                List <string> lines = new List <string>();

                lines.AddRange(from el in root.Elements("Segment")
                               where el.Element("Translated") != null
                               select el.Element("Translated").Value);

                int numberofTextSegments = 0;
                for (int m = 0; m < lines.Count; m++)
                {
                    lines[m] = lines[m].Replace("\n", "[br]");
                    if (!lines[m].Contains("[new]"))
                    {
                        lines[m] = "[00]" + lines[m];
                        numberofTextSegments++;
                    }
                }

                string allLines = string.Join("", lines);
                allLines += "[00]"; //añadir último 00

                //Console.WriteLine(allLines);

                var conversionRegex = new Regex(string.Join("|", conversion.Keys.Select(key => Regex.Escape(key))));
                var textoConvertido = conversionRegex.Replace(allLines, n => conversion[n.Value]);

                //Console.WriteLine(textoConvertido);

                string        punterosyTexto  = "";
                StringBuilder punterosyTexto2 = new StringBuilder();
                for (int m = cabeceraDatosInt * 2; m < hex.Length; m++)
                {
                    //punterosyTexto += string.Format("{0:X2}", hex[m]);
                    punterosyTexto2.Append(string.Format("{0:X2}", hex[m]));
                }

                punterosyTexto = punterosyTexto2.ToString();


                MatchCollection punterosMatch;

                if (filesTranslatedNames[i].Contains("ds_eventm"))
                {
                    punterosMatch = Regex.Matches(punterosyTexto, "(?:....0000)", RegexOptions.RightToLeft);
                }
                else
                {
                    punterosMatch = Regex.Matches(punterosyTexto, "....0{4}(0{2})(?!0*?$)", RegexOptions.RightToLeft);
                }

                //Console.WriteLine(4 + punterosMatch[0].Groups[0].Value);

                string        punteros  = "";
                StringBuilder punteros2 = new StringBuilder();
                for (int p = 0; p < 4 + punterosMatch[0].Groups[0].Index; p++)
                {
                    punteros2.Append(string.Format("{0:X2}", punterosyTexto[p]));
                }

                punteros = punteros2.ToString();

                //Console.WriteLine(punteros);

                MatchCollection punterosDiv = Regex.Matches(punteros, "(....)0000");

                //Console.WriteLine(punterosDiv[0].Groups[1] + "\n\r");
                //Console.WriteLine(punterosDiv[1].Groups[1]);

                //El primer valor que hay en punteros es la longitud de punteros + texto. [!] Hay que adaptarlo.
                //El segundo valor no sirve, solo resta -1 respecto al siguiente.
                //El tercer valor (2) es el primer puntero base.

                //En lines[] tengo las líneas convertidas en HEX ya para saber la longitud.

                var pointBase = "";

                if (filesTranslatedNames[i].Contains("ds_eventm"))
                {
                    pointBase = punterosDiv[1].Groups[1].Value;
                }
                else
                {
                    pointBase = punterosDiv[2].Groups[1].Value;
                }

                //Console.WriteLine("Pointbase: "+pointBase);

                string pointers = "";

                List <string> lineasHex = Regex.Split(textoConvertido.Substring(2), "00(?!0)").ToList();
                //Console.WriteLine(lineasHex[0]);

                StringBuilder pointers2 = new StringBuilder();
                for (int q = 0; q < lineasHex.Count() - 2; q++) //-2 porque el último texto no va punteado
                {
                    var _pointBaseLE        = pointBase.ToCharArray();
                    var _pointBaseBE        = _pointBaseLE[2].ToString() + _pointBaseLE[3].ToString() + _pointBaseLE[0].ToString() + _pointBaseLE[1].ToString();
                    var _pointBaseBEDecimal = Convert.ToInt32(_pointBaseBE, 16);
                    int lineSize            = ((lineasHex[q].Length / 2) + 1);
                    //Console.WriteLine(lineSize + "\n\r");
                    //Console.WriteLine("Point base: "+pointBase.ToString() + "\r\n");
                    var    newPointerBE = Convert.ToInt32((_pointBaseBEDecimal + lineSize)).ToString("x").PadLeft(4, '0').ToCharArray();
                    string newPointerLE = newPointerBE[2].ToString() + newPointerBE[3].ToString() + newPointerBE[0].ToString() + newPointerBE[1].ToString();
                    //pointers += newPointerLE.ToString().PadRight(8, '0');
                    pointers2.Append(newPointerLE.ToString().PadRight(8, '0'));
                    pointBase = newPointerLE;
                }

                if (filesTranslatedNames[i].Contains("ds_eventm"))
                {
                    numberofTextSegments = Convert.ToInt32(numberofTextSegments);
                    string numberofTextSegmentsS = numberofTextSegments.ToString("x").PadRight(8, '0');
                    //Console.WriteLine(numberofTextSegmentsS);
                    pointers = numberofTextSegmentsS + punterosDiv[1].Groups[1].Value + "0000" + pointers2.ToString();
                }
                else
                {
                    pointers = punterosDiv[0].Groups[1].Value + "0000" + punterosDiv[1].Groups[1].Value + "0000" + punterosDiv[2].Groups[1].Value + "0000" + pointers2.ToString();
                }

                //Console.WriteLine(pointers);


                //string archivoFinal = pointers + "00" + textoConvertido;

                string archivoFinal = "";

                if ((filesTranslatedNames[i].Equals("ds_event") == false) && (filesTranslatedNames[i].Contains("ds_eventm") == false))
                {
                    archivoFinal = pointers + textoConvertido;
                }
                else if (filesTranslatedNames[i].Contains("ds_eventm") == true)
                {
                    archivoFinal = pointers + textoConvertido.Substring(2); //Elimina los 00 añadidos antes al principio, en este tipo de ficheros sobra.
                }
                else
                {
                    //Este fixedData es para el archivo "ds_event.cmp", tiene esos datos invariables. Para ahorrar su captura los pongo aquí directamente.
                    string fixedData = "7E0000000000000062010000BD0100005E020000DB02000046030000B2030000020400005C040000FC04000077050000D50500004B06000082060000D706000045070000A5070000FC0700003A0800008F080000D80800003F090000E9090000520A00008E0A0000D80A0000370B0000930B0000E80B0000440C0000E50C00001B0D00007B0D0000E30D00004C0E0000A60E0000F70E0000420F0000840F0000F10F000086100000BB1000001F110000E01100003E12000093120000DA1200005F130000C613000079140000F314000071150000BE1500000F1600004D16000099160000EE1600006D170000CD1700001D18000082180000CB1800000919000058190000A5190000E31900004E1A0000D41A0000641B0000DA1B00001D1C0000691C0000AE1C00002A1D0000861D0000F01D00004C1E0000921E0000D21E0000141F0000551F0000F61F00003A2000007D200000CA2000003521000093210000EB21000046220000B8220000362300007F230000D3230000412400008F240000BE2400000425000039250000BC2500001A26000080260000D926000028270000772700001628000075280000B82800000D29000065290000D6290000382A0000AF2A00000D2B0000662B0000C92B00000D2C00005B2C0000B12C0000042D00003B2D00007F2D0000E72D0000232E00006E2E0000C82E00000E2F0000";
                    archivoFinal = pointers + fixedData + textoConvertido;
                }

                var datosLengthArray = Convert.ToInt32((archivoFinal.Length / 2)).ToString("x").PadLeft(4, '0').ToCharArray();
                var datosLength      = datosLengthArray[2].ToString() + datosLengthArray[3].ToString() + datosLengthArray[0].ToString() + datosLengthArray[1].ToString();



                if (filesTranslatedNames[i].Contains("ds_eventm") == false)
                {
                    archivoFinal = archivoFinal.Remove(0, 4);
                    archivoFinal = archivoFinal.Insert(0, datosLength.ToString());
                    archivoFinal = binaryData + archivoFinal;
                }

                byte[] archivoFinalBin = strToByte.StringToByteArray(archivoFinal);

                //File.WriteAllBytes("./DSSE-files/output/" + filesTranslatedNames[i] + ".decmp", archivoFinalBin);

                byte[] compressedFileOutput = CompressionManager.Compress(archivoFinalBin);


                File.WriteAllBytes("./DSSE-files/output/" + filesTranslatedNames[i] + ".cmp", compressedFileOutput);

                Stream myStreamF = File.Open("./DSSE-files/output/" + filesTranslatedNames[i] + ".cmp", FileMode.Open);
                myStreamF.Seek(myStreamF.Length, SeekOrigin.Begin);

                while ((myStreamF.Length) % 4 != 0)
                {
                    myStreamF.WriteByte(0x00);
                }


                myStreamF.Dispose();

                //Console.WriteLine(archivoFinal);

                //Console.WriteLine("Progreso: " + (i + 1) + " de " + fileNumber);

                MainWindow.generateOutputBGW.ReportProgress(i + 1);
            }
        }