Esempio n. 1
0
        public TSharkSender(string pipeName, DataLinkType linkType)
        {
            this.m_pipeName = pipeName;
            this.m_linkType = linkType;

            m_connectionCompleted = Task.Factory.StartNew(PipeCreate);
        }
Esempio n. 2
0
        public PcapFileReader(string filename, int packetQueueSize, ReadCompletedCallback captureCompleteCallback)
        {
            this.filename   = filename;
            this.fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, 262144, FileOptions.SequentialScan);

            this.packetQueueSize       = packetQueueSize;
            this.readCompletedCallback = captureCompleteCallback;

            byte[] buffer4 = new byte[4]; //32 bits is suitable
            byte[] buffer2 = new byte[2]; //16 bits is sometimes needed
            uint   wiresharkMagicNumber = 0xa1b2c3d4;

            //Section Header Block (mandatory)

            fileStream.Read(buffer4, 0, 4);

            if (wiresharkMagicNumber == this.ToUInt32(buffer4, false))
            {
                this.littleEndian = false;
            }
            else if (wiresharkMagicNumber == this.ToUInt32(buffer4, true))
            {
                this.littleEndian = true;
            }
            else
            {
                throw new System.IO.InvalidDataException("The file " + filename + " is not a PCAP file. Magic number is " + this.ToUInt32(buffer4, false).ToString("X2") + " or " + this.ToUInt32(buffer4, true).ToString("X2") + " but should be " + wiresharkMagicNumber.ToString("X2") + ".");
            }

            /* major version number */
            fileStream.Read(buffer2, 0, 2);
            this.majorVersionNumber = ToUInt16(buffer2, this.littleEndian);
            /* minor version number */
            fileStream.Read(buffer2, 0, 2);
            this.minorVersionNumber = ToUInt16(buffer2, this.littleEndian);
            /* GMT to local correction */
            fileStream.Read(buffer4, 0, 4);
            this.timezoneOffsetSeconds = (int)ToUInt32(buffer4, this.littleEndian);
            /* accuracy of timestamps */
            fileStream.Read(buffer4, 0, 4);
            /* max length of captured packets, in octets */
            fileStream.Read(buffer4, 0, 4);
            this.maximumPacketSize = ToUInt32(buffer4, this.littleEndian);
            /* data link type */
            fileStream.Read(buffer4, 0, 4);
            this.dataLinkType = (DataLinkType)ToUInt32(buffer4, this.littleEndian);

            this.pcapHeaderSize = fileStream.Position;

            this.backgroundFileReader = new System.ComponentModel.BackgroundWorker();
            this.packetQueue          = new Queue <PcapPacket>(this.packetQueueSize);
            this.enqueuedByteCount    = 0;
            this.dequeuedByteCount    = 0;

            this.StartBackgroundWorkers();
        }
Esempio n. 3
0
        public PcapFileWriter(string filename, DataLinkType dataLinkType, System.IO.FileMode fileMode, int bufferSize)
        {
            this.filename      = filename;
            this.referenceTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            this.fileStream    = new FileStream(filename, fileMode, FileAccess.Write, FileShare.Write, bufferSize, FileOptions.SequentialScan);
            this.isOpen        = true;

            fileStream.Write(ToByteArray(MAGIC_NUMBER), 0, 4);
            fileStream.Write(ToByteArray(MAJOR_VERSION_NUMBER), 0, 2);
            fileStream.Write(ToByteArray(MINOR_VERSION_NUMBER), 0, 2);
            fileStream.Write(ToByteArray((uint)0x00), 0, 4);   //Time zone offset
            fileStream.Write(ToByteArray((uint)0x00), 0, 4);   //accuracy of timestamps
            fileStream.Write(ToByteArray((uint)0xffff), 0, 4); //max length of captured packets, in octets
            fileStream.Write(ToByteArray((uint)dataLinkType), 0, 4);
        }
Esempio n. 4
0
        public TSharkBlock(TSharkProcess <TDecodedFrame> tsharkProcess, DataLinkType datalinkType = DataLinkType.Ethernet)
        {
            var m_pipename = $"ndx.tshark_{new Random().Next(Int32.MaxValue)}";

            m_wsender = new TSharkSender(m_pipename, datalinkType);

            m_inputBlock = new ActionBlock <RawCapture>(SendFrame);
            m_inputBlock.Completion.ContinueWith((t) => m_wsender.Close());

            m_outputBlock = new BufferBlock <TDecodedFrame>();

            // create and initialize TSHARK:
            m_tshark                = tsharkProcess;
            m_tshark.PipeName       = m_pipename;
            m_tshark.PacketDecoded += PacketDecoded;
            m_tshark.Start();
            m_tshark.Completion.ContinueWith((t) => m_outputBlock.Complete());

            m_wsender.Connected.Wait();
        }
Esempio n. 5
0
        // DLT_USER0 = 147
        public void WriteHeader(DataLinkType network, uint snaplen)
        {
            if (_bw == null)
                return;

            try
            {
                _bw.Write((UInt32)0xa1b2c3d4);   // MAGIC
                _bw.Write((UInt16)2);            // Ver major
                _bw.Write((UInt16)4);            // Ver minot
                _bw.Write((UInt32)0);            // ZONE
                _bw.Write((UInt32)0);            // significant figures
                _bw.Write((UInt32)snaplen);
                _bw.Write((UInt32)network);
            }
            catch
            {
                _bw.Dispose();
                _bw = null;
            }
        }
Esempio n. 6
0
        public void WriteHeader(DataLinkType network, uint snaplen) // DLT_USER0 = 147
        {
            if (_bw == null)
            {
                return;
            }

            try
            {
                _bw.Write((UInt32)0xa1b2c3d4);   // MAGIC
                _bw.Write((UInt16)2);            // Ver major
                _bw.Write((UInt16)4);            // Ver minot
                _bw.Write((UInt32)0);            // ZONE
                _bw.Write((UInt32)0);            // significant figures
                _bw.Write((UInt32)snaplen);
                _bw.Write((UInt32)network);
            }
            catch
            {
                _bw.Dispose();
                _bw = null;
            }
        }
Esempio n. 7
0
 public PcapFileWriter(string filename, DataLinkType dataLinkType)
     : this(filename, dataLinkType, System.IO.FileMode.Create, 262144)
 {
     //nothing more needed
 }
Esempio n. 8
0
        private DataCfg(string suffix)
        {
            string linkType = WRSetting.Set().getSettings(Const.LinkType + suffix);

            if ("1".Equals(linkType))
            {
                dlt = DataLinkType.dltODBC;
            }
            else if ("2".Equals(linkType))
            {
                dlt = DataLinkType.dltSocket;
            }
            else if ("3".Equals(linkType))
            {
                dlt = DataLinkType.dltWeb;
            }
            else
            {
                dlt = DataLinkType.dltNone;
            }

            switch (dlt)
            {
            case DataLinkType.dltODBC:
                string dbtype   = WRSetting.Set().getSettings(Const.ODBC + suffix + "/" + Const.DBType).ToLower();
                string ip       = WRSetting.Set().getSettings(Const.ODBC + suffix + "/" + Const.DBIP);
                string port     = WRSetting.Set().getSettings(Const.ODBC + suffix + "/" + Const.DBPort);
                string dbase    = WRSetting.Set().getSettings(Const.ODBC + suffix + "/" + Const.DBase);
                string user     = WRSetting.Set().getSettings(Const.ODBC + suffix + "/" + Const.DBUserName);
                string password = WRSetting.Set().getSettings(Const.ODBC + suffix + "/" + Const.DBUserPass);
                string ver      = WRSetting.Set().getSettings(Const.ODBC + suffix + "/" + Const.DBVer);
                string dbfile   = WRSetting.Set().getSettings(Const.ODBC + suffix + "/" + Const.DBFile).ToLower();
                password = CryptUtil.DecryptDES(password);       //密码采用DES加密算法存储在配置文件中,所以此处应该解密
                if (Const.oracle.Equals(dbtype))
                {
                    dbt = DataBaseType.dbtOracle;
                }
                else if (Const.mssql.Equals(dbtype))
                {
                    dbt = DataBaseType.dbtMSSQL;
                }
                else if (Const.mysql.Equals(dbtype))
                {
                    dbt = DataBaseType.dbtMySQL;
                }
                else if (Const.access.Equals(dbtype))
                {
                    dbt = DataBaseType.dbtAccess;
                }
                else if (Const.sqlite.Equals(dbtype))
                {
                    dbt = DataBaseType.dbtSQLite;
                }
                else if (Const.dbase.Equals(dbtype))
                {
                    dbt = DataBaseType.dbtDBase;
                }
                else
                {
                    dbt = DataBaseType.dbtNone;
                }

                dbService = new DataODBCService();

                switch (dbt)
                {
                case DataBaseType.dbtOracle:
                    (dbService as DataODBCService).db = new Oracle(ip, port, dbase, user, password, ver);
                    break;

                case DataBaseType.dbtMSSQL:
                    (dbService as DataODBCService).db = new SqlServer(ip, port, dbase, user, password, ver);
                    break;

                case DataBaseType.dbtMySQL:
                    (dbService as DataODBCService).db = new MySql(ip, port, dbase, user, password, ver);
                    break;

                case DataBaseType.dbtAccess:
                    (dbService as DataODBCService).db = new Access(dbfile, password);
                    break;

                case DataBaseType.dbtSQLite:
                    (dbService as DataODBCService).db = new SQLite(dbfile, password);
                    break;

                case DataBaseType.dbtDBase:
                    (dbService as DataODBCService).db = new DBase(dbfile, password);
                    break;

                default:
                    throw new Exception("没有设置数据库类型!");
                }
                break;

            case DataLinkType.dltSocket:
                string socketIP     = WRSetting.Set().getSettings(Const.Socket + suffix + "/" + Const.SocketIP).ToLower();
                string socketPort   = WRSetting.Set().getSettings(Const.Socket + suffix + "/" + Const.SocketPort).ToLower();
                string socketServer = WRSetting.Set().getSettings(Const.Socket + suffix + "/" + Const.SocketServer).ToLower();
                break;

            case DataLinkType.dltWeb:
                string url = WRSetting.Set().getSettings(Const.WebService + suffix + "/" + Const.WSURL).ToLower();
                break;

            default:
                throw new Exception("没有设置连接数据库方式!");
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Decodes each <see cref="RawCapture"/> of a sequence into a <typeparamref name="TRecord"/> object.
        /// </summary>
        /// <typeparam name="TRecord"></typeparam>
        /// <param name="frames">A sequence of values to invoke a transform function on.</param>
        /// <param name="tsharkProcess">A decoder process to apply to each element.</param>
        /// <param name="datalinkType">The link layer type used in decoding operation. Default is <see cref="DataLinkType.Ethernet"/>.</param>
        /// <returns>
        /// An IEnumerable<PacketFields> whose elements are the result of invoking the decode function on each element of source.
        /// </returns>
        /// <remarks>
        /// This method is implemented by using deferred execution. The immediate return value is an object that stores all the information
        /// that is required to perform the action. The query represented by this method is not executed until the object is enumerated
        /// either by calling its GetEnumerator method directly or by using foreach.
        /// </remarks>
        public static IEnumerable <TRecord> Decode <TRecord>(this IEnumerable <RawCapture> frames, TSharkProcess <TRecord> tsharkProcess, DataLinkType datalinkType = DataLinkType.Ethernet)
        {
            var pipename = $"ndx.tshark_{new Random().Next(Int32.MaxValue)}";
            var wsender  = new TSharkSender(pipename, datalinkType);

            tsharkProcess.PipeName = pipename;

            var decodedPackets = new BlockingCollection <TRecord>();

            void PacketDecoded(object sender, TRecord packet)
            {
                decodedPackets.Add(packet);
            }

            tsharkProcess.PacketDecoded += PacketDecoded;
            tsharkProcess.Start();
            if (!wsender.Connected.Wait(5000))
            {
                throw new InvalidOperationException("Cannot connect to TShark process.");
            }

            var pumpTask = Task.Run(async() =>
            {
                foreach (var frame in frames)
                {
                    await wsender.SendAsync(frame);
                }
                wsender.Close();
            });

            while (tsharkProcess.IsRunning || decodedPackets.Count > 0)
            {
                yield return(decodedPackets.Take());
            }
        }