Ejemplo n.º 1
0
        /// <summary>
        /// Creates a new listener on the specified port that listen on behalf of the specified <see cref="ErebusInstance"/>.
        /// </summary>
        /// <param name="port">The TCP port to listen on.</param>
        /// <param name="instance">The <see cref="ErebusInstance"/> that this listener provides connections to.</param>
        public TCPIPConnectionListener(int port, ErebusInstance instance)
        {
#pragma warning disable CS0618 // Type or member is obsolete
            l = new TcpListener(port);
#pragma warning restore CS0618 // Type or member is obsolete
            ei = instance;
            lt = listenProcess();
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Creates a new instance of the <see cref="SSMP"/> to send and receive messages, and connects to the specified destination.
        /// </summary>
        /// <param name="instance">The current instance.</param>
        /// <param name="dest">The address of the other host.</param>
        public SSMP(ErebusInstance instance, ErebusAddress dest) : base(instance)
        {
            var s = RequestConnection(new ErebusEndpoint(dest, 20000));

            if (s == null)
            {
                throw new IOException($"Connection to {dest} was rejected!");
            }
            r         = new BinaryReader(s, Encoding.UTF8, true);
            w         = new BinaryWriter(s, Encoding.UTF8, true);
            Connected = true;
            recvTask  = recvProcess();
        }
Ejemplo n.º 3
0
        static byte[] waitRecv3(ErebusInstance ei, int len, ushort port, Guid id)
        {
            byte[] result = null;
            var    data   = itsm.RunSafe(() => instanceData[ei]);

            using (var ewh = new EventWaitHandle(false, EventResetMode.AutoReset))
            {
                data.TSM.RunSafe(() => data.Callbacks3.AddLast(Tuple.Create(port, len, id, new Action <byte[]>(d =>
                {
                    result = d;
                    ewh.Set();
                }))));
                Task.Run(() => data.TSM.RunSafe(() => refresh3(data, id, port)));
                ewh.WaitOne();
            }
            return(result);
        }
Ejemplo n.º 4
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            bool failed = false;

            while (true)
            {
                try
                {
                    using (var k = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\472\Erebus\Client"))
                    {
                        LogFile            = k.GetValue("logfile") as string;
                        KeyFile            = k.GetValue("keyfile") as string;
                        Log.EntryRecorded += (sender, _e) => File.AppendAllLines(LogFile, new[] { $"[{DateTime.Now}] [{sender}/{_e.Severity}]: {_e.Message}" });
#if DEBUG
                        Console.Title      = "Erebus Client Log Window";
                        Log.EntryRecorded += (sender, _e) => Console.WriteLine($"[{DateTime.Now}] [{sender}/{_e.Severity}]: {_e.Message}");
#endif
                        Instance = new ErebusInstance(new ErebusAddress(k.GetValue("address") as string))
                        {
                            Services = new[] { HDPService.SSMP }
                        };
                        using (var ctk = k.OpenSubKey("Targets"))
                            ConnectionTargets = (from t in ctk.GetValueNames() select Tuple.Create(t, (int)ctk.GetValue(t))).ToArray();
                    }
                    break;
                }
                catch (Exception ex)
                {
                    if (failed)
                    {
                        Log.RecordEvent(this, $"Application startup failed a second time: {ex.Message}; unable to recover.", LogEntrySeverity.Fatal);
                        throw new Exception("Application startup failed a second time.", ex);
                    }
                    Log.RecordEvent(this, $"Error during appliciation startup: {ex.Message}; starting setup utility.", LogEntrySeverity.Error);
                    Process.Start(Path.Combine(Environment.CurrentDirectory, "Vex472.Erebus.Client.Windows.Setup.exe")).WaitForExit();
                    failed = true;
                }
            }
            Log.RecordEvent(this, "Application started.", LogEntrySeverity.Info);
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Creates a new instance of the <see cref="BCPProtocolBase"/> class given the current <see cref="ErebusInstance"/>.
 /// </summary>
 /// <param name="instance">The current <see cref="ErebusInstance"/></param>
 protected BCPProtocolBase(ErebusInstance instance)
 {
     localId = Guid.NewGuid();
     ei      = instance;
     itsm.RunSafe(() =>
     {
         if (instanceData.ContainsKey(instance))
         {
             instanceData[instance].TSM.RunSafe(() => ++ instanceData[instance].Count);
         }
         else
         {
             instanceData.Add(instance, new InstanceData());
         }
         instanceData[instance].TSM.RunSafe(() =>
         {
             instanceData[instance].CurrentPositions.Add(localId, 0);
             instanceData[instance].Overflow3.Add(localId, new byte?[0]);
         });
     });
 }
Ejemplo n.º 6
0
        static internal void HandlePacket(Packet packet, ErebusInstance instance)
        {
            RawProtocolBase p;

            try
            {
                p = ptsm.RunSafe(() => protocols[packet.Port])(instance);
            }
            catch (KeyNotFoundException)
            {
                Log.RecordEvent(typeof(RawProtocolBase), $"No protocol is associated with port {packet.Port}!", LogEntrySeverity.Warning);
                return;
            }
            try
            {
                p.HandlePacket(packet);
            }
            catch (Exception e)
            {
                Log.RecordEvent(typeof(RawProtocolBase), $"Error calling packet handler on {p.GetType()}: {e.Message}", LogEntrySeverity.Error);
            }
        }
Ejemplo n.º 7
0
        static byte[] waitRecv12(ErebusInstance ei, int max, ushort port, Predicate <byte> type, Guid id)
        {
            byte[] result = null;
            var    data   = itsm.RunSafe(() => instanceData[ei]);

            using (var ewh = new EventWaitHandle(false, EventResetMode.AutoReset))
                if (data.TSM.RunSafe(() =>
                {
                    var oflow = from x in data.Overflow12 where x.Item1 == port && type(x.Item2) && x.Item3 == id select x;
                    if (oflow.HasElements())
                    {
                        var o = oflow.First();
                        if (o.Item4.Length > max)
                        {
                            result = o.Item4.Range(0, max).ToArray();
                            data.Overflow12.Find(o).Value = Tuple.Create(o.Item1, o.Item2, o.Item3, o.Item4.Skip(max).ToArray());
                        }
                        else
                        {
                            result = o.Item4;
                            data.TSM.RunSafe(() => data.Overflow12.Remove(oflow.First()));
                        }
                    }
                    else
                    {
                        data.Callbacks12.AddLast(Tuple.Create(port, max, id, type, new Action <byte[]>(d =>
                        {
                            result = d;
                            ewh.Set();
                        })));
                        return(true);
                    }
                    return(false);
                }))
                {
                    ewh.WaitOne();
                }
            return(result);
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            Log.EntryRecorded += (sender, e) => Console.WriteLine($"{sender} ({e.Severity}): {e.Message}");
            VerificationKeyProvider.Initialize("keyinfo.dat", "hello world");
            var vkp = new VerificationKeyProvider();

            Initialization.Run();
            SSMP ssmp = null;

            SSMP.InvitationReceived += (sender, e) =>
            {
                if (ssmp == null)
                {
                    ssmp = e.Accept();
                }
                ssmp.MessageReceived  += Ssmp_MessageReceived;
                ssmp.ConnectionClosed += (_sender, _e) => ssmp = null;
            };
            var ei = new ErebusInstance(new ErebusAddress(Console.ReadLine()));

            ei.Services = new[] { HDPService.SSMP };
            var l = new TCPIPConnectionListener(int.Parse(Console.ReadLine()), ei);

            while (true)
            {
                try
                {
                    var cmd = Console.ReadLine().Split(' ');
                    switch (cmd[0])
                    {
                    case "addlink":
                        new ErebusLink(TCPIPConnectionUtils.Connect(cmd[1], int.Parse(cmd[2])), ei, false);
                        break;

                    case "listlink":
                        foreach (var link in ei.Links)
                        {
                            Console.WriteLine(link.RemoteAddress);
                        }
                        break;

                    case "hdp":
                        var hdp = new HDP(ei, HDPService.SSMP);
                        hdp.SendRequest(ErebusAddress.Broadcast);
                        hdp.InitClose();
                        break;

                    case "ssmp":
                        ssmp = new SSMP(ei, new ErebusAddress(cmd[1]));
                        ssmp.MessageReceived += Ssmp_MessageReceived;
                        break;

                    case "msg":
                        ssmp?.SendMessage(cmd.Skip(1).Aggregate((x, y) => x + " " + y));
                        break;

                    case "addkey":
                        var addr = new ErebusAddress(cmd[1]);
                        vkp.RemoveKeyPair(addr);
                        var key = vkp.CreatePrivateKey();
                        Console.WriteLine("Key: " + key.Item2.Select(x => x.ToString()).Aggregate((x, y) => x + "," + y));
                        Console.Write("Please copy other key to clipboard, then press <enter> . . .");
                        Console.ReadLine();
                        vkp.AddKeyPair(addr, key.Item1, Clipboard.GetText().Split(',').Select(x => byte.Parse(x)).ToArray());
                        break;

                    case "removekey":
                        vkp.RemoveKeyPair(new ErebusAddress(cmd[1]));
                        break;

                    case "close":
                        ssmp?.Dispose();
                        ssmp = null;
                        break;

                    case "exit":
                        return;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }
 /// <summary>
 /// Creates a new listener.
 /// </summary>
 /// <param name="instance">The <see cref="ErebusInstance"/> that this listener provides connections to.</param>
 public BluetoothConnectionListener(ErebusInstance instance)
 {
     ei = instance;
     l  = BluetoothAdapter.DefaultAdapter.ListenUsingRfcommWithServiceRecord("ErebusConnection", BluetoothUtils.RfcommConnectionService);
     lt = listenProcess();
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Creates a new instance of the <see cref="RawProtocolBase"/> class given the current <see cref="ErebusInstance"/>.
 /// </summary>
 /// <param name="instance">The current <see cref="ErebusInstance"/>.</param>
 protected RawProtocolBase(ErebusInstance instance)
 {
     ei = instance;
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Creates a new listener on the specified port that listen on behalf of the specified <see cref="ErebusInstance"/>.
 /// </summary>
 /// <param name="port">The TCP port to listen on.</param>
 /// <param name="instance">The <see cref="ErebusInstance"/> that this listener provides connections to.</param>
 public TCPIPConnectionListener(int port, ErebusInstance instance)
 {
     l  = new ServerSocket(port);
     ei = instance;
     lt = listenProcess();
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Creates a new listener.
 /// </summary>
 /// <param name="instance">The <see cref="ErebusInstance"/> that this listener provides connections to.</param>
 public BluetoothConnectionListener(dynamic instance)
 {
     ei = instance;
     lt = listenProcess();
 }
Ejemplo n.º 13
0
        static internal void HandlePacket(Packet packet, ErebusInstance instance)
        {
            try {
                if (packet.Data.Length == 0)
                {
                    Log.RecordEvent(typeof(BCPProtocolBase), $"BCP packet from {packet.Source} is empty.", LogEntrySeverity.Error);
                    return;
                }
                switch (packet.Data[0])
                {
                case 0:
                    ErebusEndpoint ep = new ErebusEndpoint(packet.Source, packet.Port);
                    if (packet.Data.Length != 17)
                    {
                        Log.RecordEvent(typeof(BCPProtocolBase), $"BCP connection request packet from {ep} is an invalid size!", LogEntrySeverity.Warning);
                    }
                    BCPProtocolBase p;
                    try
                    {
                        p          = ptsm.RunSafe(() => protocols[packet.Port])(instance);
                        p.remoteId = new Guid(packet.Data.Skip(1).ToArray());
                    }
                    catch (KeyNotFoundException)
                    {
                        Log.RecordEvent(typeof(BCPProtocolBase), $"No protocol is associated with port {packet.Port}!", LogEntrySeverity.Warning);
                        instance.SendPacket(ep, new byte[] { 2 }.Concat(packet.Data.Skip(1)).ToArray());
                        return;
                    }
                    try
                    {
                        bool accepted = false;
                        p.Endpoint = ep;
                        p.HandleConnection(ep, () =>
                        {
                            accepted = true;
                            instance.SendPacket(ep, new byte[] { 1 }.Concat(p.remoteId.ToByteArray()).Concat(p.localId.ToByteArray()).ToArray());
                            Log.RecordEvent(p, $"Connected to {ep} with local GUID {p.localId} and remote GUID {p.remoteId}", LogEntrySeverity.Info);
                            p.retrieveKeys(packet.Source);
                            return(p.createStream(ep));
                        });
                        if (!accepted)
                        {
                            instance.SendPacket(ep, new byte[] { 2 }.Concat(p.remoteId.ToByteArray()).ToArray());
                        }
                    }
                    catch (Exception e)
                    {
                        Log.RecordEvent(typeof(BCPProtocolBase), $"Error calling connection handler on {p.GetType()}: {e.Message}", LogEntrySeverity.Error);
                    }
                    break;

                case 3:
                    var i = itsm.RunSafe(() => instanceData[instance]);
                    i.TSM.RunSafe(() =>
                    {
                        Guid id   = new Guid(packet.Data.Range(1, 16).ToArray());
                        ulong pos = BitConverter.ToUInt64(packet.Data.Range(17, 8).ToArray(), 0);
                        var data  = packet.Data.Skip(25).ToArray();
                        var cp    = i.CurrentPositions[id];
                        if (pos < cp)
                        {
                            Log.RecordEvent(typeof(BCPProtocolBase), "BCP packet received for known data.", LogEntrySeverity.Warning);
                        }
                        else
                        {
                            var oflow    = i.Overflow3[id];
                            var newOflow = new byte?[Math.Max((int)((ulong)data.Length + pos - cp), oflow.Length)];
                            Array.Copy(oflow, newOflow, oflow.Length);
                            Array.Copy(data.Cast <byte?>().ToArray(), 0, newOflow, (int)(pos - cp), data.Length);
                            i.Overflow3[id] = newOflow;
                            refresh3(i, id, packet.Port);
                        }
                    });
                    break;

                default:
                    var itm = itsm.RunSafe(() => instanceData[instance]);
                    itm.TSM.RunSafe(() =>
                    {
                        var data = packet.Data.Skip(17).ToArray();
                        foreach (var c in (from d in itm.Callbacks12 where d.Item1 == packet.Port && d.Item3 == new Guid(packet.Data.Range(1, 16).ToArray()) && d.Item4(packet.Data[0]) select d).ToArray())
                        {
                            itm.Callbacks12.Remove(c);
                            c.Item5(data.Range(0, Math.Min(data.Length, c.Item2)).ToArray());
                            if (c.Item2 <= data.Length)
                            {
                                data = data.Skip(c.Item2).ToArray();
                            }
                            else
                            {
                                data = new byte[0];
                            }
                            if (data.Length == 0)
                            {
                                break;
                            }
                        }
                        if (data.Length != 0)
                        {
                            itm.Overflow12.AddLast(new Tuple <ushort, byte, Guid, byte[]>(packet.Port, packet.Data[0], new Guid(packet.Data.Range(1, 16).ToArray()), data));
                        }
                    });
                    break;
                }
            }
            catch (Exception e)
            {
                Log.RecordEvent(typeof(BCPProtocolBase), $"Exception in BCP main packet handler: {e.Message}", LogEntrySeverity.Error);
            }
        }
Ejemplo n.º 14
0
 static byte[] waitRecv12(ErebusInstance ei, int max, ushort port, byte type, Guid id) => waitRecv12(ei, max, port, t => t == type, id);
Ejemplo n.º 15
0
 SSMP(ErebusInstance instance) : base(instance)
 {
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Creates a new instance of the <see cref="HDP"/> class to request service information from servers.
 /// </summary>
 /// <param name="instance">The current instance.</param>
 /// <param name="service">The service to request.</param>
 public HDP(ErebusInstance instance, HDPService service) : base(instance)
 {
     id       = Guid.NewGuid();
     _service = service;
     instances.Add(id, this);
 }
Ejemplo n.º 17
0
 HDP(ErebusInstance instance) : base(instance)
 {
     id = new Guid();
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Creates a new instance of the <see cref="CNP"/> class that uses the specified <see cref="ErebusInstance"/>.
 /// </summary>
 /// <param name="instance">The current instance.</param>
 public CNP(ErebusInstance instance) : base(instance)
 {
 }