XmlMtomReader.cs 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.Xml
  5. {
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Globalization;
  9. using System.IO;
  10. using System.Runtime;
  11. using System.Runtime.Serialization;
  12. using System.Text;
  13. using System.Security;
  14. using System.Security.Permissions;
  15. public interface IXmlMtomReaderInitializer
  16. {
  17. void SetInput(byte[] buffer, int offset, int count, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose);
  18. void SetInput(Stream stream, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose);
  19. }
  20. class XmlMtomReader : XmlDictionaryReader, IXmlLineInfo, IXmlMtomReaderInitializer
  21. {
  22. Encoding[] encodings;
  23. XmlDictionaryReader xmlReader;
  24. XmlDictionaryReader infosetReader;
  25. MimeReader mimeReader;
  26. Dictionary<string, MimePart> mimeParts;
  27. OnXmlDictionaryReaderClose onClose;
  28. bool readingBinaryElement;
  29. int maxBufferSize;
  30. int bufferRemaining;
  31. MimePart part;
  32. public XmlMtomReader()
  33. {
  34. }
  35. internal static void DecrementBufferQuota(int maxBuffer, ref int remaining, int size)
  36. {
  37. if (remaining - size <= 0)
  38. {
  39. remaining = 0;
  40. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomBufferQuotaExceeded, maxBuffer)));
  41. }
  42. else
  43. {
  44. remaining -= size;
  45. }
  46. }
  47. void SetReadEncodings(Encoding[] encodings)
  48. {
  49. if (encodings == null)
  50. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encodings");
  51. for (int i = 0; i < encodings.Length; i++)
  52. {
  53. if (encodings[i] == null)
  54. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(String.Format(CultureInfo.InvariantCulture, "encodings[{0}]", i));
  55. }
  56. this.encodings = new Encoding[encodings.Length];
  57. encodings.CopyTo(this.encodings, 0);
  58. }
  59. void CheckContentType(string contentType)
  60. {
  61. if (contentType != null && contentType.Length == 0)
  62. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.MtomContentTypeInvalid), "contentType"));
  63. }
  64. public void SetInput(byte[] buffer, int offset, int count, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose)
  65. {
  66. SetInput(new MemoryStream(buffer, offset, count), encodings, contentType, quotas, maxBufferSize, onClose);
  67. }
  68. public void SetInput(Stream stream, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose)
  69. {
  70. SetReadEncodings(encodings);
  71. CheckContentType(contentType);
  72. Initialize(stream, contentType, quotas, maxBufferSize);
  73. this.onClose = onClose;
  74. }
  75. void Initialize(Stream stream, string contentType, XmlDictionaryReaderQuotas quotas, int maxBufferSize)
  76. {
  77. if (stream == null)
  78. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream");
  79. this.maxBufferSize = maxBufferSize;
  80. this.bufferRemaining = maxBufferSize;
  81. string boundary, start, startInfo;
  82. if (contentType == null)
  83. {
  84. MimeMessageReader messageReader = new MimeMessageReader(stream);
  85. MimeHeaders messageHeaders = messageReader.ReadHeaders(this.maxBufferSize, ref this.bufferRemaining);
  86. ReadMessageMimeVersionHeader(messageHeaders.MimeVersion);
  87. ReadMessageContentTypeHeader(messageHeaders.ContentType, out boundary, out start, out startInfo);
  88. stream = messageReader.GetContentStream();
  89. if (stream == null)
  90. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomMessageInvalidContent)));
  91. }
  92. else
  93. {
  94. ReadMessageContentTypeHeader(new ContentTypeHeader(contentType), out boundary, out start, out startInfo);
  95. }
  96. this.mimeReader = new MimeReader(stream, boundary);
  97. this.mimeParts = null;
  98. this.readingBinaryElement = false;
  99. MimePart infosetPart = (start == null) ? ReadRootMimePart() : ReadMimePart(GetStartUri(start));
  100. byte[] infosetBytes = infosetPart.GetBuffer(this.maxBufferSize, ref this.bufferRemaining);
  101. int infosetByteCount = (int)infosetPart.Length;
  102. Encoding encoding = ReadRootContentTypeHeader(infosetPart.Headers.ContentType, this.encodings, startInfo);
  103. CheckContentTransferEncodingOnRoot(infosetPart.Headers.ContentTransferEncoding);
  104. IXmlTextReaderInitializer initializer = xmlReader as IXmlTextReaderInitializer;
  105. if (initializer != null)
  106. initializer.SetInput(infosetBytes, 0, infosetByteCount, encoding, quotas, null);
  107. else
  108. xmlReader = XmlDictionaryReader.CreateTextReader(infosetBytes, 0, infosetByteCount, encoding, quotas, null);
  109. }
  110. public override XmlDictionaryReaderQuotas Quotas
  111. {
  112. get
  113. {
  114. return this.xmlReader.Quotas;
  115. }
  116. }
  117. void ReadMessageMimeVersionHeader(MimeVersionHeader header)
  118. {
  119. if (header != null && header.Version != MimeVersionHeader.Default.Version)
  120. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomMessageInvalidMimeVersion, header.Version, MimeVersionHeader.Default.Version)));
  121. }
  122. void ReadMessageContentTypeHeader(ContentTypeHeader header, out string boundary, out string start, out string startInfo)
  123. {
  124. if (header == null)
  125. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomMessageContentTypeNotFound)));
  126. if (String.Compare(MtomGlobals.MediaType, header.MediaType, StringComparison.OrdinalIgnoreCase) != 0
  127. || String.Compare(MtomGlobals.MediaSubtype, header.MediaSubtype, StringComparison.OrdinalIgnoreCase) != 0)
  128. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomMessageNotMultipart, MtomGlobals.MediaType, MtomGlobals.MediaSubtype)));
  129. string type;
  130. if (!header.Parameters.TryGetValue(MtomGlobals.TypeParam, out type) || MtomGlobals.XopType != type)
  131. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomMessageNotApplicationXopXml, MtomGlobals.XopType)));
  132. if (!header.Parameters.TryGetValue(MtomGlobals.BoundaryParam, out boundary))
  133. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomMessageRequiredParamNotSpecified, MtomGlobals.BoundaryParam)));
  134. if (!MailBnfHelper.IsValidMimeBoundary(boundary))
  135. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomBoundaryInvalid, boundary)));
  136. if (!header.Parameters.TryGetValue(MtomGlobals.StartParam, out start))
  137. start = null;
  138. if (!header.Parameters.TryGetValue(MtomGlobals.StartInfoParam, out startInfo))
  139. startInfo = null;
  140. }
  141. Encoding ReadRootContentTypeHeader(ContentTypeHeader header, Encoding[] expectedEncodings, string expectedType)
  142. {
  143. if (header == null)
  144. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomRootContentTypeNotFound)));
  145. if (String.Compare(MtomGlobals.XopMediaType, header.MediaType, StringComparison.OrdinalIgnoreCase) != 0
  146. || String.Compare(MtomGlobals.XopMediaSubtype, header.MediaSubtype, StringComparison.OrdinalIgnoreCase) != 0)
  147. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomRootNotApplicationXopXml, MtomGlobals.XopMediaType, MtomGlobals.XopMediaSubtype)));
  148. string charset;
  149. if (!header.Parameters.TryGetValue(MtomGlobals.CharsetParam, out charset)
  150. || charset == null || charset.Length == 0)
  151. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomRootRequiredParamNotSpecified, MtomGlobals.CharsetParam)));
  152. Encoding encoding = null;
  153. for (int i = 0; i < encodings.Length; i++)
  154. {
  155. if (String.Compare(charset, expectedEncodings[i].WebName, StringComparison.OrdinalIgnoreCase) == 0)
  156. {
  157. encoding = expectedEncodings[i];
  158. break;
  159. }
  160. }
  161. if (encoding == null)
  162. {
  163. // Check for alternate names
  164. if (String.Compare(charset, "utf-16LE", StringComparison.OrdinalIgnoreCase) == 0)
  165. {
  166. for (int i = 0; i < encodings.Length; i++)
  167. {
  168. if (String.Compare(expectedEncodings[i].WebName, Encoding.Unicode.WebName, StringComparison.OrdinalIgnoreCase) == 0)
  169. {
  170. encoding = expectedEncodings[i];
  171. break;
  172. }
  173. }
  174. }
  175. else if (String.Compare(charset, "utf-16BE", StringComparison.OrdinalIgnoreCase) == 0)
  176. {
  177. for (int i = 0; i < encodings.Length; i++)
  178. {
  179. if (String.Compare(expectedEncodings[i].WebName, Encoding.BigEndianUnicode.WebName, StringComparison.OrdinalIgnoreCase) == 0)
  180. {
  181. encoding = expectedEncodings[i];
  182. break;
  183. }
  184. }
  185. }
  186. if (encoding == null)
  187. {
  188. StringBuilder expectedCharSetStr = new StringBuilder();
  189. for (int i = 0; i < encodings.Length; i++)
  190. {
  191. if (expectedCharSetStr.Length != 0)
  192. expectedCharSetStr.Append(" | ");
  193. expectedCharSetStr.Append(encodings[i].WebName);
  194. }
  195. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomRootUnexpectedCharset, charset, expectedCharSetStr.ToString())));
  196. }
  197. }
  198. if (expectedType != null)
  199. {
  200. string rootType;
  201. if (!header.Parameters.TryGetValue(MtomGlobals.TypeParam, out rootType)
  202. || rootType == null || rootType.Length == 0)
  203. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomRootRequiredParamNotSpecified, MtomGlobals.TypeParam)));
  204. if (rootType != expectedType)
  205. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomRootUnexpectedType, rootType, expectedType)));
  206. }
  207. return encoding;
  208. }
  209. // 7bit is default encoding in the absence of content-transfer-encoding header
  210. void CheckContentTransferEncodingOnRoot(ContentTransferEncodingHeader header)
  211. {
  212. if (header != null && header.ContentTransferEncoding == ContentTransferEncoding.Other)
  213. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomContentTransferEncodingNotSupported,
  214. header.Value,
  215. ContentTransferEncodingHeader.SevenBit.ContentTransferEncodingValue,
  216. ContentTransferEncodingHeader.EightBit.ContentTransferEncodingValue,
  217. ContentTransferEncodingHeader.Binary.ContentTransferEncodingValue)));
  218. }
  219. void CheckContentTransferEncodingOnBinaryPart(ContentTransferEncodingHeader header)
  220. {
  221. if (header == null)
  222. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomContentTransferEncodingNotPresent,
  223. ContentTransferEncodingHeader.Binary.ContentTransferEncodingValue)));
  224. else if (header.ContentTransferEncoding != ContentTransferEncoding.Binary)
  225. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomInvalidTransferEncodingForMimePart,
  226. header.Value, ContentTransferEncodingHeader.Binary.ContentTransferEncodingValue)));
  227. }
  228. string GetStartUri(string startUri)
  229. {
  230. if (startUri.StartsWith("<", StringComparison.Ordinal))
  231. {
  232. if (startUri.EndsWith(">", StringComparison.Ordinal))
  233. return startUri;
  234. else
  235. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomInvalidStartUri, startUri)));
  236. }
  237. else
  238. return String.Format(CultureInfo.InvariantCulture, "<{0}>", startUri);
  239. }
  240. public override bool Read()
  241. {
  242. bool retVal = xmlReader.Read();
  243. if (xmlReader.NodeType == XmlNodeType.Element)
  244. {
  245. XopIncludeReader binaryDataReader = null;
  246. if (xmlReader.IsStartElement(MtomGlobals.XopIncludeLocalName, MtomGlobals.XopIncludeNamespace))
  247. {
  248. string uri = null;
  249. while (xmlReader.MoveToNextAttribute())
  250. {
  251. if (xmlReader.LocalName == MtomGlobals.XopIncludeHrefLocalName && xmlReader.NamespaceURI == MtomGlobals.XopIncludeHrefNamespace)
  252. uri = xmlReader.Value;
  253. else if (xmlReader.NamespaceURI == MtomGlobals.XopIncludeNamespace)
  254. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomXopIncludeInvalidXopAttributes, xmlReader.LocalName, MtomGlobals.XopIncludeNamespace)));
  255. }
  256. if (uri == null)
  257. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomXopIncludeHrefNotSpecified, MtomGlobals.XopIncludeHrefLocalName)));
  258. MimePart mimePart = ReadMimePart(uri);
  259. CheckContentTransferEncodingOnBinaryPart(mimePart.Headers.ContentTransferEncoding);
  260. this.part = mimePart;
  261. binaryDataReader = new XopIncludeReader(mimePart, xmlReader);
  262. binaryDataReader.Read();
  263. xmlReader.MoveToElement();
  264. if (xmlReader.IsEmptyElement)
  265. {
  266. xmlReader.Read();
  267. }
  268. else
  269. {
  270. int xopDepth = xmlReader.Depth;
  271. xmlReader.ReadStartElement();
  272. while (xmlReader.Depth > xopDepth)
  273. {
  274. if (xmlReader.IsStartElement() && xmlReader.NamespaceURI == MtomGlobals.XopIncludeNamespace)
  275. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomXopIncludeInvalidXopElement, xmlReader.LocalName, MtomGlobals.XopIncludeNamespace)));
  276. xmlReader.Skip();
  277. }
  278. xmlReader.ReadEndElement();
  279. }
  280. }
  281. if (binaryDataReader != null)
  282. {
  283. this.xmlReader.MoveToContent();
  284. this.infosetReader = this.xmlReader;
  285. this.xmlReader = binaryDataReader;
  286. binaryDataReader = null;
  287. }
  288. }
  289. if (xmlReader.ReadState == ReadState.EndOfFile && infosetReader != null)
  290. {
  291. // Read past the containing EndElement if necessary
  292. if (!retVal)
  293. retVal = infosetReader.Read();
  294. this.part.Release(this.maxBufferSize, ref this.bufferRemaining);
  295. xmlReader = infosetReader;
  296. infosetReader = null;
  297. }
  298. return retVal;
  299. }
  300. MimePart ReadMimePart(string uri)
  301. {
  302. MimePart part = null;
  303. if (uri == null || uri.Length == 0)
  304. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomInvalidEmptyURI)));
  305. string contentID = null;
  306. if (uri.StartsWith(MimeGlobals.ContentIDScheme, StringComparison.Ordinal))
  307. contentID = String.Format(CultureInfo.InvariantCulture, "<{0}>", Uri.UnescapeDataString(uri.Substring(MimeGlobals.ContentIDScheme.Length)));
  308. else if (uri.StartsWith("<", StringComparison.Ordinal))
  309. contentID = uri;
  310. if (contentID == null)
  311. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomInvalidCIDUri, uri)));
  312. if (mimeParts != null && mimeParts.TryGetValue(contentID, out part))
  313. {
  314. if (part.ReferencedFromInfoset)
  315. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomMimePartReferencedMoreThanOnce, contentID)));
  316. }
  317. else
  318. {
  319. int maxMimeParts = AppSettings.MaxMimeParts;
  320. while (part == null && mimeReader.ReadNextPart())
  321. {
  322. MimeHeaders headers = mimeReader.ReadHeaders(this.maxBufferSize, ref this.bufferRemaining);
  323. Stream contentStream = mimeReader.GetContentStream();
  324. if (contentStream == null)
  325. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomMessageInvalidContentInMimePart)));
  326. ContentIDHeader contentIDHeader = (headers == null) ? null : headers.ContentID;
  327. if (contentIDHeader == null || contentIDHeader.Value == null)
  328. {
  329. // Skip content if Content-ID header is not present
  330. int size = 256;
  331. byte[] bytes = new byte[size];
  332. int read = 0;
  333. do
  334. {
  335. read = contentStream.Read(bytes, 0, size);
  336. }
  337. while (read > 0);
  338. continue;
  339. }
  340. string currentContentID = headers.ContentID.Value;
  341. MimePart currentPart = new MimePart(contentStream, headers);
  342. if (mimeParts == null)
  343. mimeParts = new Dictionary<string, MimePart>();
  344. mimeParts.Add(currentContentID, currentPart);
  345. if (mimeParts.Count > maxMimeParts)
  346. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MaxMimePartsExceeded, maxMimeParts, AppSettings.MaxMimePartsAppSettingsString)));
  347. if (currentContentID.Equals(contentID))
  348. part = currentPart;
  349. else
  350. currentPart.GetBuffer(this.maxBufferSize, ref this.bufferRemaining);
  351. }
  352. if (part == null)
  353. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomPartNotFound, uri)));
  354. }
  355. part.ReferencedFromInfoset = true;
  356. return part;
  357. }
  358. MimePart ReadRootMimePart()
  359. {
  360. MimePart part = null;
  361. if (!mimeReader.ReadNextPart())
  362. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomRootPartNotFound)));
  363. MimeHeaders headers = mimeReader.ReadHeaders(this.maxBufferSize, ref this.bufferRemaining);
  364. Stream contentStream = mimeReader.GetContentStream();
  365. if (contentStream == null)
  366. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomMessageInvalidContentInMimePart)));
  367. part = new MimePart(contentStream, headers);
  368. return part;
  369. }
  370. void AdvanceToContentOnElement()
  371. {
  372. if (NodeType != XmlNodeType.Attribute)
  373. {
  374. MoveToContent();
  375. }
  376. }
  377. public override int AttributeCount
  378. {
  379. get
  380. {
  381. return xmlReader.AttributeCount;
  382. }
  383. }
  384. public override string BaseURI
  385. {
  386. get
  387. {
  388. return xmlReader.BaseURI;
  389. }
  390. }
  391. public override bool CanReadBinaryContent
  392. {
  393. get
  394. {
  395. return xmlReader.CanReadBinaryContent;
  396. }
  397. }
  398. public override bool CanReadValueChunk
  399. {
  400. get
  401. {
  402. return xmlReader.CanReadValueChunk;
  403. }
  404. }
  405. public override bool CanResolveEntity
  406. {
  407. get
  408. {
  409. return xmlReader.CanResolveEntity;
  410. }
  411. }
  412. public override void Close()
  413. {
  414. xmlReader.Close();
  415. mimeReader.Close();
  416. OnXmlDictionaryReaderClose onClose = this.onClose;
  417. this.onClose = null;
  418. if (onClose != null)
  419. {
  420. try
  421. {
  422. onClose(this);
  423. }
  424. catch (Exception e)
  425. {
  426. if (Fx.IsFatal(e)) throw;
  427. throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
  428. }
  429. }
  430. }
  431. public override int Depth
  432. {
  433. get
  434. {
  435. return xmlReader.Depth;
  436. }
  437. }
  438. public override bool EOF
  439. {
  440. get
  441. {
  442. return xmlReader.EOF;
  443. }
  444. }
  445. public override string GetAttribute(int index)
  446. {
  447. return xmlReader.GetAttribute(index);
  448. }
  449. public override string GetAttribute(string name)
  450. {
  451. return xmlReader.GetAttribute(name);
  452. }
  453. public override string GetAttribute(string name, string ns)
  454. {
  455. return xmlReader.GetAttribute(name, ns);
  456. }
  457. public override string GetAttribute(XmlDictionaryString localName, XmlDictionaryString ns)
  458. {
  459. return xmlReader.GetAttribute(localName, ns);
  460. }
  461. #if NO
  462. public override ArraySegment<byte> GetSubset(bool advance)
  463. {
  464. return xmlReader.GetSubset(advance);
  465. }
  466. #endif
  467. public override bool HasAttributes
  468. {
  469. get
  470. {
  471. return xmlReader.HasAttributes;
  472. }
  473. }
  474. public override bool HasValue
  475. {
  476. get
  477. {
  478. return xmlReader.HasValue;
  479. }
  480. }
  481. public override bool IsDefault
  482. {
  483. get
  484. {
  485. return xmlReader.IsDefault;
  486. }
  487. }
  488. public override bool IsEmptyElement
  489. {
  490. get
  491. {
  492. return xmlReader.IsEmptyElement;
  493. }
  494. }
  495. public override bool IsLocalName(string localName)
  496. {
  497. return xmlReader.IsLocalName(localName);
  498. }
  499. public override bool IsLocalName(XmlDictionaryString localName)
  500. {
  501. return xmlReader.IsLocalName(localName);
  502. }
  503. public override bool IsNamespaceUri(string ns)
  504. {
  505. return xmlReader.IsNamespaceUri(ns);
  506. }
  507. public override bool IsNamespaceUri(XmlDictionaryString ns)
  508. {
  509. return xmlReader.IsNamespaceUri(ns);
  510. }
  511. public override bool IsStartElement()
  512. {
  513. return xmlReader.IsStartElement();
  514. }
  515. public override bool IsStartElement(string localName)
  516. {
  517. return xmlReader.IsStartElement(localName);
  518. }
  519. public override bool IsStartElement(string localName, string ns)
  520. {
  521. return xmlReader.IsStartElement(localName, ns);
  522. }
  523. public override bool IsStartElement(XmlDictionaryString localName, XmlDictionaryString ns)
  524. {
  525. return xmlReader.IsStartElement(localName, ns);
  526. }
  527. #if NO
  528. public override bool IsStartSubsetElement()
  529. {
  530. return xmlReader.IsStartSubsetElement();
  531. }
  532. #endif
  533. public override string LocalName
  534. {
  535. get
  536. {
  537. return xmlReader.LocalName;
  538. }
  539. }
  540. public override string LookupNamespace(string ns)
  541. {
  542. return xmlReader.LookupNamespace(ns);
  543. }
  544. public override void MoveToAttribute(int index)
  545. {
  546. xmlReader.MoveToAttribute(index);
  547. }
  548. public override bool MoveToAttribute(string name)
  549. {
  550. return xmlReader.MoveToAttribute(name);
  551. }
  552. public override bool MoveToAttribute(string name, string ns)
  553. {
  554. return xmlReader.MoveToAttribute(name, ns);
  555. }
  556. public override bool MoveToElement()
  557. {
  558. return xmlReader.MoveToElement();
  559. }
  560. public override bool MoveToFirstAttribute()
  561. {
  562. return xmlReader.MoveToFirstAttribute();
  563. }
  564. public override bool MoveToNextAttribute()
  565. {
  566. return xmlReader.MoveToNextAttribute();
  567. }
  568. public override string Name
  569. {
  570. get
  571. {
  572. return xmlReader.Name;
  573. }
  574. }
  575. public override string NamespaceURI
  576. {
  577. get
  578. {
  579. return xmlReader.NamespaceURI;
  580. }
  581. }
  582. public override XmlNameTable NameTable
  583. {
  584. get
  585. {
  586. return xmlReader.NameTable;
  587. }
  588. }
  589. public override XmlNodeType NodeType
  590. {
  591. get
  592. {
  593. return xmlReader.NodeType;
  594. }
  595. }
  596. public override string Prefix
  597. {
  598. get
  599. {
  600. return xmlReader.Prefix;
  601. }
  602. }
  603. public override char QuoteChar
  604. {
  605. get
  606. {
  607. return xmlReader.QuoteChar;
  608. }
  609. }
  610. public override bool ReadAttributeValue()
  611. {
  612. return xmlReader.ReadAttributeValue();
  613. }
  614. public override object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver)
  615. {
  616. AdvanceToContentOnElement();
  617. return xmlReader.ReadContentAs(returnType, namespaceResolver);
  618. }
  619. public override byte[] ReadContentAsBase64()
  620. {
  621. AdvanceToContentOnElement();
  622. return xmlReader.ReadContentAsBase64();
  623. }
  624. public override int ReadValueAsBase64(byte[] buffer, int offset, int count)
  625. {
  626. AdvanceToContentOnElement();
  627. return xmlReader.ReadValueAsBase64(buffer, offset, count);
  628. }
  629. public override int ReadContentAsBase64(byte[] buffer, int offset, int count)
  630. {
  631. AdvanceToContentOnElement();
  632. return xmlReader.ReadContentAsBase64(buffer, offset, count);
  633. }
  634. public override int ReadElementContentAsBase64(byte[] buffer, int offset, int count)
  635. {
  636. if (!readingBinaryElement)
  637. {
  638. if (IsEmptyElement)
  639. {
  640. Read();
  641. return 0;
  642. }
  643. ReadStartElement();
  644. readingBinaryElement = true;
  645. }
  646. int i = ReadContentAsBase64(buffer, offset, count);
  647. if (i == 0)
  648. {
  649. ReadEndElement();
  650. readingBinaryElement = false;
  651. }
  652. return i;
  653. }
  654. public override int ReadElementContentAsBinHex(byte[] buffer, int offset, int count)
  655. {
  656. if (!readingBinaryElement)
  657. {
  658. if (IsEmptyElement)
  659. {
  660. Read();
  661. return 0;
  662. }
  663. ReadStartElement();
  664. readingBinaryElement = true;
  665. }
  666. int i = ReadContentAsBinHex(buffer, offset, count);
  667. if (i == 0)
  668. {
  669. ReadEndElement();
  670. readingBinaryElement = false;
  671. }
  672. return i;
  673. }
  674. public override int ReadContentAsBinHex(byte[] buffer, int offset, int count)
  675. {
  676. AdvanceToContentOnElement();
  677. return xmlReader.ReadContentAsBinHex(buffer, offset, count);
  678. }
  679. public override bool ReadContentAsBoolean()
  680. {
  681. AdvanceToContentOnElement();
  682. return xmlReader.ReadContentAsBoolean();
  683. }
  684. public override int ReadContentAsChars(char[] chars, int index, int count)
  685. {
  686. AdvanceToContentOnElement();
  687. return xmlReader.ReadContentAsChars(chars, index, count);
  688. }
  689. public override DateTime ReadContentAsDateTime()
  690. {
  691. AdvanceToContentOnElement();
  692. return xmlReader.ReadContentAsDateTime();
  693. }
  694. public override decimal ReadContentAsDecimal()
  695. {
  696. AdvanceToContentOnElement();
  697. return xmlReader.ReadContentAsDecimal();
  698. }
  699. public override double ReadContentAsDouble()
  700. {
  701. AdvanceToContentOnElement();
  702. return xmlReader.ReadContentAsDouble();
  703. }
  704. public override int ReadContentAsInt()
  705. {
  706. AdvanceToContentOnElement();
  707. return xmlReader.ReadContentAsInt();
  708. }
  709. public override long ReadContentAsLong()
  710. {
  711. AdvanceToContentOnElement();
  712. return xmlReader.ReadContentAsLong();
  713. }
  714. #if NO
  715. public override ICollection ReadContentAsList()
  716. {
  717. AdvanceToContentOnElement();
  718. return xmlReader.ReadContentAsList();
  719. }
  720. #endif
  721. public override object ReadContentAsObject()
  722. {
  723. AdvanceToContentOnElement();
  724. return xmlReader.ReadContentAsObject();
  725. }
  726. public override float ReadContentAsFloat()
  727. {
  728. AdvanceToContentOnElement();
  729. return xmlReader.ReadContentAsFloat();
  730. }
  731. public override string ReadContentAsString()
  732. {
  733. AdvanceToContentOnElement();
  734. return xmlReader.ReadContentAsString();
  735. }
  736. public override string ReadInnerXml()
  737. {
  738. return xmlReader.ReadInnerXml();
  739. }
  740. public override string ReadOuterXml()
  741. {
  742. return xmlReader.ReadOuterXml();
  743. }
  744. public override ReadState ReadState
  745. {
  746. get
  747. {
  748. if (xmlReader.ReadState != ReadState.Interactive && infosetReader != null)
  749. return infosetReader.ReadState;
  750. return xmlReader.ReadState;
  751. }
  752. }
  753. public override int ReadValueChunk(char[] buffer, int index, int count)
  754. {
  755. return xmlReader.ReadValueChunk(buffer, index, count);
  756. }
  757. public override void ResolveEntity()
  758. {
  759. xmlReader.ResolveEntity();
  760. }
  761. public override XmlReaderSettings Settings
  762. {
  763. get
  764. {
  765. return xmlReader.Settings;
  766. }
  767. }
  768. public override void Skip()
  769. {
  770. xmlReader.Skip();
  771. }
  772. public override string this[int index]
  773. {
  774. get
  775. {
  776. return xmlReader[index];
  777. }
  778. }
  779. public override string this[string name]
  780. {
  781. get
  782. {
  783. return xmlReader[name];
  784. }
  785. }
  786. public override string this[string name, string ns]
  787. {
  788. get
  789. {
  790. return xmlReader[name, ns];
  791. }
  792. }
  793. public override string Value
  794. {
  795. get
  796. {
  797. return xmlReader.Value;
  798. }
  799. }
  800. public override Type ValueType
  801. {
  802. get
  803. {
  804. return xmlReader.ValueType;
  805. }
  806. }
  807. public override string XmlLang
  808. {
  809. get
  810. {
  811. return xmlReader.XmlLang;
  812. }
  813. }
  814. public override XmlSpace XmlSpace
  815. {
  816. get
  817. {
  818. return xmlReader.XmlSpace;
  819. }
  820. }
  821. public bool HasLineInfo()
  822. {
  823. if (xmlReader.ReadState == ReadState.Closed)
  824. return false;
  825. IXmlLineInfo lineInfo = xmlReader as IXmlLineInfo;
  826. if (lineInfo == null)
  827. return false;
  828. return lineInfo.HasLineInfo();
  829. }
  830. public int LineNumber
  831. {
  832. get
  833. {
  834. if (xmlReader.ReadState == ReadState.Closed)
  835. return 0;
  836. IXmlLineInfo lineInfo = xmlReader as IXmlLineInfo;
  837. if (lineInfo == null)
  838. return 0;
  839. return lineInfo.LineNumber;
  840. }
  841. }
  842. public int LinePosition
  843. {
  844. get
  845. {
  846. if (xmlReader.ReadState == ReadState.Closed)
  847. return 0;
  848. IXmlLineInfo lineInfo = xmlReader as IXmlLineInfo;
  849. if (lineInfo == null)
  850. return 0;
  851. return lineInfo.LinePosition;
  852. }
  853. }
  854. internal class MimePart
  855. {
  856. Stream stream;
  857. MimeHeaders headers;
  858. byte[] buffer;
  859. bool isReferencedFromInfoset;
  860. internal MimePart(Stream stream, MimeHeaders headers)
  861. {
  862. this.stream = stream;
  863. this.headers = headers;
  864. }
  865. internal Stream Stream
  866. {
  867. get { return stream; }
  868. }
  869. internal MimeHeaders Headers
  870. {
  871. get { return headers; }
  872. }
  873. internal bool ReferencedFromInfoset
  874. {
  875. get { return isReferencedFromInfoset; }
  876. set { isReferencedFromInfoset = value; }
  877. }
  878. internal long Length
  879. {
  880. get { return stream.CanSeek ? stream.Length : 0; }
  881. }
  882. internal byte[] GetBuffer(int maxBuffer, ref int remaining)
  883. {
  884. if (buffer == null)
  885. {
  886. MemoryStream bufferedStream = stream.CanSeek ? new MemoryStream((int)stream.Length) : new MemoryStream();
  887. int size = 256;
  888. byte[] bytes = new byte[size];
  889. int read = 0;
  890. do
  891. {
  892. read = stream.Read(bytes, 0, size);
  893. XmlMtomReader.DecrementBufferQuota(maxBuffer, ref remaining, read);
  894. if (read > 0)
  895. bufferedStream.Write(bytes, 0, read);
  896. }
  897. while (read > 0);
  898. bufferedStream.Seek(0, SeekOrigin.Begin);
  899. buffer = bufferedStream.GetBuffer();
  900. stream = bufferedStream;
  901. }
  902. return buffer;
  903. }
  904. internal void Release(int maxBuffer, ref int remaining)
  905. {
  906. remaining += (int)this.Length;
  907. this.headers.Release(ref remaining);
  908. }
  909. }
  910. internal class XopIncludeReader : XmlDictionaryReader, IXmlLineInfo
  911. {
  912. int chunkSize = 4096; // Just a default. Serves as a max chunk size.
  913. int bytesRemaining;
  914. MimePart part;
  915. ReadState readState;
  916. XmlDictionaryReader parentReader;
  917. string stringValue;
  918. int stringOffset;
  919. XmlNodeType nodeType;
  920. MemoryStream binHexStream;
  921. byte[] valueBuffer;
  922. int valueOffset;
  923. int valueCount;
  924. bool finishedStream;
  925. public XopIncludeReader(MimePart part, XmlDictionaryReader reader)
  926. {
  927. if (part == null)
  928. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("part");
  929. if (reader == null)
  930. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
  931. this.part = part;
  932. this.parentReader = reader;
  933. this.readState = ReadState.Initial;
  934. this.nodeType = XmlNodeType.None;
  935. this.chunkSize = Math.Min(reader.Quotas.MaxBytesPerRead, chunkSize);
  936. this.bytesRemaining = this.chunkSize;
  937. this.finishedStream = false;
  938. }
  939. public override XmlDictionaryReaderQuotas Quotas
  940. {
  941. get
  942. {
  943. return this.parentReader.Quotas;
  944. }
  945. }
  946. public override XmlNodeType NodeType
  947. {
  948. get
  949. {
  950. return (readState == ReadState.Interactive) ? nodeType : parentReader.NodeType;
  951. }
  952. }
  953. public override bool Read()
  954. {
  955. bool retVal = true;
  956. switch (readState)
  957. {
  958. case ReadState.Initial:
  959. readState = ReadState.Interactive;
  960. nodeType = XmlNodeType.Text;
  961. break;
  962. case ReadState.Interactive:
  963. if (this.finishedStream || (this.bytesRemaining == this.chunkSize && this.stringValue == null))
  964. {
  965. readState = ReadState.EndOfFile;
  966. nodeType = XmlNodeType.EndElement;
  967. }
  968. else
  969. {
  970. this.bytesRemaining = this.chunkSize;
  971. }
  972. break;
  973. case ReadState.EndOfFile:
  974. nodeType = XmlNodeType.None;
  975. retVal = false;
  976. break;
  977. }
  978. this.stringValue = null;
  979. this.binHexStream = null;
  980. this.valueOffset = 0;
  981. this.valueCount = 0;
  982. this.stringOffset = 0;
  983. CloseStreams();
  984. return retVal;
  985. }
  986. public override int ReadValueAsBase64(byte[] buffer, int offset, int count)
  987. {
  988. if (buffer == null)
  989. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
  990. if (offset < 0)
  991. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative)));
  992. if (offset > buffer.Length)
  993. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.OffsetExceedsBufferSize, buffer.Length)));
  994. if (count < 0)
  995. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeNonNegative)));
  996. if (count > buffer.Length - offset)
  997. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
  998. if (this.stringValue != null)
  999. {
  1000. count = Math.Min(count, this.valueCount);
  1001. if (count > 0)
  1002. {
  1003. Buffer.BlockCopy(this.valueBuffer, this.valueOffset, buffer, offset, count);
  1004. this.valueOffset += count;
  1005. this.valueCount -= count;
  1006. }
  1007. return count;
  1008. }
  1009. if (this.bytesRemaining < count)
  1010. count = this.bytesRemaining;
  1011. int read = 0;
  1012. if (readState == ReadState.Interactive)
  1013. {
  1014. while (read < count)
  1015. {
  1016. int actual = part.Stream.Read(buffer, offset + read, count - read);
  1017. if (actual == 0)
  1018. {
  1019. this.finishedStream = true;
  1020. break;
  1021. }
  1022. read += actual;
  1023. }
  1024. }
  1025. this.bytesRemaining -= read;
  1026. return read;
  1027. }
  1028. public override int ReadContentAsBase64(byte[] buffer, int offset, int count)
  1029. {
  1030. if (buffer == null)
  1031. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
  1032. if (offset < 0)
  1033. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative)));
  1034. if (offset > buffer.Length)
  1035. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.OffsetExceedsBufferSize, buffer.Length)));
  1036. if (count < 0)
  1037. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeNonNegative)));
  1038. if (count > buffer.Length - offset)
  1039. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
  1040. if (this.valueCount > 0)
  1041. {
  1042. count = Math.Min(count, this.valueCount);
  1043. Buffer.BlockCopy(this.valueBuffer, this.valueOffset, buffer, offset, count);
  1044. this.valueOffset += count;
  1045. this.valueCount -= count;
  1046. return count;
  1047. }
  1048. if (this.chunkSize < count)
  1049. count = this.chunkSize;
  1050. int read = 0;
  1051. if (readState == ReadState.Interactive)
  1052. {
  1053. while (read < count)
  1054. {
  1055. int actual = part.Stream.Read(buffer, offset + read, count - read);
  1056. if (actual == 0)
  1057. {
  1058. this.finishedStream = true;
  1059. if (!Read())
  1060. break;
  1061. }
  1062. read += actual;
  1063. }
  1064. }
  1065. this.bytesRemaining = this.chunkSize;
  1066. return read;
  1067. }
  1068. public override int ReadContentAsBinHex(byte[] buffer, int offset, int count)
  1069. {
  1070. if (buffer == null)
  1071. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
  1072. if (offset < 0)
  1073. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative)));
  1074. if (offset > buffer.Length)
  1075. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.OffsetExceedsBufferSize, buffer.Length)));
  1076. if (count < 0)
  1077. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeNonNegative)));
  1078. if (count > buffer.Length - offset)
  1079. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
  1080. if (this.chunkSize < count)
  1081. count = this.chunkSize;
  1082. int read = 0;
  1083. int consumed = 0;
  1084. while (read < count)
  1085. {
  1086. if (binHexStream == null)
  1087. {
  1088. try
  1089. {
  1090. binHexStream = new MemoryStream(new BinHexEncoding().GetBytes(this.Value));
  1091. }
  1092. catch (FormatException e) // Wrap format exceptions from decoding document contents
  1093. {
  1094. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(e.Message, e));
  1095. }
  1096. }
  1097. int actual = binHexStream.Read(buffer, offset + read, count - read);
  1098. if (actual == 0)
  1099. {
  1100. this.finishedStream = true;
  1101. if (!Read())
  1102. break;
  1103. consumed = 0;
  1104. }
  1105. read += actual;
  1106. consumed += actual;
  1107. }
  1108. // Trim off the consumed chars
  1109. if (this.stringValue != null && consumed > 0)
  1110. {
  1111. this.stringValue = this.stringValue.Substring(consumed * 2);
  1112. this.stringOffset = Math.Max(0, this.stringOffset - consumed * 2);
  1113. this.bytesRemaining = this.chunkSize;
  1114. }
  1115. return read;
  1116. }
  1117. public override int ReadValueChunk(char[] chars, int offset, int count)
  1118. {
  1119. if (chars == null)
  1120. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("chars");
  1121. if (offset < 0)
  1122. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative)));
  1123. if (offset > chars.Length)
  1124. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.OffsetExceedsBufferSize, chars.Length)));
  1125. if (count < 0)
  1126. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeNonNegative)));
  1127. if (count > chars.Length - offset)
  1128. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.SizeExceedsRemainingBufferSpace, chars.Length - offset)));
  1129. if (readState != ReadState.Interactive)
  1130. return 0;
  1131. // Copy characters from the Value property
  1132. string str = this.Value;
  1133. count = Math.Min(stringValue.Length - stringOffset, count);
  1134. if (count > 0)
  1135. {
  1136. stringValue.CopyTo(stringOffset, chars, offset, count);
  1137. stringOffset += count;
  1138. }
  1139. return count;
  1140. }
  1141. public override string Value
  1142. {
  1143. get
  1144. {
  1145. if (readState != ReadState.Interactive)
  1146. return String.Empty;
  1147. if (stringValue == null)
  1148. {
  1149. // Compute the bytes to read
  1150. int byteCount = this.bytesRemaining;
  1151. byteCount -= byteCount % 3;
  1152. // Handle trailing bytes
  1153. if (this.valueCount > 0 && this.valueOffset > 0)
  1154. {
  1155. Buffer.BlockCopy(this.valueBuffer, this.valueOffset, this.valueBuffer, 0, this.valueCount);
  1156. this.valueOffset = 0;
  1157. }
  1158. byteCount -= this.valueCount;
  1159. // Resize buffer if needed
  1160. if (this.valueBuffer == null)
  1161. {
  1162. this.valueBuffer = new byte[byteCount];
  1163. }
  1164. else if (this.valueBuffer.Length < byteCount)
  1165. {
  1166. Array.Resize(ref this.valueBuffer, byteCount);
  1167. }
  1168. byte[] buffer = this.valueBuffer;
  1169. // Fill up the buffer
  1170. int offset = 0;
  1171. int read = 0;
  1172. while (byteCount > 0)
  1173. {
  1174. read = part.Stream.Read(buffer, offset, byteCount);
  1175. if (read == 0)
  1176. {
  1177. this.finishedStream = true;
  1178. break;
  1179. }
  1180. this.bytesRemaining -= read;
  1181. this.valueCount += read;
  1182. byteCount -= read;
  1183. offset += read;
  1184. }
  1185. // Convert the bytes
  1186. this.stringValue = Convert.ToBase64String(buffer, 0, this.valueCount);
  1187. }
  1188. return this.stringValue;
  1189. }
  1190. }
  1191. public override string ReadContentAsString()
  1192. {
  1193. int stringContentQuota = this.Quotas.MaxStringContentLength;
  1194. StringBuilder sb = new StringBuilder();
  1195. do
  1196. {
  1197. string val = this.Value;
  1198. if (val.Length > stringContentQuota)
  1199. XmlExceptionHelper.ThrowMaxStringContentLengthExceeded(this, this.Quotas.MaxStringContentLength);
  1200. stringContentQuota -= val.Length;
  1201. sb.Append(val);
  1202. } while (Read());
  1203. return sb.ToString();
  1204. }
  1205. public override int AttributeCount
  1206. {
  1207. get { return 0; }
  1208. }
  1209. public override string BaseURI
  1210. {
  1211. get { return parentReader.BaseURI; }
  1212. }
  1213. public override bool CanReadBinaryContent
  1214. {
  1215. get { return true; }
  1216. }
  1217. public override bool CanReadValueChunk
  1218. {
  1219. get { return true; }
  1220. }
  1221. public override bool CanResolveEntity
  1222. {
  1223. get { return parentReader.CanResolveEntity; }
  1224. }
  1225. public override void Close()
  1226. {
  1227. CloseStreams();
  1228. readState = ReadState.Closed;
  1229. }
  1230. void CloseStreams()
  1231. {
  1232. if (binHexStream != null)
  1233. {
  1234. binHexStream.Close();
  1235. binHexStream = null;
  1236. }
  1237. }
  1238. public override int Depth
  1239. {
  1240. get
  1241. {
  1242. return (readState == ReadState.Interactive) ? parentReader.Depth + 1 : parentReader.Depth;
  1243. }
  1244. }
  1245. public override bool EOF
  1246. {
  1247. get { return readState == ReadState.EndOfFile; }
  1248. }
  1249. public override string GetAttribute(int index)
  1250. {
  1251. return null;
  1252. }
  1253. public override string GetAttribute(string name)
  1254. {
  1255. return null;
  1256. }
  1257. public override string GetAttribute(string name, string ns)
  1258. {
  1259. return null;
  1260. }
  1261. public override string GetAttribute(XmlDictionaryString localName, XmlDictionaryString ns)
  1262. {
  1263. return null;
  1264. }
  1265. public override bool HasAttributes
  1266. {
  1267. get { return false; }
  1268. }
  1269. public override bool HasValue
  1270. {
  1271. get { return readState == ReadState.Interactive; }
  1272. }
  1273. public override bool IsDefault
  1274. {
  1275. get { return false; }
  1276. }
  1277. public override bool IsEmptyElement
  1278. {
  1279. get { return false; }
  1280. }
  1281. public override bool IsLocalName(string localName)
  1282. {
  1283. return false;
  1284. }
  1285. public override bool IsLocalName(XmlDictionaryString localName)
  1286. {
  1287. return false;
  1288. }
  1289. public override bool IsNamespaceUri(string ns)
  1290. {
  1291. return false;
  1292. }
  1293. public override bool IsNamespaceUri(XmlDictionaryString ns)
  1294. {
  1295. return false;
  1296. }
  1297. public override bool IsStartElement()
  1298. {
  1299. return false;
  1300. }
  1301. public override bool IsStartElement(string localName)
  1302. {
  1303. return false;
  1304. }
  1305. public override bool IsStartElement(string localName, string ns)
  1306. {
  1307. return false;
  1308. }
  1309. public override bool IsStartElement(XmlDictionaryString localName, XmlDictionaryString ns)
  1310. {
  1311. return false;
  1312. }
  1313. #if NO
  1314. public override bool IsStartSubsetElement()
  1315. {
  1316. return false;
  1317. }
  1318. #endif
  1319. public override string LocalName
  1320. {
  1321. get
  1322. {
  1323. return (readState == ReadState.Interactive) ? String.Empty : parentReader.LocalName;
  1324. }
  1325. }
  1326. public override string LookupNamespace(string ns)
  1327. {
  1328. return parentReader.LookupNamespace(ns);
  1329. }
  1330. public override void MoveToAttribute(int index)
  1331. {
  1332. }
  1333. public override bool MoveToAttribute(string name)
  1334. {
  1335. return false;
  1336. }
  1337. public override bool MoveToAttribute(string name, string ns)
  1338. {
  1339. return false;
  1340. }
  1341. public override bool MoveToElement()
  1342. {
  1343. return false;
  1344. }
  1345. public override bool MoveToFirstAttribute()
  1346. {
  1347. return false;
  1348. }
  1349. public override bool MoveToNextAttribute()
  1350. {
  1351. return false;
  1352. }
  1353. public override string Name
  1354. {
  1355. get
  1356. {
  1357. return (readState == ReadState.Interactive) ? String.Empty : parentReader.Name;
  1358. }
  1359. }
  1360. public override string NamespaceURI
  1361. {
  1362. get
  1363. {
  1364. return (readState == ReadState.Interactive) ? String.Empty : parentReader.NamespaceURI;
  1365. }
  1366. }
  1367. public override XmlNameTable NameTable
  1368. {
  1369. get { return parentReader.NameTable; }
  1370. }
  1371. public override string Prefix
  1372. {
  1373. get
  1374. {
  1375. return (readState == ReadState.Interactive) ? String.Empty : parentReader.Prefix;
  1376. }
  1377. }
  1378. public override char QuoteChar
  1379. {
  1380. get { return parentReader.QuoteChar; }
  1381. }
  1382. public override bool ReadAttributeValue()
  1383. {
  1384. return false;
  1385. }
  1386. public override string ReadInnerXml()
  1387. {
  1388. return ReadContentAsString();
  1389. }
  1390. public override string ReadOuterXml()
  1391. {
  1392. return ReadContentAsString();
  1393. }
  1394. public override ReadState ReadState
  1395. {
  1396. get { return readState; }
  1397. }
  1398. public override void ResolveEntity()
  1399. {
  1400. }
  1401. public override XmlReaderSettings Settings
  1402. {
  1403. get { return parentReader.Settings; }
  1404. }
  1405. public override void Skip()
  1406. {
  1407. Read();
  1408. }
  1409. public override string this[int index]
  1410. {
  1411. get { return null; }
  1412. }
  1413. public override string this[string name]
  1414. {
  1415. get { return null; }
  1416. }
  1417. public override string this[string name, string ns]
  1418. {
  1419. get { return null; }
  1420. }
  1421. public override string XmlLang
  1422. {
  1423. get { return parentReader.XmlLang; }
  1424. }
  1425. public override XmlSpace XmlSpace
  1426. {
  1427. get { return parentReader.XmlSpace; }
  1428. }
  1429. public override Type ValueType
  1430. {
  1431. get
  1432. {
  1433. return (readState == ReadState.Interactive) ? typeof(byte[]) : parentReader.ValueType;
  1434. }
  1435. }
  1436. bool IXmlLineInfo.HasLineInfo()
  1437. {
  1438. return ((IXmlLineInfo)parentReader).HasLineInfo();
  1439. }
  1440. int IXmlLineInfo.LineNumber
  1441. {
  1442. get
  1443. {
  1444. return ((IXmlLineInfo)parentReader).LineNumber;
  1445. }
  1446. }
  1447. int IXmlLineInfo.LinePosition
  1448. {
  1449. get
  1450. {
  1451. return ((IXmlLineInfo)parentReader).LinePosition;
  1452. }
  1453. }
  1454. }
  1455. }
  1456. internal class MimeMessageReader
  1457. {
  1458. static byte[] CRLFCRLF = new byte[] { (byte)'\r', (byte)'\n', (byte)'\r', (byte)'\n' };
  1459. bool getContentStreamCalled;
  1460. MimeHeaderReader mimeHeaderReader;
  1461. DelimittedStreamReader reader;
  1462. public MimeMessageReader(Stream stream)
  1463. {
  1464. if (stream == null)
  1465. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream");
  1466. this.reader = new DelimittedStreamReader(stream);
  1467. this.mimeHeaderReader = new MimeHeaderReader(this.reader.GetNextStream(CRLFCRLF));
  1468. }
  1469. public Stream GetContentStream()
  1470. {
  1471. if (getContentStreamCalled)
  1472. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MimeMessageGetContentStreamCalledAlready)));
  1473. mimeHeaderReader.Close();
  1474. Stream s = reader.GetNextStream(null);
  1475. getContentStreamCalled = true;
  1476. return s;
  1477. }
  1478. public MimeHeaders ReadHeaders(int maxBuffer, ref int remaining)
  1479. {
  1480. MimeHeaders headers = new MimeHeaders();
  1481. while (mimeHeaderReader.Read(maxBuffer, ref remaining))
  1482. {
  1483. headers.Add(mimeHeaderReader.Name, mimeHeaderReader.Value, ref remaining);
  1484. }
  1485. return headers;
  1486. }
  1487. }
  1488. internal class MimeReader
  1489. {
  1490. static byte[] CRLFCRLF = new byte[] { (byte)'\r', (byte)'\n', (byte)'\r', (byte)'\n' };
  1491. byte[] boundaryBytes;
  1492. string content;
  1493. Stream currentStream;
  1494. MimeHeaderReader mimeHeaderReader;
  1495. DelimittedStreamReader reader;
  1496. byte[] scratch = new byte[2];
  1497. public MimeReader(Stream stream, string boundary)
  1498. {
  1499. if (stream == null)
  1500. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream");
  1501. if (boundary == null)
  1502. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("boundary");
  1503. this.reader = new DelimittedStreamReader(stream);
  1504. this.boundaryBytes = MimeWriter.GetBoundaryBytes(boundary);
  1505. // Need to ensure that the content begins with a CRLF, in case the
  1506. // outer construct has consumed the trailing CRLF
  1507. this.reader.Push(this.boundaryBytes, 0, 2);
  1508. }
  1509. public void Close()
  1510. {
  1511. this.reader.Close();
  1512. }
  1513. /// Gets the content preceding the first part of the MIME multi-part message
  1514. public string Preface
  1515. {
  1516. get
  1517. {
  1518. if (content == null)
  1519. {
  1520. Stream s = this.reader.GetNextStream(this.boundaryBytes);
  1521. content = new StreamReader(s, System.Text.Encoding.ASCII, false, 256).ReadToEnd();
  1522. s.Close();
  1523. if (content == null)
  1524. content = string.Empty;
  1525. }
  1526. return content;
  1527. }
  1528. }
  1529. public Stream GetContentStream()
  1530. {
  1531. Fx.Assert(content != null, "");
  1532. mimeHeaderReader.Close();
  1533. return reader.GetNextStream(this.boundaryBytes);
  1534. }
  1535. public bool ReadNextPart()
  1536. {
  1537. string content = Preface;
  1538. if (currentStream != null)
  1539. {
  1540. currentStream.Close();
  1541. currentStream = null;
  1542. }
  1543. Stream stream = reader.GetNextStream(CRLFCRLF);
  1544. if (stream == null)
  1545. return false;
  1546. if (BlockRead(stream, scratch, 0, 2) == 2)
  1547. {
  1548. if (scratch[0] == '\r' && scratch[1] == '\n')
  1549. {
  1550. if (mimeHeaderReader == null)
  1551. mimeHeaderReader = new MimeHeaderReader(stream);
  1552. else
  1553. mimeHeaderReader.Reset(stream);
  1554. return true;
  1555. }
  1556. else if (scratch[0] == '-' && scratch[1] == '-')
  1557. {
  1558. int read = BlockRead(stream, scratch, 0, 2);
  1559. if (read < 2 || (scratch[0] == '\r' && scratch[1] == '\n'))
  1560. return false;
  1561. }
  1562. }
  1563. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeReaderTruncated)));
  1564. }
  1565. public MimeHeaders ReadHeaders(int maxBuffer, ref int remaining)
  1566. {
  1567. MimeHeaders headers = new MimeHeaders();
  1568. while (mimeHeaderReader.Read(maxBuffer, ref remaining))
  1569. {
  1570. headers.Add(mimeHeaderReader.Name, mimeHeaderReader.Value, ref remaining);
  1571. }
  1572. return headers;
  1573. }
  1574. int BlockRead(Stream stream, byte[] buffer, int offset, int count)
  1575. {
  1576. int read = 0;
  1577. do
  1578. {
  1579. int r = stream.Read(buffer, offset + read, count - read);
  1580. if (r == 0)
  1581. break;
  1582. read += r;
  1583. } while (read < count);
  1584. return read;
  1585. }
  1586. }
  1587. internal class DelimittedStreamReader
  1588. {
  1589. bool canGetNextStream = true;
  1590. // used for closing the reader, and validating that only one stream can be reading at a time.
  1591. DelimittedReadStream currentStream;
  1592. byte[] delimitter;
  1593. byte[] matchBuffer;
  1594. byte[] scratch;
  1595. BufferedReadStream stream;
  1596. public DelimittedStreamReader(Stream stream)
  1597. {
  1598. this.stream = new BufferedReadStream(stream);
  1599. }
  1600. public void Close()
  1601. {
  1602. this.stream.Close();
  1603. }
  1604. // Closes the current stream. If the current stream is not the same as the caller, nothing is done.
  1605. void Close(DelimittedReadStream caller)
  1606. {
  1607. if (currentStream == caller)
  1608. {
  1609. if (delimitter == null)
  1610. {
  1611. stream.Close();
  1612. }
  1613. else
  1614. {
  1615. if (scratch == null)
  1616. {
  1617. scratch = new byte[1024];
  1618. }
  1619. while (0 != Read(caller, this.scratch, 0, this.scratch.Length));
  1620. }
  1621. currentStream = null;
  1622. }
  1623. }
  1624. // Gets the next logical stream delimitted by the given sequence.
  1625. public Stream GetNextStream(byte[] delimitter)
  1626. {
  1627. if (currentStream != null)
  1628. {
  1629. currentStream.Close();
  1630. currentStream = null;
  1631. }
  1632. if (!canGetNextStream)
  1633. return null;
  1634. this.delimitter = delimitter;
  1635. canGetNextStream = delimitter != null;
  1636. currentStream = new DelimittedReadStream(this);
  1637. return currentStream;
  1638. }
  1639. enum MatchState
  1640. {
  1641. True,
  1642. False,
  1643. InsufficientData
  1644. }
  1645. MatchState MatchDelimitter(byte[] buffer, int start, int end)
  1646. {
  1647. if (this.delimitter.Length > end - start)
  1648. {
  1649. for (int i = end - start - 1; i >= 1; i--)
  1650. {
  1651. if (buffer[start + i] != delimitter[i])
  1652. return MatchState.False;
  1653. }
  1654. return MatchState.InsufficientData;
  1655. }
  1656. for (int i = delimitter.Length - 1; i >= 1; i--)
  1657. {
  1658. if (buffer[start + i] != delimitter[i])
  1659. return MatchState.False;
  1660. }
  1661. return MatchState.True;
  1662. }
  1663. int ProcessRead(byte[] buffer, int offset, int read)
  1664. {
  1665. // nothing to process if 0 bytes were read
  1666. if (read == 0)
  1667. return read;
  1668. for (int ptr = offset, end = offset + read; ptr < end; ptr++)
  1669. {
  1670. if (buffer[ptr] == delimitter[0])
  1671. {
  1672. switch (MatchDelimitter(buffer, ptr, end))
  1673. {
  1674. case MatchState.True:
  1675. {
  1676. int actual = ptr - offset;
  1677. ptr += this.delimitter.Length;
  1678. this.stream.Push(buffer, ptr, end - ptr);
  1679. this.currentStream = null;
  1680. return actual;
  1681. }
  1682. case MatchState.False:
  1683. break;
  1684. case MatchState.InsufficientData:
  1685. {
  1686. int actual = ptr - offset;
  1687. if (actual > 0)
  1688. {
  1689. this.stream.Push(buffer, ptr, end - ptr);
  1690. return actual;
  1691. }
  1692. else
  1693. {
  1694. return -1;
  1695. }
  1696. }
  1697. }
  1698. }
  1699. }
  1700. return read;
  1701. }
  1702. int Read(DelimittedReadStream caller, byte[] buffer, int offset, int count)
  1703. {
  1704. if (this.currentStream != caller)
  1705. return 0;
  1706. int read = this.stream.Read(buffer, offset, count);
  1707. if (read == 0)
  1708. {
  1709. this.canGetNextStream = false;
  1710. this.currentStream = null;
  1711. return read;
  1712. }
  1713. // If delimitter is null, read until the underlying stream returns 0 bytes
  1714. if (this.delimitter == null)
  1715. return read;
  1716. // Scans the read data for the delimitter. If found, the number of bytes read are adjusted
  1717. // to account for the number of bytes up to but not including the delimitter.
  1718. int actual = ProcessRead(buffer, offset, read);
  1719. if (actual < 0)
  1720. {
  1721. if (this.matchBuffer == null || this.matchBuffer.Length < this.delimitter.Length - read)
  1722. this.matchBuffer = new byte[this.delimitter.Length - read];
  1723. int matched = this.stream.ReadBlock(this.matchBuffer, 0, this.delimitter.Length - read);
  1724. if (MatchRemainder(read, matched))
  1725. {
  1726. this.currentStream = null;
  1727. actual = 0;
  1728. }
  1729. else
  1730. {
  1731. this.stream.Push(this.matchBuffer, 0, matched);
  1732. int i = 1;
  1733. for (; i < read; i++)
  1734. {
  1735. if (buffer[i] == this.delimitter[0])
  1736. break;
  1737. }
  1738. if (i < read)
  1739. this.stream.Push(buffer, offset + i, read - i);
  1740. actual = i;
  1741. }
  1742. }
  1743. return actual;
  1744. }
  1745. bool MatchRemainder(int start, int count)
  1746. {
  1747. if (start + count != this.delimitter.Length)
  1748. return false;
  1749. for (count--; count >= 0; count--)
  1750. {
  1751. if (this.delimitter[start + count] != this.matchBuffer[count])
  1752. return false;
  1753. }
  1754. return true;
  1755. }
  1756. internal void Push(byte[] buffer, int offset, int count)
  1757. {
  1758. this.stream.Push(buffer, offset, count);
  1759. }
  1760. class DelimittedReadStream : Stream
  1761. {
  1762. DelimittedStreamReader reader;
  1763. public DelimittedReadStream(DelimittedStreamReader reader)
  1764. {
  1765. if (reader == null)
  1766. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
  1767. this.reader = reader;
  1768. }
  1769. public override bool CanRead
  1770. {
  1771. get { return true; }
  1772. }
  1773. public override bool CanSeek
  1774. {
  1775. get { return false; }
  1776. }
  1777. public override bool CanWrite
  1778. {
  1779. get { return false; }
  1780. }
  1781. public override long Length
  1782. {
  1783. #pragma warning suppress 56503 // [....], required by the XmlReader
  1784. get { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupportedOnStream, this.GetType().FullName))); }
  1785. }
  1786. public override long Position
  1787. {
  1788. get
  1789. {
  1790. #pragma warning suppress 56503 // [....], required by the XmlReader
  1791. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupportedOnStream, this.GetType().FullName)));
  1792. }
  1793. set { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupportedOnStream, this.GetType().FullName))); }
  1794. }
  1795. public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  1796. {
  1797. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.WriteNotSupportedOnStream, this.GetType().FullName)));
  1798. }
  1799. public override void Close()
  1800. {
  1801. reader.Close(this);
  1802. }
  1803. public override void EndWrite(IAsyncResult asyncResult)
  1804. {
  1805. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.WriteNotSupportedOnStream, this.GetType().FullName)));
  1806. }
  1807. public override void Flush()
  1808. {
  1809. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.WriteNotSupportedOnStream, this.GetType().FullName)));
  1810. }
  1811. public override int Read(byte[] buffer, int offset, int count)
  1812. {
  1813. if (buffer == null)
  1814. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
  1815. if (offset < 0)
  1816. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative)));
  1817. if (offset > buffer.Length)
  1818. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.OffsetExceedsBufferSize, buffer.Length)));
  1819. if (count < 0)
  1820. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeNonNegative)));
  1821. if (count > buffer.Length - offset)
  1822. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
  1823. return reader.Read(this, buffer, offset, count);
  1824. }
  1825. public override long Seek(long offset, SeekOrigin origin)
  1826. {
  1827. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupportedOnStream, this.GetType().FullName)));
  1828. }
  1829. public override void SetLength(long value)
  1830. {
  1831. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.WriteNotSupportedOnStream, this.GetType().FullName)));
  1832. }
  1833. public override void Write(byte[] buffer, int offset, int count)
  1834. {
  1835. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.WriteNotSupportedOnStream, this.GetType().FullName)));
  1836. }
  1837. }
  1838. }
  1839. internal class MimeHeaders
  1840. {
  1841. static class Constants
  1842. {
  1843. public const string ContentTransferEncoding = "content-transfer-encoding";
  1844. public const string ContentID = "content-id";
  1845. public const string ContentType = "content-type";
  1846. public const string MimeVersion = "mime-version";
  1847. }
  1848. Dictionary<string, MimeHeader> headers = new Dictionary<string, MimeHeader>();
  1849. public MimeHeaders()
  1850. {
  1851. }
  1852. public ContentTypeHeader ContentType
  1853. {
  1854. get
  1855. {
  1856. MimeHeader header;
  1857. if (headers.TryGetValue(Constants.ContentType, out header))
  1858. return header as ContentTypeHeader;
  1859. return null;
  1860. }
  1861. }
  1862. public ContentIDHeader ContentID
  1863. {
  1864. get
  1865. {
  1866. MimeHeader header;
  1867. if (headers.TryGetValue(Constants.ContentID, out header))
  1868. return header as ContentIDHeader;
  1869. return null;
  1870. }
  1871. }
  1872. public ContentTransferEncodingHeader ContentTransferEncoding
  1873. {
  1874. get
  1875. {
  1876. MimeHeader header;
  1877. if (headers.TryGetValue(Constants.ContentTransferEncoding, out header))
  1878. return header as ContentTransferEncodingHeader;
  1879. return null;
  1880. }
  1881. }
  1882. public MimeVersionHeader MimeVersion
  1883. {
  1884. get
  1885. {
  1886. MimeHeader header;
  1887. if (headers.TryGetValue(Constants.MimeVersion, out header))
  1888. return header as MimeVersionHeader;
  1889. return null;
  1890. }
  1891. }
  1892. public void Add(string name, string value, ref int remaining)
  1893. {
  1894. if (name == null)
  1895. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name");
  1896. if (value == null)
  1897. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
  1898. switch (name)
  1899. {
  1900. case Constants.ContentType:
  1901. Add(new ContentTypeHeader(value));
  1902. break;
  1903. case Constants.ContentID:
  1904. Add(new ContentIDHeader(name, value));
  1905. break;
  1906. case Constants.ContentTransferEncoding:
  1907. Add(new ContentTransferEncodingHeader(value));
  1908. break;
  1909. case Constants.MimeVersion:
  1910. Add(new MimeVersionHeader(value));
  1911. break;
  1912. // Skip any fields that are not recognized
  1913. // Content-description is currently not stored since it is not used
  1914. default:
  1915. remaining += value.Length * sizeof(char);
  1916. break;
  1917. }
  1918. remaining += name.Length * sizeof(char);
  1919. }
  1920. public void Add(MimeHeader header)
  1921. {
  1922. if (header == null)
  1923. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("header");
  1924. MimeHeader existingHeader;
  1925. if (headers.TryGetValue(header.Name, out existingHeader))
  1926. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeReaderHeaderAlreadyExists, header.Name)));
  1927. else
  1928. headers.Add(header.Name, header);
  1929. }
  1930. public void Release(ref int remaining)
  1931. {
  1932. foreach (MimeHeader header in this.headers.Values)
  1933. {
  1934. remaining += header.Value.Length * sizeof(char);
  1935. }
  1936. }
  1937. }
  1938. internal class MimeHeader
  1939. {
  1940. string name;
  1941. string value;
  1942. public MimeHeader(string name, string value)
  1943. {
  1944. if (name == null)
  1945. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name");
  1946. this.name = name;
  1947. this.value = value;
  1948. }
  1949. public string Name
  1950. {
  1951. get
  1952. {
  1953. return this.name;
  1954. }
  1955. }
  1956. public string Value
  1957. {
  1958. get
  1959. {
  1960. return this.value;
  1961. }
  1962. }
  1963. }
  1964. internal class ContentTypeHeader : MimeHeader
  1965. {
  1966. public readonly static ContentTypeHeader Default = new ContentTypeHeader("application/octet-stream");
  1967. public ContentTypeHeader(string value)
  1968. : base("content-type", value)
  1969. {
  1970. }
  1971. string mediaType;
  1972. string subType;
  1973. Dictionary<string, string> parameters;
  1974. public string MediaType
  1975. {
  1976. get
  1977. {
  1978. if (this.mediaType == null && Value != null)
  1979. ParseValue();
  1980. return this.mediaType;
  1981. }
  1982. }
  1983. public string MediaSubtype
  1984. {
  1985. get
  1986. {
  1987. if (this.subType == null && Value != null)
  1988. ParseValue();
  1989. return this.subType;
  1990. }
  1991. }
  1992. public Dictionary<string, string> Parameters
  1993. {
  1994. get
  1995. {
  1996. if (this.parameters == null)
  1997. {
  1998. if (Value != null)
  1999. ParseValue();
  2000. else
  2001. this.parameters = new Dictionary<string, string>();
  2002. }
  2003. return this.parameters;
  2004. }
  2005. }
  2006. void ParseValue()
  2007. {
  2008. if (this.parameters == null)
  2009. {
  2010. int offset = 0;
  2011. this.parameters = new Dictionary<string, string>();
  2012. this.mediaType = MailBnfHelper.ReadToken(Value, ref offset, null);
  2013. if (offset >= Value.Length || Value[offset++] != '/')
  2014. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeContentTypeHeaderInvalid)));
  2015. this.subType = MailBnfHelper.ReadToken(Value, ref offset, null);
  2016. while (MailBnfHelper.SkipCFWS(Value, ref offset))
  2017. {
  2018. if (offset >= Value.Length || Value[offset++] != ';')
  2019. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeContentTypeHeaderInvalid)));
  2020. if (!MailBnfHelper.SkipCFWS(Value, ref offset))
  2021. break;
  2022. string paramAttribute = MailBnfHelper.ReadParameterAttribute(Value, ref offset, null);
  2023. if (paramAttribute == null || offset >= Value.Length || Value[offset++] != '=')
  2024. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeContentTypeHeaderInvalid)));
  2025. string paramValue = MailBnfHelper.ReadParameterValue(Value, ref offset, null);
  2026. this.parameters.Add(paramAttribute.ToLowerInvariant(), paramValue);
  2027. }
  2028. if (this.parameters.ContainsKey(MtomGlobals.StartInfoParam))
  2029. {
  2030. // This allows us to maintain back compat with Orcas clients while allowing clients
  2031. // following the spec (with action inside start-info) to interop with RFC 2387
  2032. string startInfo = this.parameters[MtomGlobals.StartInfoParam];
  2033. // we're only interested in finding the action here - skipping past the content type to the first ;
  2034. int startInfoOffset = startInfo.IndexOf(';');
  2035. if (startInfoOffset > -1)
  2036. {
  2037. // keep going through the start-info string until we've reached the end of the stream
  2038. while (MailBnfHelper.SkipCFWS(startInfo, ref startInfoOffset))
  2039. {
  2040. // after having read through an attribute=value pair, we always expect to be at a ;
  2041. if (startInfo[startInfoOffset] == ';')
  2042. {
  2043. startInfoOffset++;
  2044. }
  2045. else
  2046. {
  2047. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeContentTypeHeaderInvalid)));
  2048. }
  2049. string paramAttribute = MailBnfHelper.ReadParameterAttribute(startInfo, ref startInfoOffset, null);
  2050. if (paramAttribute == null || startInfoOffset >= startInfo.Length || startInfo[startInfoOffset++] != '=')
  2051. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeContentTypeHeaderInvalid)));
  2052. string paramValue = MailBnfHelper.ReadParameterValue(startInfo, ref startInfoOffset, null);
  2053. if (paramAttribute == MtomGlobals.ActionParam)
  2054. {
  2055. this.parameters[MtomGlobals.ActionParam] = paramValue;
  2056. }
  2057. }
  2058. }
  2059. }
  2060. }
  2061. }
  2062. }
  2063. enum ContentTransferEncoding
  2064. {
  2065. SevenBit,
  2066. EightBit,
  2067. Binary,
  2068. Other,
  2069. Unspecified
  2070. }
  2071. internal class ContentTransferEncodingHeader : MimeHeader
  2072. {
  2073. ContentTransferEncoding contentTransferEncoding;
  2074. string contentTransferEncodingValue;
  2075. public readonly static ContentTransferEncodingHeader Binary = new ContentTransferEncodingHeader(ContentTransferEncoding.Binary, "binary");
  2076. public readonly static ContentTransferEncodingHeader EightBit = new ContentTransferEncodingHeader(ContentTransferEncoding.EightBit, "8bit");
  2077. public readonly static ContentTransferEncodingHeader SevenBit = new ContentTransferEncodingHeader(ContentTransferEncoding.SevenBit, "7bit");
  2078. public ContentTransferEncodingHeader(string value)
  2079. : base("content-transfer-encoding", value.ToLowerInvariant())
  2080. {
  2081. }
  2082. public ContentTransferEncodingHeader(ContentTransferEncoding contentTransferEncoding, string value)
  2083. : base("content-transfer-encoding", null)
  2084. {
  2085. this.contentTransferEncoding = contentTransferEncoding;
  2086. this.contentTransferEncodingValue = value;
  2087. }
  2088. public ContentTransferEncoding ContentTransferEncoding
  2089. {
  2090. get
  2091. {
  2092. ParseValue();
  2093. return this.contentTransferEncoding;
  2094. }
  2095. }
  2096. public string ContentTransferEncodingValue
  2097. {
  2098. get
  2099. {
  2100. ParseValue();
  2101. return this.contentTransferEncodingValue;
  2102. }
  2103. }
  2104. void ParseValue()
  2105. {
  2106. if (this.contentTransferEncodingValue == null)
  2107. {
  2108. int offset = 0;
  2109. this.contentTransferEncodingValue = (Value.Length == 0) ? Value : ((Value[0] == '"') ? MailBnfHelper.ReadQuotedString(Value, ref offset, null) : MailBnfHelper.ReadToken(Value, ref offset, null));
  2110. switch (this.contentTransferEncodingValue)
  2111. {
  2112. case "7bit":
  2113. this.contentTransferEncoding = ContentTransferEncoding.SevenBit;
  2114. break;
  2115. case "8bit":
  2116. this.contentTransferEncoding = ContentTransferEncoding.EightBit;
  2117. break;
  2118. case "binary":
  2119. this.contentTransferEncoding = ContentTransferEncoding.Binary;
  2120. break;
  2121. default:
  2122. this.contentTransferEncoding = ContentTransferEncoding.Other;
  2123. break;
  2124. }
  2125. }
  2126. }
  2127. }
  2128. internal class ContentIDHeader : MimeHeader
  2129. {
  2130. public ContentIDHeader(string name, string value)
  2131. : base(name, value)
  2132. {
  2133. }
  2134. }
  2135. internal class MimeVersionHeader : MimeHeader
  2136. {
  2137. public static readonly MimeVersionHeader Default = new MimeVersionHeader("1.0");
  2138. public MimeVersionHeader(string value)
  2139. : base("mime-version", value)
  2140. {
  2141. }
  2142. string version;
  2143. public string Version
  2144. {
  2145. get
  2146. {
  2147. if (this.version == null && Value != null)
  2148. ParseValue();
  2149. return this.version;
  2150. }
  2151. }
  2152. void ParseValue()
  2153. {
  2154. // shortcut for the most common case.
  2155. if (Value == "1.0")
  2156. {
  2157. this.version = "1.0";
  2158. }
  2159. else
  2160. {
  2161. int offset = 0;
  2162. if (!MailBnfHelper.SkipCFWS(Value, ref offset))
  2163. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeVersionHeaderInvalid)));
  2164. StringBuilder builder = new StringBuilder();
  2165. MailBnfHelper.ReadDigits(Value, ref offset, builder);
  2166. if ((!MailBnfHelper.SkipCFWS(Value, ref offset) || offset >= Value.Length || Value[offset++] != '.') || !MailBnfHelper.SkipCFWS(Value, ref offset))
  2167. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeVersionHeaderInvalid)));
  2168. builder.Append('.');
  2169. MailBnfHelper.ReadDigits(Value, ref offset, builder);
  2170. this.version = builder.ToString();
  2171. }
  2172. }
  2173. }
  2174. internal class MimeHeaderReader
  2175. {
  2176. enum ReadState
  2177. {
  2178. ReadName,
  2179. SkipWS,
  2180. ReadValue,
  2181. ReadLF,
  2182. ReadWS,
  2183. EOF
  2184. }
  2185. string value;
  2186. byte[] buffer = new byte[1024];
  2187. int maxOffset;
  2188. string name;
  2189. int offset;
  2190. ReadState readState = ReadState.ReadName;
  2191. Stream stream;
  2192. public MimeHeaderReader(Stream stream)
  2193. {
  2194. if (stream == null)
  2195. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream");
  2196. this.stream = stream;
  2197. }
  2198. public string Value
  2199. {
  2200. get
  2201. {
  2202. return value;
  2203. }
  2204. }
  2205. public string Name
  2206. {
  2207. get
  2208. {
  2209. return name;
  2210. }
  2211. }
  2212. public void Close()
  2213. {
  2214. stream.Close();
  2215. readState = ReadState.EOF;
  2216. }
  2217. public bool Read(int maxBuffer, ref int remaining)
  2218. {
  2219. name = null;
  2220. value = null;
  2221. while (readState != ReadState.EOF)
  2222. {
  2223. if (offset == maxOffset)
  2224. {
  2225. maxOffset = stream.Read(this.buffer, 0, this.buffer.Length);
  2226. offset = 0;
  2227. if (BufferEnd())
  2228. break;
  2229. }
  2230. if (ProcessBuffer(maxBuffer, ref remaining))
  2231. break;
  2232. }
  2233. return value != null;
  2234. }
  2235. [Fx.Tag.SecurityNote(Critical = "Calls unsafe code", Safe = "Demands for FullTrust")]
  2236. [SecuritySafeCritical]
  2237. [PermissionSet(SecurityAction.Demand, Unrestricted = true)]
  2238. bool ProcessBuffer(int maxBuffer, ref int remaining)
  2239. {
  2240. unsafe
  2241. {
  2242. fixed (byte* pBuffer = this.buffer)
  2243. {
  2244. byte* start = pBuffer + this.offset;
  2245. byte* end = pBuffer + this.maxOffset;
  2246. byte* ptr = start;
  2247. switch (readState)
  2248. {
  2249. case ReadState.ReadName:
  2250. for (; ptr < end; ptr++)
  2251. {
  2252. if (*ptr == ':')
  2253. {
  2254. AppendName(new string((sbyte*)start, 0, (int)(ptr - start)), maxBuffer, ref remaining);
  2255. ptr++;
  2256. goto case ReadState.SkipWS;
  2257. }
  2258. else
  2259. {
  2260. // convert to lower case up front.
  2261. if (*ptr >= 'A' && *ptr <= 'Z')
  2262. {
  2263. *ptr += 'a' - 'A';
  2264. }
  2265. else if (*ptr < 33 || *ptr > 126)
  2266. {
  2267. if (name == null && *ptr == (byte)'\r')
  2268. {
  2269. ptr++;
  2270. if (ptr >= end || *ptr != '\n')
  2271. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeReaderMalformedHeader)));
  2272. goto case ReadState.EOF;
  2273. }
  2274. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeHeaderInvalidCharacter, (char)(*ptr), ((int)(*ptr)).ToString("X", CultureInfo.InvariantCulture))));
  2275. }
  2276. }
  2277. }
  2278. AppendName(new string((sbyte*)start, 0, (int)(ptr - start)), maxBuffer, ref remaining);
  2279. readState = ReadState.ReadName;
  2280. break;
  2281. case ReadState.SkipWS:
  2282. for (; ptr < end; ptr++)
  2283. if (*ptr != (byte)'\t' && *ptr != ' ')
  2284. goto case ReadState.ReadValue;
  2285. readState = ReadState.SkipWS;
  2286. break;
  2287. case ReadState.ReadValue:
  2288. start = ptr;
  2289. for (; ptr < end; ptr++)
  2290. {
  2291. if (*ptr == (byte)'\r')
  2292. {
  2293. AppendValue(new string((sbyte*)start, 0, (int)(ptr - start)), maxBuffer, ref remaining);
  2294. ptr++;
  2295. goto case ReadState.ReadLF;
  2296. }
  2297. else if (*ptr == (byte)'\n')
  2298. {
  2299. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeReaderMalformedHeader)));
  2300. }
  2301. }
  2302. AppendValue(new string((sbyte*)start, 0, (int)(ptr - start)), maxBuffer, ref remaining);
  2303. readState = ReadState.ReadValue;
  2304. break;
  2305. case ReadState.ReadLF:
  2306. if (ptr < end)
  2307. {
  2308. if (*ptr != (byte)'\n')
  2309. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeReaderMalformedHeader)));
  2310. ptr++;
  2311. goto case ReadState.ReadWS;
  2312. }
  2313. readState = ReadState.ReadLF;
  2314. break;
  2315. case ReadState.ReadWS:
  2316. if (ptr < end)
  2317. {
  2318. if (*ptr != (byte)' ' && *ptr != (byte)'\t')
  2319. {
  2320. readState = ReadState.ReadName;
  2321. offset = (int)(ptr - pBuffer);
  2322. return true;
  2323. }
  2324. goto case ReadState.ReadValue;
  2325. }
  2326. readState = ReadState.ReadWS;
  2327. break;
  2328. case ReadState.EOF:
  2329. readState = ReadState.EOF;
  2330. offset = (int)(ptr - pBuffer);
  2331. return true;
  2332. }
  2333. offset = (int)(ptr - pBuffer);
  2334. }
  2335. }
  2336. return false;
  2337. }
  2338. bool BufferEnd()
  2339. {
  2340. if (maxOffset == 0)
  2341. {
  2342. if (readState != ReadState.ReadWS && readState != ReadState.ReadValue)
  2343. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeReaderMalformedHeader)));
  2344. readState = ReadState.EOF;
  2345. return true;
  2346. }
  2347. return false;
  2348. }
  2349. // Resets the mail field reader to the new stream to reuse buffers
  2350. public void Reset(Stream stream)
  2351. {
  2352. if (stream == null)
  2353. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream");
  2354. if (readState != ReadState.EOF)
  2355. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MimeReaderResetCalledBeforeEOF)));
  2356. this.stream = stream;
  2357. readState = ReadState.ReadName;
  2358. maxOffset = 0;
  2359. offset = 0;
  2360. }
  2361. // helper methods
  2362. void AppendValue(string value, int maxBuffer, ref int remaining)
  2363. {
  2364. XmlMtomReader.DecrementBufferQuota(maxBuffer, ref remaining, value.Length * sizeof(char));
  2365. if (this.value == null)
  2366. this.value = value;
  2367. else
  2368. this.value += value;
  2369. }
  2370. void AppendName(string value, int maxBuffer, ref int remaining)
  2371. {
  2372. XmlMtomReader.DecrementBufferQuota(maxBuffer, ref remaining, value.Length * sizeof(char));
  2373. if (this.name == null)
  2374. this.name = value;
  2375. else
  2376. this.name += value;
  2377. }
  2378. }
  2379. internal class BufferedReadStream : Stream
  2380. {
  2381. Stream stream;
  2382. byte[] storedBuffer;
  2383. int storedLength;
  2384. int storedOffset;
  2385. bool readMore;
  2386. public BufferedReadStream(Stream stream)
  2387. : this(stream, false)
  2388. {
  2389. }
  2390. public BufferedReadStream(Stream stream, bool readMore)
  2391. {
  2392. if (stream == null)
  2393. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream");
  2394. this.stream = stream;
  2395. this.readMore = readMore;
  2396. }
  2397. public override bool CanWrite
  2398. {
  2399. get { return false; }
  2400. }
  2401. public override bool CanSeek
  2402. {
  2403. get { return false; }
  2404. }
  2405. public override bool CanRead
  2406. {
  2407. get { return stream.CanRead; }
  2408. }
  2409. public override long Length
  2410. {
  2411. get
  2412. {
  2413. #pragma warning suppress 56503 // [....], required by the Stream contract
  2414. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupportedOnStream, stream.GetType().FullName)));
  2415. }
  2416. }
  2417. public override long Position
  2418. {
  2419. get
  2420. {
  2421. #pragma warning suppress 56503 // [....], required by the Stream contract
  2422. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupportedOnStream, stream.GetType().FullName)));
  2423. }
  2424. set
  2425. {
  2426. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupportedOnStream, stream.GetType().FullName)));
  2427. }
  2428. }
  2429. public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  2430. {
  2431. if (!CanRead)
  2432. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ReadNotSupportedOnStream, stream.GetType().FullName)));
  2433. return stream.BeginRead(buffer, offset, count, callback, state);
  2434. }
  2435. public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  2436. {
  2437. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.WriteNotSupportedOnStream, stream.GetType().FullName)));
  2438. }
  2439. public override void Close()
  2440. {
  2441. stream.Close();
  2442. }
  2443. public override int EndRead(IAsyncResult asyncResult)
  2444. {
  2445. if (!CanRead)
  2446. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ReadNotSupportedOnStream, stream.GetType().FullName)));
  2447. return stream.EndRead(asyncResult);
  2448. }
  2449. public override void EndWrite(IAsyncResult asyncResult)
  2450. {
  2451. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.WriteNotSupportedOnStream, stream.GetType().FullName)));
  2452. }
  2453. public override void Flush()
  2454. {
  2455. stream.Flush();
  2456. }
  2457. public override int Read(byte[] buffer, int offset, int count)
  2458. {
  2459. if (!CanRead)
  2460. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ReadNotSupportedOnStream, stream.GetType().FullName)));
  2461. if (buffer == null)
  2462. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
  2463. if (offset < 0)
  2464. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.ValueMustBeNonNegative)));
  2465. if (offset > buffer.Length)
  2466. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", SR.GetString(SR.OffsetExceedsBufferSize, buffer.Length)));
  2467. if (count < 0)
  2468. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeNonNegative)));
  2469. if (count > buffer.Length - offset)
  2470. throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
  2471. int read = 0;
  2472. if (this.storedOffset < this.storedLength)
  2473. {
  2474. read = Math.Min(count, this.storedLength - this.storedOffset);
  2475. Buffer.BlockCopy(this.storedBuffer, this.storedOffset, buffer, offset, read);
  2476. this.storedOffset += read;
  2477. if (read == count || !this.readMore)
  2478. return read;
  2479. offset += read;
  2480. count -= read;
  2481. }
  2482. return read + stream.Read(buffer, offset, count);
  2483. }
  2484. public override int ReadByte()
  2485. {
  2486. if (this.storedOffset < this.storedLength)
  2487. return (int)this.storedBuffer[this.storedOffset++];
  2488. else
  2489. return base.ReadByte();
  2490. }
  2491. public int ReadBlock(byte[] buffer, int offset, int count)
  2492. {
  2493. int read;
  2494. int total = 0;
  2495. while (total < count && (read = Read(buffer, offset + total, count - total)) != 0)
  2496. {
  2497. total += read;
  2498. }
  2499. return total;
  2500. }
  2501. public void Push(byte[] buffer, int offset, int count)
  2502. {
  2503. if (count == 0)
  2504. return;
  2505. if (this.storedOffset == this.storedLength)
  2506. {
  2507. if (this.storedBuffer == null || this.storedBuffer.Length < count)
  2508. this.storedBuffer = new byte[count];
  2509. this.storedOffset = 0;
  2510. this.storedLength = count;
  2511. }
  2512. else
  2513. {
  2514. // if there's room to just insert before existing data
  2515. if (count <= this.storedOffset)
  2516. this.storedOffset -= count;
  2517. // if there's room in the buffer but need to shift things over
  2518. else if (count <= this.storedBuffer.Length - this.storedLength + this.storedOffset)
  2519. {
  2520. Buffer.BlockCopy(this.storedBuffer, this.storedOffset, this.storedBuffer, count, this.storedLength - this.storedOffset);
  2521. this.storedLength += count - this.storedOffset;
  2522. this.storedOffset = 0;
  2523. }
  2524. else
  2525. {
  2526. byte[] newBuffer = new byte[count + this.storedLength - this.storedOffset];
  2527. Buffer.BlockCopy(this.storedBuffer, this.storedOffset, newBuffer, count, this.storedLength - this.storedOffset);
  2528. this.storedLength += count - this.storedOffset;
  2529. this.storedOffset = 0;
  2530. this.storedBuffer = newBuffer;
  2531. }
  2532. }
  2533. Buffer.BlockCopy(buffer, offset, this.storedBuffer, this.storedOffset, count);
  2534. }
  2535. public override long Seek(long offset, SeekOrigin origin)
  2536. {
  2537. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupportedOnStream, stream.GetType().FullName)));
  2538. }
  2539. public override void SetLength(long value)
  2540. {
  2541. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupportedOnStream, stream.GetType().FullName)));
  2542. }
  2543. public override void Write(byte[] buffer, int offset, int count)
  2544. {
  2545. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.WriteNotSupportedOnStream, stream.GetType().FullName)));
  2546. }
  2547. }
  2548. internal static class MailBnfHelper
  2549. {
  2550. static bool[] s_fqtext = new bool[128];
  2551. static bool[] s_ttext = new bool[128];
  2552. static bool[] s_digits = new bool[128];
  2553. static bool[] s_boundary = new bool[128];
  2554. static MailBnfHelper()
  2555. {
  2556. // fqtext = %d1-9 / %d11 / %d12 / %d14-33 / %d35-91 / %d93-127
  2557. for (int i = 1; i <= 9; i++) { s_fqtext[i] = true; }
  2558. s_fqtext[11] = true;
  2559. s_fqtext[12] = true;
  2560. for (int i = 14; i <= 33; i++) { s_fqtext[i] = true; }
  2561. for (int i = 35; i <= 91; i++) { s_fqtext[i] = true; }
  2562. for (int i = 93; i <= 127; i++) { s_fqtext[i] = true; }
  2563. // ttext = %d33-126 except '()<>@,;:\"/[]?='
  2564. for (int i = 33; i <= 126; i++) { s_ttext[i] = true; }
  2565. s_ttext['('] = false;
  2566. s_ttext[')'] = false;
  2567. s_ttext['<'] = false;
  2568. s_ttext['>'] = false;
  2569. s_ttext['@'] = false;
  2570. s_ttext[','] = false;
  2571. s_ttext[';'] = false;
  2572. s_ttext[':'] = false;
  2573. s_ttext['\\'] = false;
  2574. s_ttext['"'] = false;
  2575. s_ttext['/'] = false;
  2576. s_ttext['['] = false;
  2577. s_ttext[']'] = false;
  2578. s_ttext['?'] = false;
  2579. s_ttext['='] = false;
  2580. // digits = %d48-57
  2581. for (int i = 48; i <= 57; i++)
  2582. s_digits[i] = true;
  2583. // boundary = DIGIT / ALPHA / "'" / "(" / ")" / "+" / "_" / "," / "-" / "." / "/" / ":" / "=" / "?" / " "
  2584. // cannot end with " "
  2585. for (int i = '0'; i <= '9'; i++) { s_boundary[i] = true; }
  2586. for (int i = 'A'; i <= 'Z'; i++) { s_boundary[i] = true; }
  2587. for (int i = 'a'; i <= 'z'; i++) { s_boundary[i] = true; }
  2588. s_boundary['\''] = true;
  2589. s_boundary['('] = true;
  2590. s_boundary[')'] = true;
  2591. s_boundary['+'] = true;
  2592. s_boundary['_'] = true;
  2593. s_boundary[','] = true;
  2594. s_boundary['-'] = true;
  2595. s_boundary['.'] = true;
  2596. s_boundary['/'] = true;
  2597. s_boundary[':'] = true;
  2598. s_boundary['='] = true;
  2599. s_boundary['?'] = true;
  2600. s_boundary[' '] = true;
  2601. }
  2602. public static bool SkipCFWS(string data, ref int offset)
  2603. {
  2604. int comments = 0;
  2605. for (; offset < data.Length; offset++)
  2606. {
  2607. if (data[offset] > 127)
  2608. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeHeaderInvalidCharacter, data[offset], ((int)data[offset]).ToString("X", CultureInfo.InvariantCulture))));
  2609. else if (data[offset] == '\\' && comments > 0)
  2610. offset += 2;
  2611. else if (data[offset] == '(')
  2612. comments++;
  2613. else if (data[offset] == ')')
  2614. comments--;
  2615. else if (data[offset] != ' ' && data[offset] != '\t' && comments == 0)
  2616. return true;
  2617. }
  2618. return false;
  2619. }
  2620. public static string ReadQuotedString(string data, ref int offset, StringBuilder builder)
  2621. {
  2622. // assume first char is the opening quote
  2623. int start = ++offset;
  2624. StringBuilder localBuilder = (builder != null ? builder : new StringBuilder());
  2625. for (; offset < data.Length; offset++)
  2626. {
  2627. if (data[offset] == '\\')
  2628. {
  2629. localBuilder.Append(data, start, offset - start);
  2630. start = ++offset;
  2631. continue;
  2632. }
  2633. else if (data[offset] == '"')
  2634. {
  2635. localBuilder.Append(data, start, offset - start);
  2636. offset++;
  2637. return (builder != null ? null : localBuilder.ToString());
  2638. }
  2639. else if (!(data[offset] < s_fqtext.Length && s_fqtext[data[offset]]))
  2640. {
  2641. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeHeaderInvalidCharacter, data[offset], ((int)data[offset]).ToString("X", CultureInfo.InvariantCulture))));
  2642. }
  2643. }
  2644. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeReaderMalformedHeader)));
  2645. }
  2646. public static string ReadParameterAttribute(string data, ref int offset, StringBuilder builder)
  2647. {
  2648. if (!SkipCFWS(data, ref offset))
  2649. return null;
  2650. return ReadToken(data, ref offset, null);
  2651. }
  2652. public static string ReadParameterValue(string data, ref int offset, StringBuilder builder)
  2653. {
  2654. if (!SkipCFWS(data, ref offset))
  2655. return string.Empty;
  2656. if (offset < data.Length && data[offset] == '"')
  2657. return ReadQuotedString(data, ref offset, builder);
  2658. else
  2659. return ReadToken(data, ref offset, builder);
  2660. }
  2661. public static string ReadToken(string data, ref int offset, StringBuilder builder)
  2662. {
  2663. int start = offset;
  2664. for (; offset < data.Length; offset++)
  2665. {
  2666. if (data[offset] > s_ttext.Length)
  2667. {
  2668. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeHeaderInvalidCharacter, data[offset], ((int)data[offset]).ToString("X", CultureInfo.InvariantCulture))));
  2669. }
  2670. else if (!s_ttext[data[offset]])
  2671. {
  2672. break;
  2673. }
  2674. }
  2675. return data.Substring(start, offset - start);
  2676. }
  2677. public static string ReadDigits(string data, ref int offset, StringBuilder builder)
  2678. {
  2679. int start = offset;
  2680. StringBuilder localBuilder = (builder != null ? builder : new StringBuilder());
  2681. for (; offset < data.Length && data[offset] < s_digits.Length && s_digits[data[offset]]; offset++);
  2682. localBuilder.Append(data, start, offset - start);
  2683. return (builder != null ? null : localBuilder.ToString());
  2684. }
  2685. public static bool IsValidMimeBoundary(string data)
  2686. {
  2687. int length = (data == null) ? 0 : data.Length;
  2688. if (length == 0 || length > 70 || data[length - 1] == ' ')
  2689. return false;
  2690. for (int i = 0; i < length; i++)
  2691. {
  2692. if (!(data[i] < s_boundary.Length && s_boundary[data[i]]))
  2693. return false;
  2694. }
  2695. return true;
  2696. }
  2697. }
  2698. }