Exemplo n.º 1
0
        public string Lookup(string query, string queryType, HeaderFlags queryOptions = HeaderFlags.RecursionDesired)
        {
            UdpClient udpChannel = null;
            try
            {
                udpChannel = new UdpClient(LOCAL_PORT);
                Message dnsRequest = new Message(queryOptions);
                dnsRequest.AddQuery(query, (RecordType) Enum.Parse(typeof (RecordType), queryType, true));
                byte[] requestDatagram = dnsRequest.AsByteArray();
                int sendResult = udpChannel.Send(requestDatagram, requestDatagram.Length, _serverEndpoint);
                    // Verify sendResult and throw exception if required..

                byte[] responseDatagram = udpChannel.Receive(ref _serverEndpoint);
                Message dnsResponse = new Message(responseDatagram);

                Debug.Assert(dnsResponse.IsForRequest(dnsRequest));
                    // Could make it an [if(isForRequest) ... else retry/throw] if required..

                return dnsResponse.AsString();
            }
            finally
            {
                if(udpChannel != null)
                    udpChannel.Close();
            }
        }
Exemplo n.º 2
0
 public Footer(Header header)
 {
     this.major_version = header.MajorVersion;
     this.revision_number = header.RevisionNumber;
     this.flags = (HeaderFlags) ((byte) (header.Flags | HeaderFlags.FooterPresent));
     this.tag_size = header.TagSize;
 }
Exemplo n.º 3
0
      public Footer (ByteVector data)
      {
         if (data.Count < Size)
            throw new CorruptFileException ("Provided data is smaller than object size.");
         
         if (!data.StartsWith (FileIdentifier))
            throw new CorruptFileException ("Provided data does not start with File Identifier");
         
         major_version   = data [3];
         revision_number = data [4];
         flags           = (HeaderFlags) data [5];
         
         
         if (major_version == 2 && (flags & (HeaderFlags) 127) != 0)
            throw new CorruptFileException ("Invalid flags set on version 2 tag.");
         
         if (major_version == 3 && (flags & (HeaderFlags) 15) != 0)
            throw new CorruptFileException ("Invalid flags set on version 3 tag.");
         
         if (major_version == 4 && (flags & (HeaderFlags) 7) != 0)
            throw new CorruptFileException ("Invalid flags set on version 4 tag.");
         
         
         ByteVector size_data = data.Mid (6, 4);
         
         foreach (byte b in size_data)
            if (b >= 128)
               throw new CorruptFileException ("One of the bytes in the header was greater than the allowed 128.");

         tag_size = SynchData.ToUInt (size_data);
      }
Exemplo n.º 4
0
 public Message(HeaderFlags flags = (HeaderFlags) 0)
 {
     _header = new Header(flags);
     _queries = new Queries();
     _answers = new Answers();
     _authorityResourceRecords = new AuthorityResourceRecords();
     _additionalInformationRecords = new AdditionalInformationRecords();
 }
Exemplo n.º 5
0
 public Header(HeaderFlags flags = (HeaderFlags) 0)
 {
     this._flags = flags;
     _id = 0;
     _queryCount = 0;
     _answerCount = 0;
     _authorityResourceRecordCount = 0;
     _additionalResourceRecordCount = 0;
 }
Exemplo n.º 6
0
		public void Deserialize(Stream input, Endian endian) {
			this.Size = input.ReadValueU32(endian);
			this.Flags = input.ReadValueEnum<HeaderFlags>(endian);
			this.Height = input.ReadValueS32(endian);
			this.Width = input.ReadValueS32(endian);
			this.PitchOrLinearSize = input.ReadValueU32(endian);
			this.Depth = input.ReadValueU32(endian);
			this.MipMapCount = input.ReadValueU32(endian);
			if (input.Read(this.Reserved1, 0, this.Reserved1.Length) != this.Reserved1.Length) {
				throw new EndOfStreamException();
			}
			this.PixelFormat.Deserialize(input, endian);
			this.SurfaceFlags = input.ReadValueU32(endian);
			this.CubemapFlags = input.ReadValueU32(endian);
			if (input.Read(this.Reserved2, 0, this.Reserved2.Length) != this.Reserved2.Length) {
				throw new EndOfStreamException();
			}
		}
Exemplo n.º 7
0
 public Footer(ByteVector data)
 {
     if (data == null)
     {
         throw new ArgumentNullException("data");
     }
     if (data.Count < 10L)
     {
         throw new CorruptFileException("Provided data is smaller than object size.");
     }
     if (!data.StartsWith(FileIdentifier))
     {
         throw new CorruptFileException("Provided data does not start with the file identifier");
     }
     this.major_version = data[3];
     this.revision_number = data[4];
     this.flags = (HeaderFlags) data[5];
     if ((this.major_version == 2) && ((((int) this.flags) & 0x7f) != 0))
     {
         throw new CorruptFileException("Invalid flags set on version 2 tag.");
     }
     if ((this.major_version == 3) && ((((int) this.flags) & 15) != 0))
     {
         throw new CorruptFileException("Invalid flags set on version 3 tag.");
     }
     if ((this.major_version == 4) && ((((int) this.flags) & 7) != 0))
     {
         throw new CorruptFileException("Invalid flags set on version 4 tag.");
     }
     for (int i = 6; i < 10; i++)
     {
         if (data[i] >= 0x80)
         {
             throw new CorruptFileException("One of the bytes in the header was greater than the allowed 128.");
         }
     }
     this.tag_size = SynchData.ToUInt(data.Mid(6, 4));
 }
Exemplo n.º 8
0
		/// <summary>
		///    Constructs and initializes a new instance of <see
		///    cref="Header" /> by reading it from raw header data.
		/// </summary>
		/// <param name="data">
		///    A <see cref="ByteVector" /> object containing the raw
		///    data to build the new instance from.
		/// </param>
		/// <exception cref="ArgumentNullException">
		///    <paramref name="data" /> is <see langword="null" />.
		/// </exception>
		/// <exception cref="CorruptFileException">
		///    <paramref name="data" /> is smaller than <see
		///    cref="Size" />, does not begin with <see
		///    cref="FileIdentifier" />, contains invalid flag data,
		///    or contains invalid size data.
		/// </exception>
		public Header (ByteVector data)
		{
			if (data == null)
				throw new ArgumentNullException ("data");
			
			if (data.Count < Size)
				throw new CorruptFileException (
					"Provided data is smaller than object size.");
			
			if (!data.StartsWith (FileIdentifier))
				throw new CorruptFileException (
					"Provided data does not start with the file identifier");
			
			major_version = data [3];
			revision_number = data [4];
			flags = (HeaderFlags) data [5];
			
			if (major_version == 2 && ((int) flags & 127) != 0)
				throw new CorruptFileException (
					"Invalid flags set on version 2 tag.");
			
			if (major_version == 3 && ((int) flags & 15) != 0)
				throw new CorruptFileException (
					"Invalid flags set on version 3 tag.");
			
			if (major_version == 4 && ((int) flags & 7) != 0)
				throw new CorruptFileException (
					"Invalid flags set on version 4 tag.");
			
			for (int i = 6; i < 10; i ++)
				if (data [i] >= 128)
					throw new CorruptFileException (
						"One of the bytes in the header was greater than the allowed 128.");
			
			tag_size = SynchData.ToUInt (data.Mid (6, 4));
		}
Exemplo n.º 9
0
		/// <summary>
		///    Constructs and intializes a new instance of <see
		///    cref="Footer" /> by reading in the contents of the header
		///    object used for the same tag.
		/// </summary>
		/// <param name="header">
		///    A <see cref="Header" /> object to base the new instance
		///    off of.
		/// </param>
		public Footer (Header header)
		{
			major_version = header.MajorVersion;
			revision_number = header.RevisionNumber;
			flags = header.Flags | HeaderFlags.FooterPresent;
			tag_size = header.TagSize;
		}
Exemplo n.º 10
0
 /// <summary>
 /// Writes to a header flag.
 /// </summary>
 /// <param name="address">
 /// The memory address.
 /// </param>
 /// <param name="flag">
 /// The header flag.
 /// </param>
 /// <param name="value">
 /// The value to write.
 /// </param>
 protected void WriteHeaderFlag(int address, HeaderFlags flag, bool value)
 {
     this.Memory.WriteFlags(address, (byte)flag, value);
 }
Exemplo n.º 11
0
 /// <summary>
 /// Reads a header flag.
 /// </summary>
 /// <param name="address">
 /// Memory address.
 /// </param>
 /// <param name="flag">
 /// The header flag.
 /// </param>
 /// <returns>
 /// Flag value.
 /// </returns>
 protected bool ReadHeaderFlag(int address, HeaderFlags flag)
 {
     return this.Memory.ReadFlags(address, (byte)flag);
 }
Exemplo n.º 12
0
 public int Parse(byte[] datagram)
 {
     _id = datagram.ToUInt16(0);
     _flags = (HeaderFlags) datagram.ToUInt16(2);
     _queryCount = datagram.ToUInt16(4);
     _answerCount = datagram.ToUInt16(6);
     _authorityResourceRecordCount = datagram.ToUInt16(8);
     _additionalResourceRecordCount = datagram.ToUInt16(10);
     return HEADER_SIZE; // Number of bytes consumed..
 }
Exemplo n.º 13
0
        private int WriteHeader(string filename, ZipWriterEntryOptions zipWriterEntryOptions, ZipCentralDirectoryEntry entry, bool useZip64)
        {
            // We err on the side of caution until the zip specification clarifies how to support this
            if (!OutputStream.CanSeek && useZip64)
            {
                throw new NotSupportedException("Zip64 extensions are not supported on non-seekable streams");
            }

            var explicitZipCompressionInfo = ToZipCompressionMethod(zipWriterEntryOptions.CompressionType ?? compressionType);

            byte[] encodedFilename = WriterOptions.ArchiveEncoding.Encode(filename);

            // TODO: Use stackalloc when we exclusively support netstandard2.1 or higher
            byte[] intBuf = new byte[4];
            BinaryPrimitives.WriteUInt32LittleEndian(intBuf, ZipHeaderFactory.ENTRY_HEADER_BYTES);
            OutputStream.Write(intBuf, 0, 4);
            if (explicitZipCompressionInfo == ZipCompressionMethod.Deflate)
            {
                if (OutputStream.CanSeek && useZip64)
                {
                    OutputStream.Write(new byte[] { 45, 0 }, 0, 2); //smallest allowed version for zip64
                }
                else
                {
                    OutputStream.Write(new byte[] { 20, 0 }, 0, 2); //older version which is more compatible
                }
            }
            else
            {
                OutputStream.Write(new byte[] { 63, 0 }, 0, 2); //version says we used PPMd or LZMA
            }
            HeaderFlags flags = Equals(WriterOptions.ArchiveEncoding.GetEncoding(), Encoding.UTF8) ? HeaderFlags.Efs : 0;

            if (!OutputStream.CanSeek)
            {
                flags |= HeaderFlags.UsePostDataDescriptor;

                if (explicitZipCompressionInfo == ZipCompressionMethod.LZMA)
                {
                    flags |= HeaderFlags.Bit1; // eos marker
                }
            }

            BinaryPrimitives.WriteUInt16LittleEndian(intBuf, (ushort)flags);
            OutputStream.Write(intBuf, 0, 2);
            BinaryPrimitives.WriteUInt16LittleEndian(intBuf, (ushort)explicitZipCompressionInfo);
            OutputStream.Write(intBuf, 0, 2); // zipping method
            BinaryPrimitives.WriteUInt32LittleEndian(intBuf, zipWriterEntryOptions.ModificationDateTime.DateTimeToDosTime());
            OutputStream.Write(intBuf, 0, 4);

            // zipping date and time
            OutputStream.Write(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0, 12);

            // unused CRC, un/compressed size, updated later
            BinaryPrimitives.WriteUInt16LittleEndian(intBuf, (ushort)encodedFilename.Length);
            OutputStream.Write(intBuf, 0, 2); // filename length

            var extralength = 0;

            if (OutputStream.CanSeek && useZip64)
            {
                extralength = 2 + 2 + 8 + 8;
            }

            BinaryPrimitives.WriteUInt16LittleEndian(intBuf, (ushort)extralength);
            OutputStream.Write(intBuf, 0, 2); // extra length
            OutputStream.Write(encodedFilename, 0, encodedFilename.Length);

            if (extralength != 0)
            {
                OutputStream.Write(new byte[extralength], 0, extralength); // reserve space for zip64 data
                entry.Zip64HeaderOffset = (ushort)(6 + 2 + 2 + 4 + 12 + 2 + 2 + encodedFilename.Length);
            }

            return(6 + 2 + 2 + 4 + 12 + 2 + 2 + encodedFilename.Length + extralength);
        }
Exemplo n.º 14
0
        ///////////////////////////////////////////////////////////////////////

        public static HeaderFlags GetHeaderFlags(
            IInteractiveHost interactiveHost,
            HeaderFlags headerFlags,
            bool debug,
            bool show,
            bool empty,
            bool @default
            )
        {
            //
            // NOTE: If we are in debug mode and no header display flags have
            //       been explicitly set for the interpreter, initialize them
            //       to the default value.
            //
            if (@default && FlagOps.HasFlags(
                    headerFlags, HeaderFlags.Invalid, true))
            {
                //
                // NOTE: Remove the "these flags have not been setup before"
                //       indicator flag.
                //
                headerFlags &= ~HeaderFlags.Invalid;

                //
                // NOTE: Add the default header flags for the interactive
                //       host.  If the interactive host is not available,
                //       fallback on the system default header flags.
                //
                HeaderFlags defaultHeaderFlags = HeaderFlags.Default;

                if (interactiveHost != null)
                {
                    headerFlags |= HostOps.GetHeaderFlags(
                        interactiveHost, defaultHeaderFlags);
                }
                else
                {
                    headerFlags |= defaultHeaderFlags;
                }
            }

            //
            // NOTE: Only modify (set or unset) the active debugger flag if we
            //       have been told to do so; otherwise, the active debugger
            //       flag may have been manually changed and should be left
            //       alone.
            //
            if (show)
            {
                //
                // NOTE: Is there an active debugger?
                //
                if (debug)
                {
                    //
                    // NOTE: Set the active debugger flag.
                    //
                    headerFlags |= HeaderFlags.Debug;
                }
                else
                {
                    //
                    // NOTE: Unset the active debugger flag.
                    //
                    headerFlags &= ~HeaderFlags.Debug;
                }
            }

            //
            // NOTE: Show empty content?
            //
            if (empty)
            {
                headerFlags |= HeaderFlags.EmptyContent;
            }

            return(headerFlags);
        }
Exemplo n.º 15
0
        static Headers()
        {
            const int MAX_ENUM_VALUE = 256;

            var knownHeaderType = typeof(KnownHeaderT).GetTypeInfo();

            if (knownHeaderType.IsEnum == false)
            {
                throw new InvalidOperationException("TKnownHeader should be enum type.");
            }
            if (Enum.GetUnderlyingType(typeof(KnownHeaderT)) != typeof(int))
            {
                throw new InvalidOperationException("TKnownHeader should be enum with System.Int32 underlying type.");
            }


            FromInt = (Func <int, KnownHeaderT>)EnumHelper <KnownHeaderT> .FromNumber;
            ToInt   = (Func <KnownHeaderT, int>)EnumHelper <KnownHeaderT> .ToNumber;

            KeyComparer = StringComparer.OrdinalIgnoreCase;

            var enumValues = Enum.GetValues(typeof(KnownHeaderT));
            var names      = Enum.GetNames(typeof(KnownHeaderT));
            var fields     = names.ConvertAll(knownHeaderType.GetDeclaredField);
            var values     = new int[enumValues.Length];
            var flags      = new HeaderFlags[fields.Length];

            for (var i = 0; i < fields.Length; i++)
            {
                var headerAttribute = fields[i].GetCustomAttributes(typeof(HeaderAttribute), false).Cast <HeaderAttribute>().FirstOrDefault();
                var name            = headerAttribute?.Name ?? fields[i].Name;
                var value           = Convert.ToInt32(Enum.ToObject(typeof(KnownHeaderT), enumValues.GetValue(i)));
                var flag            = headerAttribute?.Flags ?? HeaderFlags.None;

                names[i]  = name;
                values[i] = value;
                flags[i]  = flag;
            }

            Array.Sort(values, names); // sort by order

            var firstKnownHeader = values.Min();
            var lastKnownHeader  = values.Max();

            KnownHeadersCapacity = lastKnownHeader + 1;

            if (firstKnownHeader < 0)
            {
                throw new InvalidOperationException("Min value for enum TKnownHeader is 0.");
            }

            if (lastKnownHeader > MAX_ENUM_VALUE)
            {
                throw new InvalidOperationException($"Max value for enum TKnownHeader is {MAX_ENUM_VALUE}.");
            }

            var sortedNames        = new string[names.Length];
            var sortedByNameValues = new int[values.Length];

            var sortedValues       = new int[values.Length];
            var sortedByValueNames = new string[names.Length];
            var sortedByValueFlags = new HeaderFlags[flags.Length];

            // name -> value
            names.CopyTo(sortedNames, 0);
            values.CopyTo(sortedByNameValues, 0);
            // value -> name, flag
            values.CopyTo(sortedValues, 0);

            var sortedByValueIndexes = new int[values.Length];

            for (var i = 0; i < sortedByValueIndexes.Length; i++)
            {
                sortedByValueIndexes[i] = i;
            }

            Array.Sort(sortedNames, sortedByNameValues, KeyComparer);
            Array.Sort(sortedValues, sortedByValueIndexes);

            for (var i = 0; i < sortedByValueNames.Length; i++)
            {
                sortedByValueNames[i] = names[sortedByValueIndexes[i]];
                sortedByValueFlags[i] = flags[sortedByValueIndexes[i]];
            }

            SortedNames        = sortedNames;
            SortedByNameValues = sortedByNameValues;
            SortedValues       = sortedValues;
            SortedByValueNames = sortedByValueNames;
            SortedByValueFlags = sortedByValueFlags;
        }