Пример #1
0
        public void EncryptAES(IWriteStream writeStream, string sharedSecret)
        {
            if (!IsEncrypt)
            {
                return;
            }
            using (var aesAlg = new RijndaelManaged()) {
                var key = new Rfc2898DeriveBytes(sharedSecret, _salt);
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                var byteFragment = writeStream.ToByteFragment();

                using (var resultStream = new MemoryStream()) {
                    using (var csEncrypt = new CryptoStream(resultStream, encryptor, CryptoStreamMode.Write)) {
                        csEncrypt.Write(byteFragment.Buffer, byteFragment.Offset, byteFragment.Count);
                    }

                    writeStream.Reset();
                    writeStream.ShiftLeft(aesAlg.IV);
                    var ivLength = (ushort)aesAlg.IV.Length;
                    writeStream.ShiftLeft(ivLength);
                    writeStream.ShiftRight((ushort)byteFragment.Count);
                    var bytes = resultStream.ToArray();
                    writeStream.ShiftRight(bytes);
                }
            }
        }
Пример #2
0
        private void AcceptConnected(IUser peer, IReadStream readStream,
                                     IWriteStream writeStream)
        {
            var publicKey  = readStream.ShiftRight <string>();
            var key        = ID + "_" + SystemUtil.CreateRandomString(Ssfi.CryptoConfig.CryptonKeyLength);
            var encryptKey = Ssfi.Security.EncryptAesKey(key, publicKey);

            var securityComponent = SecurityComponent.GetObject();

            securityComponent.AesKey     = key;
            securityComponent.Encryptkey = encryptKey;

            peer.AddComponent <ISecurityComponent>(securityComponent);
            Logger.Debug($"添加{nameof(ISecurityComponent)}组件!");

            writeStream.ShiftRight((ushort)encryptKey.Length);
            Logger.Debug("EncryptKey Length:" + encryptKey.Length);
            writeStream.ShiftRight(encryptKey);
            writeStream.ShiftRight(string.Join(";", RpcMethodIds));

            var tmp = readStream.Clone();

            _serverSocket.AddEvent(() => {
                try {
                    _acceptAction.Invoke(peer, readStream);
                } catch (Exception e) {
                    Logger.Error(e);
                }
                tmp.Dispose();
            });
        }
Пример #3
0
        public Serializable(object _ = null)
        {
            WriteStream = PoolAllocator <IWriteStream> .GetObject();

            _endianBinaryWriter = new EndianBinaryWriter(WriteStream);
            WriteStream.ShiftRight((byte)0);
        }
Пример #4
0
        public override void ConnectionGenerator(IPEndPoint remoteAddress, IWriteStream writeStream, Action <SocketService> action)
        {
            if (remoteAddress == null)
            {
                throw new ArgumentNullException(nameof(remoteAddress));
            }

            if (_connections.TryGetValue(remoteAddress, out var socketService))
            {
                Logger.Warn($"已经存在连接{remoteAddress}!无需重复连接");
                WriteMessage(socketService, SendOption.Acknowledge | SendOption.Connect, null);
                return;
            }

            socketService = PoolAllocator <SocketService> .GetObject();

            socketService.Connection.RemoteAddress = remoteAddress;

            if (_connections.TryAdd(remoteAddress, socketService))
            {
                action?.Invoke(socketService);
                Acknowledge(socketService, SendOption.Acknowledge | SendOption.Connect, new PacketHead(), writeStream);
                CreateAck(socketService);

                Logger.Info($"创建{remoteAddress}连接心跳包!");
            }
            else
            {
                Logger.Error($"添加连接{remoteAddress}失败!");
            }
        }
Пример #5
0
        public override bool SendMessage(ulong id, IWriteStream writeStream)
        {
            if (Status != ConnectionStatus.Connected)
            {
                Logger.Warn($"ID:{ID}未连接状态!");
                return(false);
            }

            if (_socketService == null)
            {
                Logger.Error($"{nameof(_socketService)} 为 null");
                return(false);
            }

            var securityComponent = GetComponent <ISecurityComponent>();

            if (securityComponent == null)
            {
                Logger.Error($"{nameof(securityComponent)} 为 null");
                return(false);
            }

            Ssfi.Security.EncryptAES(writeStream, securityComponent.AesKey);
            writeStream.ShiftLeft(id);
            return(_serverSocket.Socket.Write(_socketService, writeStream));
        }
Пример #6
0
        private bool Acknowledge(
            SocketService socketService,
            SendOption sendOption,
            PacketHead packetHead,
            IWriteStream writeStream = null)
        {
            if (socketService == null)
            {
                Logger.Error($"{nameof(socketService)} 为 null !");
                return(false);
            }
            var fragment = writeStream?.ToByteFragment();

            packetHead.Length     = fragment.HasValue ? (ushort)(PacketHead.GetSize() + fragment?.Count) : (ushort)PacketHead.GetSize();
            packetHead.SendOption = sendOption;

            var ws = PoolAllocator <IWriteStream> .GetObject();

            if (writeStream != null)
            {
                ws.ShiftRight(writeStream.ToByteFragment());
            }
            Packet.ToBytes(packetHead, ws);
            var byteSegment = ws.ToByteFragment();

            var result = StartWrite(socketService, byteSegment.Buffer, byteSegment.Offset, byteSegment.Count, ws, true);

            SocketStatistics.LogUnreliableSend();
            SocketStatistics.LogTotalBytesSent(packetHead.Length);
            return(true);
        }
Пример #7
0
        /// <summary>
        /// 带数据的连接
        /// </summary>
        public void Connect(string ip, int port, IWriteStream writeStream)
        {
            if (writeStream == null)
            {
                throw new ArgumentNullException(nameof(writeStream));
            }

            var endPoint = new IPEndPoint(IPAddress.Parse(ip), port);

            var socketService = new SocketService();

            socketService.Connection.RemoteAddress = endPoint;
            socketService.Connection.LocalAddress  = endPoint;

            if (Write(socketService, writeStream, SendOption.Connect))
            {
                if (!_autoResetEvent.WaitOne(_networkConfig.AckInterval))
                {
                    HandleConnect?.Invoke(socketService, null);
                }
            }
            else
            {
                HandleConnect?.Invoke(socketService, null);
            }
        }
Пример #8
0
 public void WriteTo(IWriteStream output)
 {
     if (!string.IsNullOrEmpty(value))
     {
         output.WriteRawTag(10);
         output.WriteString(value);
     }
 }
Пример #9
0
 public void WriteTo(IWriteStream output)
 {
     if (value != 0F)
     {
         output.WriteRawTag(13);
         output.WriteFloat(value);
     }
 }
Пример #10
0
 public void WriteTo(IWriteStream output)
 {
     if (value != null && value.Length != 0)
     {
         output.WriteRawTag(10);
         output.WriteBytes(value);
     }
 }
Пример #11
0
 public void WriteTo(IWriteStream output)
 {
     if (value != 0D)
     {
         output.WriteRawTag(9);
         output.WriteDouble(value);
     }
 }
Пример #12
0
 public void WriteTo(IWriteStream output)
 {
     if (value != 0)
     {
         output.WriteRawTag(8);
         output.WriteUInt32(value);
     }
 }
Пример #13
0
 public void WriteTo(IWriteStream output)
 {
     if (value != 0L)
     {
         output.WriteRawTag(8);
         output.WriteInt64(value);
     }
 }
Пример #14
0
 public void WriteTo(IWriteStream output)
 {
     if (value != 0)
     {
         output.WriteRawTag(13);
         output.WriteSFixed32(value);
     }
 }
Пример #15
0
 public void WriteTo(IWriteStream output)
 {
     if (value != 0L)
     {
         output.WriteRawTag(9);
         output.WriteSFixed64(value);
     }
 }
Пример #16
0
 public void WriteTo(IWriteStream output)
 {
     if (value != false)
     {
         output.WriteRawTag(8);
         output.WriteBool(value);
     }
 }
Пример #17
0
        public static Bincoding ParseValue(IWriteStream value)
        {
            using (MemoryStream mS = new MemoryStream())
            {
                value.WriteTo(mS);

                return(new Bincoding(BincodingType.BINARY, mS.ToArray()));
            }
        }
Пример #18
0
 public void ToBytes(IWriteStream writeSteam)
 {
     writeSteam.ShiftLeft(TotalFragments);
     writeSteam.ShiftLeft(FragmentId);
     writeSteam.ShiftLeft(TotalBytes);
     writeSteam.ShiftLeft((byte)SendOption);
     writeSteam.ShiftLeft(PacketId);
     writeSteam.ShiftLeft(Length);
 }
Пример #19
0
        public DualBinaryStore(IStreamProvider provider, long start, long maxLength)
        {
            if (provider == null) throw new ArgumentNullException("provider");
            if (start < 0) throw new ArgumentException("start parameter must have a value equal or greater than 0");
            if (maxLength <= 0) throw new ArgumentException("maxLength parameter must have a value greater than 0");

            _provider = provider;
            _start = start;
            _maxLength = maxLength;

            _writeHeaderStream = provider.AcquireWriteStream();
            _writeLeftStream = provider.AcquireWriteStream();
            _writeRightStream = provider.AcquireWriteStream();

            _writeHeaderStream.Seek(start, SeekOrigin.Begin);
            if (_writeHeaderStream.Length > start)
            {
                using (var readStream = _provider.AcquireReadStream())
                {
                    readStream.Seek(start, SeekOrigin.Begin);
                    var headerBuffer = new byte[16];
                    readStream.Read(headerBuffer, 0, headerBuffer.Length);
                    _leftOffset = BitConverter.ToInt64(headerBuffer, 0);
                    _rightOffset = BitConverter.ToInt64(headerBuffer, 8);

                    // If the buffer was not generated by the store
                    if (_leftOffset <= 0) _leftOffset = 16;
                    if (_rightOffset <= 0) _rightOffset = maxLength;
                }

                _writeLeftStream.Seek(start + _leftOffset, SeekOrigin.Begin);
                _writeRightStream.Seek(start + _rightOffset, SeekOrigin.Begin);
            }
            else
            {
                _leftOffset = 16;
                _rightOffset = maxLength;

                var headerBuffer = BitConverter.GetBytes(_leftOffset);
                _writeHeaderStream.Write(headerBuffer, 0, headerBuffer.Length);
                headerBuffer = BitConverter.GetBytes(_rightOffset);
                _writeHeaderStream.Write(headerBuffer, 0, headerBuffer.Length);
                _writeHeaderStream.Seek(-16, SeekOrigin.Current);

                _writeRightStream.Seek(start + _leftOffset, SeekOrigin.Begin);
                var buffer = new byte[maxLength - _leftOffset];
                _writeRightStream.Write(buffer, 0, buffer.Length);
                _writeLeftStream.Seek(start + _leftOffset, SeekOrigin.Begin);
            }

            _lastFlushedLeftOffset = _leftOffset;
            _lastFlushedRightOffset = _rightOffset;

            _left = new LeftBinaryStoreSegment(this);
            _right = new RightBinaryStoreSegment(this);
        }
Пример #20
0
 public void WriteTo(IWriteStream output)
 {
     if (value != null && value.Count != 0)
     {
         output.WriteRawTag(10);
         output.WriteInt32(8 * value.Count);
         for (int i = 0; i < value.Count; ++i)
         {
             output.WriteSFixed64(value[i]);
         }
     }
 }
Пример #21
0
 public void WriteTo(IWriteStream output)
 {
     if (key != 0)
     {
         output.WriteRawTag(13);
         output.WriteSFixed32(key);
     }
     if (value != null)
     {
         output.WriteRawTag(18);
         output.WriteMessage(value);
     }
 }
Пример #22
0
        public override bool SendMessage(ulong id, IWriteStream writeStream)
        {
            if (Status != ConnectionStatus.Connected)
            {
                Logger.Warn("没有连接!");
                return(false);
            }

            Logger.Debug("Key:" + _aesKey);
            Ssui.Security.EncryptAES(writeStream, _aesKey);
            writeStream.ShiftLeft(id);
            return(_socket.Write(SocketService, writeStream));
        }
Пример #23
0
 public void WriteTo(IWriteStream output)
 {
     if (point3map != null && point3map.Count != 0)
     {
         var entry = new Point3mapEntry();
         foreach (var itor in point3map)
         {
             entry.key   = itor.Key;
             entry.value = itor.Value;
             output.WriteRawTag(10);
             output.WriteMessage(entry);
         }
     }
 }
Пример #24
0
        public void Connect(SocketConfig socketConfig, IWriteStream writeStream)
        {
            if (socketConfig == null)
            {
                throw new ArgumentNullException(nameof(socketConfig));
            }

            if (writeStream == null)
            {
                throw new ArgumentNullException(nameof(writeStream));
            }

            _messageQueue.Start();
            Socket.Connect(socketConfig, writeStream);
        }
Пример #25
0
        public static bool Invoke(IWriteStream writeStream, IPeer peer, ResponseCallback responseCallback)
        {
            if (peer == null)
            {
                Logger.Error($"{nameof(peer)} 为 null");
                return(false);
            }

            if (!_messages.TryGetValue(MessageType.RpcInvoke, out var func))
            {
                Logger.Error($"没有注册${nameof(RpcInvoke)}");
                return(false);
            }

            return(peer.SendMessage(writeStream, responseCallback));
        }
Пример #26
0
        public bool SendMessage(IWriteStream writeStream, ResponseCallback responseCallback)
        {
            if (Status != ConnectionStatus.Connected)
            {
                Logger.Warn("没有连接!");
                return(false);
            }

            if (responseCallback == null)
            {
                return(SendMessage(0, writeStream));
            }

            _acks[++_id] = responseCallback;
            return(SendMessage(_id, writeStream));
        }
Пример #27
0
        public override bool Write(SocketService socketService, IWriteStream writeSteam)
        {
            if (socketService == null)
            {
                Logger.Error($"{nameof(socketService)} 为 null !");
                return(false);
            }

            if (writeSteam == null)
            {
                socketService.OnError($"{nameof(writeSteam)} 为 null !");
                return(false);
            }

            return(WriteMessage(socketService, SendOption.Fragment, writeSteam));
        }
Пример #28
0
 public void WriteTo(IWriteStream output)
 {
     if (value != null && value.Count != 0)
     {
         output.WriteRawTag(10);
         int _total_pack_size_ = 0;
         for (int i = 0; i < value.Count; ++i)
         {
             _total_pack_size_ += ComputeSize.ComputeInt64Size(value[i]);
         }
         output.WriteInt32(_total_pack_size_);
         for (int i = 0; i < value.Count; ++i)
         {
             output.WriteInt64(value[i]);
         }
     }
 }
Пример #29
0
 public void WriteTo(IWriteStream output)
 {
     if (x != 0F)
     {
         output.WriteRawTag(13);
         output.WriteFloat(x);
     }
     if (y != 0F)
     {
         output.WriteRawTag(21);
         output.WriteFloat(y);
     }
     if (z != 0F)
     {
         output.WriteRawTag(29);
         output.WriteFloat(z);
     }
 }
Пример #30
0
        public static bool Invoke(MessageType messageType, IRpc rpc, IWriteStream writeStream, IPeer peer, ResponseCallback responseCallback)
        {
            if (peer == null)
            {
                Logger.Error($"{nameof(peer)} 为 null");
                return(false);
            }

            if (!_messages.TryGetValue(MessageType.RpcInvoke, out var func))
            {
                Logger.Error($"没有注册${nameof(RpcInvoke)}");
                return(false);
            }

            rpc.SerializeFields(writeStream);
            writeStream.ShiftLeft((short)messageType);
            return(peer.SendMessage(writeStream, responseCallback));
        }
Пример #31
0
        public bool SendMessage(IWriteStream writeStream, ResponseCallback responseCallback)
        {
            if (Status != ConnectionStatus.Connected)
            {
                Logger.Warn($"ID:{ID}没有连接");
                return(false);
            }

            if (responseCallback == null)
            {
                return(SendMessage(0, writeStream));
            }

            lock (_lockAcks) {
                _id++;
                _acks.Add(_id, responseCallback);
            }
            return(SendMessage(_id, writeStream));
        }
Пример #32
0
        private BinaryStore(IStreamProvider provider, long start, long length, bool canGrow)
        {
            _writeStream = provider.AcquireWriteStream();

            _provider = provider;
            _start = start;
            _length = length;
            _canGrow = canGrow;

            if (_writeStream.Length > start)
            {
                using (var readStream = _provider.AcquireReadStream())
                {
                    readStream.Seek(start, SeekOrigin.Begin);
                    var offsetBuffer = new byte[8];
                    readStream.Read(offsetBuffer, 0, offsetBuffer.Length);
                    _currentOffset = BitConverter.ToInt64(offsetBuffer, 0);
                }
            }
            else
            {
                _currentOffset = 8;
                var offsetBuffer = BitConverter.GetBytes(_currentOffset);
                _writeStream.Seek(start, SeekOrigin.Begin);
                _writeStream.Write(offsetBuffer, 0, offsetBuffer.Length);

                if (length > 0)
                {
                    var requiredFileSize = _start + _length;
                    var buffer = new byte[requiredFileSize - _writeStream.Length - 8];
                    _writeStream.Write(buffer, 0, buffer.Length);
                }
            }

            _lastFlushOffset = _currentOffset;
            _writeStream.Seek(start + _currentOffset, SeekOrigin.Begin);

            _offsetWriteStream = provider.AcquireWriteStream();
            _offsetWriteStream.Seek(start, SeekOrigin.Begin);
        }
 public static void WritePacket(Stream s, IWriteStream obj)
 {
     byte[] data = obj.ToArray();
     WritePacket(s, data, 0, data.Length);
 }