Example #1
0
 public override void Export(ContactWriter writer, Contact contact, OutboundVCardConverter.PropertyExporter.Context context)
 {
     byte[][] array = contact.TryGetProperty(InternalSchema.UserX509Certificates) as byte[][];
     if (array != null)
     {
         foreach (byte[] array3 in array)
         {
             if (array3 != null)
             {
                 writer.StartProperty(PropertyId.Key);
                 writer.WriteParameter(ParameterId.Type, "X509");
                 writer.WriteParameter(ParameterId.Encoding, "B");
                 using (MemoryStream memoryStream = new MemoryStream())
                 {
                     using (Stream stream = new EncoderStream(new StreamWrapper(memoryStream, false), new Base64Encoder(0), EncoderStreamAccess.Write))
                     {
                         stream.Write(array3, 0, array3.Length);
                     }
                     memoryStream.Position = 0L;
                     writer.WritePropertyValue(memoryStream);
                 }
             }
         }
     }
 }
Example #2
0
        internal static bool TryGetFileNameFromBinHex(MimePart mimePart, ref string fileName)
        {
            string text;

            using (Stream rawContentReadStream = mimePart.GetRawContentReadStream())
            {
                try
                {
                    BinHexDecoder binHexDecoder = new BinHexDecoder();
                    using (EncoderStream encoderStream = new EncoderStream(rawContentReadStream, binHexDecoder, EncoderStreamAccess.Read))
                    {
                        byte[] array = new byte[256];
                        encoderStream.Read(array, 0, array.Length);
                        text = binHexDecoder.MacBinaryHeader.FileName;
                    }
                }
                catch (ByteEncoderException)
                {
                    text = null;
                }
            }
            if (string.IsNullOrEmpty(text))
            {
                return(false);
            }
            fileName = text;
            return(true);
        }
Example #3
0
        public void SylvanEncoderStream()
        {
            using var ms = new PooledMemoryStream();
            var es = new EncoderStream(ms, new Base64Encoder());

            es.Write(inputData, 0, inputData.Length);
            es.Close();
        }
Example #4
0
 static void WriteVersionNum()
 {
     using (MemoryStream stream = new MemoryStream())
     {
         byte[] byteArray = System.Text.Encoding.Default.GetBytes(VersionManager.VersionNum);
         stream.Write(byteArray, 0, byteArray.Length);
         EncoderStream.Encoder(VersionManager.strCueOutPath + "/VersionNum.encoder", stream);
     }
 }
Example #5
0
 public override bool FilterPartBody(MimePart part, Stream stream)
 {
     if (this.embedded)
     {
         EightToSevenBitConverter.Convert(part.GetRawContentReadStream(), stream);
         this.embedded = false;
         return(true);
     }
     if (this.encoder != null)
     {
         using (Stream stream2 = new EncoderStream(part.GetRawContentReadStream(), this.encoder, EncoderStreamAccess.Read))
         {
             DataStorage.CopyStreamToStream(stream2, stream, long.MaxValue, ref this.scratchBuffer);
             this.encoder = null;
             return(true);
         }
         return(false);
     }
     return(false);
 }
Example #6
0
        static void Process()
        {
            InitXML();
            m_lstResourceList = new List <AutoPb.ResourceItem>();

            foreach (Common.AeestStruce item in m_AssetList)
            {
                ProcessFile(item);
            }

            m_XMlDoc.Save(VersionManager.strCueOutPath + "/version.xml");

            using (MemoryStream memoryStream = new MemoryStream())
            {
                ProtoBuf.Serializer.Serialize <List <AutoPb.ResourceItem> >(memoryStream, m_lstResourceList);

                EncoderStream.Encoder(VersionManager.strCueOutPath + "/SourceList.encoder", memoryStream);
            }

            WriteVersionNum();
        }
Example #7
0
 public override void Export(ContactWriter writer, Contact contact, OutboundVCardConverter.PropertyExporter.Context context)
 {
     foreach (AttachmentHandle handle in contact.AttachmentCollection)
     {
         using (Attachment attachment = contact.AttachmentCollection.Open(handle, null))
         {
             if (attachment.IsContactPhoto)
             {
                 StreamAttachment streamAttachment = attachment as StreamAttachment;
                 if (streamAttachment != null)
                 {
                     string text = streamAttachment.ContentType;
                     if (string.IsNullOrEmpty(text))
                     {
                         text = streamAttachment.CalculatedContentType;
                     }
                     string value = null;
                     if (!string.IsNullOrEmpty(text) && OutboundVCardConverter.PhotoExporter.contentTypeToType.TryGetValue(text, out value))
                     {
                         using (Stream stream = streamAttachment.TryGetContentStream(PropertyOpenMode.ReadOnly))
                         {
                             if (stream != null)
                             {
                                 writer.StartProperty(PropertyId.Photo);
                                 writer.WriteParameter(ParameterId.Type, value);
                                 writer.WriteParameter(ParameterId.Encoding, "B");
                                 using (Stream stream2 = new EncoderStream(stream, new Base64Encoder(0), EncoderStreamAccess.Read))
                                 {
                                     writer.WritePropertyValue(stream2);
                                     break;
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
Example #8
0
        internal async Task InnerProcessRequestsAsync <TContext>(IHttpApplication <TContext> application)
        {
            // Start other three unidirectional streams here.
            var controlTask = CreateControlStream(application);
            var encoderTask = CreateEncoderStream(application);
            var decoderTask = CreateDecoderStream(application);

            try
            {
                while (true)
                {
                    var streamContext = await _multiplexedContext.AcceptAsync();

                    if (streamContext == null || _haveSentGoAway)
                    {
                        break;
                    }

                    var quicStreamFeature = streamContext.Features.Get <IStreamDirectionFeature>();
                    var streamIdFeature   = streamContext.Features.Get <IStreamIdFeature>();

                    Debug.Assert(quicStreamFeature != null);

                    var httpConnectionContext = new Http3StreamContext
                    {
                        ConnectionId  = streamContext.ConnectionId,
                        StreamContext = streamContext,
                        // TODO connection context is null here. Should we set it to anything?
                        ServiceContext     = _context.ServiceContext,
                        ConnectionFeatures = streamContext.Features,
                        MemoryPool         = _context.MemoryPool,
                        Transport          = streamContext.Transport,
                        TimeoutControl     = _context.TimeoutControl,
                        LocalEndPoint      = streamContext.LocalEndPoint as IPEndPoint,
                        RemoteEndPoint     = streamContext.RemoteEndPoint as IPEndPoint
                    };

                    if (!quicStreamFeature.CanWrite)
                    {
                        // Unidirectional stream
                        var stream = new Http3ControlStream <TContext>(application, this, httpConnectionContext);
                        ThreadPool.UnsafeQueueUserWorkItem(stream, preferLocal: false);
                    }
                    else
                    {
                        // Keep track of highest stream id seen for GOAWAY
                        var streamId = streamIdFeature.StreamId;
                        HighestStreamId = streamId;

                        var http3Stream = new Http3Stream <TContext>(application, this, httpConnectionContext);
                        var stream      = http3Stream;
                        lock (_streams)
                        {
                            _streams[streamId] = http3Stream;
                        }
                        KestrelEventSource.Log.RequestQueuedStart(stream, AspNetCore.Http.HttpProtocol.Http3);
                        ThreadPool.UnsafeQueueUserWorkItem(stream, preferLocal: false);
                    }
                }
            }
            finally
            {
                // Abort all streams as connection has shutdown.
                lock (_streams)
                {
                    foreach (var stream in _streams.Values)
                    {
                        stream.Abort(new ConnectionAbortedException("Connection is shutting down."));
                    }
                }

                ControlStream?.Abort(new ConnectionAbortedException("Connection is shutting down."));
                EncoderStream?.Abort(new ConnectionAbortedException("Connection is shutting down."));
                DecoderStream?.Abort(new ConnectionAbortedException("Connection is shutting down."));

                await controlTask;
                await encoderTask;
                await decoderTask;
            }
        }
        // Token: 0x06000107 RID: 263 RVA: 0x000041B0 File Offset: 0x000023B0
        public Stream GetAttachmentStream(AttachmentHandler.IAttachmentRetriever attachmentRetriever, AttachmentHandler.IAttachmentPolicyChecker policyChecker, bool asDataUri)
        {
            ExTraceGlobals.AttachmentHandlingTracer.TraceDebug <string>((long)this.GetHashCode(), "AttachmentHandler.GetAttachmentStream: Getting attachment stream for id={0}", this.id);
            if (string.IsNullOrEmpty(this.id))
            {
                ExTraceGlobals.AttachmentHandlingTracer.TraceDebug((long)this.GetHashCode(), "Attachment id is empty or null. returning null stream.");
                throw new FaultException("Id cannot be null or empty.");
            }
            Stream      stream      = null;
            ByteEncoder byteEncoder = null;
            Stream      stream2     = null;
            Stream      result;

            try
            {
                Attachment            attachment = attachmentRetriever.Attachment;
                AttachmentPolicyLevel policy     = policyChecker.GetPolicy(attachment, this.webOperationContext.IsPublicLogon);
                if (AudioFile.IsProtectedVoiceAttachment(attachment.FileName))
                {
                    attachment.ContentType = Utils.GetUnProtectedVoiceAttachmentContentType(attachment.FileName);
                    stream = DRMUtils.OpenProtectedAttachment(attachment, this.callContext.AccessingADUser.OrganizationId);
                    string fileName;
                    if (AudioFile.TryGetNonDRMFileNameFromDRM(attachment.FileName, out fileName))
                    {
                        attachment.FileName = fileName;
                    }
                }
                string        text          = AttachmentUtilities.GetContentType(attachment);
                string        fileExtension = attachment.FileExtension;
                OleAttachment oleAttachment = attachment as OleAttachment;
                if (oleAttachment != null)
                {
                    stream = oleAttachment.ConvertToImage(ImageFormat.Jpeg);
                    if (stream != null)
                    {
                        text = "image/jpeg";
                    }
                }
                if (this.IsBlocked(policy) && !attachment.IsInline && !this.IsImagePreview)
                {
                    ExTraceGlobals.AttachmentHandlingTracer.TraceDebug <string>((long)this.GetHashCode(), "Attachment is blocked. Returning null stream. id is {0}", this.id);
                    result = null;
                }
                else
                {
                    this.WriteResponseHeaders(text, policy, attachment);
                    if (stream == null)
                    {
                        StreamAttachment streamAttachment = attachment as StreamAttachment;
                        if (streamAttachment != null)
                        {
                            if (string.Equals(text, "audio/mpeg", StringComparison.OrdinalIgnoreCase))
                            {
                                stream = streamAttachment.GetContentStream(PropertyOpenMode.Modify);
                            }
                            else
                            {
                                stream = streamAttachment.GetContentStream(PropertyOpenMode.ReadOnly);
                            }
                        }
                        else
                        {
                            ItemAttachment itemAttachment = attachment as ItemAttachment;
                            if (itemAttachment != null)
                            {
                                using (Item item = itemAttachment.GetItem(StoreObjectSchema.ContentConversionProperties))
                                {
                                    IRecipientSession         adrecipientSession        = item.Session.GetADRecipientSession(true, ConsistencyMode.IgnoreInvalid);
                                    OutboundConversionOptions outboundConversionOptions = new OutboundConversionOptions(this.callContext.DefaultDomain.DomainName.Domain);
                                    outboundConversionOptions.ClearCategories = false;
                                    outboundConversionOptions.UserADSession   = adrecipientSession;
                                    outboundConversionOptions.LoadPerOrganizationCharsetDetectionOptions(adrecipientSession.SessionSettings.CurrentOrganizationId);
                                    stream = new MemoryStream();
                                    ItemConversion.ConvertItemToMime(item, stream, outboundConversionOptions);
                                    stream.Seek(0L, SeekOrigin.Begin);
                                }
                            }
                        }
                    }
                    long num  = 0L;
                    long num2 = 0L;
                    if (AttachmentUtilities.NeedToFilterHtml(text, fileExtension, policy, this.configurationContext))
                    {
                        stream = AttachmentUtilities.GetFilteredStream(this.configurationContext, stream, attachment.TextCharset, attachmentRetriever.BlockStatus);
                    }
                    else if (this.NeedToSendPartialContent(stream, out num, out num2))
                    {
                        string value = string.Format(CultureInfo.InvariantCulture, "bytes {0}-{1}/{2}", new object[]
                        {
                            num,
                            num2,
                            stream.Length
                        });
                        this.webOperationContext.Headers["Accept-Ranges"] = "bytes";
                        this.webOperationContext.Headers["Content-Range"] = value;
                        this.webOperationContext.ETag       = this.id;
                        this.webOperationContext.StatusCode = HttpStatusCode.PartialContent;
                        long num3 = num2 - num + 1L;
                        if (num3 < stream.Length)
                        {
                            ExTraceGlobals.AttachmentHandlingTracer.TraceDebug <long, long, long>((long)this.GetHashCode(), "RangeBytes:{0} - Seek:{1} - SetLength:{2}", num3, num, num2 + 1L);
                            stream.Seek(num, SeekOrigin.Begin);
                            return(new BoundedStream(stream, true, num, num2));
                        }
                    }
                    if (asDataUri)
                    {
                        byteEncoder = new Base64Encoder();
                        stream2     = new EncoderStream(stream, byteEncoder, EncoderStreamAccess.Read);
                        stream      = new DataUriStream(stream2, text);
                    }
                    result = stream;
                }
            }
            catch (Exception ex)
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
                if (stream2 != null)
                {
                    stream2.Dispose();
                }
                if (byteEncoder != null)
                {
                    byteEncoder.Dispose();
                }
                string formatString = string.Empty;
                if (ex is ExchangeDataException)
                {
                    formatString = "Fail to sanitize HTML getting attachment. id is {0}, Exception: {1}";
                }
                else if (ex is StoragePermanentException)
                {
                    formatString = "StoragePermanentException when getting attachment. id is {0}, Exception: {1}";
                }
                else
                {
                    if (!(ex is StorageTransientException))
                    {
                        throw;
                    }
                    formatString = "StorageTransientException when getting attachment. id is {0}, Exception: {1}";
                }
                ExTraceGlobals.AttachmentHandlingTracer.TraceError <string, Exception>((long)this.GetHashCode(), formatString, this.id, ex);
                throw new CannotOpenFileAttachmentException(ex);
            }
            return(result);
        }
Example #10
0
        static void Main(string[] args)
        {
            #region Test1

            IAbstractValue[] Test1_InitialDataArray = new IAbstractValue[] { new IntValue(685000), new StringValue("Hello!") };
            TableValue       Test1_InitialData      = TableValue.ArrayToTable(Test1_InitialDataArray);

            Console.WriteLine("Begin Test 1");
            Console.WriteLine();

            EncoderStream Test1_EnStream = new EncoderStream();
            string        Test1_EncodeResult;

            Console.Write("Encoding...");
            Test1_EnStream.InputValue(Test1_InitialData);
            Test1_EncodeResult = Test1_EnStream.PopOutput();
            Console.WriteLine(" Done!");
            Console.WriteLine(string.Concat("Encode Result: ", Test1_EncodeResult));

            Console.WriteLine();
            Console.WriteLine("End Test 1");

            #endregion

            Console.WriteLine();

            #region Test2

            // The string that was in the Specification.odt document.
            string Test2_InitialString = "[\"My name is PC!\";800;]||[\"Data1\":0.56;\"Data2\":\"true \\| false\";]||[[\"My home.\";T;1000;F;];]||";

            Console.WriteLine("Begin Test 2");
            Console.WriteLine();
            Console.WriteLine(string.Concat("Initial String: ", Test2_InitialString));
            Console.WriteLine();

            DecoderStream    Test2_DeStream = new DecoderStream();
            EncoderStream    Test2_EnStream = new EncoderStream();
            IAbstractValue[] Test2_DecodeResult;
            string           Test2_EncodeResult;

            Console.Write("Decoding...");
            Test2_DeStream.InputValue(Test2_InitialString);
            Test2_DeStream.RunParser();
            Test2_DecodeResult = Test2_DeStream.PopOutput(); // ((TableValue)Test2_DeStream.PopOutput()[0]).Value;
            Console.WriteLine(" Done!");
            Console.Write("Encoding...");
            foreach (var item in Test2_DecodeResult)
            {
                Test2_EnStream.InputValue(item);
            }
            Test2_EncodeResult = Test2_EnStream.PopOutput();
            Console.WriteLine(" Done!");

            Console.WriteLine();
            Console.WriteLine(string.Concat("Encode Result: ", Test2_EncodeResult));
            Console.WriteLine(string.Concat("Strings Match: ", (Test2_InitialString == Test2_EncodeResult).ToString()));
            Console.WriteLine();
            Console.WriteLine("End Test 2");

            #endregion

            Console.WriteLine();
            Console.WriteLine("Exiting Program...");

            return;
        }
Example #11
0
            public Stream BeginWriteFile(IArchiveWriterEntry file)
            {
                FinishCurrentFile();

                if (file == null)
                    throw new ArgumentNullException("file");

                mCurrentFile = new FileEntry
                {
                    Name = file.Name,
                    CTime = EnsureUTC(file.CreationTime),
                    MTime = EnsureUTC(file.LastWriteTime),
                    ATime = EnsureUTC(file.LastAccessTime),
                };

                var attributes = file.Attributes;
                if (attributes.HasValue)
                    mCurrentFile.Flags = (uint)attributes.Value;

                if (mWriter == null && mBuffer == null)
                    mBuffer = new FragmentedMemoryStream();

                if (mEncryption != null)
                    mEncryptionEncoder = mEncryption.CreateEncoder();

                return mCurrentStream = new EncoderStream(this);
            }
Example #12
0
            private void FinishCurrentFile()
            {
                if (mCurrentFile != null)
                {
                    mCurrentStream.Close(mCurrentFile);
                    mCurrentStream = null;

                    if (mFiles == null)
                        mFiles = new List<FileEntry>();

                    mFiles.Add(mCurrentFile);
                    mCurrentFile = null;
                }
            }
Example #13
0
        public static void Convert(Stream source, Stream destination)
        {
            int i = 0;

            byte[][] array  = null;
            byte[]   array2 = null;
            using (Stream stream = new SuppressCloseStream(source))
            {
                using (MimeReader mimeReader = new MimeReader(stream, true, DecodingOptions.Default, MimeLimits.Unlimited, true, false))
                {
                    while (mimeReader.ReadNextPart())
                    {
                        while (i >= mimeReader.Depth)
                        {
                            byte[] array3 = array[--i];
                            if (array3 != null)
                            {
                                destination.Write(array3, 0, array3.Length - 2);
                                destination.Write(MimeString.TwoDashesCRLF, 0, MimeString.TwoDashesCRLF.Length);
                            }
                        }
                        if (i > 0)
                        {
                            byte[] array3 = array[i - 1];
                            if (array3 != null)
                            {
                                destination.Write(array3, 0, array3.Length);
                            }
                        }
                        HeaderList        headerList        = HeaderList.ReadFrom(mimeReader);
                        ContentTypeHeader contentTypeHeader = headerList.FindFirst(HeaderId.ContentType) as ContentTypeHeader;
                        bool flag;
                        bool flag2;
                        bool flag3;
                        EightToSevenBitConverter.Analyse(contentTypeHeader, out flag, out flag2, out flag3);
                        Header header = headerList.FindFirst(HeaderId.ContentTransferEncoding);
                        if (flag2 || flag)
                        {
                            if (header != null)
                            {
                                headerList.RemoveChild(header);
                            }
                            headerList.WriteTo(destination);
                            byte[] array3;
                            if (flag)
                            {
                                array3 = null;
                                destination.Write(MimeString.CrLf, 0, MimeString.CrLf.Length);
                            }
                            else
                            {
                                array3 = MimePart.GetBoundary(contentTypeHeader);
                            }
                            if (array == null)
                            {
                                array = new byte[4][];
                            }
                            else if (array.Length == i)
                            {
                                byte[][] array4 = new byte[array.Length * 2][];
                                Array.Copy(array, 0, array4, 0, i);
                                array = array4;
                            }
                            array[i++] = array3;
                        }
                        else
                        {
                            Stream stream2 = null;
                            try
                            {
                                stream2 = mimeReader.GetRawContentReadStream();
                                if (header != null && stream2 != null)
                                {
                                    ContentTransferEncoding encodingType = MimePart.GetEncodingType(header.FirstRawToken);
                                    if (encodingType == ContentTransferEncoding.EightBit || encodingType == ContentTransferEncoding.Binary)
                                    {
                                        if (flag3)
                                        {
                                            header.RawValue = MimeString.QuotedPrintable;
                                            stream2         = new EncoderStream(stream2, new QPEncoder(), EncoderStreamAccess.Read);
                                        }
                                        else
                                        {
                                            header.RawValue = MimeString.Base64;
                                            stream2         = new EncoderStream(stream2, new Base64Encoder(), EncoderStreamAccess.Read);
                                        }
                                    }
                                }
                                headerList.WriteTo(destination);
                                destination.Write(MimeString.CrLf, 0, MimeString.CrLf.Length);
                                if (stream2 != null)
                                {
                                    DataStorage.CopyStreamToStream(stream2, destination, long.MaxValue, ref array2);
                                }
                            }
                            finally
                            {
                                if (stream2 != null)
                                {
                                    stream2.Dispose();
                                }
                            }
                        }
                    }
                    while (i > 0)
                    {
                        byte[] array3 = array[--i];
                        if (array3 != null)
                        {
                            destination.Write(array3, 0, array3.Length - 2);
                            destination.Write(MimeString.TwoDashesCRLF, 0, MimeString.TwoDashesCRLF.Length);
                        }
                    }
                }
            }
        }
Example #14
0
        public async Task ProcessRequestsAsync <TContext>(IHttpApplication <TContext> application)
        {
            var streamListenerFeature = Context.ConnectionFeatures.Get <IQuicStreamListenerFeature>();

            // Start other three unidirectional streams here.
            var controlTask = CreateControlStream(application);
            var encoderTask = CreateEncoderStream(application);
            var decoderTask = CreateDecoderStream(application);

            try
            {
                while (true)
                {
                    var connectionContext = await streamListenerFeature.AcceptAsync();

                    if (connectionContext == null || _haveSentGoAway)
                    {
                        break;
                    }

                    var httpConnectionContext = new HttpConnectionContext
                    {
                        ConnectionId       = connectionContext.ConnectionId,
                        ConnectionContext  = connectionContext,
                        Protocols          = Context.Protocols,
                        ServiceContext     = Context.ServiceContext,
                        ConnectionFeatures = connectionContext.Features,
                        MemoryPool         = Context.MemoryPool,
                        Transport          = connectionContext.Transport,
                        TimeoutControl     = Context.TimeoutControl,
                        LocalEndPoint      = connectionContext.LocalEndPoint as IPEndPoint,
                        RemoteEndPoint     = connectionContext.RemoteEndPoint as IPEndPoint
                    };

                    var streamFeature = httpConnectionContext.ConnectionFeatures.Get <IQuicStreamFeature>();

                    if (!streamFeature.CanWrite)
                    {
                        // Unidirectional stream
                        var stream = new Http3ControlStream <TContext>(application, this, httpConnectionContext);
                        ThreadPool.UnsafeQueueUserWorkItem(stream, preferLocal: false);
                    }
                    else
                    {
                        // Keep track of highest stream id seen for GOAWAY
                        var streamId = streamFeature.StreamId;

                        HighestStreamId = streamId;

                        var http3Stream = new Http3Stream <TContext>(application, this, httpConnectionContext);
                        var stream      = http3Stream;
                        _streams[streamId] = http3Stream;
                        ThreadPool.UnsafeQueueUserWorkItem(stream, preferLocal: false);
                    }
                }
            }
            finally
            {
                // Abort all streams as connection has shutdown.
                foreach (var stream in _streams.Values)
                {
                    stream.Abort(new ConnectionAbortedException("Connection is shutting down."));
                }

                ControlStream.Abort(new ConnectionAbortedException("Connection is shutting down."));
                EncoderStream.Abort(new ConnectionAbortedException("Connection is shutting down."));
                DecoderStream.Abort(new ConnectionAbortedException("Connection is shutting down."));

                await controlTask;
                await encoderTask;
                await decoderTask;
            }
        }