示例#1
0
        private byte[] DumpMifareStandard(PcscSdk.MifareStandard.AccessHandler mifare)
        {
            byte[] madData = new byte[32];
            mifare.Read(1, PcscSdk.MifareStandard.GeneralAuthenticate.GeneralAuthenticateKeyType.MifareKeyA, 0).CopyTo(madData, 0);
            mifare.Read(2, PcscSdk.MifareStandard.GeneralAuthenticate.GeneralAuthenticateKeyType.MifareKeyA, 0).CopyTo(madData, 16);

            byte crc     = madData[0];
            byte calcCrc = PcscSdk.MifareStandard.CRC8.Calc(madData.Skip(1).ToArray());

            if (crc != calcCrc)
            {
                throw new NfcHandlerException("MAD CRC mismatch. 0x" + BitConverter.ToString(new[] { crc }) + " != 0x" + BitConverter.ToString(new[] { calcCrc }));
            }

            StatusMessage?.Invoke("CRC 0x" + BitConverter.ToString(new[] { crc }) + " OK");

            using (MemoryStream mem = new MemoryStream())
            {
                for (int sec = 1; sec < 16; sec++)
                {
                    if (madData[sec * 2] != 0x03 || madData[sec * 2 + 1] != 0xE1)
                    {
                        continue;
                    }
                    for (int block = sec * 4; block < sec * 4 + 3; block++)
                    {
                        mem.Write(mifare.Read((ushort)block, PcscSdk.MifareStandard.GeneralAuthenticate.GeneralAuthenticateKeyType.MifareKeyA, 1), 0, 16);
                    }
                }

                return(mem.ToArray());
            }
        }
示例#2
0
        public UCCefSharpX64(string url)
        {
            InitializeComponent();

            var setting = new CefSettings();

            // 设置语言
            setting.Locale = "zh-CN";
            //cef设置userAgent
            setting.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36";
            //配置浏览器路径
            setting.BrowserSubprocessPath = $"{CefSharpHelp.PathX64}\\CefSharp.BrowserSubprocess.exe";
            Cef.Initialize(setting, true, true);
            // Add it to the form and fill it to the form window.
            chromeBrowser = new ChromiumWebBrowser(url);
            this.Controls.Add(chromeBrowser);
            chromeBrowser.Dock                         = DockStyle.Fill;
            chromeBrowser.AddressChanged              += (sender, e) => { AddressChanged?.Invoke(sender, e.Address); };
            chromeBrowser.StatusMessage               += (sender, e) => { StatusMessage?.Invoke(sender, e.Value); };
            chromeBrowser.ConsoleMessage              += (sender, e) => { ConsoleMessage?.Invoke(sender, new ICefSharp.Model.ConsoleMessageEventArgs(e.Message, e.Source, e.Line)); };
            chromeBrowser.LoadingStateChanged         += (sender, e) => { LoadingStateChanged?.Invoke(sender, new ICefSharp.Model.LoadingStateChangedEventArgs(e.CanGoForward, e.CanGoBack, e.CanReload, e.IsLoading)); };
            chromeBrowser.LoadError                   += (sender, e) => { LoadError?.Invoke(sender, new ICefSharp.Model.LoadErrorEventArgs((int)e.ErrorCode, e.FailedUrl, e.ErrorText)); };
            chromeBrowser.IsBrowserInitializedChanged += (sender, e) => { IsBrowserInitializedChanged?.Invoke(sender, e.IsBrowserInitialized); };
            chromeBrowser.TitleChanged                += (sender, e) => { TitleChanged?.Invoke(sender, e.Title); };
        }
示例#3
0
        private void WriteNdefToMifareStandard(PcscSdk.MifareStandard.AccessHandler mifare, byte[] ndefData)
        {
            InitializeMifareStandard(mifare);

            const int capacity = 15 * 3 * 16;

            byte[] wrappedData = GenerateTLVData(ndefData);

            if (wrappedData.Length > capacity)
            {
                throw new NfcHandlerException("Data size of " + wrappedData.Length + " bytes exceeds capacity of " + capacity + " bytes!");
            }

            int data_length = wrappedData.Length;

            Array.Resize(ref wrappedData, (data_length / 16) * 16 + 16);

            byte writeBlock = 3;

            for (byte pos = 0; pos < wrappedData.Length; pos += 16)
            {
                if (++writeBlock % 4 == 3)
                {
                    writeBlock++;
                }
                mifare.Write(writeBlock, wrappedData.Skip(pos).Take(16).ToArray(), GeneralAuthenticate.GeneralAuthenticateKeyType.MifareKeyA, 1);
            }

            StatusMessage?.Invoke("Written " + data_length + " bytes of data. Ndef message length is " + ndefData.Length + " bytes.");
        }
示例#4
0
        private void HandleSmartCard(String readerName)
        {
            using (ISCardContext ctx = contextFactory.Establish(SCardScope.System))
                using (ICardReader reader = ctx.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any))
                {
                    StatusMessage?.Invoke("Connected to tag");

                    IccDetection cardIdent = new IccDetection(reader);
                    cardIdent.DetectCardType();

                    StatusMessage?.Invoke("Device class: " + cardIdent.PcscDeviceClass.ToString());
                    StatusMessage?.Invoke("Card name: " + cardIdent.PcscCardName.ToString());
                    StatusMessage?.Invoke("ATR: " + BitConverter.ToString(cardIdent.Atr));

                    if (cardIdent.PcscDeviceClass == DeviceClass.StorageClass &&
                        (cardIdent.PcscCardName == CardName.MifareUltralight ||
                         cardIdent.PcscCardName == CardName.MifareUltralightC ||
                         cardIdent.PcscCardName == CardName.MifareUltralightEV1))
                    {
                        HandleMifareUL(reader);
                    }
                    else if (cardIdent.PcscDeviceClass == DeviceClass.StorageClass &&
                             (cardIdent.PcscCardName == CardName.MifareStandard1K ||
                              cardIdent.PcscCardName == CardName.MifareStandard4K))
                    {
                        HandleMifareStandard(reader);
                    }
                    else
                    {
                        HandleHCEClient(reader);
                    }
                }
        }
示例#5
0
        private byte InitAndGetGPMifareStandard(PcscSdk.MifareStandard.AccessHandler mifare)
        {
            mifare.LoadKey(new byte[] { 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5 }, 0);
            StatusMessage?.Invoke("Loaded public MAD key in slot 0.");

            mifare.LoadKey(new byte[] { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 }, 1);
            StatusMessage?.Invoke("Loaded public NDEF key in slot 1.");

            byte[] infoData;
            try
            {
                infoData = mifare.Read(3, GeneralAuthenticate.GeneralAuthenticateKeyType.MifareKeyA, 0);
            }
            catch (Exception)
            {
                StatusMessage?.Invoke("Failed reading with default key.");

                mifare.LoadKey(PcscSdk.MifareStandard.DefaultKeys.FactoryDefault, 0);
                StatusMessage?.Invoke("Loaded factory default key in slot 0.");

                infoData = mifare.Read(3, GeneralAuthenticate.GeneralAuthenticateKeyType.MifareKeyA, 0);
                StatusMessage?.Invoke("Card uses factory default key!");
            }
            byte gpByte = infoData[9];

            StatusMessage?.Invoke("General purpose byte: " + BitConverter.ToString(new[] { gpByte }));

            return(gpByte);
        }
示例#6
0
        private void RekordboxDoko()
        {
            while (running)
            {
                try
                {
                    RekordBox = Process.GetProcessesByName("rekordbox").FirstOrDefault();
                    if (RekordBox != null)
                    {
                        handle         = OpenProcess(ProcessAccessFlags.VMRead, false, RekordBox.Id);
                        RekordboxFound = true;

                        // Invoke needed as this is being run in a separate thread.
                        StatusMessage.Invoke((Action)(() =>
                        {
                            StatusMessage.Text = "Status: Rekordbox process found. Reading.";
                        }));

                        break;
                    }

                    StatusMessage.Invoke((Action)(() =>
                    {
                        StatusMessage.Text = "Status: Rekordbox process was not found.";
                    }));

                    Thread.Sleep(1000);
                }
                catch (ThreadAbortException)
                {
                    break;
                }
            }
        }
示例#7
0
        private void HandleMifareUL(ICardReader reader)
        {
            var mifare = new PcscSdk.MifareUltralight.AccessHandler(reader);

            StatusMessage?.Invoke("Handling as Mifare Ultralight");

            byte[] uid = mifare.GetUid();
            StatusMessage?.Invoke("UID: " + BitConverter.ToString(uid));
            Array.Resize(ref uid, uid.Length + 1);
            uid[uid.Length - 1] = 0xAA;
            NewTagUid?.Invoke(uid);

            byte[] infoData = mifare.Read(0);
            StatusMessage?.Invoke("CC: " + BitConverter.ToString(infoData.Skip(12).ToArray()));

            try
            {
                byte[] versionData = mifare.GetVersion();
                StatusMessage?.Invoke("Mifare Version: " + BitConverter.ToString(versionData));

                int capacity    = versionData[6] >> 1;
                int capacityMax = capacity;
                if ((versionData[6] & 1) == 1)
                {
                    capacityMax += 1;
                }
                capacity    = (int)Math.Pow(2, capacity);
                capacityMax = (int)Math.Pow(2, capacityMax);
                StatusMessage?.Invoke("Capacity is between " + capacity + " and " + capacityMax + " bytes");
            }
            catch (ApduFailedException e)
            {
                StatusMessage?.Invoke("Failed getting Mifare Version: " + e.Message);
            }

            byte identMagic    = infoData[12];
            byte identVersion  = infoData[13];
            int  identCapacity = infoData[14] * 8;
            int  major         = identVersion >> 4;
            int  minor         = identVersion & 0x0F;

            if (identMagic != 0xE1 || identVersion < 0x10)
            {
                throw new NfcHandlerException("Tag format is unsupported");
            }

            StatusMessage?.Invoke("Found Type 2 Tag version " + major + "." + minor + " with " + identCapacity + " bytes capacity.");

            if (ndefDataToWrite != null)
            {
                WriteNdefToMifareUL(mifare, ndefDataToWrite);
                ndefDataToWrite = null;
            }
            else
            {
                byte[] data = DumpMifareUL(mifare);
                ParseTLVData(data);
            }
        }
示例#8
0
        private void Monitor_CardRemoved(object sender, CardStatusEventArgs args)
        {
            if (blockCardEvents > 0)
            {
                return;
            }

            StatusMessage?.Invoke("Tag removed on " + args.ReaderName);

            CardRemoved?.Invoke(args.ReaderName);
        }
示例#9
0
        /// <summary>
        /// Raise the StatusMessage event.
        /// </summary>
        /// <param name="e">Event arguments (if null the event is cancelled).</param>
        protected virtual void OnStatusMessage(StatusMessageEventArgs e)
        {
            if (e == null)
            {
                return;
            }

            Debug.WriteLine(e.Status);

            StatusMessage?.Invoke(this, e);
        }
示例#10
0
        /// <summary>
        /// Raises the <see cref="StatusMessage"/> event and sends this data to the <see cref="Logger"/>.
        /// </summary>
        /// <param name="level">The <see cref="MessageLevel"/> to assign to this message</param>
        /// <param name="status">New status message.</param>
        /// <param name="eventName">A fixed string to classify this event; defaults to <c>null</c>.</param>
        /// <param name="flags"><see cref="MessageFlags"/> to use, if any; defaults to <see cref="MessageFlags.None"/>.</param>
        /// <remarks>
        /// <see pref="eventName"/> should be a constant string value associated with what type of message is being
        /// generated. In general, there should only be a few dozen distinct event names per class. Exceeding this
        /// threshold will cause the EventName to be replaced with a general warning that a usage issue has occurred.
        /// </remarks>
        protected virtual void OnStatusMessage(MessageLevel level, string status, string eventName = null, MessageFlags flags = MessageFlags.None)
        {
            try
            {
                Log.Publish(level, flags, eventName ?? "DataGapRecovery", status);

                using (Logger.SuppressLogMessages())
                    StatusMessage?.Invoke(this, new EventArgs <string>(AdapterBase.GetStatusWithMessageLevelPrefix(status, level)));
            }
            catch (Exception ex)
            {
                // We protect our code from consumer thrown exceptions
                OnProcessException(MessageLevel.Info, new InvalidOperationException($"Exception in consumer handler for StatusMessage event: {ex.Message}", ex), "ConsumerEventException");
            }
        }
示例#11
0
        private void Monitor_CardInserted(object sender, CardStatusEventArgs args)
        {
            if (blockCardEvents > 0)
            {
                return;
            }

            CardAdded?.Invoke(args.ReaderName);
            StatusMessage?.Invoke("Tag detected on " + args.ReaderName);

            try
            {
                HandleSmartCard(args.ReaderName);
            }
            catch (Exception e)
            {
                ErrorMessage?.Invoke("Error handling tag: " + e.Message);
            }

            CardHandlingDone?.Invoke(args.ReaderName);
        }
示例#12
0
        private void HandleMifareStandard(ICardReader reader)
        {
            var mifare = new PcscSdk.MifareStandard.AccessHandler(reader);

            StatusMessage?.Invoke("Handling as Mifare Standard 1K");

            byte[] uid = mifare.GetUid();
            StatusMessage?.Invoke("UID: " + BitConverter.ToString(uid));
            Array.Resize(ref uid, uid.Length + 1);
            uid[uid.Length - 1] = 0xBB;
            NewTagUid?.Invoke(uid);

            byte gpByte = InitAndGetGPMifareStandard(mifare);

            bool usesMad    = (gpByte & 0x80) != 0;
            bool multiApp   = (gpByte & 0x40) != 0;
            int  madVersion = gpByte & 0x03;

            StatusMessage?.Invoke("Uses MAD: " + usesMad + "; Multi App: " + multiApp + "; Version: " + madVersion);

            if (ndefDataToWrite != null)
            {
                WriteNdefToMifareStandard(mifare, ndefDataToWrite);
                ndefDataToWrite = null;
            }
            else
            {
                if (!usesMad)
                {
                    throw new NfcHandlerException("No MAD in use");
                }
                if (madVersion != 1)
                {
                    throw new NfcHandlerException("Unsupported MAD version: " + madVersion + " (Only version 1 is supported)");
                }

                byte[] data = DumpMifareStandard(mifare);
                ParseTLVData(data);
            }
        }
示例#13
0
        private void WriteNdefToMifareUL(PcscSdk.MifareUltralight.AccessHandler mifare, byte[] ndefData)
        {
            byte[] infoData = mifare.Read(3);
            int    capacity = infoData[2] * 8;

            byte[] wrappedData = GenerateTLVData(ndefData);

            if (wrappedData.Length > capacity)
            {
                throw new NfcHandlerException("Data size of " + wrappedData.Length + " bytes exceeds capacity of " + capacity + " bytes!");
            }

            int data_length = wrappedData.Length;

            Array.Resize(ref wrappedData, (data_length / 4) * 4 + 4);

            for (byte pos = 4; (pos - 4) * 4 < wrappedData.Length; pos++)
            {
                mifare.Write(pos, wrappedData.Skip((pos - 4) * 4).Take(4).ToArray());
            }

            StatusMessage?.Invoke("Written " + data_length + " bytes of data. Ndef message length is " + ndefData.Length + " bytes.");
        }
示例#14
0
        private void TryTurnOffBeep(string readerName)
        {
            if (!readerName.Contains("ACR"))
            {
                return;
            }

            try
            {
                using (ISCardContext ctx = contextFactory.Establish(SCardScope.System))
                    using (ICardReader reader = ctx.ConnectReader(readerName, SCardShareMode.Direct, SCardProtocol.Unset))
                    {
                        var apdu = new Iso7816.ApduCommand(0xFF, 0x00, 0x52, 0x00, null, 0x00);
                        var res  = reader.Control(apdu);
                        if (res.Succeeded)
                        {
                            StatusMessage?.Invoke("Turned off buzzer on " + reader.Name);
                        }
                    }
            }
            catch (Exception)
            {
            }
        }
示例#15
0
        /// <summary>
        /// Receiving file on specified ip and port. It will start listening for a connection
        /// and will stop listening after the transfer.
        /// </summary>
        /// <param name="ip">Local ip address to listen on</param>
        /// <param name="port">Local port to listen on</param>
        /// <param name="destinationFolder">Folder where the recieved file is going to be saved to</param>
        public void ReceiveFile(IPAddress ip, int port, string destinationFolder)
        {
            // lock to prevent bad things in case buffer size is changed
            lock (_lockReceiving)
            {
                try
                {
                    // Reset progress and update status
                    _progress = 0;
                    ProgressPercent?.Invoke(this, _progress);

                    // Listen for incoming coonnections
                    var listener = new TcpListener(ip, port);
                    listener.Start();

                    // Update status
                    StatusMessage?.Invoke(this, $"Listening on {ip}:{port}");

                    try
                    {
                        while (true)
                        {
                            using (var client = listener.AcceptTcpClient())
                                using (var stream = client.GetStream())
                                {
                                    client.ReceiveBufferSize = BufferSize;
                                    StatusMessage?.Invoke(this, "Receiving file...");

                                    byte[] buffer = new byte[BufferSize];

                                    // Get file info from first packet
                                    int bytesRead = stream.Read(buffer, 0, buffer.Length);
                                    // Header: 4 bytes for file length (int) + 4 bytes for file name length (int) + fileName + 20 bytes checksum
                                    int headerOffset = 0;
                                    int fileLen      = BitConverter.ToInt32(buffer, headerOffset);
                                    headerOffset += sizeof(int);
                                    int fileNameLen = BitConverter.ToInt32(buffer, headerOffset);
                                    headerOffset += sizeof(int);
                                    string fileName = Encoding.ASCII.GetString(buffer, headerOffset, fileNameLen);
                                    headerOffset += fileNameLen;
                                    byte[] checksumByte = new byte[20];
                                    Array.Copy(buffer, headerOffset, checksumByte, 0, checksumByte.Length);
                                    headerOffset += checksumByte.Length;
                                    bool checksumAvailable = !checksumByte.All(singleByte => singleByte == 0);

                                    // Update status and progress and calculate progress percent increment
                                    StatusMessage?.Invoke(this, $"Receiving {fileName} on {ip}:{port} from {client.Client.RemoteEndPoint}");
                                    double progressBarIncrement    = 100.0 / (Convert.ToDouble(fileLen) / BufferSize);
                                    int    progressSingleIncrement = 0;
                                    _progress += progressBarIncrement;
                                    ProgressPercent?.Invoke(this, _progress);

                                    // Create file to safe incoming data to
                                    using (var output = File.Create(Path.Combine(destinationFolder, fileName)))
                                    {
                                        output.Write(buffer, headerOffset, bytesRead - headerOffset);
                                        if (bytesRead >= buffer.Length)
                                        {
                                            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                                            {
                                                output.Write(buffer, 0, bytesRead);

                                                // Update progress only every percent
                                                _progress += progressBarIncrement;
                                                if (!(_progress > progressSingleIncrement + 1))
                                                {
                                                    continue;
                                                }
                                                progressSingleIncrement = Convert.ToInt32(_progress);
                                                ProgressPercent?.Invoke(this, progressSingleIncrement);
                                            }
                                        }
                                    }

                                    StatusMessage?.Invoke(this, "File received");

                                    if (checksumAvailable)
                                    {
                                        StatusMessage?.Invoke(this, "File received - Calculating checksum...");
                                        using (var fileStream = new BufferedStream(File.OpenRead(Path.Combine(destinationFolder, fileName)), 32768))
                                        {
                                            SHA1Managed sha = new SHA1Managed();
                                            byte[]      checksumByteCalc = sha.ComputeHash(fileStream);
                                            string      checksumCalc     = BitConverter.ToString(checksumByteCalc).Replace("-", String.Empty).ToLower();
                                            string      checksumSent     = BitConverter.ToString(checksumByte).Replace("-", String.Empty).ToLower();
                                            Debug.WriteLine($"sent: {checksumSent} | calc: {checksumCalc}");

                                            if (!Enumerable.SequenceEqual(checksumByte, checksumByteCalc))
                                            {
                                                ChecksumError?.Invoke(this, $"sent: {checksumSent} != calc: {checksumCalc}");
                                                StatusMessage?.Invoke(this, $"Checksum missmatch\nSent: {checksumSent}\nCalc: {checksumCalc}");
                                            }
                                            else
                                            {
                                                StatusMessage?.Invoke(this, $"Checksum match\nSent: {checksumSent}\nCalc: {checksumCalc}");
                                            }
                                        }
                                    }

                                    // Raise new file received event
                                    NewFileReceived?.Invoke(this, fileName);
                                    ProgressPercent?.Invoke(this, 100);
                                }

                            break;
                        }
                    }
                    finally
                    {
                        // Stop listening
                        listener.Stop();
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                    StatusMessage?.Invoke(this, ex.Message);
                }
                finally
                {
                    // Send cleanup event, e.g. usefull to enable buttens again
                    Cleanup?.Invoke(this, EventArgs.Empty);
                }
            }
        }
示例#16
0
 internal protected virtual void OnStatusMessage(StatusMessageEventArgs e)
 {
     StatusMessage?.Invoke(this, e);
 }
示例#17
0
 private void OnStatusMessage(string message)
 {
     StatusMessage?.Invoke(this, new EventArgs <string>(message));
 }
示例#18
0
 /// <summary>
 /// The on status message.
 /// </summary>
 /// <param name="eventArgs">
 /// The event args.
 /// </param>
 public void OnStatusMessage(StatusMessageEventArgs eventArgs)
 {
     StatusMessage?.Invoke(this, eventArgs);
 }
示例#19
0
 /// <summary>
 /// Handles the <see cref="E:StatusMessage" /> event.
 /// </summary>
 /// <param name="args">The <see cref="StatusMessageEventArgs"/> instance containing the event data.</param>
 void IWebBrowserInternal.OnStatusMessage(StatusMessageEventArgs args)
 {
     StatusMessage?.Invoke(this, args);
 }
示例#20
0
        private void HandleHCEClient(ICardReader reader)
        {
            StatusMessage?.Invoke("Attemtping to talk to Android HCE device.");

            var selectCmd = new Iso7816.SelectCommand(FLAGCARRIER_HCE_AID, 0);
            var res       = reader.Transceive(selectCmd);

            if (res.SW == 0x6a82)
            {
                ErrorMessage?.Invoke("Device has no idea who we are.");
                return;
            }
            else if (!res.Succeeded)
            {
                ErrorMessage?.Invoke("Failed communicating with device: " + res.ToString());
                return;
            }

            StatusMessage?.Invoke("Connected to FlagCarrier HCE device!");

            byte[] challengeToken = new byte[32];
            random.NextBytes(challengeToken, 0, challengeToken.Length);

            var updateCmd = new Iso7816.UpdateBinaryCommand(challengeToken);

            res = reader.Transceive(updateCmd);

            if (res.SW == 0x6A82)
            {
                ErrorMessage?.Invoke("HCE Device does not have any data for us.");
                return;
            }

            if (!res.Succeeded)
            {
                ErrorMessage?.Invoke("Failed sending challenge token: " + res.ToString());
                return;
            }

            StatusMessage?.Invoke("Sent challenge token.");

            byte[]    ndefData = new byte[0];
            const int len      = 250;
            int       offset   = 0;

            do
            {
                var readCmd = new Iso7816.ReadBinaryCommand(len, offset);
                res = reader.Transceive(readCmd);

                if (!res.Succeeded)
                {
                    ErrorMessage?.Invoke("Failed reading data at " + offset + ": " + res.ToString());
                    return;
                }

                if (res.ResponseData == null || res.ResponseData.Length == 0)
                {
                    break;
                }

                Array.Resize(ref ndefData, ndefData.Length + res.ResponseData.Length);
                res.ResponseData.CopyTo(ndefData, offset);
                offset += res.ResponseData.Length;
            } while (res.ResponseData.Length == len);

            StatusMessage?.Invoke("Read " + ndefData.Length + " bytes of ndef data from device.");

            NdefMessage msg = NdefMessage.FromByteArray(ndefData);

            NewTagUid?.Invoke(challengeToken);
            ReceiveNdefMessage?.Invoke(msg);

            var eraseCmd = new Iso7816.EraseBinaryCommand();

            res = reader.Transceive(eraseCmd);

            if (!res.Succeeded)
            {
                ErrorMessage?.Invoke("Failed confirming transaction to device.");
            }
        }
示例#21
0
 public void RaiseStatusMessage(string message)
 {
     StatusMessage?.Invoke(this, new StringEventArgs(message));
 }
 private static void OnStatusMessage(string status)
 {
     StatusMessage?.Invoke(typeof(GrafanaAuthProxyController), new EventArgs <string>(status));
 }
示例#23
0
        /// <summary>
        /// Sends a file with header composed of file size and file name
        /// </summary>
        /// <param name="ip">Receiving end ip address</param>
        /// <param name="port">Receiving end port</param>
        /// <param name="filePath">Full path to file</param>
        public void SendFile(IPAddress ip, int port, string filePath, bool checksum = false)
        {
            // lock to prevent bad things in case buffer size is changed
            lock (_lockSending)
            {
                try
                {
                    // Reset progress and update status
                    _progress = 0;
                    ProgressPercent?.Invoke(this, _progress);
                    StatusMessage?.Invoke(this, "Connecting...");

                    // Open socket
                    using (Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                    {
                        // Get file info
                        // Header: 4 bytes for file length (int) + 4 bytes for file name length (int) + fileName + 20 bytes checksum
                        FileInfo fi           = new FileInfo(filePath);
                        byte[]   fileLen      = BitConverter.GetBytes((int)fi.Length);
                        byte[]   fileNameByte = Encoding.ASCII.GetBytes(Path.GetFileName(filePath));
                        byte[]   fileNameLen  = BitConverter.GetBytes(fileNameByte.Length);
                        byte[]   checksumByte = new byte[20]; // SHA1 checksum is byte[20]
                        byte[]   header       = new byte[fileLen.Length + fileNameLen.Length + fileNameByte.Length + checksumByte.Length];
                        if (checksum)
                        {
                            using (var stream = new BufferedStream(File.OpenRead(filePath), 32768))
                            {
                                SHA1Managed sha = new SHA1Managed();
                                checksumByte = sha.ComputeHash(stream);
                                Debug.WriteLine(BitConverter.ToString(checksumByte).Replace("-", String.Empty).ToLower());
                            }
                        }
                        // Copy data into send byte array
                        int headerOffset = 0;
                        fileLen.CopyTo(header, headerOffset);
                        headerOffset += fileLen.Length;
                        fileNameLen.CopyTo(header, headerOffset);
                        headerOffset += fileNameLen.Length;
                        fileNameByte.CopyTo(header, headerOffset);
                        headerOffset += fileNameByte.Length;
                        checksumByte.CopyTo(header, headerOffset);

                        // Connect to end point
                        IPEndPoint ipEndPoint = new IPEndPoint(ip, port);
                        soc.SendBufferSize = BufferSize;
                        soc.Connect(ipEndPoint);

                        // Update status and calculate progress percent increment
                        StatusMessage?.Invoke(this, $"Sending {Path.GetFileName(filePath)} to {ip}:{port} from {soc.LocalEndPoint}");
                        double progressBarIncrement    = 100.0 / (Convert.ToDouble(fi.Length) / BufferSize);
                        int    progressSingleIncrement = 0;

                        using (FileStream fsSource = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                        {
                            int numBytesToRead = (int)fsSource.Length;

                            // Initial packet
                            var firstPacket = (int)fi.Length >= BufferSize ? new byte[BufferSize] : new byte[header.Length + (int)fi.Length];
                            header.CopyTo(firstPacket, 0);
                            // Fill rest of first packet up with file data
                            int transmitOffset = fsSource.Read(firstPacket, header.Length, firstPacket.Length - header.Length);
                            // Send initial packet
                            soc.Send(firstPacket, firstPacket.Length, SocketFlags.None);
                            _progress += progressBarIncrement;
                            // Transmit data in buffer size chunks
                            if (transmitOffset >= BufferSize - header.Length)
                            {
                                byte[] buffer = new byte[BufferSize];
                                while (true)
                                {
                                    // Calculate remaining bytes to send
                                    int sendsize = numBytesToRead - transmitOffset;
                                    // Send buffer sized chunk if enough data is left, otherwise send remaining bytes
                                    if (sendsize > BufferSize)
                                    {
                                        sendsize = BufferSize;
                                    }
                                    fsSource.Read(buffer, 0, sendsize);
                                    soc.Send(buffer, sendsize, SocketFlags.None);
                                    transmitOffset += sendsize;

                                    // Update progress only every percent
                                    _progress += progressBarIncrement;
                                    if (_progress > progressSingleIncrement + 1)
                                    {
                                        progressSingleIncrement = Convert.ToInt32(_progress);
                                        ProgressPercent?.Invoke(this, progressSingleIncrement);
                                    }

                                    if (transmitOffset >= numBytesToRead)
                                    {
                                        break;
                                    }
                                }
                            }
                        }

                        // Closing socket
                        soc.Shutdown(SocketShutdown.Both);
                        soc.Close();
                        StatusMessage?.Invoke(this, "File sent");
                        ProgressPercent?.Invoke(this, 100);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    StatusMessage?.Invoke(this, ex.Message);
                }
                finally
                {
                    // Send cleanup event, e.g. usefull to enable buttens again
                    Cleanup?.Invoke(this, EventArgs.Empty);
                }
            }
        }
示例#24
0
 private void OnStatusMessage(string message)
 {
     StatusMessage?.Invoke(this, message);
 }
 protected virtual void OnStatusMessage(string status)
 {
     StatusMessage?.Invoke(this, status);
 }
示例#26
0
 /// <summary>
 /// Handles the <see cref="E:StatusMessage" /> event.
 /// </summary>
 /// <param name="args">The <see cref="StatusMessageEventArgs"/> instance containing the event data.</param>
 internal void OnStatusMessage(StatusMessageEventArgs args)
 {
     StatusMessage?.Invoke(this, args);
 }
示例#27
0
 void UpdateStatusMessage(string status)
 {
     StatusMessage?.Invoke(status);
 }
    public void OnMessageReception(TCPConnection connection, string channel, List <byte> data)
    {
        switch (channel)
        {
        case "status": {
            byte  battery = data.ReadByte();
            short fps     = data.ReadShort();
            byte  temp    = data.ReadByte();
            status.Invoke(connection, battery, fps, temp);
        }
        break;

        case "guide-lock":
            guideLock.Invoke(connection);
            break;

        case "guide-unlock":
            guideUnlock.Invoke(connection);
            break;

        case "autopair":
            autopair.Invoke(connection);
            break;

        case "guide-pair":
            guidePair.Invoke(connection);
            break;

        case "guide-unpair":
            guideUnpair.Invoke(connection);
            break;

        case "pair-confirm":
            string pairedId = data.ReadString();
            string lockedId = data.ReadString();
            pairConfirm.Invoke(connection, pairedId, lockedId);
            break;

        case "logs-query":
            logsQuery.Invoke(connection);
            break;

        case "logs": {
            string log = data.ReadString();
            logs.Invoke(connection, log);
        }
        break;

        case "has-video": {
            string videoName = data.ReadString();
            hasVideo.Invoke(connection, videoName);
        }
        break;

        case "has-video-response": {
            string videoName = data.ReadString();
            hasVideoResponse.Invoke(connection, videoName);
        }
        break;

        case "is-empty":
            isEmpty.Invoke(connection);
            break;

        case "load-video": {
            string videoName = data.ReadString();
            string mode      = data.ReadString();
            loadVideo.Invoke(connection, videoName, mode);
        }
        break;

        case "load-video-response": {
            bool   ok           = data.ReadBool();
            string errorMessage = data.ReadString();
            loadVideoResponse.Invoke(connection, ok, errorMessage);
        }
        break;

        case "play-video": {
            DateTime stamp    = data.ReadTimestamp();
            float    syncTime = data.ReadFloat();
            Vector3  settings = data.ReadVector3();
            playVideo.Invoke(connection, stamp, syncTime, settings);
        }
        break;

        case "pause-video": {
            DateTime stamp = data.ReadTimestamp();
            double   time  = data.ReadDouble();
            bool     pause = data.ReadBool();
            pauseVideo.Invoke(connection, stamp, time, pause);
        }
        break;

        case "stop-video":
            stopVideo.Invoke(connection);
            break;

        case "sync": {
            DateTime stamp = data.ReadTimestamp();
            double   time  = data.ReadDouble();
            sync.Invoke(connection, stamp, time);
        }
        break;

        case "calibrate":
            calibrate.Invoke(connection);
            break;

        case "start-choice": {
            string question = data.ReadString();
            string choice1  = data.ReadString();
            string choice2  = data.ReadString();
            startChoice.Invoke(connection, question, choice1, choice2);
        }
        break;

        case "select-option": {
            byte option = data.ReadByte();
            selectOption.Invoke(connection, option);
        }
        break;

        case "reorient": {
            Vector3 angles = data.ReadVector3();
            reorient.Invoke(connection, angles);
        }
        break;

        case "autocalibration": {
            byte command = data.ReadByte();
            autocalibration.Invoke(connection, command);
        }
        break;

        case "autocalibration-result": {
            byte  command = data.ReadByte();
            float drift   = data.ReadFloat();
            autocalibrationResult.Invoke(connection, command, drift);
        }
        break;

        case "goto": {
            double time = data.ReadDouble();
            gotoTime.Invoke(connection, time);
        }
        break;

        default:
            if (!ignoreIncorrectChannels)
            {
                Haze.Logger.LogWarning("Received message on illegal channel: " + channel);
            }
            break;
        }
    }
示例#29
0
        private void InitializeMifareStandard(PcscSdk.MifareStandard.AccessHandler mifare)
        {
            byte[] mad1 = mifare.Read(1, PcscSdk.MifareStandard.GeneralAuthenticate.GeneralAuthenticateKeyType.MifareKeyA, 0);
            byte[] mad2 = mifare.Read(2, PcscSdk.MifareStandard.GeneralAuthenticate.GeneralAuthenticateKeyType.MifareKeyA, 0);

            // One of my readers only has two key slots, another one does not allow overwriting them, but has at least 3. So here we go...
            // Also, the Microsoft IFD emulation(?) reports 0x0000 in response, but it still seems to have worked.
            byte factoryKeySlot = 0;

            try
            {
                mifare.LoadKey(PcscSdk.MifareStandard.DefaultKeys.FactoryDefault, 0);
                StatusMessage?.Invoke("Loaded factory default key in slot 0.");
            }
            catch (ApduFailedException e)
            {
                if (e.Response.SW == 0x0000 && e.Response.ResponseData.Length == 0 && mifare.CardReader.Name.Contains("Microsoft IFD"))
                {
                    StatusMessage?.Invoke("Loaded factory default key in slot 0. (MS Quirk)");
                }
                else
                {
                    StatusMessage?.Invoke("Could not re-load to slot 0, trying slot 2: " + e.Message);
                    mifare.LoadKey(PcscSdk.MifareStandard.DefaultKeys.FactoryDefault, 2);
                    StatusMessage?.Invoke("Loaded factory default key in slot 2.");
                    factoryKeySlot = 2;
                }
            }

            if (!mad1.SequenceEqual(ndefMadData[1]) || !mad2.SequenceEqual(ndefMadData[2]))
            {
                StatusMessage?.Invoke("Writing NDEF MAD block.");

                for (byte block = 1; block < 4; block++)
                {
                    StatusMessage?.Invoke("Writing MAD block " + block);
                    try
                    {
                        mifare.Write(block, ndefMadData[block], GeneralAuthenticate.GeneralAuthenticateKeyType.MifareKeyA, factoryKeySlot);
                    }
                    catch (Exception)
                    {
                        mifare.Write(block, ndefMadData[block], GeneralAuthenticate.GeneralAuthenticateKeyType.PicoTagPassKeyB, factoryKeySlot);
                    }
                }
            }

            for (int sector = 1; sector < 16; sector++)
            {
                byte block = (byte)(sector * 4 + 3);
                try
                {
                    for (int i = 1; i < 4; i++)
                    {
                        var authRes = mifare.CardReader.Transceive(new PcscSdk.MifareStandard.GeneralAuthenticate((byte)(block - i), 1, GeneralAuthenticate.GeneralAuthenticateKeyType.MifareKeyA));
                        if (!authRes.Succeeded)
                        {
                            StatusMessage?.Invoke("NDEF read authentication failed, trying trailer rewrite.");
                            throw new Exception();
                        }
                    }

                    byte[] sectorIdent = mifare.Read(block, GeneralAuthenticate.GeneralAuthenticateKeyType.MifareKeyA, 1);
                    if (!sectorIdent.SequenceEqual(ndefComparator))
                    {
                        throw new Exception();
                    }
                }
                catch (Exception)
                {
                    StatusMessage?.Invoke("Writing NDEF trailer into sector " + sector);
                    try
                    {
                        mifare.Write(block, ndefSectorIdent, GeneralAuthenticate.GeneralAuthenticateKeyType.MifareKeyA, factoryKeySlot);
                    }
                    catch (Exception)
                    {
                        mifare.Write(block, ndefSectorIdent, GeneralAuthenticate.GeneralAuthenticateKeyType.PicoTagPassKeyB, factoryKeySlot);
                    }
                }
            }

            StatusMessage?.Invoke("Tag is NDEF formated");
        }
示例#30
0
        private void ParseTLVData(byte[] data)
        {
            using (MemoryStream stream = new MemoryStream(data))
                using (BinaryReader reader = new BinaryReader(stream))
                {
                    while (stream.Position < stream.Length)
                    {
                        byte   tag    = reader.ReadByte();
                        int    length = 0;
                        byte[] val    = null;
                        if (tag != 0x00 && tag != 0xFE)
                        {
                            length = reader.ReadByte();
                            if (length >= 0xFF)
                            {
                                byte[] lengthBytes = reader.ReadBytes(2);
                                if (BitConverter.IsLittleEndian)
                                {
                                    Array.Reverse(lengthBytes);
                                }
                                length = BitConverter.ToUInt16(lengthBytes, 0);
                            }
                            val = length > 0 ? reader.ReadBytes(length) : null;
                        }

                        switch (tag)
                        {
                        case 0x00:
                            StatusMessage?.Invoke("Skipping NULL TLV");
                            break;

                        case 0x01:
                            StatusMessage?.Invoke("Skipping Lock Control TLV");
                            break;

                        case 0x02:
                            StatusMessage?.Invoke("Skipping Memory Control TLV");
                            break;

                        case 0xFE:
                            StatusMessage?.Invoke("Reached terminator TLV");
                            return;

                        case 0x03:
                            if (val != null)
                            {
                                StatusMessage?.Invoke("Found NDEF TLV (" + length + " bytes)");
                                NdefMessage msg = NdefMessage.FromByteArray(val);
                                ReceiveNdefMessage?.Invoke(msg);
                            }
                            else
                            {
                                StatusMessage?.Invoke("Found empty NDEF TLV");
                            }
                            break;

                        default:
                            StatusMessage?.Invoke("Skipping unknown TLV " + BitConverter.ToString(new byte[] { tag }));
                            break;
                        }
                    }
                }
        }