static void CopyPart()
        {
            try
            {
                ByteRange range = new ByteRange(10, 20);

                CopyPartRequest request = new CopyPartRequest()
                {
                    SourceBucketName = bucketName,
                    SourceObjectKey  = objectName,
                    SourceVersionId  = versionId,
                    ObjectKey        = destobjectName,
                    PartNumber       = 1,
                    UploadId         = uploadId,
                    ByteRange        = range
                };
                CopyPartResponse response = client.CopyPart(request);

                Console.WriteLine("Copy part response: {0}", response.StatusCode);
                Console.WriteLine("ETag: {0}", response.ETag);
                etag = response.ETag;
            }
            catch (ObsException ex)
            {
                Console.WriteLine("Exception errorcode: {0}, when copy part.", ex.ErrorCode);
                Console.WriteLine("Exception errormessage: {0}", ex.ErrorMessage);
            }
        }
        public static List <ByteRange> RangeStringToArray(string rangeString)
        {
            var byteRanges  = new List <ByteRange>();
            var rangeValues = rangeString.Remove(0, Bytes.Length).Split(',');

            foreach (var item in rangeValues)
            {
                var part      = item.Split('-');
                var byteRange = new ByteRange();

                if (part.Length == 2)
                {
                    if (part[1] == string.Empty)
                    {
                        byteRange.End = 0;
                    }
                    else
                    {
                        byteRange.End = (ulong)Convert.ToInt32(part[1]);
                    }
                }
                byteRange.Start = (ulong)Convert.ToInt32(part[0]);

                byteRanges.Add(byteRange);
            }

            return(byteRanges);
        }
Esempio n. 3
0
 public Dummy(IStructuralNode?parent, string name, ByteRange byteRange, Func <IList <IStructuralNode> > childFactory)
     : base(parent)
 {
     Name          = name;
     ByteRange     = byteRange;
     _childFactory = childFactory;
 }
Esempio n. 4
0
        /// <summary>
        /// 输出文件
        /// </summary>
        /// <param name="response">回复对象</param>
        public void ExecuteResult(HttpResponse response)
        {
            if (string.IsNullOrEmpty(this.ContentType))
            {
                this.ContentType = "application/ocelet-stream";
            }
            response.Charset = null;
            response.ContentType = this.ContentType;
            response.ContentDisposition = this.ContentDisposition;

            using (var stream = new FileStream(this.FileName, FileMode.Open, FileAccess.Read))
            {
                const int size = 8 * 1024;               
                var state = response.WriteHeader((int)stream.Length);

                while (state == true)
                {
                    var bytes = new byte[size];
                    var length = stream.Read(bytes, 0, size);
                    if (length == 0)
                    {
                        break;
                    }
                    var content = new ByteRange(bytes, 0, length);
                    state = response.WriteContent(content);
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// 输出文件
        /// </summary>
        /// <param name="response">回复对象</param>
        public void ExecuteResult(HttpResponse response)
        {
            if (string.IsNullOrEmpty(this.ContentType))
            {
                this.ContentType = "application/ocelet-stream";
            }
            response.Charset            = null;
            response.ContentType        = this.ContentType;
            response.ContentDisposition = this.ContentDisposition;

            using (var stream = new FileStream(this.FileName, FileMode.Open, FileAccess.Read))
            {
                const int size  = 8 * 1024;
                var       state = response.WriteHeader((int)stream.Length);

                while (state == true)
                {
                    var bytes  = new byte[size];
                    var length = stream.Read(bytes, 0, size);
                    if (length == 0)
                    {
                        break;
                    }
                    var content = new ByteRange(bytes, 0, length);
                    state = response.WriteContent(content);
                }
            }
        }
Esempio n. 6
0
        /// <summary>
        ///		Extension method that performs a transformation on the <see cref="Byte"/> subject using
        ///		linear mapping to re-map from the provided initial range <paramref name="startRange"/>
        ///		to the target range <paramref name="endRange"/>.
        /// </summary>
        /// <param name="this">
        ///		The subject <see cref="Byte"/> in which to perform the linear map range re-mapping upon.
        /// </param>
        /// <param name="startRange">
        ///		An instance of the type <see cref="ByteRange"/>, describing a range of a pair of numeric
        ///   <see cref="Byte"/> values in which the linear re-mapping uses as the inital range.
        /// </param>
        /// <param name="endRange">
        ///		An instance of the type <see cref="ByteRange"/>, describing a range of a pair of numeric
        ///   <see cref="Byte"/> values in which the linear re-mapping uses as the target range.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///		Thrown when either the <paramref name="startRange"/> or the <paramref name="endRange"/>
        ///		parameters are equal to <see langword="null"/>.
        ///	</exception>
        /// <exception cref="ArgumentOutOfRangeException">
        ///		Thrown when either the <paramref name="@this"/> subject parameter is not within the bounds
        ///   of the provided <paramref name="startRange"/>. This is determined with a call to the
        ///   <see cref="IsNotWithin"/> method, with an implicit <see cref="EndpointExclusivity"/> value
        ///   of <see cref="EndpointExclusivity.Inclusive"/> by default, unless it is specified explicitly
        ///   set this property to <see cref="EndpointExclusivity.Exclusive"/>.
        ///	</exception>
        /// <returns>
        ///		A <see cref="Byte"/> value that has been linearly mapped on the <paramref name="startRange"/>
        ///		parameter, and re-mapped to the <paramref name="endRange"/> parameter.
        /// </returns>
        public static Byte LinearMap(
            this Byte @this,
            [NotNull] ByteRange startRange,
            [NotNull] ByteRange endRange)
        {
            startRange.IsNotNull(nameof(startRange));
            endRange.IsNotNull(nameof(endRange));

            if (@this.IsNotWithin(startRange))
            {
                throw new ArgumentOutOfRangeException(
                          nameof(@this),
                          @this,
                          $"The {nameof(@this).SQuote()} parameter value is outside of the acceptable range. The " +
                          $"value must be within the {nameof(startRange).SQuote()} parameter. The current value is " +
                          $"{@this.ToString().SQuote()}, and the {nameof(startRange).SQuote()} parameter range is " +
                          $"{startRange}.");
            }

            var linearMapped
                = (@this - startRange.Minimum) *
                  (endRange.Maximum - endRange.Minimum) /
                  (startRange.Maximum - startRange.Minimum) +
                  endRange.Minimum;

            return(Convert
                   .ToByte(
                       linearMapped));
        }
        /// <summary>
        /// 接收到策略请求
        /// </summary>
        /// <param name="session">会话对象</param>
        /// <param name="buffer">数据</param>
        protected override void OnReceive(SessionBase session, ReceiveBuffer buffer)
        {
            var xml = new StringBuilder();

            xml.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            xml.AppendLine("<access-policy>");
            xml.AppendLine("<cross-domain-access>");
            xml.AppendLine("<policy>");
            xml.AppendLine("<allow-from>");
            xml.AppendLine("<domain uri=\"*\"/>");
            xml.AppendLine("</allow-from>");
            xml.AppendLine("<grant-to>");
            xml.AppendLine("<socket-resource port=\"4502-4534\" protocol=\"tcp\"/>");
            xml.AppendLine("</grant-to>");
            xml.AppendLine("</policy>");
            xml.AppendLine("</cross-domain-access>");
            xml.AppendLine("</access-policy>");

            var bytes     = Encoding.UTF8.GetBytes(xml.ToString());
            var byteRange = new ByteRange(bytes);

            try
            {
                session.Send(byteRange);
            }
            finally
            {
                session.Close();
            }
        }
Esempio n. 8
0
 public TableStreamNode(PEStructuralNodeProvider provider, IStructuralNode parent, string name, long offset, long length)
     : base(parent)
 {
     _provider = provider;
     Name      = name;
     ByteRange = new ByteRange(offset, length);
 }
Esempio n. 9
0
        public void TestOverwrite()
        {
            var bytes    = Helpers.CreateByteArray(100);
            var filename = Path.GetTempPath() + "test.dat";

            File.WriteAllBytes(filename, bytes);
            using (var buffer = new ByteBuffer(filename)) {
                var dr1 = new ByteRange(20, new byte[] { 65, 66, 67, 68 });
                buffer.Overwrite(dr1);

                var dr2 = new ByteRange(18, new byte[] { 65, 66, 67, 68, 69, 3, 4, 5, 6, 7, 8 });
                buffer.Overwrite(dr2);

                var dr3 = new ByteRange(50, new byte[] { 65, 66, 67, 68 });
                buffer.Overwrite(dr3);

                var dr4 = new ByteRange(48, new byte[] { 65, 66, 67, 68 });
                buffer.Overwrite(dr4);

                var dr5 = new ByteRange(50, new byte[] { 11, 33, 37, 5, 5, 6, 7, 8, 9 });
                buffer.Overwrite(dr5);

                foreach (var dr in buffer.DataRanges)
                {
                    Debug.WriteLine(dr);
                }

                Assert.IsTrue(buffer.DataRanges.Count() == 6);
                Assert.IsTrue(buffer.Size == 100);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// 从流中读取count字节的范围标记
        /// 并将流内的位置向前推进count个字节
        /// </summary>
        /// <param name="count">字节数</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public IByteRange ReadByteRange(int count)
        {
            var range = new ByteRange(base.GetBuffer(), this.Position, count);

            this.Position = this.Position + count;
            return(range);
        }
        public async Task <byte[]> GetBytes(ByteRange range, CancellationToken cancellationToken = default)
        {
            var stream = new System.IO.MemoryStream();
            await _getRequest.DownloadRangeAsync(stream, new RangeHeaderValue(range.Start, range.End), cancellationToken);

            return(stream.ToArray());
        }
Esempio n. 12
0
        public void WithoutMaxBytesTest()
        {
            // given: range and byte rule
            ByteRange range = new ByteRange(0, 11);
            EveryNthByteIndexProvider rule = new EveryNthByteIndexProvider(range, 2);

            rule.CreatePossibleByteIndexes();

            List <uint> expectedIndexes = new List <uint>()
            {
                1,
                3,
                5,
                7,
                9,
                11
            };

            // when: getting the bytes
            List <uint> actualIndexes = new List <uint>();

            while (rule.ByteIndexPool.Count != 0)
            {
                actualIndexes.Add(rule.GetNextByteIndex());
            }

            // then: indexes match
            CollectionAssert.AreEqual(expectedIndexes, actualIndexes);
        }
Esempio n. 13
0
        public DeleteBulkTextCommand(HexEdit hexEdit, Range range) : base(hexEdit)
        {
            var data = new byte[range.Count];

            hexEdit.Buffer.GetBytes(range.Start, (int)range.Count, data);
            _byteRange = new ByteRange(range.Start, data);
        }
Esempio n. 14
0
 public void Append(ByteRange other)
 {
     if (!CanAppend(other))
     {
         throw new InvalidOperationException();
     }
     Length += other.Length;
 }
 public Dummy(IStructuralNode?parent, string name, ByteRange byteRange, int count, Func <int, IStructuralNode> factory)
     : base(parent)
 {
     Name      = name;
     ByteRange = byteRange;
     Count     = count;
     _factory  = factory;
 }
Esempio n. 16
0
 public void PopConstraint()
 {
     if (_ConstraintStack.Count > 0) _CurrentConstraint = _ConstraintStack.Pop();
     else
     {
         Trace.WriteLine("Attempted to pop constraint too many times.", "WARNING");
         _CurrentConstraint = ByteRange.MaxValue;
     }
 }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="range">The byte range to get possible indexes from.</param>
        /// <param name="numBytesToGlitch">Amount of bytes to glitch.</param>
        public ByteIndexProviderBase(ByteRange range, uint numBytesToGlitch)
        {
            _range = range;

              if (numBytesToGlitch <= 0)
            throw new ArgumentOutOfRangeException(nameof(numBytesToGlitch));

              _numBytesToGlitch = numBytesToGlitch;
              _possibleByteIndexes = new List<uint>();
        }
Esempio n. 18
0
        /// <summary>
        ///		Extension method that allows for <see cref="IntegralRangeBase{TIntegralType}.Constrain"/>
        ///		to be called on a <see cref="Byte"/> subject with the range and exclusivity passed as a
        ///		parameter, rather than on the <see cref="IntegralRangeBase{TIntegralType}"/> object
        ///		with a <see cref="Byte"/> parameter.
        /// </summary>
        /// <param name="this">
        ///		The subject <see cref="Byte"/> value in which to check against the <paramref name="range"/>
        ///		parameter to constrain a value within a range with an implicit inclusive comparison mode.
        /// </param>
        /// <param name="range">
        ///		An instance of the type <see cref="ByteRange"/>, describing a range of numeric values in
        ///		which the <paramref name="this"/> subject is to be compared against.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///		Thrown when the specified <paramref name="range"/> is <see langword="null"/>.
        ///	</exception>
        /// <returns>
        ///		A <see cref="Byte"/> value that is the <paramref name="this"/> subject value adjusted to
        ///		force the range of possible values to be within the provided <paramref cref="range"/>
        ///		parameter, using <see cref="EndpointExclusivity.Inclusive"/> as the comparison mode.
        /// </returns>
        public static Byte Constrain(
            this Byte @this,
            [NotNull] ByteRange range)
        {
            range.IsNotNull(nameof(range));

            return(range
                   .Constrain(
                       @this));
        }
        private async Task <byte[]> GetRangeBytes(string Bucket, string Key, ByteRange Range)
        {
            GetObjectRequest request = new GetObjectRequest
            {
                BucketName = Bucket,
                Key        = Key,
                ByteRange  = Range
            };
            var response = await s3.GetObjectAsync(request);

            return(StreamToArray(response.ResponseStream));
        }
Esempio n. 20
0
        /// <summary>
        ///		Extension method that allows for <see cref="IntegralRangeBase{TIntegralType}.IsNotWithin"/>
        ///		to be called on a <see cref="Byte"/> subject with the range and exclusivity passed as a
        ///		parameter, rather than on the <see cref="IntegralRangeBase{TIntegralType}"/> object
        ///		with a <see cref="Byte"/> parameter.
        /// </summary>
        /// <param name="this">
        ///		The subject <see cref="Byte"/> value in which to check against the <paramref name="range"/>
        ///		parameter to determine whether it is within the range, taking into account the exclusivity.
        /// </param>
        /// <param name="range">
        ///		An instance of the type <see cref="ByteRange"/>, describing a range of numeric values in
        ///		which the <paramref name="this"/> subject is to be compared against.
        /// </param>
        /// <param name="exclusivity">
        ///		A value indicating whether to perform the upper and lower bounds comparisons including
        ///		the range's Minimum and Maximum bounds, or to exclude them. This parameter is optional,
        ///		and the default value is <see cref="EndpointExclusivity.Inclusive"/>.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///		Thrown when the specified <paramref name="range"/> is <see langword="null"/>.
        ///	</exception>
        /// <returns>
        ///		A <see cref="Byte"/> value indicating whether or not the <paramref name="this"/> subject
        ///		is within the provided <paramref cref="range"/> parameter, taking into account the
        ///		<see cref="EndpointExclusivity"/> mode via the <paramref name="exclusivity"/> parameter.
        ///		This comparison is the logical inverse of the <see cref="IsNotWithin"/> extension method.
        /// </returns>
        public static bool IsNotWithin(
            this Byte @this,
            [NotNull] ByteRange range,
            EndpointExclusivity exclusivity = EndpointExclusivity.Inclusive)
        {
            range.IsNotNull(nameof(range));

            return(range
                   .IsNotWithin(
                       @this,
                       exclusivity));
        }
Esempio n. 21
0
        public static async Task <String> CreateAsync(ByteRange byteRange)
        {
            return(await Task.Run(() => {
                int byteRangeValue = (int)byteRange;

                byte[] randomBytes = new byte[byteRangeValue / 8];
                using (var generator = RandomNumberGenerator.Create())
                {
                    generator.GetBytes(randomBytes);
                    return Convert.ToBase64String(randomBytes);
                }
            }));
        }
Esempio n. 22
0
 public static async Task <String> CreateAsync(string password, string salt, ByteRange byteRange)
 {
     return(await Task.Run(() => {
         return Convert.ToBase64String(KeyDerivation.Pbkdf2(
                                           password: password,
                                           salt: Encoding.UTF8.GetBytes(salt),
                                           prf: KeyDerivationPrf.HMACSHA1,
                                           iterationCount: 10000,
                                           //numBytesRequested: 256 / 8)
                                           numBytesRequested: (int)byteRange / 8)
                                       );
     }));
 }
Esempio n. 23
0
 public ResumeFileResult(string fileName, string ifNoneMatch, string ifModifiedSince, string ifMatch, string ifUnmodifiedSince, string ifRange, string range, string downloadFileName) : base(fileName, new MimeMapper().GetMimeFromPath(fileName))
 {
     _file              = new FileInfo(fileName);
     _lastModified      = _file.LastWriteTime.ToString("R");
     _rangeRequest      = range != null;
     _byteRange         = Range(range);
     _etag              = Etag();
     _ifNoneMatch       = ifNoneMatch;
     _ifModifiedSince   = ifModifiedSince;
     _ifMatch           = ifMatch;
     _ifUnmodifiedSince = ifUnmodifiedSince;
     _ifRange           = ifRange;
     _downloadFileName  = downloadFileName;
 }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="range">Range to glitch.</param>
        /// <param name="maxNumBytesToGlitch">Maximum number of bytes to glitch.</param>
        /// <param name="n"/>Byte skip factor.
        public EveryNthByteIndexProvider(ByteRange range, uint maxNumBytesToGlitch, uint n)
            : base(range, maxNumBytesToGlitch)
        {
            if (n == 0 || n > range.End - range.Start)
            {
                throw new ArgumentOutOfRangeException(nameof(n));
            }
            if (maxNumBytesToGlitch == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(maxNumBytesToGlitch));
            }

            _n = n;
        }
Esempio n. 25
0
        /// <summary>
        ///		Extension method that performs a transformation on the <see cref="Byte"/> subject using
        ///		linear mapping to re-map from the provided initial range <paramref name="startRange"/>
        ///		to the target range <paramref name="endRange"/>.
        /// </summary>
        /// <param name="this">
        ///		The subject <see cref="Byte"/> to perform the linear map range re-mapping upon.
        /// </param>
        /// <param name="startRange">
        ///		An instance of the type <see cref="ByteRange"/>, describing a range of numeric values in
        ///		which the linear re-mapping uses as the initial range of the subject.
        /// </param>
        /// <param name="endRange">
        ///		An instance of the type <see cref="ByteRange"/>, describing a range of numeric values in
        ///		which the linear re-mapping uses as the target range of the return value.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///		Thrown when either the <paramref name="startRange"/> or the <paramref name="endRange"/>
        ///		parameters are equal to <see langword="null"/>.
        ///	</exception>
        /// <returns>
        ///		A <see cref="Byte"/> value that has been linearly mapped to the <paramref name="startRange"/>
        ///		parameter and re-mapped to the <paramref name="endRange"/> parameter.
        /// </returns>
        public static Byte LinearMap(
            this Byte @this,
            [NotNull] ByteRange startRange,
            [NotNull] ByteRange endRange)
        {
            startRange.IsNotNull(nameof(startRange));
            endRange.IsNotNull(nameof(endRange));

            return((
                       (@this - startRange.Minimum) *
                       (endRange.Maximum - endRange.Minimum) /
                       (startRange.Maximum - startRange.Minimum) +
                       endRange.Minimum)
                   .To <Byte>());
        }
Esempio n. 26
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="range">Range to glitch.</param>
        /// <param name="maxNumBytesToGlitch">Maximum number of bytes to glitch.</param>
        /// <param name="bytes">The bytes to check with the <paramref name="conditionPredicate"/>.</param>
        /// <param name="conditionPredicate">The condition to check each byte for.</param>
        public ConditionedByteIndexProvider(ByteRange range, uint maxNumBytesToGlitch, byte[] bytes, Func <byte, bool> conditionPredicate)
            : base(range, maxNumBytesToGlitch)
        {
            if (bytes == null)
            {
                throw new ArgumentNullException(nameof(bytes));
            }
            if (bytes.Length == 0)
            {
                throw new ArgumentException(string.Format("{0} can't be empty", nameof(bytes)));
            }

            _possibleBytes      = bytes.SubArray(_range.Start, _range.End - _range.Start);
            _conditionPredicate = conditionPredicate ?? throw new ArgumentNullException(nameof(conditionPredicate));
        }
        /// <summary>
        /// 接收到策略请求
        /// </summary>
        /// <param name="session">会话对象</param>
        /// <param name="buffer">数据</param>
        protected override void OnReceive(SessionBase session, ReceiveBuffer buffer)
        {
            var xml       = "<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\"/></cross-domain-policy>\0";
            var bytes     = Encoding.UTF8.GetBytes(xml.ToCharArray()); // 需要把字符串转为Char[]
            var byteRange = new ByteRange(bytes);

            try
            {
                session.Send(byteRange);
            }
            finally
            {
                session.Close();
            }
        }
Esempio n. 28
0
        public void PushConstraint(long offset, long length)
        {

            if (offset < _CurrentConstraint.Start)
            {
                Trace.WriteLine(String.Format("Attempted to set a new constraint ({0},{1}) offset outside the bounds of the existing constraint({2},{3}).", offset, length, _CurrentConstraint.Start, _CurrentConstraint.Length), "WARNING");
                offset = _CurrentConstraint.Start;
            }
            if (offset + length > _CurrentConstraint.End)
            {
                Trace.WriteLine(String.Format("Attempted to set a new constraint ({0},{1}) length outside the bounds of the existing constraint({2},{3}).", offset, length, _CurrentConstraint.Start, _CurrentConstraint.Length), "WARNING");
                length = _CurrentConstraint.End - offset;
            }

            if (_CurrentConstraint != null) _ConstraintStack.Push(_CurrentConstraint);
            _CurrentConstraint = new ByteRange(offset, offset + length);
        }
Esempio n. 29
0
        /// <summary>
        /// 尝试发送数据到客户端
        /// </summary>
        /// <param name="range"></param>
        /// <returns></returns>
        private bool TrySend(ByteRange range)
        {
            if (range == null)
            {
                return(false);
            }

            try
            {
                this.session.Send(range);
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Esempio n. 30
0
        /// <summary>
        /// Returns the amount of bytes remaining that need to be pulled down from S3.
        /// </summary>
        /// <param name="filepath">The fully qualified path of the file.</param>
        /// <returns></returns>
        static ByteRange ByteRangeRemainingForDownload(string filepath)
        {
            /*
             * Initialize the ByteRange as the whole file.
             * long.MaxValue works regardless of the size because
             * S3 will stop sending bits if you specify beyond the
             * size of the file anyways.
             */
            ByteRange byteRange = new ByteRange(0, long.MaxValue);

            if (File.Exists(filepath))
            {
                FileInfo info = new FileInfo(filepath);
                byteRange.Start = info.Length;
            }

            return(byteRange);
        }
Esempio n. 31
0
        public void TestInsert()
        {
            var bytes    = Helpers.CreateByteArray(100);
            var filename = Path.GetTempPath() + "test.dat";

            File.WriteAllBytes(filename, bytes);
            using (var buffer = new ByteBuffer(filename)) {
                var dr1 = new ByteRange(20, new byte[] { 65, 66, 67, 68 });
                buffer.Insert(dr1);

                var dr2 = new ByteRange(50, new byte[] { 65, 66, 67, 68, 80 });
                buffer.Insert(dr2);

                var dr3 = new ByteRange(48, new byte[] { 65, 66, 67, 68, 77, 33, 55 });
                buffer.Insert(dr3);

                Assert.IsTrue(buffer.Size == 116);
            }
        }
        private void DownloadIndexOnce()
        {
            //Create index storage only if index segment is provided
            if (this.indexDownloaded)
            {
                return;
            }

            indexDownloaded = true;

            ByteRange range = new ByteRange(IndexSegment.ByteRange);

            try
            {
                Logger.Debug($"Downloading Index Segment {IndexSegment.Url} {range}");
                byte[] data = Downloader.DownloadData(IndexSegment.Url, range);
                Logger.Debug($"Downloaded successfully Index Segment {IndexSegment.Url} {range}");
                ProcessIndexData(data, (UInt64)range.High);

                // Update Duration to correspond to what's contained in index data
                if (segments_.Count > 0)
                {
                    var lastEntry = segments_.Count - 1;

                    // Update duration with information from index segment data.
                    // Index segment data is used for seeks. If varies from Manifest Duration
                    // especially if it is shorter, this will cause missing segments.
                    //
                    Duration = segments_[lastEntry].Period.Start + segments_[lastEntry].Period.Duration;
                }
            }
            catch (WebException e)
            {
                Logger.Error(e, $"Downloading Index Segment FAILED {IndexSegment.Url} ({e.Status})");
                // No need to add any special error handling for failed downloads. Indexed content
                // will return null segments if no index data is present.
            }
            catch (Exception e)
            {
                Logger.Error(e, $"Downloading Index Segment FAILED {IndexSegment.Url}");
            }
        }
Esempio n. 33
0
        public static void ThrowIfNotWithin(
            [AssertionCondition(IS_NOT_NULL)] this Byte @this,
            [NotNull] ByteRange range,
            [InvokerParameterName] string elementName,
            EndpointExclusivity exclusivity            = Inclusive,
            [CallerMemberName] string callerMemberName = "")
        {
            range.IsNotNull(nameof(range));

            if (range
                .IsNotWithin(
                    @this,
                    exclusivity))
            {
                throw new ArgumentOutOfRangeException(
                          elementName,
                          $"Parameter {elementName.SQuote()} passed to the method {callerMemberName.SQuote()} " +
                          $"must be within [{range.Minimum} and {range.Maximum}], {exclusivity}ly.");
            }
        }
 public SequencePoint(FilePath path, int startLine, int startColumn, int endLine, int endColumn, ByteRange byteRange)
     : base(path, startLine, startColumn, endLine, endColumn)
 {
     ByteRange = byteRange;
 }
Esempio n. 35
0
 internal static unsafe bool ProcessRangeRequest(HttpContext context, string physicalPath, long fileLength, string rangeHeader, string etag, DateTime lastModified)
 {
     long offset;
     long length;
     HttpRequest request = context.Request;
     HttpResponse response = context.Response;
     bool flag = false;
     if (fileLength <= 0L)
     {
         SendRangeNotSatisfiable(response, fileLength);
         return true;
     }
     string ifRangeHeader = request.Headers["If-Range"];
     if ((ifRangeHeader != null) && (ifRangeHeader.Length > 1))
     {
         if (ifRangeHeader[0] == '"')
         {
             if (ifRangeHeader != etag)
             {
                 return flag;
             }
         }
         else
         {
             if ((ifRangeHeader[0] == 'W') && (ifRangeHeader[1] == '/'))
             {
                 return flag;
             }
             if (IsOutDated(ifRangeHeader, lastModified))
             {
                 return flag;
             }
         }
     }
     int index = rangeHeader.IndexOf('=');
     if ((index == -1) || (index == (rangeHeader.Length - 1)))
     {
         return flag;
     }
     int startIndex = index + 1;
     bool flag2 = true;
     bool flag4 = false;
     ByteRange[] rangeArray = null;
     int num5 = 0;
     long num6 = 0L;
     while ((startIndex < rangeHeader.Length) && flag2)
     {
         bool flag3;
         flag2 = GetNextRange(rangeHeader, ref startIndex, fileLength, out offset, out length, out flag3);
         if (!flag2)
         {
             break;
         }
         if (flag3)
         {
             if (rangeArray == null)
             {
                 rangeArray = new ByteRange[0x10];
             }
             if (num5 >= rangeArray.Length)
             {
                 ByteRange[] rangeArray2 = new ByteRange[rangeArray.Length * 2];
                 int len = rangeArray.Length * Marshal.SizeOf(rangeArray[0]);
                 fixed (ByteRange* rangeRef = rangeArray)
                 {
                     fixed (ByteRange* rangeRef2 = rangeArray2)
                     {
                         memcpyimpl((byte*)rangeRef, (byte*)rangeRef2, len);
                     }
                 }
                 rangeArray = rangeArray2;
             }
             rangeArray[num5].Offset = offset;
             rangeArray[num5].Length = length;
             num5++;
             num6 += length;
             if (num6 > (fileLength * 5L))
             {
                 flag4 = true;
                 break;
             }
         }
     }
     if (!flag2)
     {
         return flag;
     }
     if (flag4)
     {
         SendBadRequest(response);
         return true;
     }
     if (num5 == 0)
     {
         SendRangeNotSatisfiable(response, fileLength);
         return true;
     }
     string mimeMapping = MimeMapping.GetMimeMapping(physicalPath);
     if (num5 == 1)
     {
         offset = rangeArray[0].Offset;
         length = rangeArray[0].Length;
         response.ContentType = mimeMapping;
         string str3 = string.Format(CultureInfo.InvariantCulture, "bytes {0}-{1}/{2}", new object[] { offset, (offset + length) - 1L, fileLength });
         response.AppendHeader("Content-Range", str3);
         SendFile(physicalPath, offset, length, fileLength, context);
     }
     else
     {
         response.ContentType = "multipart/byteranges; boundary=<q1w2e3r4t5y6u7i8o9p0zaxscdvfbgnhmjklkl>";
         string s = "Content-Type: " + mimeMapping + "\r\n";
         for (int i = 0; i < num5; i++)
         {
             offset = rangeArray[i].Offset;
             length = rangeArray[i].Length;
             response.Write("--<q1w2e3r4t5y6u7i8o9p0zaxscdvfbgnhmjklkl>\r\n");
             response.Write(s);
             response.Write("Content-Range: ");
             string str4 = string.Format(CultureInfo.InvariantCulture, "bytes {0}-{1}/{2}", new object[] { offset, (offset + length) - 1L, fileLength });
             response.Write(str4);
             response.Write("\r\n\r\n");
             SendFile(physicalPath, offset, length, fileLength, context);
             response.Write("\r\n");
         }
         response.Write("--<q1w2e3r4t5y6u7i8o9p0zaxscdvfbgnhmjklkl>--\r\n\r\n");
     }
     response.StatusCode = 0xce;
     response.AppendHeader("Last-Modified", (string)typeof(HttpUtility).GetMethod("FormatHttpDateTime").Invoke(typeof(HttpUtility), new object[] { lastModified }));
     response.AppendHeader("Accept-Ranges", "bytes");
     response.AppendHeader("ETag", etag);
     response.AppendHeader("Cache-Control", "public");
     return true;
 }
Esempio n. 36
0
 /// <summary>
 /// 输出内容
 /// </summary>
 /// <param name="range">内容</param>
 /// <returns></returns>
 public bool WriteContent(ByteRange range)
 {
     return this.TrySend(range);
 }
Esempio n. 37
0
        /// <summary>
        /// 尝试发送数据到客户端
        /// </summary>
        /// <param name="range"></param>
        /// <returns></returns>
        private bool TrySend(ByteRange range)
        {
            if (range == null)
            {
                return false;
            }

            try
            {
                this.session.Send(range);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }