HttpChannelHelpers.cs 169 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Channels
  5. {
  6. using System.Collections.Generic;
  7. using System.Collections.Specialized;
  8. using System.Diagnostics;
  9. using System.Globalization;
  10. using System.IO;
  11. using System.Net;
  12. using System.Net.Http;
  13. using System.Net.Http.Headers;
  14. using System.Net.Mime;
  15. using System.Net.Security;
  16. using System.Net.Sockets;
  17. using System.Reflection;
  18. using System.Runtime;
  19. using System.Runtime.CompilerServices;
  20. using System.Runtime.Diagnostics;
  21. using System.Security.Authentication.ExtendedProtection;
  22. using System.Security.Principal;
  23. using System.ServiceModel;
  24. using System.ServiceModel.Activation;
  25. using System.ServiceModel.Diagnostics;
  26. using System.ServiceModel.Diagnostics.Application;
  27. using System.ServiceModel.Security;
  28. using System.ServiceModel.Security.Tokens;
  29. using System.Text;
  30. using System.Threading;
  31. using System.Threading.Tasks;
  32. using System.Xml;
  33. // abstract out the common functionality of an "HttpInput"
  34. abstract class HttpInput
  35. {
  36. const string multipartRelatedMediaType = "multipart/related";
  37. const string startInfoHeaderParam = "start-info";
  38. const string defaultContentType = "application/octet-stream";
  39. BufferManager bufferManager;
  40. bool isRequest;
  41. MessageEncoder messageEncoder;
  42. IHttpTransportFactorySettings settings;
  43. bool streamed;
  44. WebException webException;
  45. Stream inputStream;
  46. bool enableChannelBinding;
  47. bool errorGettingInputStream;
  48. protected HttpInput(IHttpTransportFactorySettings settings, bool isRequest, bool enableChannelBinding)
  49. {
  50. this.settings = settings;
  51. this.bufferManager = settings.BufferManager;
  52. this.messageEncoder = settings.MessageEncoderFactory.Encoder;
  53. this.webException = null;
  54. this.isRequest = isRequest;
  55. this.inputStream = null;
  56. this.enableChannelBinding = enableChannelBinding;
  57. if (isRequest)
  58. {
  59. this.streamed = TransferModeHelper.IsRequestStreamed(settings.TransferMode);
  60. }
  61. else
  62. {
  63. this.streamed = TransferModeHelper.IsResponseStreamed(settings.TransferMode);
  64. }
  65. }
  66. internal static HttpInput CreateHttpInput(HttpWebResponse httpWebResponse, IHttpTransportFactorySettings settings, ChannelBinding channelBinding)
  67. {
  68. return new WebResponseHttpInput(httpWebResponse, settings, channelBinding);
  69. }
  70. internal WebException WebException
  71. {
  72. get { return webException; }
  73. set { webException = value; }
  74. }
  75. // Note: This method will return null in the case where throwOnError is false, and a non-fatal error occurs.
  76. // Please exercice caution when passing in throwOnError = false. This should basically only be done in error
  77. // code paths, or code paths where there is very good reason that you would not want this method to throw.
  78. // When passing in throwOnError = false, please handle the case where this method returns null.
  79. public Stream GetInputStream(bool throwOnError)
  80. {
  81. if (inputStream == null && (throwOnError || !this.errorGettingInputStream))
  82. {
  83. try
  84. {
  85. inputStream = GetInputStream();
  86. this.errorGettingInputStream = false;
  87. }
  88. catch (Exception e)
  89. {
  90. this.errorGettingInputStream = true;
  91. if (throwOnError || Fx.IsFatal(e))
  92. {
  93. throw;
  94. }
  95. DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
  96. }
  97. }
  98. return inputStream;
  99. }
  100. // -1 if chunked
  101. public abstract long ContentLength { get; }
  102. protected abstract string ContentTypeCore { get; }
  103. protected abstract bool HasContent { get; }
  104. protected abstract string SoapActionHeader { get; }
  105. protected abstract Stream GetInputStream();
  106. protected virtual ChannelBinding ChannelBinding { get { return null; } }
  107. protected string ContentType
  108. {
  109. get
  110. {
  111. string contentType = ContentTypeCore;
  112. if (string.IsNullOrEmpty(contentType))
  113. {
  114. return defaultContentType;
  115. }
  116. return contentType;
  117. }
  118. }
  119. void ThrowMaxReceivedMessageSizeExceeded()
  120. {
  121. if (TD.MaxReceivedMessageSizeExceededIsEnabled())
  122. {
  123. TD.MaxReceivedMessageSizeExceeded(SR.GetString(SR.MaxReceivedMessageSizeExceeded, settings.MaxReceivedMessageSize));
  124. }
  125. if (isRequest)
  126. {
  127. ThrowHttpProtocolException(SR.GetString(SR.MaxReceivedMessageSizeExceeded, settings.MaxReceivedMessageSize), HttpStatusCode.RequestEntityTooLarge);
  128. }
  129. else
  130. {
  131. string message = SR.GetString(SR.MaxReceivedMessageSizeExceeded, settings.MaxReceivedMessageSize);
  132. Exception inner = new QuotaExceededException(message);
  133. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(message, inner));
  134. }
  135. }
  136. Message DecodeBufferedMessage(ArraySegment<byte> buffer, Stream inputStream)
  137. {
  138. try
  139. {
  140. // if we're chunked, make sure we've consumed the whole body
  141. if (ContentLength == -1 && buffer.Count == settings.MaxReceivedMessageSize)
  142. {
  143. byte[] extraBuffer = new byte[1];
  144. int extraReceived = inputStream.Read(extraBuffer, 0, 1);
  145. if (extraReceived > 0)
  146. {
  147. ThrowMaxReceivedMessageSizeExceeded();
  148. }
  149. }
  150. try
  151. {
  152. return messageEncoder.ReadMessage(buffer, bufferManager, ContentType);
  153. }
  154. catch (XmlException xmlException)
  155. {
  156. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  157. new ProtocolException(SR.GetString(SR.MessageXmlProtocolError), xmlException));
  158. }
  159. }
  160. finally
  161. {
  162. inputStream.Close();
  163. }
  164. }
  165. Message ReadBufferedMessage(Stream inputStream)
  166. {
  167. ArraySegment<byte> messageBuffer = GetMessageBuffer();
  168. byte[] buffer = messageBuffer.Array;
  169. int offset = 0;
  170. int count = messageBuffer.Count;
  171. while (count > 0)
  172. {
  173. int bytesRead = inputStream.Read(buffer, offset, count);
  174. if (bytesRead == 0) // EOF
  175. {
  176. if (ContentLength != -1)
  177. {
  178. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  179. new ProtocolException(SR.GetString(SR.HttpContentLengthIncorrect)));
  180. }
  181. break;
  182. }
  183. count -= bytesRead;
  184. offset += bytesRead;
  185. }
  186. return DecodeBufferedMessage(new ArraySegment<byte>(buffer, 0, offset), inputStream);
  187. }
  188. Message ReadChunkedBufferedMessage(Stream inputStream)
  189. {
  190. try
  191. {
  192. return messageEncoder.ReadMessage(inputStream, bufferManager, settings.MaxBufferSize, ContentType);
  193. }
  194. catch (XmlException xmlException)
  195. {
  196. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  197. new ProtocolException(SR.GetString(SR.MessageXmlProtocolError), xmlException));
  198. }
  199. }
  200. Message ReadStreamedMessage(Stream inputStream)
  201. {
  202. MaxMessageSizeStream maxMessageSizeStream = new MaxMessageSizeStream(inputStream, settings.MaxReceivedMessageSize);
  203. try
  204. {
  205. return messageEncoder.ReadMessage(maxMessageSizeStream, settings.MaxBufferSize, ContentType);
  206. }
  207. catch (XmlException xmlException)
  208. {
  209. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  210. new ProtocolException(SR.GetString(SR.MessageXmlProtocolError), xmlException));
  211. }
  212. }
  213. protected abstract void AddProperties(Message message);
  214. void ApplyChannelBinding(Message message)
  215. {
  216. if (this.enableChannelBinding)
  217. {
  218. ChannelBindingUtility.TryAddToMessage(this.ChannelBinding, message, true);
  219. }
  220. }
  221. // makes sure that appropriate HTTP level headers are included in the received Message
  222. Exception ProcessHttpAddressing(Message message)
  223. {
  224. Exception result = null;
  225. AddProperties(message);
  226. // check if user is receiving WS-1 messages
  227. if (message.Version.Addressing == AddressingVersion.None)
  228. {
  229. bool actionAbsent = false;
  230. try
  231. {
  232. actionAbsent = (message.Headers.Action == null);
  233. }
  234. catch (XmlException e)
  235. {
  236. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  237. }
  238. catch (CommunicationException e)
  239. {
  240. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  241. }
  242. if (!actionAbsent)
  243. {
  244. result = new ProtocolException(SR.GetString(SR.HttpAddressingNoneHeaderOnWire,
  245. XD.AddressingDictionary.Action.Value));
  246. }
  247. bool toAbsent = false;
  248. try
  249. {
  250. toAbsent = (message.Headers.To == null);
  251. }
  252. catch (XmlException e)
  253. {
  254. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  255. }
  256. catch (CommunicationException e)
  257. {
  258. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  259. }
  260. if (!toAbsent)
  261. {
  262. result = new ProtocolException(SR.GetString(SR.HttpAddressingNoneHeaderOnWire,
  263. XD.AddressingDictionary.To.Value));
  264. }
  265. message.Headers.To = message.Properties.Via;
  266. }
  267. if (isRequest)
  268. {
  269. string action = null;
  270. if (message.Version.Envelope == EnvelopeVersion.Soap11)
  271. {
  272. action = SoapActionHeader;
  273. }
  274. else if (message.Version.Envelope == EnvelopeVersion.Soap12 && !String.IsNullOrEmpty(ContentType))
  275. {
  276. ContentType parsedContentType = new ContentType(ContentType);
  277. if (parsedContentType.MediaType == multipartRelatedMediaType && parsedContentType.Parameters.ContainsKey(startInfoHeaderParam))
  278. {
  279. // fix to grab action from start-info as stated in RFC2387
  280. action = new ContentType(parsedContentType.Parameters[startInfoHeaderParam]).Parameters["action"];
  281. }
  282. if (action == null)
  283. {
  284. // only if we can't find an action inside start-info
  285. action = parsedContentType.Parameters["action"];
  286. }
  287. }
  288. if (action != null)
  289. {
  290. action = UrlUtility.UrlDecode(action, Encoding.UTF8);
  291. if (action.Length >= 2 && action[0] == '"' && action[action.Length - 1] == '"')
  292. {
  293. action = action.Substring(1, action.Length - 2);
  294. }
  295. if (message.Version.Addressing == AddressingVersion.None)
  296. {
  297. message.Headers.Action = action;
  298. }
  299. try
  300. {
  301. if (action.Length > 0 && string.Compare(message.Headers.Action, action, StringComparison.Ordinal) != 0)
  302. {
  303. result = new ActionMismatchAddressingException(SR.GetString(SR.HttpSoapActionMismatchFault,
  304. message.Headers.Action, action), message.Headers.Action, action);
  305. }
  306. }
  307. catch (XmlException e)
  308. {
  309. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  310. }
  311. catch (CommunicationException e)
  312. {
  313. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  314. }
  315. }
  316. }
  317. ApplyChannelBinding(message);
  318. if (DiagnosticUtility.ShouldUseActivity)
  319. {
  320. TraceUtility.TransferFromTransport(message);
  321. }
  322. if (DiagnosticUtility.ShouldTraceInformation)
  323. {
  324. TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.MessageReceived, SR.GetString(SR.TraceCodeMessageReceived),
  325. MessageTransmitTraceRecord.CreateReceiveTraceRecord(message), this, null, message);
  326. }
  327. // MessageLogger doesn't log AddressingVersion.None in the encoder since we want to make sure we log
  328. // as much of the message as possible. Here we log after stamping the addressing information
  329. if (MessageLogger.LoggingEnabled && message.Version.Addressing == AddressingVersion.None)
  330. {
  331. MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportReceive | MessageLoggingSource.LastChance);
  332. }
  333. return result;
  334. }
  335. void ValidateContentType()
  336. {
  337. if (!HasContent)
  338. return;
  339. if (string.IsNullOrEmpty(ContentType))
  340. {
  341. if (MessageLogger.ShouldLogMalformed)
  342. {
  343. // We pass in throwOnError = false below so that the exception which is eventually thrown is the ProtocolException below, with Http status code 415 "UnsupportedMediaType"
  344. Stream stream = this.GetInputStream(false);
  345. if (stream != null)
  346. {
  347. MessageLogger.LogMessage(stream, MessageLoggingSource.Malformed);
  348. }
  349. }
  350. ThrowHttpProtocolException(SR.GetString(SR.HttpContentTypeHeaderRequired), HttpStatusCode.UnsupportedMediaType, HttpChannelUtilities.StatusDescriptionStrings.HttpContentTypeMissing);
  351. }
  352. if (!messageEncoder.IsContentTypeSupported(ContentType))
  353. {
  354. if (MessageLogger.ShouldLogMalformed)
  355. {
  356. // We pass in throwOnError = false below so that the exception which is eventually thrown is the ProtocolException below, with Http status code 415 "UnsupportedMediaType"
  357. Stream stream = this.GetInputStream(false);
  358. if (stream != null)
  359. {
  360. MessageLogger.LogMessage(stream, MessageLoggingSource.Malformed);
  361. }
  362. }
  363. string statusDescription = string.Format(CultureInfo.InvariantCulture, HttpChannelUtilities.StatusDescriptionStrings.HttpContentTypeMismatch, ContentType, messageEncoder.ContentType);
  364. ThrowHttpProtocolException(SR.GetString(SR.ContentTypeMismatch, ContentType, messageEncoder.ContentType), HttpStatusCode.UnsupportedMediaType, statusDescription);
  365. }
  366. }
  367. public IAsyncResult BeginParseIncomingMessage(AsyncCallback callback, object state)
  368. {
  369. return this.BeginParseIncomingMessage(null, callback, state);
  370. }
  371. public IAsyncResult BeginParseIncomingMessage(HttpRequestMessage httpRequestMessage, AsyncCallback callback, object state)
  372. {
  373. bool throwing = true;
  374. try
  375. {
  376. IAsyncResult result = new ParseMessageAsyncResult(httpRequestMessage, this, callback, state);
  377. throwing = false;
  378. return result;
  379. }
  380. finally
  381. {
  382. if (throwing)
  383. {
  384. Close();
  385. }
  386. }
  387. }
  388. public Message EndParseIncomingMessage(IAsyncResult result, out Exception requestException)
  389. {
  390. bool throwing = true;
  391. try
  392. {
  393. Message message = ParseMessageAsyncResult.End(result, out requestException);
  394. throwing = false;
  395. return message;
  396. }
  397. finally
  398. {
  399. if (throwing)
  400. {
  401. Close();
  402. }
  403. }
  404. }
  405. public HttpRequestMessageHttpInput CreateHttpRequestMessageInput()
  406. {
  407. HttpRequestMessage message = new HttpRequestMessage();
  408. if (this.HasContent)
  409. {
  410. message.Content = new StreamContent(new MaxMessageSizeStream(this.GetInputStream(true), this.settings.MaxReceivedMessageSize));
  411. }
  412. HttpChannelUtilities.EnsureHttpRequestMessageContentNotNull(message);
  413. this.ConfigureHttpRequestMessage(message);
  414. ChannelBinding channelBinding = this.enableChannelBinding ? this.ChannelBinding : null;
  415. return new HttpRequestMessageHttpInput(message, this.settings, this.enableChannelBinding, channelBinding);
  416. }
  417. public abstract void ConfigureHttpRequestMessage(HttpRequestMessage message);
  418. public Message ParseIncomingMessage(out Exception requestException)
  419. {
  420. return this.ParseIncomingMessage(null, out requestException);
  421. }
  422. public Message ParseIncomingMessage(HttpRequestMessage httpRequestMessage, out Exception requestException)
  423. {
  424. Message message = null;
  425. requestException = null;
  426. bool throwing = true;
  427. try
  428. {
  429. ValidateContentType();
  430. ServiceModelActivity activity = null;
  431. if (DiagnosticUtility.ShouldUseActivity &&
  432. ((ServiceModelActivity.Current == null) ||
  433. (ServiceModelActivity.Current.ActivityType != ActivityType.ProcessAction)))
  434. {
  435. activity = ServiceModelActivity.CreateBoundedActivity(true);
  436. }
  437. using (activity)
  438. {
  439. if (DiagnosticUtility.ShouldUseActivity && activity != null)
  440. {
  441. // Only update the Start identifier if the activity is not null.
  442. ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityProcessingMessage, TraceUtility.RetrieveMessageNumber()), ActivityType.ProcessMessage);
  443. }
  444. if (!this.HasContent)
  445. {
  446. if (this.messageEncoder.MessageVersion == MessageVersion.None)
  447. {
  448. message = new NullMessage();
  449. }
  450. else
  451. {
  452. return null;
  453. }
  454. }
  455. else
  456. {
  457. Stream stream = this.GetInputStream(true);
  458. if (streamed)
  459. {
  460. message = ReadStreamedMessage(stream);
  461. }
  462. else if (this.ContentLength == -1)
  463. {
  464. message = ReadChunkedBufferedMessage(stream);
  465. }
  466. else
  467. {
  468. if (httpRequestMessage == null)
  469. {
  470. message = ReadBufferedMessage(stream);
  471. }
  472. else
  473. {
  474. message = ReadBufferedMessage(httpRequestMessage);
  475. }
  476. }
  477. }
  478. requestException = ProcessHttpAddressing(message);
  479. throwing = false;
  480. return message;
  481. }
  482. }
  483. finally
  484. {
  485. if (throwing)
  486. {
  487. Close();
  488. }
  489. }
  490. }
  491. Message ReadBufferedMessage(HttpRequestMessage httpRequestMessage)
  492. {
  493. Fx.Assert(httpRequestMessage != null, "httpRequestMessage cannot be null.");
  494. Message message;
  495. using (HttpContent currentContent = httpRequestMessage.Content)
  496. {
  497. int length = (int)this.ContentLength;
  498. byte[] buffer = this.bufferManager.TakeBuffer(length);
  499. bool success = false;
  500. try
  501. {
  502. MemoryStream ms = new MemoryStream(buffer);
  503. currentContent.CopyToAsync(ms).Wait<CommunicationException>();
  504. httpRequestMessage.Content = new ByteArrayContent(buffer, 0, length);
  505. foreach (var header in currentContent.Headers)
  506. {
  507. httpRequestMessage.Content.Headers.Add(header.Key, header.Value);
  508. }
  509. //
  510. message = this.messageEncoder.ReadMessage(new ArraySegment<byte>(buffer, 0, length), this.bufferManager, this.ContentType);
  511. success = true;
  512. }
  513. finally
  514. {
  515. if (!success)
  516. {
  517. // We don't have to return it in success case since the buffer will be returned to bufferManager when the message is disposed.
  518. this.bufferManager.ReturnBuffer(buffer);
  519. }
  520. }
  521. }
  522. return message;
  523. }
  524. void ThrowHttpProtocolException(string message, HttpStatusCode statusCode)
  525. {
  526. ThrowHttpProtocolException(message, statusCode, null);
  527. }
  528. void ThrowHttpProtocolException(string message, HttpStatusCode statusCode, string statusDescription)
  529. {
  530. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateHttpProtocolException(message, statusCode, statusDescription, webException));
  531. }
  532. internal static ProtocolException CreateHttpProtocolException(string message, HttpStatusCode statusCode, string statusDescription, Exception innerException)
  533. {
  534. ProtocolException exception = new ProtocolException(message, innerException);
  535. exception.Data.Add(HttpChannelUtilities.HttpStatusCodeExceptionKey, statusCode);
  536. if (statusDescription != null && statusDescription.Length > 0)
  537. {
  538. exception.Data.Add(HttpChannelUtilities.HttpStatusDescriptionExceptionKey, statusDescription);
  539. }
  540. return exception;
  541. }
  542. protected virtual void Close()
  543. {
  544. }
  545. ArraySegment<byte> GetMessageBuffer()
  546. {
  547. long count = ContentLength;
  548. int bufferSize;
  549. if (count > settings.MaxReceivedMessageSize)
  550. {
  551. ThrowMaxReceivedMessageSizeExceeded();
  552. }
  553. bufferSize = (int)count;
  554. return new ArraySegment<byte>(bufferManager.TakeBuffer(bufferSize), 0, bufferSize);
  555. }
  556. class ParseMessageAsyncResult : TraceAsyncResult
  557. {
  558. ArraySegment<byte> buffer;
  559. int count;
  560. int offset;
  561. HttpInput httpInput;
  562. Stream inputStream;
  563. Message message;
  564. Exception requestException = null;
  565. HttpRequestMessage httpRequestMessage;
  566. static AsyncCallback onRead = Fx.ThunkCallback(new AsyncCallback(OnRead));
  567. public ParseMessageAsyncResult(
  568. HttpRequestMessage httpRequestMessage,
  569. HttpInput httpInput,
  570. AsyncCallback callback,
  571. object state)
  572. : base(callback, state)
  573. {
  574. this.httpInput = httpInput;
  575. this.httpRequestMessage = httpRequestMessage;
  576. this.BeginParse();
  577. }
  578. void BeginParse()
  579. {
  580. httpInput.ValidateContentType();
  581. this.inputStream = httpInput.GetInputStream(true);
  582. if (!httpInput.HasContent)
  583. {
  584. if (httpInput.messageEncoder.MessageVersion == MessageVersion.None)
  585. {
  586. this.message = new NullMessage();
  587. }
  588. else
  589. {
  590. base.Complete(true);
  591. return;
  592. }
  593. }
  594. else if (httpInput.streamed || httpInput.ContentLength == -1)
  595. {
  596. if (httpInput.streamed)
  597. {
  598. this.message = httpInput.ReadStreamedMessage(inputStream);
  599. }
  600. else
  601. {
  602. this.message = httpInput.ReadChunkedBufferedMessage(inputStream);
  603. }
  604. }
  605. if (this.message != null)
  606. {
  607. this.requestException = httpInput.ProcessHttpAddressing(this.message);
  608. base.Complete(true);
  609. return;
  610. }
  611. AsyncCompletionResult result;
  612. if (httpRequestMessage == null)
  613. {
  614. result = this.DecodeBufferedMessageAsync();
  615. }
  616. else
  617. {
  618. result = this.DecodeBufferedHttpRequestMessageAsync();
  619. }
  620. if (result == AsyncCompletionResult.Completed)
  621. {
  622. base.Complete(true);
  623. }
  624. }
  625. AsyncCompletionResult DecodeBufferedMessageAsync()
  626. {
  627. this.buffer = this.httpInput.GetMessageBuffer();
  628. this.count = this.buffer.Count;
  629. this.offset = 0;
  630. IAsyncResult result = inputStream.BeginRead(buffer.Array, offset, count, onRead, this);
  631. if (result.CompletedSynchronously)
  632. {
  633. if (ContinueReading(inputStream.EndRead(result)))
  634. {
  635. return AsyncCompletionResult.Completed;
  636. }
  637. }
  638. return AsyncCompletionResult.Queued;
  639. }
  640. bool ContinueReading(int bytesRead)
  641. {
  642. while (true)
  643. {
  644. if (bytesRead == 0) // EOF
  645. {
  646. break;
  647. }
  648. else
  649. {
  650. offset += bytesRead;
  651. count -= bytesRead;
  652. if (count <= 0)
  653. {
  654. break;
  655. }
  656. else
  657. {
  658. IAsyncResult result = inputStream.BeginRead(buffer.Array, offset, count, onRead, this);
  659. if (!result.CompletedSynchronously)
  660. {
  661. return false;
  662. }
  663. bytesRead = inputStream.EndRead(result);
  664. }
  665. }
  666. }
  667. using (DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.BoundOperation(this.CallbackActivity) : null)
  668. {
  669. using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity(true) : null)
  670. {
  671. if (DiagnosticUtility.ShouldUseActivity)
  672. {
  673. ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityProcessingMessage, TraceUtility.RetrieveMessageNumber()), ActivityType.ProcessMessage);
  674. }
  675. this.message = this.httpInput.DecodeBufferedMessage(new ArraySegment<byte>(buffer.Array, 0, offset), inputStream);
  676. this.requestException = this.httpInput.ProcessHttpAddressing(this.message);
  677. }
  678. return true;
  679. }
  680. }
  681. static void OnRead(IAsyncResult result)
  682. {
  683. if (result.CompletedSynchronously)
  684. return;
  685. ParseMessageAsyncResult thisPtr = (ParseMessageAsyncResult)result.AsyncState;
  686. Exception completionException = null;
  687. bool completeSelf;
  688. try
  689. {
  690. completeSelf = thisPtr.ContinueReading(thisPtr.inputStream.EndRead(result));
  691. }
  692. #pragma warning suppress 56500 // [....], transferring exception to another thread
  693. catch (Exception e)
  694. {
  695. if (Fx.IsFatal(e))
  696. {
  697. throw;
  698. }
  699. completeSelf = true;
  700. completionException = e;
  701. }
  702. if (completeSelf)
  703. {
  704. thisPtr.Complete(false, completionException);
  705. }
  706. }
  707. public static Message End(IAsyncResult result, out Exception requestException)
  708. {
  709. ParseMessageAsyncResult thisPtr = AsyncResult.End<ParseMessageAsyncResult>(result);
  710. requestException = thisPtr.requestException;
  711. return thisPtr.message;
  712. }
  713. AsyncCompletionResult DecodeBufferedHttpRequestMessageAsync()
  714. {
  715. // Need to consider moving this to async implemenation for HttpContent reading.(CSDMAIN: 229108)
  716. this.message = this.httpInput.ReadBufferedMessage(this.httpRequestMessage);
  717. this.requestException = this.httpInput.ProcessHttpAddressing(this.message);
  718. return AsyncCompletionResult.Completed;
  719. }
  720. }
  721. class WebResponseHttpInput : HttpInput
  722. {
  723. HttpWebResponse httpWebResponse;
  724. byte[] preReadBuffer;
  725. ChannelBinding channelBinding;
  726. bool hasContent;
  727. public WebResponseHttpInput(HttpWebResponse httpWebResponse, IHttpTransportFactorySettings settings, ChannelBinding channelBinding)
  728. : base(settings, false, channelBinding != null)
  729. {
  730. this.channelBinding = channelBinding;
  731. this.httpWebResponse = httpWebResponse;
  732. if (this.httpWebResponse.ContentLength == -1)
  733. {
  734. this.preReadBuffer = new byte[1];
  735. if (this.httpWebResponse.GetResponseStream().Read(preReadBuffer, 0, 1) == 0)
  736. {
  737. this.preReadBuffer = null;
  738. }
  739. }
  740. this.hasContent = (this.preReadBuffer != null || this.httpWebResponse.ContentLength > 0);
  741. if (!this.hasContent)
  742. {
  743. // Close the response stream to avoid leaking the connection.
  744. this.httpWebResponse.GetResponseStream().Close();
  745. }
  746. }
  747. protected override ChannelBinding ChannelBinding
  748. {
  749. get
  750. {
  751. return this.channelBinding;
  752. }
  753. }
  754. public override long ContentLength
  755. {
  756. get
  757. {
  758. return httpWebResponse.ContentLength;
  759. }
  760. }
  761. protected override string ContentTypeCore
  762. {
  763. get
  764. {
  765. return httpWebResponse.ContentType;
  766. }
  767. }
  768. protected override bool HasContent
  769. {
  770. get { return this.hasContent; }
  771. }
  772. protected override string SoapActionHeader
  773. {
  774. get
  775. {
  776. return httpWebResponse.Headers["SOAPAction"];
  777. }
  778. }
  779. protected override void AddProperties(Message message)
  780. {
  781. HttpResponseMessageProperty responseProperty = new HttpResponseMessageProperty(httpWebResponse.Headers);
  782. responseProperty.StatusCode = httpWebResponse.StatusCode;
  783. responseProperty.StatusDescription = httpWebResponse.StatusDescription;
  784. message.Properties.Add(HttpResponseMessageProperty.Name, responseProperty);
  785. message.Properties.Via = message.Version.Addressing.AnonymousUri;
  786. }
  787. public override void ConfigureHttpRequestMessage(HttpRequestMessage message)
  788. {
  789. // HTTP pipeline for client side is not implemented yet
  790. // DCR CSDMain 216853 is tracking this
  791. // This API is never going to be called in current stack
  792. Fx.Assert(false, "HTTP pipeline for client is not implemented yet. This method should not be called.");
  793. throw FxTrace.Exception.AsError(new NotSupportedException());
  794. }
  795. protected override void Close()
  796. {
  797. try
  798. {
  799. httpWebResponse.Close();
  800. }
  801. catch (Exception exception)
  802. {
  803. if (Fx.IsFatal(exception))
  804. throw;
  805. DiagnosticUtility.TraceHandledException(exception, TraceEventType.Error);
  806. }
  807. }
  808. protected override Stream GetInputStream()
  809. {
  810. Fx.Assert(this.HasContent, "this.HasContent must be true.");
  811. if (this.preReadBuffer != null)
  812. {
  813. return new WebResponseInputStream(httpWebResponse, preReadBuffer);
  814. }
  815. else
  816. {
  817. return new WebResponseInputStream(httpWebResponse);
  818. }
  819. }
  820. class WebResponseInputStream : DetectEofStream
  821. {
  822. // in order to avoid ----ing kernel buffers, we throttle our reads. http.sys
  823. // deals with this fine, but System.Net doesn't do any such throttling.
  824. const int maxSocketRead = 64 * 1024;
  825. HttpWebResponse webResponse;
  826. bool responseClosed;
  827. public WebResponseInputStream(HttpWebResponse httpWebResponse)
  828. : base(httpWebResponse.GetResponseStream())
  829. {
  830. this.webResponse = httpWebResponse;
  831. }
  832. public WebResponseInputStream(HttpWebResponse httpWebResponse, byte[] prereadBuffer)
  833. : base(new PreReadStream(httpWebResponse.GetResponseStream(), prereadBuffer))
  834. {
  835. this.webResponse = httpWebResponse;
  836. }
  837. public override void Close()
  838. {
  839. base.Close();
  840. CloseResponse();
  841. }
  842. protected override void OnReceivedEof()
  843. {
  844. base.OnReceivedEof();
  845. CloseResponse();
  846. }
  847. void CloseResponse()
  848. {
  849. if (responseClosed)
  850. {
  851. return;
  852. }
  853. responseClosed = true;
  854. this.webResponse.Close();
  855. }
  856. public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  857. {
  858. try
  859. {
  860. return BaseStream.BeginRead(buffer, offset, Math.Min(count, maxSocketRead), callback, state);
  861. }
  862. catch (IOException ioException)
  863. {
  864. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateResponseIOException(ioException, TimeoutHelper.FromMilliseconds(this.ReadTimeout)));
  865. }
  866. catch (ObjectDisposedException objectDisposedException)
  867. {
  868. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(objectDisposedException.Message, objectDisposedException));
  869. }
  870. catch (WebException webException)
  871. {
  872. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateResponseWebException(webException, this.webResponse));
  873. }
  874. }
  875. public override int EndRead(IAsyncResult result)
  876. {
  877. try
  878. {
  879. return BaseStream.EndRead(result);
  880. }
  881. catch (IOException ioException)
  882. {
  883. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateResponseIOException(ioException, TimeoutHelper.FromMilliseconds(this.ReadTimeout)));
  884. }
  885. catch (ObjectDisposedException objectDisposedException)
  886. {
  887. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(objectDisposedException.Message, objectDisposedException));
  888. }
  889. catch (WebException webException)
  890. {
  891. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateResponseWebException(webException, this.webResponse));
  892. }
  893. }
  894. public override int Read(byte[] buffer, int offset, int count)
  895. {
  896. try
  897. {
  898. return BaseStream.Read(buffer, offset, Math.Min(count, maxSocketRead));
  899. }
  900. catch (ObjectDisposedException objectDisposedException)
  901. {
  902. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(objectDisposedException.Message, objectDisposedException));
  903. }
  904. catch (IOException ioException)
  905. {
  906. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateResponseIOException(ioException, TimeoutHelper.FromMilliseconds(this.ReadTimeout)));
  907. }
  908. catch (WebException webException)
  909. {
  910. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateResponseWebException(webException, this.webResponse));
  911. }
  912. }
  913. public override int ReadByte()
  914. {
  915. try
  916. {
  917. return BaseStream.ReadByte();
  918. }
  919. catch (ObjectDisposedException objectDisposedException)
  920. {
  921. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(objectDisposedException.Message, objectDisposedException));
  922. }
  923. catch (IOException ioException)
  924. {
  925. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateResponseIOException(ioException, TimeoutHelper.FromMilliseconds(this.ReadTimeout)));
  926. }
  927. catch (WebException webException)
  928. {
  929. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateResponseWebException(webException, this.webResponse));
  930. }
  931. }
  932. }
  933. }
  934. }
  935. // abstract out the common functionality of an "HttpOutput"
  936. abstract class HttpOutput
  937. {
  938. const string DefaultMimeVersion = "1.0";
  939. HttpAbortReason abortReason;
  940. bool isDisposed;
  941. bool isRequest;
  942. Message message;
  943. IHttpTransportFactorySettings settings;
  944. byte[] bufferToRecycle;
  945. BufferManager bufferManager;
  946. MessageEncoder messageEncoder;
  947. bool streamed;
  948. static Action<object> onStreamSendTimeout;
  949. string mtomBoundary;
  950. Stream outputStream;
  951. bool supportsConcurrentIO;
  952. EventTraceActivity eventTraceActivity;
  953. bool canSendCompressedResponses;
  954. protected HttpOutput(IHttpTransportFactorySettings settings, Message message, bool isRequest, bool supportsConcurrentIO)
  955. {
  956. this.settings = settings;
  957. this.message = message;
  958. this.isRequest = isRequest;
  959. this.bufferManager = settings.BufferManager;
  960. this.messageEncoder = settings.MessageEncoderFactory.Encoder;
  961. ICompressedMessageEncoder compressedMessageEncoder = this.messageEncoder as ICompressedMessageEncoder;
  962. this.canSendCompressedResponses = compressedMessageEncoder != null && compressedMessageEncoder.CompressionEnabled;
  963. if (isRequest)
  964. {
  965. this.streamed = TransferModeHelper.IsRequestStreamed(settings.TransferMode);
  966. }
  967. else
  968. {
  969. this.streamed = TransferModeHelper.IsResponseStreamed(settings.TransferMode);
  970. }
  971. this.supportsConcurrentIO = supportsConcurrentIO;
  972. if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled)
  973. {
  974. this.eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
  975. }
  976. }
  977. protected virtual bool IsChannelBindingSupportEnabled { get { return false; } }
  978. protected virtual ChannelBinding ChannelBinding { get { return null; } }
  979. protected void Abort()
  980. {
  981. Abort(HttpAbortReason.Aborted);
  982. }
  983. public virtual void Abort(HttpAbortReason reason)
  984. {
  985. if (isDisposed)
  986. {
  987. return;
  988. }
  989. this.abortReason = reason;
  990. TraceRequestResponseAborted(reason);
  991. CleanupBuffer();
  992. }
  993. private void TraceRequestResponseAborted(HttpAbortReason reason)
  994. {
  995. if (isRequest)
  996. {
  997. if (TD.HttpChannelRequestAbortedIsEnabled())
  998. {
  999. TD.HttpChannelRequestAborted(this.eventTraceActivity);
  1000. }
  1001. }
  1002. else if (TD.HttpChannelResponseAbortedIsEnabled())
  1003. {
  1004. TD.HttpChannelResponseAborted(this.eventTraceActivity);
  1005. }
  1006. if (DiagnosticUtility.ShouldTraceWarning)
  1007. {
  1008. TraceUtility.TraceEvent(TraceEventType.Warning,
  1009. isRequest ? TraceCode.HttpChannelRequestAborted : TraceCode.HttpChannelResponseAborted,
  1010. isRequest ? SR.GetString(SR.TraceCodeHttpChannelRequestAborted) : SR.GetString(SR.TraceCodeHttpChannelResponseAborted),
  1011. this.message);
  1012. }
  1013. }
  1014. public void Close()
  1015. {
  1016. if (isDisposed)
  1017. {
  1018. return;
  1019. }
  1020. try
  1021. {
  1022. if (this.outputStream != null)
  1023. {
  1024. outputStream.Close();
  1025. }
  1026. }
  1027. finally
  1028. {
  1029. CleanupBuffer();
  1030. }
  1031. }
  1032. void CleanupBuffer()
  1033. {
  1034. byte[] bufferToRecycleSnapshot = Interlocked.Exchange<byte[]>(ref this.bufferToRecycle, null);
  1035. if (bufferToRecycleSnapshot != null)
  1036. {
  1037. bufferManager.ReturnBuffer(bufferToRecycleSnapshot);
  1038. }
  1039. isDisposed = true;
  1040. }
  1041. protected abstract void AddMimeVersion(string version);
  1042. protected abstract void AddHeader(string name, string value);
  1043. protected abstract void SetContentType(string contentType);
  1044. protected abstract void SetContentEncoding(string contentEncoding);
  1045. protected abstract void SetStatusCode(HttpStatusCode statusCode);
  1046. protected abstract void SetStatusDescription(string statusDescription);
  1047. protected virtual bool CleanupChannelBinding { get { return true; } }
  1048. protected virtual void SetContentLength(int contentLength)
  1049. {
  1050. }
  1051. protected virtual string HttpMethod { get { return null; } }
  1052. public virtual ChannelBinding TakeChannelBinding()
  1053. {
  1054. return null;
  1055. }
  1056. private void ApplyChannelBinding()
  1057. {
  1058. if (this.IsChannelBindingSupportEnabled)
  1059. {
  1060. ChannelBindingUtility.TryAddToMessage(this.ChannelBinding, this.message, this.CleanupChannelBinding);
  1061. }
  1062. }
  1063. protected abstract Stream GetOutputStream();
  1064. protected virtual bool WillGetOutputStreamCompleteSynchronously
  1065. {
  1066. get { return true; }
  1067. }
  1068. protected bool CanSendCompressedResponses
  1069. {
  1070. get { return this.canSendCompressedResponses; }
  1071. }
  1072. protected virtual IAsyncResult BeginGetOutputStream(AsyncCallback callback, object state)
  1073. {
  1074. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
  1075. }
  1076. protected virtual Stream EndGetOutputStream(IAsyncResult result)
  1077. {
  1078. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
  1079. }
  1080. public void ConfigureHttpResponseMessage(Message message, HttpResponseMessage httpResponseMessage, HttpResponseMessageProperty responseProperty)
  1081. {
  1082. HttpChannelUtilities.EnsureHttpResponseMessageContentNotNull(httpResponseMessage);
  1083. string action = message.Headers.Action;
  1084. if (message.Version.Addressing == AddressingVersion.None)
  1085. {
  1086. if (MessageLogger.LogMessagesAtTransportLevel)
  1087. {
  1088. message.Properties.Add(AddressingProperty.Name, new AddressingProperty(message.Headers));
  1089. }
  1090. message.Headers.Action = null;
  1091. message.Headers.To = null;
  1092. }
  1093. bool httpResponseMessagePropertyFound = responseProperty != null;
  1094. string contentType = null;
  1095. if (message.Version == MessageVersion.None && httpResponseMessagePropertyFound && !string.IsNullOrEmpty(responseProperty.Headers[HttpResponseHeader.ContentType]))
  1096. {
  1097. contentType = responseProperty.Headers[HttpResponseHeader.ContentType];
  1098. responseProperty.Headers.Remove(HttpResponseHeader.ContentType);
  1099. if (!messageEncoder.IsContentTypeSupported(contentType))
  1100. {
  1101. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  1102. new ProtocolException(SR.GetString(SR.ResponseContentTypeNotSupported,
  1103. contentType)));
  1104. }
  1105. }
  1106. if (string.IsNullOrEmpty(contentType))
  1107. {
  1108. MtomMessageEncoder mtomMessageEncoder = messageEncoder as MtomMessageEncoder;
  1109. if (mtomMessageEncoder == null)
  1110. {
  1111. contentType = messageEncoder.ContentType;
  1112. }
  1113. else
  1114. {
  1115. contentType = mtomMessageEncoder.GetContentType(out this.mtomBoundary);
  1116. // For MTOM messages, add a MIME version header
  1117. httpResponseMessage.Headers.Add(HttpChannelUtilities.MIMEVersionHeader, DefaultMimeVersion);
  1118. }
  1119. }
  1120. if (isRequest && FxTrace.Trace.IsEnd2EndActivityTracingEnabled)
  1121. {
  1122. EnsureEventTraceActivity(message);
  1123. }
  1124. if (this.CanSendCompressedResponses)
  1125. {
  1126. string contentEncoding;
  1127. string compressionContentType = contentType;
  1128. if (HttpChannelUtilities.GetHttpResponseTypeAndEncodingForCompression(ref compressionContentType, out contentEncoding))
  1129. {
  1130. contentType = compressionContentType;
  1131. this.SetContentEncoding(contentEncoding);
  1132. }
  1133. }
  1134. if (httpResponseMessage.Content != null && !string.IsNullOrEmpty(contentType))
  1135. {
  1136. MediaTypeHeaderValue mediaTypeHeaderValue;
  1137. if (!MediaTypeHeaderValue.TryParse(contentType, out mediaTypeHeaderValue))
  1138. {
  1139. throw FxTrace.Exception.Argument("contentType", SR.GetString(SR.InvalidContentTypeError, contentType));
  1140. }
  1141. httpResponseMessage.Content.Headers.ContentType = mediaTypeHeaderValue;
  1142. }
  1143. bool httpMethodIsHead = string.Compare(this.HttpMethod, "HEAD", StringComparison.OrdinalIgnoreCase) == 0;
  1144. if (httpMethodIsHead ||
  1145. httpResponseMessagePropertyFound && responseProperty.SuppressEntityBody)
  1146. {
  1147. httpResponseMessage.Content.Headers.ContentLength = 0;
  1148. httpResponseMessage.Content.Headers.ContentType = null;
  1149. }
  1150. if (httpResponseMessagePropertyFound)
  1151. {
  1152. httpResponseMessage.StatusCode = responseProperty.StatusCode;
  1153. if (responseProperty.StatusDescription != null)
  1154. {
  1155. responseProperty.StatusDescription = responseProperty.StatusDescription;
  1156. }
  1157. foreach (string key in responseProperty.Headers.AllKeys)
  1158. {
  1159. httpResponseMessage.AddHeader(key, responseProperty.Headers[key]);
  1160. }
  1161. }
  1162. if (!message.IsEmpty)
  1163. {
  1164. using (HttpContent content = httpResponseMessage.Content)
  1165. {
  1166. if (this.streamed)
  1167. {
  1168. IStreamedMessageEncoder streamedMessageEncoder = this.messageEncoder as IStreamedMessageEncoder;
  1169. Stream stream = null;
  1170. if (streamedMessageEncoder != null)
  1171. {
  1172. stream = streamedMessageEncoder.GetResponseMessageStream(message);
  1173. }
  1174. if (stream != null)
  1175. {
  1176. httpResponseMessage.Content = new StreamContent(stream);
  1177. }
  1178. else
  1179. {
  1180. httpResponseMessage.Content = new OpaqueContent(this.messageEncoder, message, this.mtomBoundary);
  1181. }
  1182. }
  1183. else
  1184. {
  1185. // HttpOutputByteArrayContent assumes responsibility for returning the buffer to the bufferManager.
  1186. ArraySegment<byte> messageBytes = this.SerializeBufferedMessage(message, false);
  1187. httpResponseMessage.Content = new HttpOutputByteArrayContent(messageBytes.Array, messageBytes.Offset, messageBytes.Count, this.bufferManager);
  1188. }
  1189. httpResponseMessage.Content.Headers.Clear();
  1190. foreach (var header in content.Headers)
  1191. {
  1192. httpResponseMessage.Content.Headers.Add(header.Key, header.Value);
  1193. }
  1194. }
  1195. }
  1196. }
  1197. protected virtual bool PrepareHttpSend(Message message)
  1198. {
  1199. string action = message.Headers.Action;
  1200. if (message.Version.Addressing == AddressingVersion.None)
  1201. {
  1202. if (MessageLogger.LogMessagesAtTransportLevel)
  1203. {
  1204. message.Properties.Add(AddressingProperty.Name, new AddressingProperty(message.Headers));
  1205. }
  1206. message.Headers.Action = null;
  1207. message.Headers.To = null;
  1208. }
  1209. string contentType = null;
  1210. if (message.Version == MessageVersion.None)
  1211. {
  1212. object property = null;
  1213. if (message.Properties.TryGetValue(HttpResponseMessageProperty.Name, out property))
  1214. {
  1215. HttpResponseMessageProperty responseProperty = (HttpResponseMessageProperty)property;
  1216. if (!string.IsNullOrEmpty(responseProperty.Headers[HttpResponseHeader.ContentType]))
  1217. {
  1218. contentType = responseProperty.Headers[HttpResponseHeader.ContentType];
  1219. if (!messageEncoder.IsContentTypeSupported(contentType))
  1220. {
  1221. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  1222. new ProtocolException(SR.GetString(SR.ResponseContentTypeNotSupported,
  1223. contentType)));
  1224. }
  1225. }
  1226. }
  1227. }
  1228. if (string.IsNullOrEmpty(contentType))
  1229. {
  1230. MtomMessageEncoder mtomMessageEncoder = messageEncoder as MtomMessageEncoder;
  1231. if (mtomMessageEncoder == null)
  1232. {
  1233. contentType = messageEncoder.ContentType;
  1234. }
  1235. else
  1236. {
  1237. contentType = mtomMessageEncoder.GetContentType(out this.mtomBoundary);
  1238. // For MTOM messages, add a MIME version header
  1239. AddMimeVersion("1.0");
  1240. }
  1241. }
  1242. if (isRequest && FxTrace.Trace.IsEnd2EndActivityTracingEnabled)
  1243. {
  1244. EnsureEventTraceActivity(message);
  1245. }
  1246. SetContentType(contentType);
  1247. return message is NullMessage;
  1248. }
  1249. protected bool PrepareHttpSend(HttpResponseMessage httpResponseMessage)
  1250. {
  1251. this.PrepareHttpSendCore(httpResponseMessage);
  1252. return HttpChannelUtilities.IsEmpty(httpResponseMessage);
  1253. }
  1254. protected abstract void PrepareHttpSendCore(HttpResponseMessage message);
  1255. private static void EnsureEventTraceActivity(Message message)
  1256. {
  1257. //We need to send this only if there is no message id.
  1258. if (message.Headers.MessageId == null)
  1259. {
  1260. EventTraceActivity eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
  1261. if (eventTraceActivity == null)
  1262. {
  1263. //Whoops no activity on the message yet.
  1264. eventTraceActivity = new EventTraceActivity();
  1265. EventTraceActivityHelper.TryAttachActivity(message, eventTraceActivity);
  1266. }
  1267. HttpRequestMessageProperty httpProperties;
  1268. if (!message.Properties.TryGetValue<HttpRequestMessageProperty>(HttpRequestMessageProperty.Name, out httpProperties))
  1269. {
  1270. httpProperties = new HttpRequestMessageProperty();
  1271. message.Properties.Add(HttpRequestMessageProperty.Name, httpProperties);
  1272. }
  1273. httpProperties.Headers.Add(EventTraceActivity.Name, Convert.ToBase64String(eventTraceActivity.ActivityId.ToByteArray()));
  1274. }
  1275. }
  1276. ArraySegment<byte> SerializeBufferedMessage(Message message)
  1277. {
  1278. // by default, the HttpOutput should own the buffer and clean it up
  1279. return SerializeBufferedMessage(message, true);
  1280. }
  1281. ArraySegment<byte> SerializeBufferedMessage(Message message, bool shouldRecycleBuffer)
  1282. {
  1283. ArraySegment<byte> result;
  1284. MtomMessageEncoder mtomMessageEncoder = messageEncoder as MtomMessageEncoder;
  1285. if (mtomMessageEncoder == null)
  1286. {
  1287. result = messageEncoder.WriteMessage(message, int.MaxValue, bufferManager);
  1288. }
  1289. else
  1290. {
  1291. result = mtomMessageEncoder.WriteMessage(message, int.MaxValue, bufferManager, 0, this.mtomBoundary);
  1292. }
  1293. if (shouldRecycleBuffer)
  1294. {
  1295. // Only set this.bufferToRecycle if the HttpOutput owns the buffer, we will clean it up upon httpOutput.Close()
  1296. // Otherwise, caller of SerializeBufferedMessage assumes responsiblity for returning the buffer to the buffer pool
  1297. this.bufferToRecycle = result.Array;
  1298. }
  1299. return result;
  1300. }
  1301. Stream GetWrappedOutputStream()
  1302. {
  1303. const int ChunkSize = 32768; // buffer size used for synchronous writes
  1304. const int BufferSize = 16384; // buffer size used for asynchronous writes
  1305. const int BufferCount = 4; // buffer count used for asynchronous writes
  1306. // Writing an HTTP request chunk has a high fixed cost, so use BufferedStream to avoid writing
  1307. // small ones.
  1308. return this.supportsConcurrentIO ? (Stream)new BufferedOutputAsyncStream(this.outputStream, BufferSize, BufferCount) : new BufferedStream(this.outputStream, ChunkSize);
  1309. }
  1310. void WriteStreamedMessage(TimeSpan timeout)
  1311. {
  1312. this.outputStream = GetWrappedOutputStream();
  1313. // Since HTTP streams don't support timeouts, we can't just use TimeoutStream here.
  1314. // Rather, we need to run a timer to bound the overall operation
  1315. if (onStreamSendTimeout == null)
  1316. {
  1317. onStreamSendTimeout = new Action<object>(OnStreamSendTimeout);
  1318. }
  1319. IOThreadTimer sendTimer = new IOThreadTimer(onStreamSendTimeout, this, true);
  1320. sendTimer.Set(timeout);
  1321. try
  1322. {
  1323. MtomMessageEncoder mtomMessageEncoder = messageEncoder as MtomMessageEncoder;
  1324. if (mtomMessageEncoder == null)
  1325. {
  1326. messageEncoder.WriteMessage(this.message, this.outputStream);
  1327. }
  1328. else
  1329. {
  1330. mtomMessageEncoder.WriteMessage(this.message, this.outputStream, this.mtomBoundary);
  1331. }
  1332. }
  1333. finally
  1334. {
  1335. sendTimer.Cancel();
  1336. }
  1337. }
  1338. static void OnStreamSendTimeout(object state)
  1339. {
  1340. HttpOutput thisPtr = (HttpOutput)state;
  1341. thisPtr.Abort(HttpAbortReason.TimedOut);
  1342. }
  1343. IAsyncResult BeginWriteStreamedMessage(HttpResponseMessage httpResponseMessage, TimeSpan timeout, AsyncCallback callback, object state)
  1344. {
  1345. return new WriteStreamedMessageAsyncResult(timeout, this, httpResponseMessage, callback, state);
  1346. }
  1347. void EndWriteStreamedMessage(IAsyncResult result)
  1348. {
  1349. WriteStreamedMessageAsyncResult.End(result);
  1350. }
  1351. class HttpOutputByteArrayContent : ByteArrayContent
  1352. {
  1353. BufferManager bufferManager;
  1354. volatile bool cleaned = false;
  1355. ArraySegment<byte> content;
  1356. public HttpOutputByteArrayContent(byte[] content, int offset, int count, BufferManager bufferManager)
  1357. : base(content, offset, count)
  1358. {
  1359. Fx.Assert(bufferManager != null, "bufferManager should not be null");
  1360. Fx.Assert(content != null, "content should not be null");
  1361. this.content = new ArraySegment<byte>(content, offset, count);
  1362. this.bufferManager = bufferManager;
  1363. }
  1364. public ArraySegment<byte> Content
  1365. {
  1366. get
  1367. {
  1368. return this.content;
  1369. }
  1370. }
  1371. protected override Task<Stream> CreateContentReadStreamAsync()
  1372. {
  1373. return base.CreateContentReadStreamAsync().ContinueWith<Stream>(t =>
  1374. new HttpOutputByteArrayContentStream(t.Result, this));
  1375. }
  1376. protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
  1377. {
  1378. return base.SerializeToStreamAsync(stream, context).ContinueWith(t =>
  1379. {
  1380. this.Cleanup();
  1381. HttpChannelUtilities.HandleContinueWithTask(t);
  1382. });
  1383. }
  1384. void Cleanup()
  1385. {
  1386. if (!cleaned)
  1387. {
  1388. lock (this)
  1389. {
  1390. if (!cleaned)
  1391. {
  1392. cleaned = true;
  1393. this.bufferManager.ReturnBuffer(this.content.Array);
  1394. }
  1395. }
  1396. }
  1397. }
  1398. class HttpOutputByteArrayContentStream : DelegatingStream
  1399. {
  1400. HttpOutputByteArrayContent content;
  1401. public HttpOutputByteArrayContentStream(Stream innerStream, HttpOutputByteArrayContent content)
  1402. : base(innerStream)
  1403. {
  1404. this.content = content;
  1405. }
  1406. public override void Close()
  1407. {
  1408. base.Close();
  1409. this.content.Cleanup();
  1410. }
  1411. }
  1412. }
  1413. class WriteStreamedMessageAsyncResult : AsyncResult
  1414. {
  1415. HttpOutput httpOutput;
  1416. IOThreadTimer sendTimer;
  1417. static AsyncCallback onWriteStreamedMessage = Fx.ThunkCallback(OnWriteStreamedMessage);
  1418. HttpResponseMessage httpResponseMessage;
  1419. public WriteStreamedMessageAsyncResult(TimeSpan timeout, HttpOutput httpOutput, HttpResponseMessage httpResponseMessage, AsyncCallback callback, object state)
  1420. : base(callback, state)
  1421. {
  1422. this.httpResponseMessage = httpResponseMessage;
  1423. this.httpOutput = httpOutput;
  1424. httpOutput.outputStream = httpOutput.GetWrappedOutputStream();
  1425. // Since HTTP streams don't support timeouts, we can't just use TimeoutStream here.
  1426. // Rather, we need to run a timer to bound the overall operation
  1427. if (onStreamSendTimeout == null)
  1428. {
  1429. onStreamSendTimeout = new Action<object>(OnStreamSendTimeout);
  1430. }
  1431. this.SetTimer(timeout);
  1432. bool completeSelf = false;
  1433. bool throwing = true;
  1434. try
  1435. {
  1436. completeSelf = HandleWriteStreamedMessage(null);
  1437. throwing = false;
  1438. }
  1439. finally
  1440. {
  1441. if (completeSelf || throwing)
  1442. {
  1443. this.sendTimer.Cancel();
  1444. }
  1445. }
  1446. if (completeSelf)
  1447. {
  1448. this.Complete(true);
  1449. }
  1450. }
  1451. bool HandleWriteStreamedMessage(IAsyncResult result)
  1452. {
  1453. if (this.httpResponseMessage == null)
  1454. {
  1455. if (result == null)
  1456. {
  1457. MtomMessageEncoder mtomMessageEncoder = httpOutput.messageEncoder as MtomMessageEncoder;
  1458. if (mtomMessageEncoder == null)
  1459. {
  1460. result = httpOutput.messageEncoder.BeginWriteMessage(httpOutput.message, httpOutput.outputStream, onWriteStreamedMessage, this);
  1461. }
  1462. else
  1463. {
  1464. result = mtomMessageEncoder.BeginWriteMessage(httpOutput.message, httpOutput.outputStream, httpOutput.mtomBoundary, onWriteStreamedMessage, this);
  1465. }
  1466. if (!result.CompletedSynchronously)
  1467. {
  1468. return false;
  1469. }
  1470. }
  1471. httpOutput.messageEncoder.EndWriteMessage(result);
  1472. return true;
  1473. }
  1474. else
  1475. {
  1476. OpaqueContent content = this.httpResponseMessage.Content as OpaqueContent;
  1477. if (result == null)
  1478. {
  1479. Fx.Assert(this.httpResponseMessage.Content != null, "httpOutput.httpResponseMessage.Content should not be null.");
  1480. if (content != null)
  1481. {
  1482. result = content.BeginWriteToStream(httpOutput.outputStream, onWriteStreamedMessage, this);
  1483. }
  1484. else
  1485. {
  1486. result = this.httpResponseMessage.Content.CopyToAsync(httpOutput.outputStream).AsAsyncResult(onWriteStreamedMessage, this);
  1487. }
  1488. if (!result.CompletedSynchronously)
  1489. {
  1490. return false;
  1491. }
  1492. }
  1493. if (content != null)
  1494. {
  1495. content.EndWriteToStream(result);
  1496. }
  1497. return true;
  1498. }
  1499. }
  1500. static void OnWriteStreamedMessage(IAsyncResult result)
  1501. {
  1502. if (result.CompletedSynchronously)
  1503. {
  1504. return;
  1505. }
  1506. WriteStreamedMessageAsyncResult thisPtr = (WriteStreamedMessageAsyncResult)result.AsyncState;
  1507. Exception completionException = null;
  1508. bool completeSelf = false;
  1509. try
  1510. {
  1511. completeSelf = thisPtr.HandleWriteStreamedMessage(result);
  1512. }
  1513. catch (Exception ex)
  1514. {
  1515. if (Fx.IsFatal(ex))
  1516. {
  1517. throw;
  1518. }
  1519. completeSelf = true;
  1520. completionException = ex;
  1521. }
  1522. if (completeSelf)
  1523. {
  1524. thisPtr.sendTimer.Cancel();
  1525. thisPtr.Complete(false, completionException);
  1526. }
  1527. }
  1528. void SetTimer(TimeSpan timeout)
  1529. {
  1530. Fx.Assert(this.sendTimer == null, "SetTimer should only be called once");
  1531. this.sendTimer = new IOThreadTimer(onStreamSendTimeout, this.httpOutput, true);
  1532. this.sendTimer.Set(timeout);
  1533. }
  1534. public static void End(IAsyncResult result)
  1535. {
  1536. AsyncResult.End<WriteStreamedMessageAsyncResult>(result);
  1537. }
  1538. }
  1539. public IAsyncResult BeginSend(HttpResponseMessage httpResponseMessage, TimeSpan timeout, AsyncCallback callback, object state)
  1540. {
  1541. Fx.Assert(httpResponseMessage != null, "httpResponseMessage should not be null.");
  1542. return this.BeginSendCore(httpResponseMessage, timeout, callback, state);
  1543. }
  1544. public IAsyncResult BeginSend(TimeSpan timeout, AsyncCallback callback, object state)
  1545. {
  1546. return this.BeginSendCore(null, timeout, callback, state);
  1547. }
  1548. IAsyncResult BeginSendCore(HttpResponseMessage httpResponseMessage, TimeSpan timeout, AsyncCallback callback, object state)
  1549. {
  1550. bool throwing = true;
  1551. try
  1552. {
  1553. bool suppressEntityBody;
  1554. if (httpResponseMessage != null)
  1555. {
  1556. suppressEntityBody = this.PrepareHttpSend(httpResponseMessage);
  1557. }
  1558. else
  1559. {
  1560. suppressEntityBody = PrepareHttpSend(message);
  1561. }
  1562. this.TraceHttpSendStart();
  1563. IAsyncResult result = new SendAsyncResult(this, httpResponseMessage, suppressEntityBody, timeout, callback, state);
  1564. throwing = false;
  1565. return result;
  1566. }
  1567. finally
  1568. {
  1569. if (throwing)
  1570. {
  1571. Abort();
  1572. }
  1573. }
  1574. }
  1575. private void TraceHttpSendStart()
  1576. {
  1577. if (TD.HttpSendMessageStartIsEnabled())
  1578. {
  1579. if (streamed)
  1580. {
  1581. TD.HttpSendStreamedMessageStart(this.eventTraceActivity);
  1582. }
  1583. else
  1584. {
  1585. TD.HttpSendMessageStart(this.eventTraceActivity);
  1586. }
  1587. }
  1588. }
  1589. public virtual void EndSend(IAsyncResult result)
  1590. {
  1591. bool throwing = true;
  1592. try
  1593. {
  1594. SendAsyncResult.End(result);
  1595. throwing = false;
  1596. }
  1597. finally
  1598. {
  1599. if (throwing)
  1600. {
  1601. Abort();
  1602. }
  1603. }
  1604. }
  1605. void LogMessage()
  1606. {
  1607. if (MessageLogger.LogMessagesAtTransportLevel)
  1608. {
  1609. MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportSend);
  1610. }
  1611. }
  1612. public void Send(HttpResponseMessage httpResponseMessage, TimeSpan timeout)
  1613. {
  1614. bool suppressEntityBody = this.PrepareHttpSend(httpResponseMessage);
  1615. TraceHttpSendStart();
  1616. if (suppressEntityBody)
  1617. {
  1618. // requests can't always support an output stream (for GET, etc)
  1619. if (!isRequest)
  1620. {
  1621. outputStream = GetOutputStream();
  1622. }
  1623. else
  1624. {
  1625. this.SetContentLength(0);
  1626. LogMessage();
  1627. }
  1628. }
  1629. else if (streamed)
  1630. {
  1631. outputStream = this.GetOutputStream();
  1632. ApplyChannelBinding();
  1633. OpaqueContent content = httpResponseMessage.Content as OpaqueContent;
  1634. if (content != null)
  1635. {
  1636. content.WriteToStream(this.outputStream);
  1637. }
  1638. else
  1639. {
  1640. if (!httpResponseMessage.Content.CopyToAsync(this.outputStream).Wait<CommunicationException>(timeout))
  1641. {
  1642. throw FxTrace.Exception.AsError(new TimeoutException(SR.GetString(SR.TimeoutOnSend, timeout)));
  1643. }
  1644. }
  1645. }
  1646. else
  1647. {
  1648. if (this.IsChannelBindingSupportEnabled)
  1649. {
  1650. //need to get the Channel binding token (CBT), apply channel binding info to the message and then write the message
  1651. //CBT is only enabled when message security is in the stack, which also requires an HTTP entity body, so we
  1652. //should be safe to always get the stream.
  1653. outputStream = this.GetOutputStream();
  1654. ApplyChannelBinding();
  1655. ArraySegment<byte> buffer = SerializeBufferedMessage(httpResponseMessage);
  1656. Fx.Assert(buffer.Count != 0, "We should always have an entity body in this case...");
  1657. outputStream.Write(buffer.Array, buffer.Offset, buffer.Count);
  1658. }
  1659. else
  1660. {
  1661. ArraySegment<byte> buffer = SerializeBufferedMessage(httpResponseMessage);
  1662. SetContentLength(buffer.Count);
  1663. // requests can't always support an output stream (for GET, etc)
  1664. if (!isRequest || buffer.Count > 0)
  1665. {
  1666. outputStream = this.GetOutputStream();
  1667. outputStream.Write(buffer.Array, buffer.Offset, buffer.Count);
  1668. }
  1669. }
  1670. }
  1671. TraceSend();
  1672. }
  1673. ArraySegment<byte> SerializeBufferedMessage(HttpResponseMessage httpResponseMessage)
  1674. {
  1675. HttpOutputByteArrayContent content = httpResponseMessage.Content as HttpOutputByteArrayContent;
  1676. if (content == null)
  1677. {
  1678. byte[] byteArray = httpResponseMessage.Content.ReadAsByteArrayAsync().Result;
  1679. return new ArraySegment<byte>(byteArray, 0, byteArray.Length);
  1680. }
  1681. else
  1682. {
  1683. return content.Content;
  1684. }
  1685. }
  1686. public void Send(TimeSpan timeout)
  1687. {
  1688. bool suppressEntityBody = PrepareHttpSend(message);
  1689. TraceHttpSendStart();
  1690. if (suppressEntityBody)
  1691. {
  1692. // requests can't always support an output stream (for GET, etc)
  1693. if (!isRequest)
  1694. {
  1695. outputStream = GetOutputStream();
  1696. }
  1697. else
  1698. {
  1699. this.SetContentLength(0);
  1700. LogMessage();
  1701. }
  1702. }
  1703. else if (streamed)
  1704. {
  1705. outputStream = GetOutputStream();
  1706. ApplyChannelBinding();
  1707. WriteStreamedMessage(timeout);
  1708. }
  1709. else
  1710. {
  1711. if (this.IsChannelBindingSupportEnabled)
  1712. {
  1713. //need to get the Channel binding token (CBT), apply channel binding info to the message and then write the message
  1714. //CBT is only enabled when message security is in the stack, which also requires an HTTP entity body, so we
  1715. //should be safe to always get the stream.
  1716. outputStream = GetOutputStream();
  1717. ApplyChannelBinding();
  1718. ArraySegment<byte> buffer = SerializeBufferedMessage(message);
  1719. Fx.Assert(buffer.Count != 0, "We should always have an entity body in this case...");
  1720. outputStream.Write(buffer.Array, buffer.Offset, buffer.Count);
  1721. }
  1722. else
  1723. {
  1724. ArraySegment<byte> buffer = SerializeBufferedMessage(message);
  1725. SetContentLength(buffer.Count);
  1726. // requests can't always support an output stream (for GET, etc)
  1727. if (!isRequest || buffer.Count > 0)
  1728. {
  1729. outputStream = GetOutputStream();
  1730. outputStream.Write(buffer.Array, buffer.Offset, buffer.Count);
  1731. }
  1732. }
  1733. }
  1734. TraceSend();
  1735. }
  1736. void TraceSend()
  1737. {
  1738. if (DiagnosticUtility.ShouldTraceInformation)
  1739. {
  1740. TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.MessageSent, SR.GetString(SR.TraceCodeMessageSent),
  1741. new MessageTraceRecord(this.message), this, null);
  1742. }
  1743. if (TD.HttpSendStopIsEnabled())
  1744. {
  1745. TD.HttpSendStop(this.eventTraceActivity);
  1746. }
  1747. }
  1748. class SendAsyncResult : AsyncResult
  1749. {
  1750. HttpOutput httpOutput;
  1751. static AsyncCallback onGetOutputStream;
  1752. static Action<object> onWriteStreamedMessageLater;
  1753. static AsyncCallback onWriteStreamedMessage;
  1754. static AsyncCallback onWriteBody;
  1755. bool suppressEntityBody;
  1756. ArraySegment<byte> buffer;
  1757. TimeoutHelper timeoutHelper;
  1758. HttpResponseMessage httpResponseMessage;
  1759. public SendAsyncResult(HttpOutput httpOutput, HttpResponseMessage httpResponseMessage, bool suppressEntityBody, TimeSpan timeout, AsyncCallback callback, object state)
  1760. : base(callback, state)
  1761. {
  1762. this.httpOutput = httpOutput;
  1763. this.httpResponseMessage = httpResponseMessage;
  1764. this.suppressEntityBody = suppressEntityBody;
  1765. if (suppressEntityBody)
  1766. {
  1767. if (httpOutput.isRequest)
  1768. {
  1769. httpOutput.SetContentLength(0);
  1770. this.httpOutput.TraceSend();
  1771. this.httpOutput.LogMessage();
  1772. base.Complete(true);
  1773. return;
  1774. }
  1775. }
  1776. this.timeoutHelper = new TimeoutHelper(timeout);
  1777. Send();
  1778. }
  1779. void Send()
  1780. {
  1781. if (httpOutput.IsChannelBindingSupportEnabled)
  1782. {
  1783. SendWithChannelBindingToken();
  1784. }
  1785. else
  1786. {
  1787. SendWithoutChannelBindingToken();
  1788. }
  1789. }
  1790. void SendWithoutChannelBindingToken()
  1791. {
  1792. if (!suppressEntityBody && !httpOutput.streamed)
  1793. {
  1794. if (this.httpResponseMessage != null)
  1795. {
  1796. buffer = httpOutput.SerializeBufferedMessage(this.httpResponseMessage);
  1797. }
  1798. else
  1799. {
  1800. buffer = httpOutput.SerializeBufferedMessage(httpOutput.message);
  1801. }
  1802. httpOutput.SetContentLength(buffer.Count);
  1803. }
  1804. if (this.httpOutput.WillGetOutputStreamCompleteSynchronously)
  1805. {
  1806. httpOutput.outputStream = httpOutput.GetOutputStream();
  1807. }
  1808. else
  1809. {
  1810. if (onGetOutputStream == null)
  1811. {
  1812. onGetOutputStream = Fx.ThunkCallback(new AsyncCallback(OnGetOutputStream));
  1813. }
  1814. IAsyncResult result = httpOutput.BeginGetOutputStream(onGetOutputStream, this);
  1815. if (!result.CompletedSynchronously)
  1816. return;
  1817. httpOutput.outputStream = httpOutput.EndGetOutputStream(result);
  1818. }
  1819. if (WriteMessage(true))
  1820. {
  1821. this.httpOutput.TraceSend();
  1822. base.Complete(true);
  1823. }
  1824. }
  1825. void SendWithChannelBindingToken()
  1826. {
  1827. if (this.httpOutput.WillGetOutputStreamCompleteSynchronously)
  1828. {
  1829. httpOutput.outputStream = httpOutput.GetOutputStream();
  1830. httpOutput.ApplyChannelBinding();
  1831. }
  1832. else
  1833. {
  1834. if (onGetOutputStream == null)
  1835. {
  1836. onGetOutputStream = Fx.ThunkCallback(new AsyncCallback(OnGetOutputStream));
  1837. }
  1838. IAsyncResult result = httpOutput.BeginGetOutputStream(onGetOutputStream, this);
  1839. if (!result.CompletedSynchronously)
  1840. return;
  1841. httpOutput.outputStream = httpOutput.EndGetOutputStream(result);
  1842. httpOutput.ApplyChannelBinding();
  1843. }
  1844. if (!httpOutput.streamed)
  1845. {
  1846. if (this.httpResponseMessage != null)
  1847. {
  1848. buffer = httpOutput.SerializeBufferedMessage(this.httpResponseMessage);
  1849. }
  1850. else
  1851. {
  1852. buffer = httpOutput.SerializeBufferedMessage(httpOutput.message);
  1853. }
  1854. httpOutput.SetContentLength(buffer.Count);
  1855. }
  1856. if (WriteMessage(true))
  1857. {
  1858. this.httpOutput.TraceSend();
  1859. base.Complete(true);
  1860. }
  1861. }
  1862. bool WriteMessage(bool isStillSynchronous)
  1863. {
  1864. if (suppressEntityBody)
  1865. {
  1866. return true;
  1867. }
  1868. if (httpOutput.streamed)
  1869. {
  1870. if (isStillSynchronous)
  1871. {
  1872. if (onWriteStreamedMessageLater == null)
  1873. {
  1874. onWriteStreamedMessageLater = new Action<object>(OnWriteStreamedMessageLater);
  1875. }
  1876. ActionItem.Schedule(onWriteStreamedMessageLater, this);
  1877. return false;
  1878. }
  1879. else
  1880. {
  1881. return WriteStreamedMessage();
  1882. }
  1883. }
  1884. else
  1885. {
  1886. if (onWriteBody == null)
  1887. {
  1888. onWriteBody = Fx.ThunkCallback(new AsyncCallback(OnWriteBody));
  1889. }
  1890. IAsyncResult writeResult =
  1891. httpOutput.outputStream.BeginWrite(buffer.Array, buffer.Offset, buffer.Count, onWriteBody, this);
  1892. if (!writeResult.CompletedSynchronously)
  1893. {
  1894. return false;
  1895. }
  1896. CompleteWriteBody(writeResult);
  1897. }
  1898. return true;
  1899. }
  1900. bool WriteStreamedMessage()
  1901. {
  1902. // return a bool to determine if we are [....].
  1903. if (onWriteStreamedMessage == null)
  1904. {
  1905. onWriteStreamedMessage = Fx.ThunkCallback(OnWriteStreamedMessage);
  1906. }
  1907. return HandleWriteStreamedMessage(null); // completed synchronously
  1908. }
  1909. bool HandleWriteStreamedMessage(IAsyncResult result)
  1910. {
  1911. if (result == null)
  1912. {
  1913. result = httpOutput.BeginWriteStreamedMessage(this.httpResponseMessage, timeoutHelper.RemainingTime(), onWriteStreamedMessage, this);
  1914. if (!result.CompletedSynchronously)
  1915. {
  1916. return false;
  1917. }
  1918. }
  1919. httpOutput.EndWriteStreamedMessage(result);
  1920. return true;
  1921. }
  1922. static void OnWriteStreamedMessage(IAsyncResult result)
  1923. {
  1924. if (result.CompletedSynchronously)
  1925. {
  1926. return;
  1927. }
  1928. SendAsyncResult thisPtr = (SendAsyncResult)result.AsyncState;
  1929. Exception completionException = null;
  1930. bool completeSelf = false;
  1931. try
  1932. {
  1933. completeSelf = thisPtr.HandleWriteStreamedMessage(result);
  1934. }
  1935. catch (Exception ex)
  1936. {
  1937. if (Fx.IsFatal(ex))
  1938. {
  1939. throw;
  1940. }
  1941. completeSelf = true;
  1942. completionException = ex;
  1943. }
  1944. if (completeSelf)
  1945. {
  1946. if (completionException != null)
  1947. {
  1948. thisPtr.httpOutput.TraceSend();
  1949. }
  1950. thisPtr.Complete(false, completionException);
  1951. }
  1952. }
  1953. void CompleteWriteBody(IAsyncResult result)
  1954. {
  1955. httpOutput.outputStream.EndWrite(result);
  1956. }
  1957. public static void End(IAsyncResult result)
  1958. {
  1959. AsyncResult.End<SendAsyncResult>(result);
  1960. }
  1961. static void OnGetOutputStream(IAsyncResult result)
  1962. {
  1963. if (result.CompletedSynchronously)
  1964. return;
  1965. SendAsyncResult thisPtr = (SendAsyncResult)result.AsyncState;
  1966. Exception completionException = null;
  1967. bool completeSelf = false;
  1968. try
  1969. {
  1970. thisPtr.httpOutput.outputStream = thisPtr.httpOutput.EndGetOutputStream(result);
  1971. thisPtr.httpOutput.ApplyChannelBinding();
  1972. if (!thisPtr.httpOutput.streamed && thisPtr.httpOutput.IsChannelBindingSupportEnabled)
  1973. {
  1974. thisPtr.buffer = thisPtr.httpOutput.SerializeBufferedMessage(thisPtr.httpOutput.message);
  1975. thisPtr.httpOutput.SetContentLength(thisPtr.buffer.Count);
  1976. }
  1977. if (thisPtr.WriteMessage(false))
  1978. {
  1979. thisPtr.httpOutput.TraceSend();
  1980. completeSelf = true;
  1981. }
  1982. }
  1983. #pragma warning suppress 56500 // [....], transferring exception to another thread
  1984. catch (Exception e)
  1985. {
  1986. if (Fx.IsFatal(e))
  1987. {
  1988. throw;
  1989. }
  1990. completeSelf = true;
  1991. completionException = e;
  1992. }
  1993. if (completeSelf)
  1994. {
  1995. thisPtr.Complete(false, completionException);
  1996. }
  1997. }
  1998. static void OnWriteStreamedMessageLater(object state)
  1999. {
  2000. SendAsyncResult thisPtr = (SendAsyncResult)state;
  2001. bool completeSelf = false;
  2002. Exception completionException = null;
  2003. try
  2004. {
  2005. completeSelf = thisPtr.WriteStreamedMessage();
  2006. }
  2007. #pragma warning suppress 56500 // [....], transferring exception to another thread
  2008. catch (Exception e)
  2009. {
  2010. if (Fx.IsFatal(e))
  2011. {
  2012. throw;
  2013. }
  2014. completeSelf = true;
  2015. completionException = e;
  2016. }
  2017. if (completeSelf)
  2018. {
  2019. if (completionException != null)
  2020. {
  2021. thisPtr.httpOutput.TraceSend();
  2022. }
  2023. thisPtr.Complete(false, completionException);
  2024. }
  2025. }
  2026. static void OnWriteBody(IAsyncResult result)
  2027. {
  2028. if (result.CompletedSynchronously)
  2029. return;
  2030. SendAsyncResult thisPtr = (SendAsyncResult)result.AsyncState;
  2031. Exception completionException = null;
  2032. try
  2033. {
  2034. thisPtr.CompleteWriteBody(result);
  2035. thisPtr.httpOutput.TraceSend();
  2036. }
  2037. #pragma warning suppress 56500 // [....], transferring exception to another thread
  2038. catch (Exception e)
  2039. {
  2040. if (Fx.IsFatal(e))
  2041. {
  2042. throw;
  2043. }
  2044. completionException = e;
  2045. }
  2046. thisPtr.Complete(false, completionException);
  2047. }
  2048. }
  2049. internal static HttpOutput CreateHttpOutput(HttpWebRequest httpWebRequest, IHttpTransportFactorySettings settings, Message message, bool enableChannelBindingSupport)
  2050. {
  2051. return new WebRequestHttpOutput(httpWebRequest, settings, message, enableChannelBindingSupport);
  2052. }
  2053. internal static HttpOutput CreateHttpOutput(HttpListenerResponse httpListenerResponse, IHttpTransportFactorySettings settings, Message message, string httpMethod)
  2054. {
  2055. return new ListenerResponseHttpOutput(httpListenerResponse, settings, message, httpMethod);
  2056. }
  2057. class WebRequestHttpOutput : HttpOutput
  2058. {
  2059. HttpWebRequest httpWebRequest;
  2060. ChannelBinding channelBindingToken;
  2061. bool enableChannelBindingSupport;
  2062. public WebRequestHttpOutput(HttpWebRequest httpWebRequest, IHttpTransportFactorySettings settings, Message message, bool enableChannelBindingSupport)
  2063. : base(settings, message, true, false)
  2064. {
  2065. this.httpWebRequest = httpWebRequest;
  2066. this.enableChannelBindingSupport = enableChannelBindingSupport;
  2067. }
  2068. public override void Abort(HttpAbortReason abortReason)
  2069. {
  2070. httpWebRequest.Abort();
  2071. base.Abort(abortReason);
  2072. }
  2073. protected override void AddMimeVersion(string version)
  2074. {
  2075. httpWebRequest.Headers[HttpChannelUtilities.MIMEVersionHeader] = version;
  2076. }
  2077. protected override void AddHeader(string name, string value)
  2078. {
  2079. httpWebRequest.Headers.Add(name, value);
  2080. }
  2081. protected override void SetContentType(string contentType)
  2082. {
  2083. httpWebRequest.ContentType = contentType;
  2084. }
  2085. protected override void SetContentEncoding(string contentEncoding)
  2086. {
  2087. this.httpWebRequest.Headers.Add(HttpChannelUtilities.ContentEncodingHeader, contentEncoding);
  2088. }
  2089. protected override void SetContentLength(int contentLength)
  2090. {
  2091. if (contentLength == 0 // work around whidbey issue with setting ContentLength - (see MB36881)
  2092. && !this.enableChannelBindingSupport) //When ChannelBinding is enabled, content length isn't supported
  2093. {
  2094. httpWebRequest.ContentLength = contentLength;
  2095. }
  2096. }
  2097. protected override void SetStatusCode(HttpStatusCode statusCode)
  2098. {
  2099. }
  2100. protected override void SetStatusDescription(string statusDescription)
  2101. {
  2102. }
  2103. protected override bool WillGetOutputStreamCompleteSynchronously
  2104. {
  2105. get { return false; }
  2106. }
  2107. protected override bool IsChannelBindingSupportEnabled
  2108. {
  2109. get
  2110. {
  2111. return this.enableChannelBindingSupport;
  2112. }
  2113. }
  2114. protected override ChannelBinding ChannelBinding
  2115. {
  2116. get
  2117. {
  2118. return this.channelBindingToken;
  2119. }
  2120. }
  2121. protected override bool CleanupChannelBinding
  2122. {
  2123. get
  2124. {
  2125. //client side channel binding token will be attached to the inbound response message also, so
  2126. //we need to not clean up the CBT object for this HttpOutput object.
  2127. return false;
  2128. }
  2129. }
  2130. //Used to allow the channel binding object to be transferred to the
  2131. //WebResponseHttpInput object.
  2132. public override ChannelBinding TakeChannelBinding()
  2133. {
  2134. ChannelBinding result = this.channelBindingToken;
  2135. this.channelBindingToken = null;
  2136. return result;
  2137. }
  2138. protected override Stream GetOutputStream()
  2139. {
  2140. try
  2141. {
  2142. Stream outputStream;
  2143. if (this.IsChannelBindingSupportEnabled)
  2144. {
  2145. TransportContext context;
  2146. outputStream = httpWebRequest.GetRequestStream(out context);
  2147. this.channelBindingToken = ChannelBindingUtility.GetToken(context);
  2148. }
  2149. else
  2150. {
  2151. outputStream = httpWebRequest.GetRequestStream();
  2152. }
  2153. outputStream = new WebRequestOutputStream(outputStream, httpWebRequest, this);
  2154. return outputStream;
  2155. }
  2156. catch (WebException webException)
  2157. {
  2158. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateRequestWebException(webException, httpWebRequest, abortReason));
  2159. }
  2160. }
  2161. protected override IAsyncResult BeginGetOutputStream(AsyncCallback callback, object state)
  2162. {
  2163. return new GetOutputStreamAsyncResult(httpWebRequest, this, callback, state);
  2164. }
  2165. protected override Stream EndGetOutputStream(IAsyncResult result)
  2166. {
  2167. return GetOutputStreamAsyncResult.End(result, out this.channelBindingToken);
  2168. }
  2169. protected override bool PrepareHttpSend(Message message)
  2170. {
  2171. bool wasContentTypeSet = false;
  2172. string action = message.Headers.Action;
  2173. if (action != null)
  2174. {
  2175. //This code is calling UrlPathEncode due to MessageBus bug 53362.
  2176. //After reviewing this decision, we
  2177. //feel that this was probably the wrong thing to do because UrlPathEncode
  2178. //doesn't escape some characters like '+', '%', etc. The real issue behind
  2179. //bug 53362 may have been as simple as being encoded multiple times on the client
  2180. //but being decoded one time on the server. Calling UrlEncode would correctly
  2181. //escape these characters, but since we don't want to break any customers and no
  2182. //customers have complained, we will leave this as is for now...
  2183. action = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", UrlUtility.UrlPathEncode(action));
  2184. }
  2185. bool suppressEntityBody = base.PrepareHttpSend(message);
  2186. object property;
  2187. if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property))
  2188. {
  2189. HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property;
  2190. httpWebRequest.Method = requestProperty.Method;
  2191. // Query string was applied in HttpChannelFactory.ApplyManualAddressing
  2192. WebHeaderCollection requestHeaders = requestProperty.Headers;
  2193. suppressEntityBody = suppressEntityBody || requestProperty.SuppressEntityBody;
  2194. for (int i = 0; i < requestHeaders.Count; i++)
  2195. {
  2196. string name = requestHeaders.Keys[i];
  2197. string value = requestHeaders[i];
  2198. if (string.Compare(name, "accept", StringComparison.OrdinalIgnoreCase) == 0)
  2199. {
  2200. httpWebRequest.Accept = value;
  2201. }
  2202. else if (string.Compare(name, "connection", StringComparison.OrdinalIgnoreCase) == 0)
  2203. {
  2204. if (value.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) != -1)
  2205. {
  2206. httpWebRequest.KeepAlive = true;
  2207. }
  2208. else
  2209. {
  2210. httpWebRequest.Connection = value;
  2211. }
  2212. }
  2213. else if (string.Compare(name, "SOAPAction", StringComparison.OrdinalIgnoreCase) == 0)
  2214. {
  2215. if (action == null)
  2216. {
  2217. action = value;
  2218. }
  2219. else
  2220. {
  2221. if (value.Length > 0 && string.Compare(value, action, StringComparison.Ordinal) != 0)
  2222. {
  2223. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  2224. new ProtocolException(SR.GetString(SR.HttpSoapActionMismatch, action, value)));
  2225. }
  2226. }
  2227. }
  2228. else if (string.Compare(name, "content-length", StringComparison.OrdinalIgnoreCase) == 0)
  2229. {
  2230. // this will be taken care of by System.Net when we write to the content
  2231. }
  2232. else if (string.Compare(name, "content-type", StringComparison.OrdinalIgnoreCase) == 0)
  2233. {
  2234. httpWebRequest.ContentType = value;
  2235. wasContentTypeSet = true;
  2236. }
  2237. else if (string.Compare(name, "expect", StringComparison.OrdinalIgnoreCase) == 0)
  2238. {
  2239. if (value.ToUpperInvariant().IndexOf("100-CONTINUE", StringComparison.OrdinalIgnoreCase) != -1)
  2240. {
  2241. httpWebRequest.ServicePoint.Expect100Continue = true;
  2242. }
  2243. else
  2244. {
  2245. httpWebRequest.Expect = value;
  2246. }
  2247. }
  2248. else if (string.Compare(name, "host", StringComparison.OrdinalIgnoreCase) == 0)
  2249. {
  2250. // this should be controlled through Via
  2251. }
  2252. else if (string.Compare(name, "referer", StringComparison.OrdinalIgnoreCase) == 0)
  2253. {
  2254. // referrer is proper spelling, but referer is the what is in the protocol.
  2255. httpWebRequest.Referer = value;
  2256. }
  2257. else if (string.Compare(name, "transfer-encoding", StringComparison.OrdinalIgnoreCase) == 0)
  2258. {
  2259. if (value.ToUpperInvariant().IndexOf("CHUNKED", StringComparison.OrdinalIgnoreCase) != -1)
  2260. {
  2261. httpWebRequest.SendChunked = true;
  2262. }
  2263. else
  2264. {
  2265. httpWebRequest.TransferEncoding = value;
  2266. }
  2267. }
  2268. else if (string.Compare(name, "user-agent", StringComparison.OrdinalIgnoreCase) == 0)
  2269. {
  2270. httpWebRequest.UserAgent = value;
  2271. }
  2272. else if (string.Compare(name, "if-modified-since", StringComparison.OrdinalIgnoreCase) == 0)
  2273. {
  2274. DateTime modifiedSinceDate;
  2275. if (DateTime.TryParse(value, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AssumeLocal, out modifiedSinceDate))
  2276. {
  2277. httpWebRequest.IfModifiedSince = modifiedSinceDate;
  2278. }
  2279. else
  2280. {
  2281. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  2282. new ProtocolException(SR.GetString(SR.HttpIfModifiedSinceParseError, value)));
  2283. }
  2284. }
  2285. else if (string.Compare(name, "date", StringComparison.OrdinalIgnoreCase) == 0)
  2286. {
  2287. // this will be taken care of by System.Net when we make the request
  2288. }
  2289. else if (string.Compare(name, "proxy-connection", StringComparison.OrdinalIgnoreCase) == 0)
  2290. {
  2291. // set by System.Net if using a proxy.
  2292. }
  2293. else if (string.Compare(name, "range", StringComparison.OrdinalIgnoreCase) == 0)
  2294. {
  2295. // we don't support ranges in v1.
  2296. }
  2297. else
  2298. {
  2299. httpWebRequest.Headers.Add(name, value);
  2300. }
  2301. }
  2302. }
  2303. if (action != null)
  2304. {
  2305. if (message.Version.Envelope == EnvelopeVersion.Soap11)
  2306. {
  2307. httpWebRequest.Headers["SOAPAction"] = action;
  2308. }
  2309. else if (message.Version.Envelope == EnvelopeVersion.Soap12)
  2310. {
  2311. if (message.Version.Addressing == AddressingVersion.None)
  2312. {
  2313. bool shouldSetContentType = true;
  2314. if (wasContentTypeSet)
  2315. {
  2316. if (httpWebRequest.ContentType.Contains("action")
  2317. || httpWebRequest.ContentType.ToUpperInvariant().IndexOf("ACTION", StringComparison.OrdinalIgnoreCase) != -1)
  2318. {
  2319. try
  2320. {
  2321. ContentType parsedContentType = new ContentType(httpWebRequest.ContentType);
  2322. if (parsedContentType.Parameters.ContainsKey("action"))
  2323. {
  2324. string value = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", parsedContentType.Parameters["action"]);
  2325. if (string.Compare(value, action, StringComparison.Ordinal) != 0)
  2326. {
  2327. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  2328. new ProtocolException(SR.GetString(SR.HttpSoapActionMismatchContentType, action, value)));
  2329. }
  2330. shouldSetContentType = false;
  2331. }
  2332. }
  2333. catch (FormatException formatException)
  2334. {
  2335. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  2336. new ProtocolException(SR.GetString(SR.HttpContentTypeFormatException, formatException.Message, httpWebRequest.ContentType), formatException));
  2337. }
  2338. }
  2339. }
  2340. if (shouldSetContentType)
  2341. {
  2342. httpWebRequest.ContentType = string.Format(CultureInfo.InvariantCulture, "{0}; action={1}", httpWebRequest.ContentType, action);
  2343. }
  2344. }
  2345. }
  2346. else if (message.Version.Envelope != EnvelopeVersion.None)
  2347. {
  2348. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  2349. new ProtocolException(SR.GetString(SR.EnvelopeVersionUnknown,
  2350. message.Version.Envelope.ToString())));
  2351. }
  2352. }
  2353. // since we don't get the output stream in send when retVal == true,
  2354. // we need to disable chunking for some verbs (DELETE/PUT)
  2355. if (suppressEntityBody)
  2356. {
  2357. httpWebRequest.SendChunked = false;
  2358. }
  2359. else if (this.IsChannelBindingSupportEnabled)
  2360. {
  2361. //force chunked upload since the length of the message is unknown before encoding.
  2362. httpWebRequest.SendChunked = true;
  2363. }
  2364. return suppressEntityBody;
  2365. }
  2366. protected override void PrepareHttpSendCore(HttpResponseMessage message)
  2367. {
  2368. // HTTP pipeline for client side is not implemented yet
  2369. // DCR CSDMain 216853 is tracking this
  2370. Fx.Assert(false, "HTTP pipeline for client is not implemented yet. This method should not be called.");
  2371. }
  2372. class GetOutputStreamAsyncResult : AsyncResult
  2373. {
  2374. static AsyncCallback onGetRequestStream = Fx.ThunkCallback(new AsyncCallback(OnGetRequestStream));
  2375. HttpOutput httpOutput;
  2376. HttpWebRequest httpWebRequest;
  2377. Stream outputStream;
  2378. ChannelBinding channelBindingToken;
  2379. public GetOutputStreamAsyncResult(HttpWebRequest httpWebRequest, HttpOutput httpOutput, AsyncCallback callback, object state)
  2380. : base(callback, state)
  2381. {
  2382. this.httpWebRequest = httpWebRequest;
  2383. this.httpOutput = httpOutput;
  2384. IAsyncResult result = null;
  2385. try
  2386. {
  2387. result = httpWebRequest.BeginGetRequestStream(onGetRequestStream, this);
  2388. }
  2389. catch (WebException webException)
  2390. {
  2391. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateRequestWebException(webException, httpWebRequest, httpOutput.abortReason));
  2392. }
  2393. if (result.CompletedSynchronously)
  2394. {
  2395. CompleteGetRequestStream(result);
  2396. base.Complete(true);
  2397. }
  2398. }
  2399. void CompleteGetRequestStream(IAsyncResult result)
  2400. {
  2401. try
  2402. {
  2403. TransportContext context;
  2404. this.outputStream = new WebRequestOutputStream(httpWebRequest.EndGetRequestStream(result, out context), httpWebRequest, this.httpOutput);
  2405. this.channelBindingToken = ChannelBindingUtility.GetToken(context);
  2406. }
  2407. catch (WebException webException)
  2408. {
  2409. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateRequestWebException(webException, httpWebRequest, httpOutput.abortReason));
  2410. }
  2411. }
  2412. public static Stream End(IAsyncResult result, out ChannelBinding channelBindingToken)
  2413. {
  2414. GetOutputStreamAsyncResult thisPtr = AsyncResult.End<GetOutputStreamAsyncResult>(result);
  2415. channelBindingToken = thisPtr.channelBindingToken;
  2416. return thisPtr.outputStream;
  2417. }
  2418. static void OnGetRequestStream(IAsyncResult result)
  2419. {
  2420. if (result.CompletedSynchronously)
  2421. return;
  2422. GetOutputStreamAsyncResult thisPtr = (GetOutputStreamAsyncResult)result.AsyncState;
  2423. Exception completionException = null;
  2424. try
  2425. {
  2426. thisPtr.CompleteGetRequestStream(result);
  2427. }
  2428. #pragma warning suppress 56500 // [....], transferring exception to another thread
  2429. catch (Exception e)
  2430. {
  2431. if (Fx.IsFatal(e))
  2432. {
  2433. throw;
  2434. }
  2435. completionException = e;
  2436. }
  2437. thisPtr.Complete(false, completionException);
  2438. }
  2439. }
  2440. class WebRequestOutputStream : BytesReadPositionStream
  2441. {
  2442. HttpWebRequest httpWebRequest;
  2443. HttpOutput httpOutput;
  2444. int bytesSent = 0;
  2445. public WebRequestOutputStream(Stream requestStream, HttpWebRequest httpWebRequest, HttpOutput httpOutput)
  2446. : base(requestStream)
  2447. {
  2448. this.httpWebRequest = httpWebRequest;
  2449. this.httpOutput = httpOutput;
  2450. }
  2451. public override void Close()
  2452. {
  2453. try
  2454. {
  2455. base.Close();
  2456. }
  2457. catch (ObjectDisposedException objectDisposedException)
  2458. {
  2459. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateRequestCanceledException(objectDisposedException, httpWebRequest, httpOutput.abortReason));
  2460. }
  2461. catch (IOException ioException)
  2462. {
  2463. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateRequestIOException(ioException, httpWebRequest));
  2464. }
  2465. catch (WebException webException)
  2466. {
  2467. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateRequestWebException(webException, httpWebRequest, httpOutput.abortReason));
  2468. }
  2469. }
  2470. public override long Position
  2471. {
  2472. get
  2473. {
  2474. return bytesSent;
  2475. }
  2476. set
  2477. {
  2478. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupported)));
  2479. }
  2480. }
  2481. public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  2482. {
  2483. this.bytesSent += count;
  2484. try
  2485. {
  2486. return base.BeginWrite(buffer, offset, count, callback, state);
  2487. }
  2488. catch (ObjectDisposedException objectDisposedException)
  2489. {
  2490. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateRequestCanceledException(objectDisposedException, httpWebRequest, httpOutput.abortReason));
  2491. }
  2492. catch (IOException ioException)
  2493. {
  2494. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateRequestIOException(ioException, httpWebRequest));
  2495. }
  2496. catch (WebException webException)
  2497. {
  2498. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateRequestWebException(webException, httpWebRequest, httpOutput.abortReason));
  2499. }
  2500. }
  2501. public override void EndWrite(IAsyncResult result)
  2502. {
  2503. try
  2504. {
  2505. base.EndWrite(result);
  2506. }
  2507. catch (ObjectDisposedException objectDisposedException)
  2508. {
  2509. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateRequestCanceledException(objectDisposedException, httpWebRequest, httpOutput.abortReason));
  2510. }
  2511. catch (IOException ioException)
  2512. {
  2513. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateRequestIOException(ioException, httpWebRequest));
  2514. }
  2515. catch (WebException webException)
  2516. {
  2517. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateRequestWebException(webException, httpWebRequest, httpOutput.abortReason));
  2518. }
  2519. }
  2520. public override void Write(byte[] buffer, int offset, int count)
  2521. {
  2522. try
  2523. {
  2524. base.Write(buffer, offset, count);
  2525. }
  2526. catch (ObjectDisposedException objectDisposedException)
  2527. {
  2528. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateRequestCanceledException(objectDisposedException, httpWebRequest, httpOutput.abortReason));
  2529. }
  2530. catch (IOException ioException)
  2531. {
  2532. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateRequestIOException(ioException, httpWebRequest));
  2533. }
  2534. catch (WebException webException)
  2535. {
  2536. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateRequestWebException(webException, httpWebRequest, httpOutput.abortReason));
  2537. }
  2538. this.bytesSent += count;
  2539. }
  2540. }
  2541. }
  2542. class ListenerResponseHttpOutput : HttpOutput
  2543. {
  2544. HttpListenerResponse listenerResponse;
  2545. string httpMethod;
  2546. [System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.Usage, "CA2214", Justification = "No one else is inhiriting from this class.")]
  2547. public ListenerResponseHttpOutput(HttpListenerResponse listenerResponse, IHttpTransportFactorySettings settings, Message message, string httpMethod)
  2548. : base(settings, message, false, true)
  2549. {
  2550. this.listenerResponse = listenerResponse;
  2551. this.httpMethod = httpMethod;
  2552. if (message.IsFault)
  2553. {
  2554. this.SetStatusCode(HttpStatusCode.InternalServerError);
  2555. }
  2556. else
  2557. {
  2558. this.SetStatusCode(HttpStatusCode.OK);
  2559. }
  2560. }
  2561. protected override string HttpMethod
  2562. {
  2563. get { return this.httpMethod; }
  2564. }
  2565. public override void Abort(HttpAbortReason abortReason)
  2566. {
  2567. listenerResponse.Abort();
  2568. base.Abort(abortReason);
  2569. }
  2570. protected override void AddMimeVersion(string version)
  2571. {
  2572. listenerResponse.Headers[HttpChannelUtilities.MIMEVersionHeader] = version;
  2573. }
  2574. protected override bool PrepareHttpSend(Message message)
  2575. {
  2576. bool result = base.PrepareHttpSend(message);
  2577. if (this.CanSendCompressedResponses)
  2578. {
  2579. string contentType = this.listenerResponse.ContentType;
  2580. string contentEncoding;
  2581. if (HttpChannelUtilities.GetHttpResponseTypeAndEncodingForCompression(ref contentType, out contentEncoding))
  2582. {
  2583. if (contentType != this.listenerResponse.ContentType)
  2584. {
  2585. this.SetContentType(contentType);
  2586. }
  2587. this.SetContentEncoding(contentEncoding);
  2588. }
  2589. }
  2590. HttpResponseMessageProperty responseProperty = message.Properties.GetValue<HttpResponseMessageProperty>(HttpResponseMessageProperty.Name, true);
  2591. bool httpResponseMessagePropertyFound = responseProperty != null;
  2592. bool httpMethodIsHead = string.Compare(this.httpMethod, "HEAD", StringComparison.OrdinalIgnoreCase) == 0;
  2593. if (httpMethodIsHead ||
  2594. httpResponseMessagePropertyFound && responseProperty.SuppressEntityBody)
  2595. {
  2596. result = true;
  2597. this.SetContentLength(0);
  2598. this.SetContentType(null);
  2599. listenerResponse.SendChunked = false;
  2600. }
  2601. if (httpResponseMessagePropertyFound)
  2602. {
  2603. this.SetStatusCode(responseProperty.StatusCode);
  2604. if (responseProperty.StatusDescription != null)
  2605. {
  2606. this.SetStatusDescription(responseProperty.StatusDescription);
  2607. }
  2608. WebHeaderCollection responseHeaders = responseProperty.Headers;
  2609. for (int i = 0; i < responseHeaders.Count; i++)
  2610. {
  2611. string name = responseHeaders.Keys[i];
  2612. string value = responseHeaders[i];
  2613. if (string.Compare(name, "content-length", StringComparison.OrdinalIgnoreCase) == 0)
  2614. {
  2615. int contentLength = -1;
  2616. if (httpMethodIsHead &&
  2617. int.TryParse(value, out contentLength))
  2618. {
  2619. this.SetContentLength(contentLength);
  2620. }
  2621. // else
  2622. //this will be taken care of by System.Net when we write to the content
  2623. }
  2624. else if (string.Compare(name, "content-type", StringComparison.OrdinalIgnoreCase) == 0)
  2625. {
  2626. if (httpMethodIsHead ||
  2627. !responseProperty.SuppressEntityBody)
  2628. {
  2629. this.SetContentType(value);
  2630. }
  2631. }
  2632. else
  2633. {
  2634. this.AddHeader(name, value);
  2635. }
  2636. }
  2637. }
  2638. return result;
  2639. }
  2640. protected override void PrepareHttpSendCore(HttpResponseMessage message)
  2641. {
  2642. this.listenerResponse.StatusCode = (int)message.StatusCode;
  2643. if (message.ReasonPhrase != null)
  2644. {
  2645. this.listenerResponse.StatusDescription = message.ReasonPhrase;
  2646. }
  2647. HttpChannelUtilities.CopyHeaders(message, AddHeader);
  2648. }
  2649. protected override void AddHeader(string name, string value)
  2650. {
  2651. if (string.Compare(name, "WWW-Authenticate", StringComparison.OrdinalIgnoreCase) == 0)
  2652. {
  2653. listenerResponse.AddHeader(name, value);
  2654. }
  2655. else
  2656. {
  2657. listenerResponse.AppendHeader(name, value);
  2658. }
  2659. }
  2660. protected override void SetContentType(string contentType)
  2661. {
  2662. listenerResponse.ContentType = contentType;
  2663. }
  2664. protected override void SetContentEncoding(string contentEncoding)
  2665. {
  2666. this.listenerResponse.AddHeader(HttpChannelUtilities.ContentEncodingHeader, contentEncoding);
  2667. }
  2668. protected override void SetContentLength(int contentLength)
  2669. {
  2670. listenerResponse.ContentLength64 = contentLength;
  2671. }
  2672. protected override void SetStatusCode(HttpStatusCode statusCode)
  2673. {
  2674. listenerResponse.StatusCode = (int)statusCode;
  2675. }
  2676. protected override void SetStatusDescription(string statusDescription)
  2677. {
  2678. listenerResponse.StatusDescription = statusDescription;
  2679. }
  2680. protected override Stream GetOutputStream()
  2681. {
  2682. return new ListenerResponseOutputStream(listenerResponse);
  2683. }
  2684. class ListenerResponseOutputStream : BytesReadPositionStream
  2685. {
  2686. public ListenerResponseOutputStream(HttpListenerResponse listenerResponse)
  2687. : base(listenerResponse.OutputStream)
  2688. {
  2689. }
  2690. public override void Close()
  2691. {
  2692. try
  2693. {
  2694. base.Close();
  2695. }
  2696. catch (HttpListenerException listenerException)
  2697. {
  2698. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  2699. HttpChannelUtilities.CreateCommunicationException(listenerException));
  2700. }
  2701. }
  2702. public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  2703. {
  2704. try
  2705. {
  2706. return base.BeginWrite(buffer, offset, count, callback, state);
  2707. }
  2708. catch (HttpListenerException listenerException)
  2709. {
  2710. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  2711. HttpChannelUtilities.CreateCommunicationException(listenerException));
  2712. }
  2713. catch (ApplicationException applicationException)
  2714. {
  2715. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  2716. new CommunicationObjectAbortedException(SR.GetString(SR.HttpResponseAborted),
  2717. applicationException));
  2718. }
  2719. }
  2720. public override void EndWrite(IAsyncResult result)
  2721. {
  2722. try
  2723. {
  2724. base.EndWrite(result);
  2725. }
  2726. catch (HttpListenerException listenerException)
  2727. {
  2728. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  2729. HttpChannelUtilities.CreateCommunicationException(listenerException));
  2730. }
  2731. catch (ApplicationException applicationException)
  2732. {
  2733. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  2734. new CommunicationObjectAbortedException(SR.GetString(SR.HttpResponseAborted),
  2735. applicationException));
  2736. }
  2737. }
  2738. public override void Write(byte[] buffer, int offset, int count)
  2739. {
  2740. try
  2741. {
  2742. base.Write(buffer, offset, count);
  2743. }
  2744. catch (HttpListenerException listenerException)
  2745. {
  2746. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  2747. HttpChannelUtilities.CreateCommunicationException(listenerException));
  2748. }
  2749. catch (ApplicationException applicationException)
  2750. {
  2751. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  2752. new CommunicationObjectAbortedException(SR.GetString(SR.HttpResponseAborted),
  2753. applicationException));
  2754. }
  2755. }
  2756. }
  2757. }
  2758. }
  2759. enum HttpAbortReason
  2760. {
  2761. None,
  2762. Aborted,
  2763. TimedOut
  2764. }
  2765. delegate void AddHeaderDelegate(string headerName, string headerValue);
  2766. static class HttpChannelUtilities
  2767. {
  2768. internal static class StatusDescriptionStrings
  2769. {
  2770. internal const string HttpContentTypeMissing = "Missing Content Type";
  2771. internal const string HttpContentTypeMismatch = "Cannot process the message because the content type '{0}' was not the expected type '{1}'.";
  2772. internal const string HttpStatusServiceActivationException = "System.ServiceModel.ServiceActivationException";
  2773. }
  2774. internal static class ObsoleteDescriptionStrings
  2775. {
  2776. internal const string PropertyObsoleteUseAllowCookies = "This property is obsolete. To enable Http CookieContainer, use the AllowCookies property instead.";
  2777. internal const string TypeObsoleteUseAllowCookies = "This type is obsolete. To enable the Http CookieContainer, use the AllowCookies property on the http binding or on the HttpTransportBindingElement.";
  2778. }
  2779. internal const string HttpStatusCodeKey = "HttpStatusCode";
  2780. internal const string HttpStatusCodeExceptionKey = "System.ServiceModel.Channels.HttpInput.HttpStatusCode";
  2781. internal const string HttpStatusDescriptionExceptionKey = "System.ServiceModel.Channels.HttpInput.HttpStatusDescription";
  2782. internal const int ResponseStreamExcerptSize = 1024;
  2783. internal const string MIMEVersionHeader = "MIME-Version";
  2784. internal const string ContentEncodingHeader = "Content-Encoding";
  2785. internal const string AcceptEncodingHeader = "Accept-Encoding";
  2786. private const string ContentLengthHeader = "Content-Length";
  2787. private static readonly HashSet<string> httpContentHeaders = new HashSet<string>()
  2788. {
  2789. "Allow", "Content-Encoding", "Content-Language", "Content-Location", "Content-MD5",
  2790. "Content-Range", "Expires", "Last-Modified", "Content-Type", ContentLengthHeader
  2791. };
  2792. static bool allReferencedAssembliesLoaded = false;
  2793. public static Exception CreateCommunicationException(HttpListenerException listenerException)
  2794. {
  2795. switch (listenerException.NativeErrorCode)
  2796. {
  2797. case UnsafeNativeMethods.ERROR_NO_TRACKING_SERVICE:
  2798. return new CommunicationException(SR.GetString(SR.HttpNoTrackingService, listenerException.Message), listenerException);
  2799. case UnsafeNativeMethods.ERROR_NETNAME_DELETED:
  2800. return new CommunicationException(SR.GetString(SR.HttpNetnameDeleted, listenerException.Message), listenerException);
  2801. case UnsafeNativeMethods.ERROR_INVALID_HANDLE:
  2802. return new CommunicationObjectAbortedException(SR.GetString(SR.HttpResponseAborted), listenerException);
  2803. case UnsafeNativeMethods.ERROR_NOT_ENOUGH_MEMORY:
  2804. case UnsafeNativeMethods.ERROR_OUTOFMEMORY:
  2805. case UnsafeNativeMethods.ERROR_NO_SYSTEM_RESOURCES:
  2806. return new InsufficientMemoryException(SR.GetString(SR.InsufficentMemory), listenerException);
  2807. default:
  2808. return new CommunicationException(listenerException.Message, listenerException);
  2809. }
  2810. }
  2811. public static void EnsureHttpRequestMessageContentNotNull(HttpRequestMessage httpRequestMessage)
  2812. {
  2813. if (httpRequestMessage.Content == null)
  2814. {
  2815. httpRequestMessage.Content = new ByteArrayContent(EmptyArray<byte>.Instance);
  2816. }
  2817. }
  2818. public static void EnsureHttpResponseMessageContentNotNull(HttpResponseMessage httpResponseMessage)
  2819. {
  2820. if (httpResponseMessage.Content == null)
  2821. {
  2822. httpResponseMessage.Content = new ByteArrayContent(EmptyArray<byte>.Instance);
  2823. }
  2824. }
  2825. public static bool IsEmpty(HttpResponseMessage httpResponseMessage)
  2826. {
  2827. return httpResponseMessage.Content == null
  2828. || (httpResponseMessage.Content.Headers.ContentLength.HasValue && httpResponseMessage.Content.Headers.ContentLength.Value == 0);
  2829. }
  2830. internal static void HandleContinueWithTask(Task task)
  2831. {
  2832. HandleContinueWithTask(task, null);
  2833. }
  2834. internal static void HandleContinueWithTask(Task task, Action<Exception> exceptionHandler)
  2835. {
  2836. if (task.IsFaulted)
  2837. {
  2838. if (exceptionHandler == null)
  2839. {
  2840. throw FxTrace.Exception.AsError<FaultException>(task.Exception);
  2841. }
  2842. else
  2843. {
  2844. exceptionHandler.Invoke(task.Exception);
  2845. }
  2846. }
  2847. else if (task.IsCanceled)
  2848. {
  2849. throw FxTrace.Exception.AsError(new TimeoutException(SR.GetString(SR.TaskCancelledError)));
  2850. }
  2851. }
  2852. public static void AbortRequest(HttpWebRequest request)
  2853. {
  2854. request.Abort();
  2855. }
  2856. public static void SetRequestTimeout(HttpWebRequest request, TimeSpan timeout)
  2857. {
  2858. int millisecondsTimeout = TimeoutHelper.ToMilliseconds(timeout);
  2859. if (millisecondsTimeout == 0)
  2860. {
  2861. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.GetString(
  2862. SR.HttpRequestTimedOut, request.RequestUri, timeout)));
  2863. }
  2864. request.Timeout = millisecondsTimeout;
  2865. request.ReadWriteTimeout = millisecondsTimeout;
  2866. }
  2867. public static void AddReplySecurityProperty(HttpChannelFactory<IRequestChannel> factory, HttpWebRequest webRequest,
  2868. HttpWebResponse webResponse, Message replyMessage)
  2869. {
  2870. SecurityMessageProperty securityProperty = factory.CreateReplySecurityProperty(webRequest, webResponse);
  2871. if (securityProperty != null)
  2872. {
  2873. replyMessage.Properties.Security = securityProperty;
  2874. }
  2875. }
  2876. public static void CopyHeaders(HttpRequestMessage request, AddHeaderDelegate addHeader)
  2877. {
  2878. HttpChannelUtilities.CopyHeaders(request.Headers, addHeader);
  2879. if (request.Content != null)
  2880. {
  2881. HttpChannelUtilities.CopyHeaders(request.Content.Headers, addHeader);
  2882. }
  2883. }
  2884. public static void CopyHeaders(HttpResponseMessage response, AddHeaderDelegate addHeader)
  2885. {
  2886. HttpChannelUtilities.CopyHeaders(response.Headers, addHeader);
  2887. if (response.Content != null)
  2888. {
  2889. HttpChannelUtilities.CopyHeaders(response.Content.Headers, addHeader);
  2890. }
  2891. }
  2892. static void CopyHeaders(HttpHeaders headers, AddHeaderDelegate addHeader)
  2893. {
  2894. foreach (KeyValuePair<string, IEnumerable<string>> header in headers)
  2895. {
  2896. foreach (string value in header.Value)
  2897. {
  2898. TryAddToCollection(addHeader, header.Key, value);
  2899. }
  2900. }
  2901. }
  2902. public static void CopyHeaders(NameValueCollection headers, AddHeaderDelegate addHeader)
  2903. {
  2904. //this nested loop logic was copied from NameValueCollection.Add(NameValueCollection)
  2905. int count = headers.Count;
  2906. for (int i = 0; i < count; i++)
  2907. {
  2908. string key = headers.GetKey(i);
  2909. string[] values = headers.GetValues(i);
  2910. if (values != null)
  2911. {
  2912. for (int j = 0; j < values.Length; j++)
  2913. {
  2914. TryAddToCollection(addHeader, key, values[j]);
  2915. }
  2916. }
  2917. else
  2918. {
  2919. addHeader(key, null);
  2920. }
  2921. }
  2922. }
  2923. public static void CopyHeadersToNameValueCollection(NameValueCollection headers, NameValueCollection destination)
  2924. {
  2925. CopyHeaders(headers, destination.Add);
  2926. }
  2927. [System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability104",
  2928. Justification = "The exceptions are traced already.")]
  2929. static void TryAddToCollection(AddHeaderDelegate addHeader, string headerName, string value)
  2930. {
  2931. try
  2932. {
  2933. addHeader(headerName, value);
  2934. }
  2935. catch (ArgumentException ex)
  2936. {
  2937. string encodedValue = null;
  2938. if (TryEncodeHeaderValueAsUri(headerName, value, out encodedValue))
  2939. {
  2940. //note: if the hosthame of a referer header contains illegal chars, we will still throw from here
  2941. //because Uri will not fix this up for us, which is ok. The request will get rejected in the error code path.
  2942. addHeader(headerName, encodedValue);
  2943. }
  2944. else
  2945. {
  2946. // In self-hosted scenarios, some of the headers like Content-Length cannot be added directly.
  2947. // It will throw ArgumentException instead.
  2948. FxTrace.Exception.AsInformation(ex);
  2949. }
  2950. }
  2951. }
  2952. static bool TryEncodeHeaderValueAsUri(string headerName, string value, out string result)
  2953. {
  2954. result = null;
  2955. //Internet Explorer will send the referrer header on the wire in unicode without encoding it
  2956. //this will cause errors when added to a WebHeaderCollection. This is a workaround for sharepoint,
  2957. //but will only work for WebHosted Scenarios.
  2958. if (String.Compare(headerName, "Referer", StringComparison.OrdinalIgnoreCase) == 0)
  2959. {
  2960. Uri uri;
  2961. if (Uri.TryCreate(value, UriKind.RelativeOrAbsolute, out uri))
  2962. {
  2963. if (uri.IsAbsoluteUri)
  2964. {
  2965. result = uri.AbsoluteUri;
  2966. }
  2967. else
  2968. {
  2969. result = uri.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped);
  2970. }
  2971. return true;
  2972. }
  2973. }
  2974. return false;
  2975. }
  2976. //
  2977. internal static Type GetTypeFromAssembliesInCurrentDomain(string typeString)
  2978. {
  2979. Type type = Type.GetType(typeString, false);
  2980. if (null == type)
  2981. {
  2982. if (!allReferencedAssembliesLoaded)
  2983. {
  2984. allReferencedAssembliesLoaded = true;
  2985. AspNetEnvironment.Current.EnsureAllReferencedAssemblyLoaded();
  2986. }
  2987. Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
  2988. for (int i = 0; i < assemblies.Length; i++)
  2989. {
  2990. type = assemblies[i].GetType(typeString, false);
  2991. if (null != type)
  2992. {
  2993. break;
  2994. }
  2995. }
  2996. }
  2997. return type;
  2998. }
  2999. public static NetworkCredential GetCredential(AuthenticationSchemes authenticationScheme,
  3000. SecurityTokenProviderContainer credentialProvider, TimeSpan timeout,
  3001. out TokenImpersonationLevel impersonationLevel, out AuthenticationLevel authenticationLevel)
  3002. {
  3003. impersonationLevel = TokenImpersonationLevel.None;
  3004. authenticationLevel = AuthenticationLevel.None;
  3005. NetworkCredential result = null;
  3006. if (authenticationScheme != AuthenticationSchemes.Anonymous)
  3007. {
  3008. result = GetCredentialCore(authenticationScheme, credentialProvider, timeout, out impersonationLevel, out authenticationLevel);
  3009. }
  3010. return result;
  3011. }
  3012. [MethodImpl(MethodImplOptions.NoInlining)]
  3013. static NetworkCredential GetCredentialCore(AuthenticationSchemes authenticationScheme,
  3014. SecurityTokenProviderContainer credentialProvider, TimeSpan timeout,
  3015. out TokenImpersonationLevel impersonationLevel, out AuthenticationLevel authenticationLevel)
  3016. {
  3017. impersonationLevel = TokenImpersonationLevel.None;
  3018. authenticationLevel = AuthenticationLevel.None;
  3019. NetworkCredential result = null;
  3020. switch (authenticationScheme)
  3021. {
  3022. case AuthenticationSchemes.Basic:
  3023. result = TransportSecurityHelpers.GetUserNameCredential(credentialProvider, timeout);
  3024. impersonationLevel = TokenImpersonationLevel.Delegation;
  3025. break;
  3026. case AuthenticationSchemes.Digest:
  3027. result = TransportSecurityHelpers.GetSspiCredential(credentialProvider, timeout,
  3028. out impersonationLevel, out authenticationLevel);
  3029. HttpChannelUtilities.ValidateDigestCredential(ref result, impersonationLevel);
  3030. break;
  3031. case AuthenticationSchemes.Negotiate:
  3032. result = TransportSecurityHelpers.GetSspiCredential(credentialProvider, timeout,
  3033. out impersonationLevel, out authenticationLevel);
  3034. break;
  3035. case AuthenticationSchemes.Ntlm:
  3036. result = TransportSecurityHelpers.GetSspiCredential(credentialProvider, timeout,
  3037. out impersonationLevel, out authenticationLevel);
  3038. if (authenticationLevel == AuthenticationLevel.MutualAuthRequired)
  3039. {
  3040. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  3041. new InvalidOperationException(SR.GetString(SR.CredentialDisallowsNtlm)));
  3042. }
  3043. break;
  3044. default:
  3045. // The setter for this property should prevent this.
  3046. throw Fx.AssertAndThrow("GetCredential: Invalid authentication scheme");
  3047. }
  3048. return result;
  3049. }
  3050. public static HttpWebResponse ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
  3051. {
  3052. HttpWebResponse response = null;
  3053. if (webException.Status == WebExceptionStatus.Success ||
  3054. webException.Status == WebExceptionStatus.ProtocolError)
  3055. {
  3056. response = (HttpWebResponse)webException.Response;
  3057. }
  3058. if (response == null)
  3059. {
  3060. Exception convertedException = ConvertWebException(webException, request, abortReason);
  3061. if (convertedException != null)
  3062. {
  3063. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(convertedException);
  3064. }
  3065. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(webException.Message,
  3066. webException));
  3067. }
  3068. if (response.StatusCode == HttpStatusCode.NotFound)
  3069. {
  3070. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new EndpointNotFoundException(SR.GetString(SR.EndpointNotFound, request.RequestUri.AbsoluteUri), webException));
  3071. }
  3072. if (response.StatusCode == HttpStatusCode.ServiceUnavailable)
  3073. {
  3074. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ServerTooBusyException(SR.GetString(SR.HttpServerTooBusy, request.RequestUri.AbsoluteUri), webException));
  3075. }
  3076. if (response.StatusCode == HttpStatusCode.UnsupportedMediaType)
  3077. {
  3078. string statusDescription = response.StatusDescription;
  3079. if (!string.IsNullOrEmpty(statusDescription))
  3080. {
  3081. if (string.Compare(statusDescription, HttpChannelUtilities.StatusDescriptionStrings.HttpContentTypeMissing, StringComparison.OrdinalIgnoreCase) == 0)
  3082. {
  3083. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.GetString(SR.MissingContentType, request.RequestUri), webException));
  3084. }
  3085. }
  3086. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.GetString(SR.FramingContentTypeMismatch, request.ContentType, request.RequestUri), webException));
  3087. }
  3088. if (response.StatusCode == HttpStatusCode.GatewayTimeout)
  3089. {
  3090. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(webException.Message, webException));
  3091. }
  3092. // if http.sys has a request queue on the TCP port, then if the path fails to match it will send
  3093. // back "<h1>Bad Request (Invalid Hostname)</h1>" in the body of a 400 response.
  3094. // See code at \\index1\sddnsrv\net\http\sys\httprcv.c for details
  3095. if (response.StatusCode == HttpStatusCode.BadRequest)
  3096. {
  3097. const string httpSysRequestQueueNotFound = "<h1>Bad Request (Invalid Hostname)</h1>";
  3098. const string httpSysRequestQueueNotFoundVista = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\"http://www.w3.org/TR/html4/strict.dtd\">\r\n<HTML><HEAD><TITLE>Bad Request</TITLE>\r\n<META HTTP-EQUIV=\"Content-Type\" Content=\"text/html; charset=us-ascii\"></HEAD>\r\n<BODY><h2>Bad Request - Invalid Hostname</h2>\r\n<hr><p>HTTP Error 400. The request hostname is invalid.</p>\r\n</BODY></HTML>\r\n";
  3099. string notFoundTestString = null;
  3100. if (response.ContentLength == httpSysRequestQueueNotFound.Length)
  3101. {
  3102. notFoundTestString = httpSysRequestQueueNotFound;
  3103. }
  3104. else if (response.ContentLength == httpSysRequestQueueNotFoundVista.Length)
  3105. {
  3106. notFoundTestString = httpSysRequestQueueNotFoundVista;
  3107. }
  3108. if (notFoundTestString != null)
  3109. {
  3110. Stream responseStream = response.GetResponseStream();
  3111. byte[] responseBytes = new byte[notFoundTestString.Length];
  3112. int bytesRead = responseStream.Read(responseBytes, 0, responseBytes.Length);
  3113. // since the response is buffered by System.Net (it's an error response), we should have read
  3114. // the amount we were expecting
  3115. if (bytesRead == notFoundTestString.Length
  3116. && notFoundTestString == UTF8Encoding.ASCII.GetString(responseBytes))
  3117. {
  3118. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new EndpointNotFoundException(SR.GetString(SR.EndpointNotFound, request.RequestUri.AbsoluteUri), webException));
  3119. }
  3120. }
  3121. }
  3122. return response;
  3123. }
  3124. public static Exception ConvertWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
  3125. {
  3126. switch (webException.Status)
  3127. {
  3128. case WebExceptionStatus.ConnectFailure:
  3129. case WebExceptionStatus.NameResolutionFailure:
  3130. case WebExceptionStatus.ProxyNameResolutionFailure:
  3131. return new EndpointNotFoundException(SR.GetString(SR.EndpointNotFound, request.RequestUri.AbsoluteUri), webException);
  3132. case WebExceptionStatus.SecureChannelFailure:
  3133. return new SecurityNegotiationException(SR.GetString(SR.SecureChannelFailure, request.RequestUri.Authority), webException);
  3134. case WebExceptionStatus.TrustFailure:
  3135. return new SecurityNegotiationException(SR.GetString(SR.TrustFailure, request.RequestUri.Authority), webException);
  3136. case WebExceptionStatus.Timeout:
  3137. return new TimeoutException(CreateRequestTimedOutMessage(request), webException);
  3138. case WebExceptionStatus.ReceiveFailure:
  3139. return new CommunicationException(SR.GetString(SR.HttpReceiveFailure, request.RequestUri), webException);
  3140. case WebExceptionStatus.SendFailure:
  3141. return new CommunicationException(SR.GetString(SR.HttpSendFailure, request.RequestUri), webException);
  3142. case WebExceptionStatus.RequestCanceled:
  3143. return CreateRequestCanceledException(webException, request, abortReason);
  3144. case WebExceptionStatus.ProtocolError:
  3145. HttpWebResponse response = (HttpWebResponse)webException.Response;
  3146. Fx.Assert(response != null, "'response' MUST NOT be NULL for WebExceptionStatus=='ProtocolError'.");
  3147. if (response.StatusCode == HttpStatusCode.InternalServerError &&
  3148. string.Compare(response.StatusDescription, HttpChannelUtilities.StatusDescriptionStrings.HttpStatusServiceActivationException, StringComparison.OrdinalIgnoreCase) == 0)
  3149. {
  3150. return new ServiceActivationException(SR.GetString(SR.Hosting_ServiceActivationFailed, request.RequestUri));
  3151. }
  3152. else
  3153. {
  3154. return null;
  3155. }
  3156. default:
  3157. return null;
  3158. }
  3159. }
  3160. public static Exception CreateResponseIOException(IOException ioException, TimeSpan receiveTimeout)
  3161. {
  3162. if (ioException.InnerException is SocketException)
  3163. {
  3164. return SocketConnection.ConvertTransferException((SocketException)ioException.InnerException, receiveTimeout, ioException);
  3165. }
  3166. return new CommunicationException(SR.GetString(SR.HttpTransferError, ioException.Message), ioException);
  3167. }
  3168. public static Exception CreateResponseWebException(WebException webException, HttpWebResponse response)
  3169. {
  3170. switch (webException.Status)
  3171. {
  3172. case WebExceptionStatus.RequestCanceled:
  3173. return TraceResponseException(new CommunicationObjectAbortedException(SR.GetString(SR.HttpRequestAborted, response.ResponseUri), webException));
  3174. case WebExceptionStatus.ConnectionClosed:
  3175. return TraceResponseException(new CommunicationException(webException.Message, webException));
  3176. case WebExceptionStatus.Timeout:
  3177. return TraceResponseException(new TimeoutException(SR.GetString(SR.HttpResponseTimedOut, response.ResponseUri,
  3178. TimeSpan.FromMilliseconds(response.GetResponseStream().ReadTimeout)), webException));
  3179. default:
  3180. return CreateUnexpectedResponseException(webException, response);
  3181. }
  3182. }
  3183. public static Exception CreateRequestCanceledException(Exception webException, HttpWebRequest request, HttpAbortReason abortReason)
  3184. {
  3185. switch (abortReason)
  3186. {
  3187. case HttpAbortReason.Aborted:
  3188. return new CommunicationObjectAbortedException(SR.GetString(SR.HttpRequestAborted, request.RequestUri), webException);
  3189. case HttpAbortReason.TimedOut:
  3190. return new TimeoutException(CreateRequestTimedOutMessage(request), webException);
  3191. default:
  3192. return new CommunicationException(SR.GetString(SR.HttpTransferError, webException.Message), webException);
  3193. }
  3194. }
  3195. public static Exception CreateRequestIOException(IOException ioException, HttpWebRequest request)
  3196. {
  3197. return CreateRequestIOException(ioException, request, null);
  3198. }
  3199. public static Exception CreateRequestIOException(IOException ioException, HttpWebRequest request, Exception originalException)
  3200. {
  3201. Exception exception = originalException == null ? ioException : originalException;
  3202. if (ioException.InnerException is SocketException)
  3203. {
  3204. return SocketConnection.ConvertTransferException((SocketException)ioException.InnerException, TimeSpan.FromMilliseconds(request.Timeout), exception);
  3205. }
  3206. return new CommunicationException(SR.GetString(SR.HttpTransferError, exception.Message), exception);
  3207. }
  3208. static string CreateRequestTimedOutMessage(HttpWebRequest request)
  3209. {
  3210. return SR.GetString(SR.HttpRequestTimedOut, request.RequestUri, TimeSpan.FromMilliseconds(request.Timeout));
  3211. }
  3212. public static Exception CreateRequestWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
  3213. {
  3214. Exception convertedException = ConvertWebException(webException, request, abortReason);
  3215. if (webException.Response != null)
  3216. {
  3217. //free the connection for use by another request
  3218. webException.Response.Close();
  3219. }
  3220. if (convertedException != null)
  3221. {
  3222. return convertedException;
  3223. }
  3224. if (webException.InnerException is IOException)
  3225. {
  3226. return CreateRequestIOException((IOException)webException.InnerException, request, webException);
  3227. }
  3228. if (webException.InnerException is SocketException)
  3229. {
  3230. return SocketConnectionInitiator.ConvertConnectException((SocketException)webException.InnerException, request.RequestUri, TimeSpan.MaxValue, webException);
  3231. }
  3232. return new EndpointNotFoundException(SR.GetString(SR.EndpointNotFound, request.RequestUri.AbsoluteUri), webException);
  3233. }
  3234. static Exception CreateUnexpectedResponseException(WebException responseException, HttpWebResponse response)
  3235. {
  3236. string statusDescription = response.StatusDescription;
  3237. if (string.IsNullOrEmpty(statusDescription))
  3238. statusDescription = response.StatusCode.ToString();
  3239. return TraceResponseException(
  3240. new ProtocolException(SR.GetString(SR.UnexpectedHttpResponseCode,
  3241. (int)response.StatusCode, statusDescription), responseException));
  3242. }
  3243. public static Exception CreateNullReferenceResponseException(NullReferenceException nullReferenceException)
  3244. {
  3245. return TraceResponseException(
  3246. new ProtocolException(SR.GetString(SR.NullReferenceOnHttpResponse), nullReferenceException));
  3247. }
  3248. static string GetResponseStreamString(HttpWebResponse webResponse, out int bytesRead)
  3249. {
  3250. Stream responseStream = webResponse.GetResponseStream();
  3251. long bufferSize = webResponse.ContentLength;
  3252. if (bufferSize < 0 || bufferSize > ResponseStreamExcerptSize)
  3253. {
  3254. bufferSize = ResponseStreamExcerptSize;
  3255. }
  3256. byte[] responseBuffer = DiagnosticUtility.Utility.AllocateByteArray(checked((int)bufferSize));
  3257. bytesRead = responseStream.Read(responseBuffer, 0, (int)bufferSize);
  3258. responseStream.Close();
  3259. return System.Text.Encoding.UTF8.GetString(responseBuffer, 0, bytesRead);
  3260. }
  3261. static Exception TraceResponseException(Exception exception)
  3262. {
  3263. if (DiagnosticUtility.ShouldTraceError)
  3264. {
  3265. TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.HttpChannelUnexpectedResponse, SR.GetString(SR.TraceCodeHttpChannelUnexpectedResponse), (object)null, exception);
  3266. }
  3267. return exception;
  3268. }
  3269. static bool ValidateEmptyContent(HttpWebResponse response)
  3270. {
  3271. bool responseIsEmpty = true;
  3272. if (response.ContentLength > 0)
  3273. {
  3274. responseIsEmpty = false;
  3275. }
  3276. else if (response.ContentLength == -1) // chunked
  3277. {
  3278. Stream responseStream = response.GetResponseStream();
  3279. byte[] testBuffer = new byte[1];
  3280. responseIsEmpty = (responseStream.Read(testBuffer, 0, 1) != 1);
  3281. }
  3282. return responseIsEmpty;
  3283. }
  3284. static void ValidateAuthentication(HttpWebRequest request, HttpWebResponse response,
  3285. WebException responseException, HttpChannelFactory<IRequestChannel> factory)
  3286. {
  3287. if (response.StatusCode == HttpStatusCode.Unauthorized)
  3288. {
  3289. string message = SR.GetString(SR.HttpAuthorizationFailed, factory.AuthenticationScheme,
  3290. response.Headers[HttpResponseHeader.WwwAuthenticate]);
  3291. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  3292. TraceResponseException(new MessageSecurityException(message, responseException)));
  3293. }
  3294. if (response.StatusCode == HttpStatusCode.Forbidden)
  3295. {
  3296. string message = SR.GetString(SR.HttpAuthorizationForbidden, factory.AuthenticationScheme);
  3297. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  3298. TraceResponseException(new MessageSecurityException(message, responseException)));
  3299. }
  3300. if ((request.AuthenticationLevel == AuthenticationLevel.MutualAuthRequired) &&
  3301. !response.IsMutuallyAuthenticated)
  3302. {
  3303. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
  3304. TraceResponseException(new SecurityNegotiationException(SR.GetString(SR.HttpMutualAuthNotSatisfied),
  3305. responseException)));
  3306. }
  3307. }
  3308. public static void ValidateDigestCredential(ref NetworkCredential credential, TokenImpersonationLevel impersonationLevel)
  3309. {
  3310. // this is a work-around to VSWhidbey#470545 (Since the service always uses Impersonation,
  3311. // we mitigate EOP by preemtively not allowing Identification)
  3312. if (!SecurityUtils.IsDefaultNetworkCredential(credential))
  3313. {
  3314. // With a non-default credential, Digest will not honor a client impersonation constraint of
  3315. // TokenImpersonationLevel.Identification.
  3316. if (!TokenImpersonationLevelHelper.IsGreaterOrEqual(impersonationLevel,
  3317. TokenImpersonationLevel.Impersonation))
  3318. {
  3319. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(
  3320. SR.DigestExplicitCredsImpersonationLevel, impersonationLevel)));
  3321. }
  3322. }
  3323. }
  3324. // only valid response codes are 500 (if it's a fault) or 200 (iff it's a response message)
  3325. public static HttpInput ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response,
  3326. HttpChannelFactory<IRequestChannel> factory, WebException responseException, ChannelBinding channelBinding)
  3327. {
  3328. ValidateAuthentication(request, response, responseException, factory);
  3329. HttpInput httpInput = null;
  3330. // We will close the HttpWebResponse if we got an error code betwen 200 and 300 and
  3331. // 1) an exception was thrown out or
  3332. // 2) it's an empty message and we are using SOAP.
  3333. // For responses with status code above 300, System.Net will close the underlying connection so we don't need to worry about that.
  3334. if ((200 <= (int)response.StatusCode && (int)response.StatusCode < 300) || response.StatusCode == HttpStatusCode.InternalServerError)
  3335. {
  3336. if (response.StatusCode == HttpStatusCode.InternalServerError
  3337. && string.Compare(response.StatusDescription, HttpChannelUtilities.StatusDescriptionStrings.HttpStatusServiceActivationException, StringComparison.OrdinalIgnoreCase) == 0)
  3338. {
  3339. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ServiceActivationException(SR.GetString(SR.Hosting_ServiceActivationFailed, request.RequestUri)));
  3340. }
  3341. else
  3342. {
  3343. bool throwing = true;
  3344. try
  3345. {
  3346. if (string.IsNullOrEmpty(response.ContentType))
  3347. {
  3348. if (!ValidateEmptyContent(response))
  3349. {
  3350. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(TraceResponseException(
  3351. new ProtocolException(
  3352. SR.GetString(SR.HttpContentTypeHeaderRequired),
  3353. responseException)));
  3354. }
  3355. }
  3356. else if (response.ContentLength != 0)
  3357. {
  3358. MessageEncoder encoder = factory.MessageEncoderFactory.Encoder;
  3359. if (!encoder.IsContentTypeSupported(response.ContentType))
  3360. {
  3361. int bytesRead;
  3362. String responseExcerpt = GetResponseStreamString(response, out bytesRead);
  3363. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(TraceResponseException(
  3364. new ProtocolException(
  3365. SR.GetString(
  3366. SR.ResponseContentTypeMismatch,
  3367. response.ContentType,
  3368. encoder.ContentType,
  3369. bytesRead,
  3370. responseExcerpt), responseException)));
  3371. }
  3372. httpInput = HttpInput.CreateHttpInput(response, factory, channelBinding);
  3373. httpInput.WebException = responseException;
  3374. }
  3375. throwing = false;
  3376. }
  3377. finally
  3378. {
  3379. if (throwing)
  3380. {
  3381. response.Close();
  3382. }
  3383. }
  3384. }
  3385. if (httpInput == null)
  3386. {
  3387. if (factory.MessageEncoderFactory.MessageVersion == MessageVersion.None)
  3388. {
  3389. httpInput = HttpInput.CreateHttpInput(response, factory, channelBinding);
  3390. httpInput.WebException = responseException;
  3391. }
  3392. else
  3393. {
  3394. // In this case, we got a response with
  3395. // 1) status code between 200 and 300
  3396. // 2) Non-empty Content Type string
  3397. // 3) Zero content length
  3398. // Since we are trying to use SOAP here, the message seems to be malicious and we should
  3399. // just close the response directly.
  3400. response.Close();
  3401. }
  3402. }
  3403. }
  3404. else
  3405. {
  3406. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedResponseException(responseException, response));
  3407. }
  3408. return httpInput;
  3409. }
  3410. public static bool GetHttpResponseTypeAndEncodingForCompression(ref string contentType, out string contentEncoding)
  3411. {
  3412. contentEncoding = null;
  3413. bool isSession = false;
  3414. bool isDeflate = false;
  3415. if (string.Equals(BinaryVersion.GZipVersion1.ContentType, contentType, StringComparison.OrdinalIgnoreCase) ||
  3416. (isSession = string.Equals(BinaryVersion.GZipVersion1.SessionContentType, contentType, StringComparison.OrdinalIgnoreCase)) ||
  3417. (isDeflate = (string.Equals(BinaryVersion.DeflateVersion1.ContentType, contentType, StringComparison.OrdinalIgnoreCase) ||
  3418. (isSession = string.Equals(BinaryVersion.DeflateVersion1.SessionContentType, contentType, StringComparison.OrdinalIgnoreCase)))))
  3419. {
  3420. contentType = isSession ? BinaryVersion.Version1.SessionContentType : BinaryVersion.Version1.ContentType;
  3421. contentEncoding = isDeflate ? MessageEncoderCompressionHandler.DeflateContentEncoding : MessageEncoderCompressionHandler.GZipContentEncoding;
  3422. return true;
  3423. }
  3424. return false;
  3425. }
  3426. }
  3427. abstract class HttpDelayedAcceptStream : DetectEofStream
  3428. {
  3429. HttpOutput httpOutput;
  3430. bool isHttpOutputClosed;
  3431. /// <summary>
  3432. /// Indicates whether the HttpOutput should be closed when this stream is closed. In the streamed case,
  3433. /// we�ll leave the HttpOutput opened (and it will be closed by the HttpRequestContext, so we won't leak it).
  3434. /// </summary>
  3435. bool closeHttpOutput;
  3436. // sometimes we can't flush the HTTP output until we're done reading the end of the
  3437. // incoming stream of the HTTP input
  3438. protected HttpDelayedAcceptStream(Stream stream)
  3439. : base(stream)
  3440. {
  3441. }
  3442. public bool EnableDelayedAccept(HttpOutput output, bool closeHttpOutput)
  3443. {
  3444. if (IsAtEof)
  3445. {
  3446. return false;
  3447. }
  3448. this.closeHttpOutput = closeHttpOutput;
  3449. this.httpOutput = output;
  3450. return true;
  3451. }
  3452. protected override void OnReceivedEof()
  3453. {
  3454. if (this.closeHttpOutput)
  3455. {
  3456. CloseHttpOutput();
  3457. }
  3458. }
  3459. public override void Close()
  3460. {
  3461. if (this.closeHttpOutput)
  3462. {
  3463. CloseHttpOutput();
  3464. }
  3465. base.Close();
  3466. }
  3467. void CloseHttpOutput()
  3468. {
  3469. if (this.httpOutput != null && !this.isHttpOutputClosed)
  3470. {
  3471. this.httpOutput.Close();
  3472. this.isHttpOutputClosed = true;
  3473. }
  3474. }
  3475. }
  3476. abstract class BytesReadPositionStream : DelegatingStream
  3477. {
  3478. int bytesSent = 0;
  3479. protected BytesReadPositionStream(Stream stream)
  3480. : base(stream)
  3481. {
  3482. }
  3483. public override long Position
  3484. {
  3485. get
  3486. {
  3487. return bytesSent;
  3488. }
  3489. set
  3490. {
  3491. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SeekNotSupported)));
  3492. }
  3493. }
  3494. public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  3495. {
  3496. this.bytesSent += count;
  3497. return BaseStream.BeginWrite(buffer, offset, count, callback, state);
  3498. }
  3499. public override void Write(byte[] buffer, int offset, int count)
  3500. {
  3501. BaseStream.Write(buffer, offset, count);
  3502. this.bytesSent += count;
  3503. }
  3504. public override void WriteByte(byte value)
  3505. {
  3506. BaseStream.WriteByte(value);
  3507. this.bytesSent++;
  3508. }
  3509. }
  3510. class PreReadStream : DelegatingStream
  3511. {
  3512. byte[] preReadBuffer;
  3513. public PreReadStream(Stream stream, byte[] preReadBuffer)
  3514. : base(stream)
  3515. {
  3516. this.preReadBuffer = preReadBuffer;
  3517. }
  3518. bool ReadFromBuffer(byte[] buffer, int offset, int count, out int bytesRead)
  3519. {
  3520. if (this.preReadBuffer != null)
  3521. {
  3522. if (buffer == null)
  3523. {
  3524. throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("buffer");
  3525. }
  3526. if (offset >= buffer.Length)
  3527. {
  3528. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", offset,
  3529. SR.GetString(SR.OffsetExceedsBufferBound, buffer.Length - 1)));
  3530. }
  3531. if (count < 0)
  3532. {
  3533. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", count,
  3534. SR.GetString(SR.ValueMustBeNonNegative)));
  3535. }
  3536. if (count == 0)
  3537. {
  3538. bytesRead = 0;
  3539. }
  3540. else
  3541. {
  3542. buffer[offset] = this.preReadBuffer[0];
  3543. this.preReadBuffer = null;
  3544. bytesRead = 1;
  3545. }
  3546. return true;
  3547. }
  3548. bytesRead = -1;
  3549. return false;
  3550. }
  3551. public override int Read(byte[] buffer, int offset, int count)
  3552. {
  3553. int bytesRead;
  3554. if (ReadFromBuffer(buffer, offset, count, out bytesRead))
  3555. {
  3556. return bytesRead;
  3557. }
  3558. return base.Read(buffer, offset, count);
  3559. }
  3560. public override int ReadByte()
  3561. {
  3562. if (this.preReadBuffer != null)
  3563. {
  3564. byte[] tempBuffer = new byte[1];
  3565. int bytesRead;
  3566. if (ReadFromBuffer(tempBuffer, 0, 1, out bytesRead))
  3567. {
  3568. return tempBuffer[0];
  3569. }
  3570. }
  3571. return base.ReadByte();
  3572. }
  3573. public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  3574. {
  3575. int bytesRead;
  3576. if (ReadFromBuffer(buffer, offset, count, out bytesRead))
  3577. {
  3578. return new CompletedAsyncResult<int>(bytesRead, callback, state);
  3579. }
  3580. return base.BeginRead(buffer, offset, count, callback, state);
  3581. }
  3582. public override int EndRead(IAsyncResult result)
  3583. {
  3584. if (result is CompletedAsyncResult<int>)
  3585. {
  3586. return CompletedAsyncResult<int>.End(result);
  3587. }
  3588. else
  3589. {
  3590. return base.EndRead(result);
  3591. }
  3592. }
  3593. }
  3594. class HttpRequestMessageHttpInput : HttpInput, HttpRequestMessageProperty.IHttpHeaderProvider
  3595. {
  3596. const string SoapAction = "SOAPAction";
  3597. HttpRequestMessage httpRequestMessage;
  3598. ChannelBinding channelBinding;
  3599. public HttpRequestMessageHttpInput(HttpRequestMessage httpRequestMessage, IHttpTransportFactorySettings settings, bool enableChannelBinding, ChannelBinding channelBinding)
  3600. : base(settings, true, enableChannelBinding)
  3601. {
  3602. this.httpRequestMessage = httpRequestMessage;
  3603. this.channelBinding = channelBinding;
  3604. }
  3605. public override long ContentLength
  3606. {
  3607. get
  3608. {
  3609. if (this.httpRequestMessage.Content.Headers.ContentLength == null)
  3610. {
  3611. // Chunked transfer mode
  3612. return -1;
  3613. }
  3614. return this.httpRequestMessage.Content.Headers.ContentLength.Value;
  3615. }
  3616. }
  3617. protected override ChannelBinding ChannelBinding
  3618. {
  3619. get
  3620. {
  3621. return this.channelBinding;
  3622. }
  3623. }
  3624. public HttpRequestMessage HttpRequestMessage
  3625. {
  3626. get { return this.httpRequestMessage; }
  3627. }
  3628. protected override bool HasContent
  3629. {
  3630. get
  3631. {
  3632. // In Chunked transfer mode, the ContentLength header is null
  3633. // Otherwise we just rely on the ContentLength header
  3634. return this.httpRequestMessage.Content.Headers.ContentLength == null || this.httpRequestMessage.Content.Headers.ContentLength.Value > 0;
  3635. }
  3636. }
  3637. protected override string ContentTypeCore
  3638. {
  3639. get
  3640. {
  3641. if (!this.HasContent)
  3642. {
  3643. return null;
  3644. }
  3645. return this.httpRequestMessage.Content.Headers.ContentType == null ? null : this.httpRequestMessage.Content.Headers.ContentType.MediaType;
  3646. }
  3647. }
  3648. public override void ConfigureHttpRequestMessage(HttpRequestMessage message)
  3649. {
  3650. throw FxTrace.Exception.AsError(new InvalidOperationException());
  3651. }
  3652. protected override Stream GetInputStream()
  3653. {
  3654. if (this.httpRequestMessage.Content == null)
  3655. {
  3656. return Stream.Null;
  3657. }
  3658. return this.httpRequestMessage.Content.ReadAsStreamAsync().Result;
  3659. }
  3660. protected override void AddProperties(Message message)
  3661. {
  3662. HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty(this.httpRequestMessage);
  3663. message.Properties.Add(HttpRequestMessageProperty.Name, requestProperty);
  3664. message.Properties.Via = this.httpRequestMessage.RequestUri;
  3665. foreach (KeyValuePair<string, object> property in this.httpRequestMessage.Properties)
  3666. {
  3667. message.Properties.Add(property.Key, property.Value);
  3668. }
  3669. this.httpRequestMessage.Properties.Clear();
  3670. }
  3671. protected override string SoapActionHeader
  3672. {
  3673. get
  3674. {
  3675. IEnumerable<string> values;
  3676. if (this.httpRequestMessage.Headers.TryGetValues(SoapAction, out values))
  3677. {
  3678. foreach (string headerValue in values)
  3679. {
  3680. return headerValue;
  3681. }
  3682. }
  3683. return null;
  3684. }
  3685. }
  3686. public void CopyHeaders(WebHeaderCollection headers)
  3687. {
  3688. // No special-casing for the "WWW-Authenticate" header required here,
  3689. // because this method is only called for the incoming request
  3690. // and the WWW-Authenticate header is a header only applied to responses.
  3691. HttpChannelUtilities.CopyHeaders(this.httpRequestMessage, headers.Add);
  3692. }
  3693. internal void SetHttpRequestMessage(HttpRequestMessage httpRequestMessage)
  3694. {
  3695. Fx.Assert(httpRequestMessage != null, "httpRequestMessage should not be null.");
  3696. this.httpRequestMessage = httpRequestMessage;
  3697. }
  3698. }
  3699. }